tinymce.js 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786
  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.6.2 (2020-12-08)
  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 call = function (f) {
  157. f();
  158. };
  159. var never = constant(false);
  160. var always = constant(true);
  161. var none = function () {
  162. return NONE;
  163. };
  164. var NONE = function () {
  165. var eq = function (o) {
  166. return o.isNone();
  167. };
  168. var call = function (thunk) {
  169. return thunk();
  170. };
  171. var id = function (n) {
  172. return n;
  173. };
  174. var me = {
  175. fold: function (n, _s) {
  176. return n();
  177. },
  178. is: never,
  179. isSome: never,
  180. isNone: always,
  181. getOr: id,
  182. getOrThunk: call,
  183. getOrDie: function (msg) {
  184. throw new Error(msg || 'error: getOrDie called on none.');
  185. },
  186. getOrNull: constant(null),
  187. getOrUndefined: constant(undefined),
  188. or: id,
  189. orThunk: call,
  190. map: none,
  191. each: noop,
  192. bind: none,
  193. exists: never,
  194. forall: always,
  195. filter: none,
  196. equals: eq,
  197. equals_: eq,
  198. toArray: function () {
  199. return [];
  200. },
  201. toString: constant('none()')
  202. };
  203. return me;
  204. }();
  205. var some = function (a) {
  206. var constant_a = constant(a);
  207. var self = function () {
  208. return me;
  209. };
  210. var bind = function (f) {
  211. return f(a);
  212. };
  213. var me = {
  214. fold: function (n, s) {
  215. return s(a);
  216. },
  217. is: function (v) {
  218. return a === v;
  219. },
  220. isSome: always,
  221. isNone: never,
  222. getOr: constant_a,
  223. getOrThunk: constant_a,
  224. getOrDie: constant_a,
  225. getOrNull: constant_a,
  226. getOrUndefined: constant_a,
  227. or: self,
  228. orThunk: self,
  229. map: function (f) {
  230. return some(f(a));
  231. },
  232. each: function (f) {
  233. f(a);
  234. },
  235. bind: bind,
  236. exists: bind,
  237. forall: bind,
  238. filter: function (f) {
  239. return f(a) ? me : NONE;
  240. },
  241. toArray: function () {
  242. return [a];
  243. },
  244. toString: function () {
  245. return 'some(' + a + ')';
  246. },
  247. equals: function (o) {
  248. return o.is(a);
  249. },
  250. equals_: function (o, elementEq) {
  251. return o.fold(never, function (b) {
  252. return elementEq(a, b);
  253. });
  254. }
  255. };
  256. return me;
  257. };
  258. var from = function (value) {
  259. return value === null || value === undefined ? NONE : some(value);
  260. };
  261. var Optional = {
  262. some: some,
  263. none: none,
  264. from: from
  265. };
  266. var typeOf$1 = function (x) {
  267. var t = typeof x;
  268. if (x === null) {
  269. return 'null';
  270. } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  271. return 'array';
  272. } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  273. return 'string';
  274. } else {
  275. return t;
  276. }
  277. };
  278. var isType = function (type) {
  279. return function (value) {
  280. return typeOf$1(value) === type;
  281. };
  282. };
  283. var isSimpleType = function (type) {
  284. return function (value) {
  285. return typeof value === type;
  286. };
  287. };
  288. var eq$1 = function (t) {
  289. return function (a) {
  290. return t === a;
  291. };
  292. };
  293. var isString = isType('string');
  294. var isObject = isType('object');
  295. var isArray = isType('array');
  296. var isNull = eq$1(null);
  297. var isBoolean = isSimpleType('boolean');
  298. var isUndefined = eq$1(undefined);
  299. var isNullable = function (a) {
  300. return a === null || a === undefined;
  301. };
  302. var isNonNullable = function (a) {
  303. return !isNullable(a);
  304. };
  305. var isFunction = isSimpleType('function');
  306. var isNumber = isSimpleType('number');
  307. var nativeSlice = Array.prototype.slice;
  308. var nativeIndexOf = Array.prototype.indexOf;
  309. var nativePush = Array.prototype.push;
  310. var rawIndexOf = function (ts, t) {
  311. return nativeIndexOf.call(ts, t);
  312. };
  313. var indexOf = function (xs, x) {
  314. var r = rawIndexOf(xs, x);
  315. return r === -1 ? Optional.none() : Optional.some(r);
  316. };
  317. var contains = function (xs, x) {
  318. return rawIndexOf(xs, x) > -1;
  319. };
  320. var exists = function (xs, pred) {
  321. for (var i = 0, len = xs.length; i < len; i++) {
  322. var x = xs[i];
  323. if (pred(x, i)) {
  324. return true;
  325. }
  326. }
  327. return false;
  328. };
  329. var map = function (xs, f) {
  330. var len = xs.length;
  331. var r = new Array(len);
  332. for (var i = 0; i < len; i++) {
  333. var x = xs[i];
  334. r[i] = f(x, i);
  335. }
  336. return r;
  337. };
  338. var each = function (xs, f) {
  339. for (var i = 0, len = xs.length; i < len; i++) {
  340. var x = xs[i];
  341. f(x, i);
  342. }
  343. };
  344. var eachr = function (xs, f) {
  345. for (var i = xs.length - 1; i >= 0; i--) {
  346. var x = xs[i];
  347. f(x, i);
  348. }
  349. };
  350. var partition = function (xs, pred) {
  351. var pass = [];
  352. var fail = [];
  353. for (var i = 0, len = xs.length; i < len; i++) {
  354. var x = xs[i];
  355. var arr = pred(x, i) ? pass : fail;
  356. arr.push(x);
  357. }
  358. return {
  359. pass: pass,
  360. fail: fail
  361. };
  362. };
  363. var filter = function (xs, pred) {
  364. var r = [];
  365. for (var i = 0, len = xs.length; i < len; i++) {
  366. var x = xs[i];
  367. if (pred(x, i)) {
  368. r.push(x);
  369. }
  370. }
  371. return r;
  372. };
  373. var foldr = function (xs, f, acc) {
  374. eachr(xs, function (x) {
  375. acc = f(acc, x);
  376. });
  377. return acc;
  378. };
  379. var foldl = function (xs, f, acc) {
  380. each(xs, function (x) {
  381. acc = f(acc, x);
  382. });
  383. return acc;
  384. };
  385. var findUntil = function (xs, pred, until) {
  386. for (var i = 0, len = xs.length; i < len; i++) {
  387. var x = xs[i];
  388. if (pred(x, i)) {
  389. return Optional.some(x);
  390. } else if (until(x, i)) {
  391. break;
  392. }
  393. }
  394. return Optional.none();
  395. };
  396. var find = function (xs, pred) {
  397. return findUntil(xs, pred, never);
  398. };
  399. var findIndex = function (xs, pred) {
  400. for (var i = 0, len = xs.length; i < len; i++) {
  401. var x = xs[i];
  402. if (pred(x, i)) {
  403. return Optional.some(i);
  404. }
  405. }
  406. return Optional.none();
  407. };
  408. var flatten = function (xs) {
  409. var r = [];
  410. for (var i = 0, len = xs.length; i < len; ++i) {
  411. if (!isArray(xs[i])) {
  412. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  413. }
  414. nativePush.apply(r, xs[i]);
  415. }
  416. return r;
  417. };
  418. var bind = function (xs, f) {
  419. return flatten(map(xs, f));
  420. };
  421. var forall = function (xs, pred) {
  422. for (var i = 0, len = xs.length; i < len; ++i) {
  423. var x = xs[i];
  424. if (pred(x, i) !== true) {
  425. return false;
  426. }
  427. }
  428. return true;
  429. };
  430. var reverse = function (xs) {
  431. var r = nativeSlice.call(xs, 0);
  432. r.reverse();
  433. return r;
  434. };
  435. var difference = function (a1, a2) {
  436. return filter(a1, function (x) {
  437. return !contains(a2, x);
  438. });
  439. };
  440. var mapToObject = function (xs, f) {
  441. var r = {};
  442. for (var i = 0, len = xs.length; i < len; i++) {
  443. var x = xs[i];
  444. r[String(x)] = f(x, i);
  445. }
  446. return r;
  447. };
  448. var sort$1 = function (xs, comparator) {
  449. var copy = nativeSlice.call(xs, 0);
  450. copy.sort(comparator);
  451. return copy;
  452. };
  453. var get = function (xs, i) {
  454. return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
  455. };
  456. var head = function (xs) {
  457. return get(xs, 0);
  458. };
  459. var last = function (xs) {
  460. return get(xs, xs.length - 1);
  461. };
  462. var from$1 = isFunction(Array.from) ? Array.from : function (x) {
  463. return nativeSlice.call(x);
  464. };
  465. var findMap = function (arr, f) {
  466. for (var i = 0; i < arr.length; i++) {
  467. var r = f(arr[i], i);
  468. if (r.isSome()) {
  469. return r;
  470. }
  471. }
  472. return Optional.none();
  473. };
  474. var keys = Object.keys;
  475. var hasOwnProperty = Object.hasOwnProperty;
  476. var each$1 = function (obj, f) {
  477. var props = keys(obj);
  478. for (var k = 0, len = props.length; k < len; k++) {
  479. var i = props[k];
  480. var x = obj[i];
  481. f(x, i);
  482. }
  483. };
  484. var map$1 = function (obj, f) {
  485. return tupleMap(obj, function (x, i) {
  486. return {
  487. k: i,
  488. v: f(x, i)
  489. };
  490. });
  491. };
  492. var tupleMap = function (obj, f) {
  493. var r = {};
  494. each$1(obj, function (x, i) {
  495. var tuple = f(x, i);
  496. r[tuple.k] = tuple.v;
  497. });
  498. return r;
  499. };
  500. var objAcc = function (r) {
  501. return function (x, i) {
  502. r[i] = x;
  503. };
  504. };
  505. var internalFilter = function (obj, pred, onTrue, onFalse) {
  506. var r = {};
  507. each$1(obj, function (x, i) {
  508. (pred(x, i) ? onTrue : onFalse)(x, i);
  509. });
  510. return r;
  511. };
  512. var bifilter = function (obj, pred) {
  513. var t = {};
  514. var f = {};
  515. internalFilter(obj, pred, objAcc(t), objAcc(f));
  516. return {
  517. t: t,
  518. f: f
  519. };
  520. };
  521. var filter$1 = function (obj, pred) {
  522. var t = {};
  523. internalFilter(obj, pred, objAcc(t), noop);
  524. return t;
  525. };
  526. var mapToArray = function (obj, f) {
  527. var r = [];
  528. each$1(obj, function (value, name) {
  529. r.push(f(value, name));
  530. });
  531. return r;
  532. };
  533. var values = function (obj) {
  534. return mapToArray(obj, function (v) {
  535. return v;
  536. });
  537. };
  538. var get$1 = function (obj, key) {
  539. return has(obj, key) ? Optional.from(obj[key]) : Optional.none();
  540. };
  541. var has = function (obj, key) {
  542. return hasOwnProperty.call(obj, key);
  543. };
  544. var hasNonNullableKey = function (obj, key) {
  545. return has(obj, key) && obj[key] !== undefined && obj[key] !== null;
  546. };
  547. var equal = function (a1, a2, eq) {
  548. if (eq === void 0) {
  549. eq = eqAny;
  550. }
  551. return eqRecord(eq).eq(a1, a2);
  552. };
  553. var isArray$1 = Array.isArray;
  554. var toArray = function (obj) {
  555. if (!isArray$1(obj)) {
  556. var array = [];
  557. for (var i = 0, l = obj.length; i < l; i++) {
  558. array[i] = obj[i];
  559. }
  560. return array;
  561. } else {
  562. return obj;
  563. }
  564. };
  565. var each$2 = function (o, cb, s) {
  566. var n, l;
  567. if (!o) {
  568. return false;
  569. }
  570. s = s || o;
  571. if (o.length !== undefined) {
  572. for (n = 0, l = o.length; n < l; n++) {
  573. if (cb.call(s, o[n], n, o) === false) {
  574. return false;
  575. }
  576. }
  577. } else {
  578. for (n in o) {
  579. if (o.hasOwnProperty(n)) {
  580. if (cb.call(s, o[n], n, o) === false) {
  581. return false;
  582. }
  583. }
  584. }
  585. }
  586. return true;
  587. };
  588. var map$2 = function (array, callback) {
  589. var out = [];
  590. each$2(array, function (item, index) {
  591. out.push(callback(item, index, array));
  592. });
  593. return out;
  594. };
  595. var filter$2 = function (a, f) {
  596. var o = [];
  597. each$2(a, function (v, index) {
  598. if (!f || f(v, index, a)) {
  599. o.push(v);
  600. }
  601. });
  602. return o;
  603. };
  604. var indexOf$1 = function (a, v) {
  605. if (a) {
  606. for (var i = 0, l = a.length; i < l; i++) {
  607. if (a[i] === v) {
  608. return i;
  609. }
  610. }
  611. }
  612. return -1;
  613. };
  614. var reduce = function (collection, iteratee, accumulator, thisArg) {
  615. var acc = isUndefined(accumulator) ? collection[0] : accumulator;
  616. for (var i = 0; i < collection.length; i++) {
  617. acc = iteratee.call(thisArg, acc, collection[i], i);
  618. }
  619. return acc;
  620. };
  621. var findIndex$1 = function (array, predicate, thisArg) {
  622. var i, l;
  623. for (i = 0, l = array.length; i < l; i++) {
  624. if (predicate.call(thisArg, array[i], i, array)) {
  625. return i;
  626. }
  627. }
  628. return -1;
  629. };
  630. var last$1 = function (collection) {
  631. return collection[collection.length - 1];
  632. };
  633. var __assign = function () {
  634. __assign = Object.assign || function __assign(t) {
  635. for (var s, i = 1, n = arguments.length; i < n; i++) {
  636. s = arguments[i];
  637. for (var p in s)
  638. if (Object.prototype.hasOwnProperty.call(s, p))
  639. t[p] = s[p];
  640. }
  641. return t;
  642. };
  643. return __assign.apply(this, arguments);
  644. };
  645. function __rest(s, e) {
  646. var t = {};
  647. for (var p in s)
  648. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  649. t[p] = s[p];
  650. if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  651. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  652. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  653. t[p[i]] = s[p[i]];
  654. }
  655. return t;
  656. }
  657. function __spreadArrays() {
  658. for (var s = 0, i = 0, il = arguments.length; i < il; i++)
  659. s += arguments[i].length;
  660. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  661. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  662. r[k] = a[j];
  663. return r;
  664. }
  665. var cached = function (f) {
  666. var called = false;
  667. var r;
  668. return function () {
  669. var args = [];
  670. for (var _i = 0; _i < arguments.length; _i++) {
  671. args[_i] = arguments[_i];
  672. }
  673. if (!called) {
  674. called = true;
  675. r = f.apply(null, args);
  676. }
  677. return r;
  678. };
  679. };
  680. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  681. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  682. var isiPhone = os.isiOS() && !isiPad;
  683. var isMobile = os.isiOS() || os.isAndroid();
  684. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  685. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  686. var isPhone = isiPhone || isMobile && !isTablet;
  687. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  688. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  689. return {
  690. isiPad: constant(isiPad),
  691. isiPhone: constant(isiPhone),
  692. isTablet: constant(isTablet),
  693. isPhone: constant(isPhone),
  694. isTouch: constant(isTouch),
  695. isAndroid: os.isAndroid,
  696. isiOS: os.isiOS,
  697. isWebView: constant(iOSwebview),
  698. isDesktop: constant(isDesktop)
  699. };
  700. };
  701. var firstMatch = function (regexes, s) {
  702. for (var i = 0; i < regexes.length; i++) {
  703. var x = regexes[i];
  704. if (x.test(s)) {
  705. return x;
  706. }
  707. }
  708. return undefined;
  709. };
  710. var find$1 = function (regexes, agent) {
  711. var r = firstMatch(regexes, agent);
  712. if (!r) {
  713. return {
  714. major: 0,
  715. minor: 0
  716. };
  717. }
  718. var group = function (i) {
  719. return Number(agent.replace(r, '$' + i));
  720. };
  721. return nu(group(1), group(2));
  722. };
  723. var detect = function (versionRegexes, agent) {
  724. var cleanedAgent = String(agent).toLowerCase();
  725. if (versionRegexes.length === 0) {
  726. return unknown();
  727. }
  728. return find$1(versionRegexes, cleanedAgent);
  729. };
  730. var unknown = function () {
  731. return nu(0, 0);
  732. };
  733. var nu = function (major, minor) {
  734. return {
  735. major: major,
  736. minor: minor
  737. };
  738. };
  739. var Version = {
  740. nu: nu,
  741. detect: detect,
  742. unknown: unknown
  743. };
  744. var detect$1 = function (candidates, userAgent) {
  745. var agent = String(userAgent).toLowerCase();
  746. return find(candidates, function (candidate) {
  747. return candidate.search(agent);
  748. });
  749. };
  750. var detectBrowser = function (browsers, userAgent) {
  751. return detect$1(browsers, userAgent).map(function (browser) {
  752. var version = Version.detect(browser.versionRegexes, userAgent);
  753. return {
  754. current: browser.name,
  755. version: version
  756. };
  757. });
  758. };
  759. var detectOs = function (oses, userAgent) {
  760. return detect$1(oses, userAgent).map(function (os) {
  761. var version = Version.detect(os.versionRegexes, userAgent);
  762. return {
  763. current: os.name,
  764. version: version
  765. };
  766. });
  767. };
  768. var UaString = {
  769. detectBrowser: detectBrowser,
  770. detectOs: detectOs
  771. };
  772. var removeFromStart = function (str, numChars) {
  773. return str.substring(numChars);
  774. };
  775. var checkRange = function (str, substr, start) {
  776. return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  777. };
  778. var removeLeading = function (str, prefix) {
  779. return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
  780. };
  781. var contains$1 = function (str, substr) {
  782. return str.indexOf(substr) !== -1;
  783. };
  784. var startsWith = function (str, prefix) {
  785. return checkRange(str, prefix, 0);
  786. };
  787. var blank = function (r) {
  788. return function (s) {
  789. return s.replace(r, '');
  790. };
  791. };
  792. var trim = blank(/^\s+|\s+$/g);
  793. var lTrim = blank(/^\s+/g);
  794. var rTrim = blank(/\s+$/g);
  795. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  796. var checkContains = function (target) {
  797. return function (uastring) {
  798. return contains$1(uastring, target);
  799. };
  800. };
  801. var browsers = [
  802. {
  803. name: 'Edge',
  804. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  805. search: function (uastring) {
  806. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  807. }
  808. },
  809. {
  810. name: 'Chrome',
  811. versionRegexes: [
  812. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  813. normalVersionRegex
  814. ],
  815. search: function (uastring) {
  816. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  817. }
  818. },
  819. {
  820. name: 'IE',
  821. versionRegexes: [
  822. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  823. /.*?rv:([0-9]+)\.([0-9]+).*/
  824. ],
  825. search: function (uastring) {
  826. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  827. }
  828. },
  829. {
  830. name: 'Opera',
  831. versionRegexes: [
  832. normalVersionRegex,
  833. /.*?opera\/([0-9]+)\.([0-9]+).*/
  834. ],
  835. search: checkContains('opera')
  836. },
  837. {
  838. name: 'Firefox',
  839. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  840. search: checkContains('firefox')
  841. },
  842. {
  843. name: 'Safari',
  844. versionRegexes: [
  845. normalVersionRegex,
  846. /.*?cpu os ([0-9]+)_([0-9]+).*/
  847. ],
  848. search: function (uastring) {
  849. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  850. }
  851. }
  852. ];
  853. var oses = [
  854. {
  855. name: 'Windows',
  856. search: checkContains('win'),
  857. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  858. },
  859. {
  860. name: 'iOS',
  861. search: function (uastring) {
  862. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  863. },
  864. versionRegexes: [
  865. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  866. /.*cpu os ([0-9]+)_([0-9]+).*/,
  867. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  868. ]
  869. },
  870. {
  871. name: 'Android',
  872. search: checkContains('android'),
  873. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  874. },
  875. {
  876. name: 'OSX',
  877. search: checkContains('mac os x'),
  878. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  879. },
  880. {
  881. name: 'Linux',
  882. search: checkContains('linux'),
  883. versionRegexes: []
  884. },
  885. {
  886. name: 'Solaris',
  887. search: checkContains('sunos'),
  888. versionRegexes: []
  889. },
  890. {
  891. name: 'FreeBSD',
  892. search: checkContains('freebsd'),
  893. versionRegexes: []
  894. },
  895. {
  896. name: 'ChromeOS',
  897. search: checkContains('cros'),
  898. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  899. }
  900. ];
  901. var PlatformInfo = {
  902. browsers: constant(browsers),
  903. oses: constant(oses)
  904. };
  905. var edge = 'Edge';
  906. var chrome = 'Chrome';
  907. var ie = 'IE';
  908. var opera = 'Opera';
  909. var firefox = 'Firefox';
  910. var safari = 'Safari';
  911. var unknown$1 = function () {
  912. return nu$1({
  913. current: undefined,
  914. version: Version.unknown()
  915. });
  916. };
  917. var nu$1 = function (info) {
  918. var current = info.current;
  919. var version = info.version;
  920. var isBrowser = function (name) {
  921. return function () {
  922. return current === name;
  923. };
  924. };
  925. return {
  926. current: current,
  927. version: version,
  928. isEdge: isBrowser(edge),
  929. isChrome: isBrowser(chrome),
  930. isIE: isBrowser(ie),
  931. isOpera: isBrowser(opera),
  932. isFirefox: isBrowser(firefox),
  933. isSafari: isBrowser(safari)
  934. };
  935. };
  936. var Browser = {
  937. unknown: unknown$1,
  938. nu: nu$1,
  939. edge: constant(edge),
  940. chrome: constant(chrome),
  941. ie: constant(ie),
  942. opera: constant(opera),
  943. firefox: constant(firefox),
  944. safari: constant(safari)
  945. };
  946. var windows = 'Windows';
  947. var ios = 'iOS';
  948. var android = 'Android';
  949. var linux = 'Linux';
  950. var osx = 'OSX';
  951. var solaris = 'Solaris';
  952. var freebsd = 'FreeBSD';
  953. var chromeos = 'ChromeOS';
  954. var unknown$2 = function () {
  955. return nu$2({
  956. current: undefined,
  957. version: Version.unknown()
  958. });
  959. };
  960. var nu$2 = function (info) {
  961. var current = info.current;
  962. var version = info.version;
  963. var isOS = function (name) {
  964. return function () {
  965. return current === name;
  966. };
  967. };
  968. return {
  969. current: current,
  970. version: version,
  971. isWindows: isOS(windows),
  972. isiOS: isOS(ios),
  973. isAndroid: isOS(android),
  974. isOSX: isOS(osx),
  975. isLinux: isOS(linux),
  976. isSolaris: isOS(solaris),
  977. isFreeBSD: isOS(freebsd),
  978. isChromeOS: isOS(chromeos)
  979. };
  980. };
  981. var OperatingSystem = {
  982. unknown: unknown$2,
  983. nu: nu$2,
  984. windows: constant(windows),
  985. ios: constant(ios),
  986. android: constant(android),
  987. linux: constant(linux),
  988. osx: constant(osx),
  989. solaris: constant(solaris),
  990. freebsd: constant(freebsd),
  991. chromeos: constant(chromeos)
  992. };
  993. var detect$2 = function (userAgent, mediaMatch) {
  994. var browsers = PlatformInfo.browsers();
  995. var oses = PlatformInfo.oses();
  996. var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
  997. var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  998. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  999. return {
  1000. browser: browser,
  1001. os: os,
  1002. deviceType: deviceType
  1003. };
  1004. };
  1005. var PlatformDetection = { detect: detect$2 };
  1006. var mediaMatch = function (query) {
  1007. return window.matchMedia(query).matches;
  1008. };
  1009. var platform = cached(function () {
  1010. return PlatformDetection.detect(navigator.userAgent, mediaMatch);
  1011. });
  1012. var detect$3 = function () {
  1013. return platform();
  1014. };
  1015. var userAgent = navigator.userAgent;
  1016. var platform$1 = detect$3();
  1017. var browser = platform$1.browser;
  1018. var os = platform$1.os;
  1019. var deviceType = platform$1.deviceType;
  1020. var webkit = /WebKit/.test(userAgent) && !browser.isEdge();
  1021. var fileApi = 'FormData' in window && 'FileReader' in window && 'URL' in window && !!URL.createObjectURL;
  1022. var windowsPhone = userAgent.indexOf('Windows Phone') !== -1;
  1023. var Env = {
  1024. opera: browser.isOpera(),
  1025. webkit: webkit,
  1026. ie: browser.isIE() || browser.isEdge() ? browser.version.major : false,
  1027. gecko: browser.isFirefox(),
  1028. mac: os.isOSX() || os.isiOS(),
  1029. iOS: deviceType.isiPad() || deviceType.isiPhone(),
  1030. android: os.isAndroid(),
  1031. contentEditable: true,
  1032. transparentSrc: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
  1033. caretAfter: true,
  1034. range: window.getSelection && 'Range' in window,
  1035. documentMode: browser.isIE() ? document.documentMode || 7 : 10,
  1036. fileApi: fileApi,
  1037. ceFalse: true,
  1038. cacheSuffix: null,
  1039. container: null,
  1040. experimentalShadowDom: false,
  1041. canHaveCSP: !browser.isIE(),
  1042. desktop: deviceType.isDesktop(),
  1043. windowsPhone: windowsPhone,
  1044. browser: {
  1045. current: browser.current,
  1046. version: browser.version,
  1047. isChrome: browser.isChrome,
  1048. isEdge: browser.isEdge,
  1049. isFirefox: browser.isFirefox,
  1050. isIE: browser.isIE,
  1051. isOpera: browser.isOpera,
  1052. isSafari: browser.isSafari
  1053. },
  1054. os: {
  1055. current: os.current,
  1056. version: os.version,
  1057. isAndroid: os.isAndroid,
  1058. isChromeOS: os.isChromeOS,
  1059. isFreeBSD: os.isFreeBSD,
  1060. isiOS: os.isiOS,
  1061. isLinux: os.isLinux,
  1062. isOSX: os.isOSX,
  1063. isSolaris: os.isSolaris,
  1064. isWindows: os.isWindows
  1065. },
  1066. deviceType: {
  1067. isDesktop: deviceType.isDesktop,
  1068. isiPad: deviceType.isiPad,
  1069. isiPhone: deviceType.isiPhone,
  1070. isPhone: deviceType.isPhone,
  1071. isTablet: deviceType.isTablet,
  1072. isTouch: deviceType.isTouch,
  1073. isWebView: deviceType.isWebView
  1074. }
  1075. };
  1076. var whiteSpaceRegExp = /^\s*|\s*$/g;
  1077. var trim$1 = function (str) {
  1078. return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp, '');
  1079. };
  1080. var is = function (obj, type) {
  1081. if (!type) {
  1082. return obj !== undefined;
  1083. }
  1084. if (type === 'array' && isArray$1(obj)) {
  1085. return true;
  1086. }
  1087. return typeof obj === type;
  1088. };
  1089. var makeMap = function (items, delim, map) {
  1090. var i;
  1091. items = items || [];
  1092. delim = delim || ',';
  1093. if (typeof items === 'string') {
  1094. items = items.split(delim);
  1095. }
  1096. map = map || {};
  1097. i = items.length;
  1098. while (i--) {
  1099. map[items[i]] = {};
  1100. }
  1101. return map;
  1102. };
  1103. var hasOwnProperty$1 = function (obj, prop) {
  1104. return Object.prototype.hasOwnProperty.call(obj, prop);
  1105. };
  1106. var create = function (s, p, root) {
  1107. var self = this;
  1108. var sp, scn, c, de = 0;
  1109. s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
  1110. var cn = s[3].match(/(^|\.)(\w+)$/i)[2];
  1111. var ns = self.createNS(s[3].replace(/\.\w+$/, ''), root);
  1112. if (ns[cn]) {
  1113. return;
  1114. }
  1115. if (s[2] === 'static') {
  1116. ns[cn] = p;
  1117. if (this.onCreate) {
  1118. this.onCreate(s[2], s[3], ns[cn]);
  1119. }
  1120. return;
  1121. }
  1122. if (!p[cn]) {
  1123. p[cn] = function () {
  1124. };
  1125. de = 1;
  1126. }
  1127. ns[cn] = p[cn];
  1128. self.extend(ns[cn].prototype, p);
  1129. if (s[5]) {
  1130. sp = self.resolve(s[5]).prototype;
  1131. scn = s[5].match(/\.(\w+)$/i)[1];
  1132. c = ns[cn];
  1133. if (de) {
  1134. ns[cn] = function () {
  1135. return sp[scn].apply(this, arguments);
  1136. };
  1137. } else {
  1138. ns[cn] = function () {
  1139. this.parent = sp[scn];
  1140. return c.apply(this, arguments);
  1141. };
  1142. }
  1143. ns[cn].prototype[cn] = ns[cn];
  1144. self.each(sp, function (f, n) {
  1145. ns[cn].prototype[n] = sp[n];
  1146. });
  1147. self.each(p, function (f, n) {
  1148. if (sp[n]) {
  1149. ns[cn].prototype[n] = function () {
  1150. this.parent = sp[n];
  1151. return f.apply(this, arguments);
  1152. };
  1153. } else {
  1154. if (n !== cn) {
  1155. ns[cn].prototype[n] = f;
  1156. }
  1157. }
  1158. });
  1159. }
  1160. self.each(p.static, function (f, n) {
  1161. ns[cn][n] = f;
  1162. });
  1163. };
  1164. var extend = function (obj) {
  1165. var exts = [];
  1166. for (var _i = 1; _i < arguments.length; _i++) {
  1167. exts[_i - 1] = arguments[_i];
  1168. }
  1169. for (var i = 0; i < exts.length; i++) {
  1170. var ext = exts[i];
  1171. for (var name_1 in ext) {
  1172. if (ext.hasOwnProperty(name_1)) {
  1173. var value = ext[name_1];
  1174. if (value !== undefined) {
  1175. obj[name_1] = value;
  1176. }
  1177. }
  1178. }
  1179. }
  1180. return obj;
  1181. };
  1182. var walk = function (o, f, n, s) {
  1183. s = s || this;
  1184. if (o) {
  1185. if (n) {
  1186. o = o[n];
  1187. }
  1188. each$2(o, function (o, i) {
  1189. if (f.call(s, o, i, n) === false) {
  1190. return false;
  1191. }
  1192. walk(o, f, n, s);
  1193. });
  1194. }
  1195. };
  1196. var createNS = function (n, o) {
  1197. var i, v;
  1198. o = o || window;
  1199. n = n.split('.');
  1200. for (i = 0; i < n.length; i++) {
  1201. v = n[i];
  1202. if (!o[v]) {
  1203. o[v] = {};
  1204. }
  1205. o = o[v];
  1206. }
  1207. return o;
  1208. };
  1209. var resolve = function (n, o) {
  1210. var i, l;
  1211. o = o || window;
  1212. n = n.split('.');
  1213. for (i = 0, l = n.length; i < l; i++) {
  1214. o = o[n[i]];
  1215. if (!o) {
  1216. break;
  1217. }
  1218. }
  1219. return o;
  1220. };
  1221. var explode = function (s, d) {
  1222. if (!s || is(s, 'array')) {
  1223. return s;
  1224. }
  1225. return map$2(s.split(d || ','), trim$1);
  1226. };
  1227. var _addCacheSuffix = function (url) {
  1228. var cacheSuffix = Env.cacheSuffix;
  1229. if (cacheSuffix) {
  1230. url += (url.indexOf('?') === -1 ? '?' : '&') + cacheSuffix;
  1231. }
  1232. return url;
  1233. };
  1234. var Tools = {
  1235. trim: trim$1,
  1236. isArray: isArray$1,
  1237. is: is,
  1238. toArray: toArray,
  1239. makeMap: makeMap,
  1240. each: each$2,
  1241. map: map$2,
  1242. grep: filter$2,
  1243. inArray: indexOf$1,
  1244. hasOwn: hasOwnProperty$1,
  1245. extend: extend,
  1246. create: create,
  1247. walk: walk,
  1248. createNS: createNS,
  1249. resolve: resolve,
  1250. explode: explode,
  1251. _addCacheSuffix: _addCacheSuffix
  1252. };
  1253. var fromHtml = function (html, scope) {
  1254. var doc = scope || document;
  1255. var div = doc.createElement('div');
  1256. div.innerHTML = html;
  1257. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  1258. console.error('HTML does not have a single root node', html);
  1259. throw new Error('HTML must have a single root node');
  1260. }
  1261. return fromDom(div.childNodes[0]);
  1262. };
  1263. var fromTag = function (tag, scope) {
  1264. var doc = scope || document;
  1265. var node = doc.createElement(tag);
  1266. return fromDom(node);
  1267. };
  1268. var fromText = function (text, scope) {
  1269. var doc = scope || document;
  1270. var node = doc.createTextNode(text);
  1271. return fromDom(node);
  1272. };
  1273. var fromDom = function (node) {
  1274. if (node === null || node === undefined) {
  1275. throw new Error('Node cannot be null or undefined');
  1276. }
  1277. return { dom: node };
  1278. };
  1279. var fromPoint = function (docElm, x, y) {
  1280. return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
  1281. };
  1282. var SugarElement = {
  1283. fromHtml: fromHtml,
  1284. fromTag: fromTag,
  1285. fromText: fromText,
  1286. fromDom: fromDom,
  1287. fromPoint: fromPoint
  1288. };
  1289. var toArray$1 = function (target, f) {
  1290. var r = [];
  1291. var recurse = function (e) {
  1292. r.push(e);
  1293. return f(e);
  1294. };
  1295. var cur = f(target);
  1296. do {
  1297. cur = cur.bind(recurse);
  1298. } while (cur.isSome());
  1299. return r;
  1300. };
  1301. var compareDocumentPosition = function (a, b, match) {
  1302. return (a.compareDocumentPosition(b) & match) !== 0;
  1303. };
  1304. var documentPositionContainedBy = function (a, b) {
  1305. return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
  1306. };
  1307. var COMMENT = 8;
  1308. var DOCUMENT = 9;
  1309. var DOCUMENT_FRAGMENT = 11;
  1310. var ELEMENT = 1;
  1311. var TEXT = 3;
  1312. var is$1 = function (element, selector) {
  1313. var dom = element.dom;
  1314. if (dom.nodeType !== ELEMENT) {
  1315. return false;
  1316. } else {
  1317. var elem = dom;
  1318. if (elem.matches !== undefined) {
  1319. return elem.matches(selector);
  1320. } else if (elem.msMatchesSelector !== undefined) {
  1321. return elem.msMatchesSelector(selector);
  1322. } else if (elem.webkitMatchesSelector !== undefined) {
  1323. return elem.webkitMatchesSelector(selector);
  1324. } else if (elem.mozMatchesSelector !== undefined) {
  1325. return elem.mozMatchesSelector(selector);
  1326. } else {
  1327. throw new Error('Browser lacks native selectors');
  1328. }
  1329. }
  1330. };
  1331. var bypassSelector = function (dom) {
  1332. return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  1333. };
  1334. var all = function (selector, scope) {
  1335. var base = scope === undefined ? document : scope.dom;
  1336. return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), SugarElement.fromDom);
  1337. };
  1338. var one = function (selector, scope) {
  1339. var base = scope === undefined ? document : scope.dom;
  1340. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  1341. };
  1342. var eq$2 = function (e1, e2) {
  1343. return e1.dom === e2.dom;
  1344. };
  1345. var regularContains = function (e1, e2) {
  1346. var d1 = e1.dom;
  1347. var d2 = e2.dom;
  1348. return d1 === d2 ? false : d1.contains(d2);
  1349. };
  1350. var ieContains = function (e1, e2) {
  1351. return documentPositionContainedBy(e1.dom, e2.dom);
  1352. };
  1353. var contains$2 = function (e1, e2) {
  1354. return detect$3().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
  1355. };
  1356. var Global = typeof window !== 'undefined' ? window : Function('return this;')();
  1357. var name = function (element) {
  1358. var r = element.dom.nodeName;
  1359. return r.toLowerCase();
  1360. };
  1361. var type = function (element) {
  1362. return element.dom.nodeType;
  1363. };
  1364. var isType$1 = function (t) {
  1365. return function (element) {
  1366. return type(element) === t;
  1367. };
  1368. };
  1369. var isComment = function (element) {
  1370. return type(element) === COMMENT || name(element) === '#comment';
  1371. };
  1372. var isElement = isType$1(ELEMENT);
  1373. var isText = isType$1(TEXT);
  1374. var isDocument = isType$1(DOCUMENT);
  1375. var isDocumentFragment = isType$1(DOCUMENT_FRAGMENT);
  1376. var owner = function (element) {
  1377. return SugarElement.fromDom(element.dom.ownerDocument);
  1378. };
  1379. var documentOrOwner = function (dos) {
  1380. return isDocument(dos) ? dos : owner(dos);
  1381. };
  1382. var documentElement = function (element) {
  1383. return SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
  1384. };
  1385. var defaultView = function (element) {
  1386. return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  1387. };
  1388. var parent = function (element) {
  1389. return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  1390. };
  1391. var parents = function (element, isRoot) {
  1392. var stop = isFunction(isRoot) ? isRoot : never;
  1393. var dom = element.dom;
  1394. var ret = [];
  1395. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  1396. var rawParent = dom.parentNode;
  1397. var p = SugarElement.fromDom(rawParent);
  1398. ret.push(p);
  1399. if (stop(p) === true) {
  1400. break;
  1401. } else {
  1402. dom = rawParent;
  1403. }
  1404. }
  1405. return ret;
  1406. };
  1407. var siblings = function (element) {
  1408. var filterSelf = function (elements) {
  1409. return filter(elements, function (x) {
  1410. return !eq$2(element, x);
  1411. });
  1412. };
  1413. return parent(element).map(children).map(filterSelf).getOr([]);
  1414. };
  1415. var prevSibling = function (element) {
  1416. return Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
  1417. };
  1418. var nextSibling = function (element) {
  1419. return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  1420. };
  1421. var prevSiblings = function (element) {
  1422. return reverse(toArray$1(element, prevSibling));
  1423. };
  1424. var nextSiblings = function (element) {
  1425. return toArray$1(element, nextSibling);
  1426. };
  1427. var children = function (element) {
  1428. return map(element.dom.childNodes, SugarElement.fromDom);
  1429. };
  1430. var child = function (element, index) {
  1431. var cs = element.dom.childNodes;
  1432. return Optional.from(cs[index]).map(SugarElement.fromDom);
  1433. };
  1434. var firstChild = function (element) {
  1435. return child(element, 0);
  1436. };
  1437. var lastChild = function (element) {
  1438. return child(element, element.dom.childNodes.length - 1);
  1439. };
  1440. var childNodesCount = function (element) {
  1441. return element.dom.childNodes.length;
  1442. };
  1443. var getHead = function (doc) {
  1444. var b = doc.dom.head;
  1445. if (b === null || b === undefined) {
  1446. throw new Error('Head is not available yet');
  1447. }
  1448. return SugarElement.fromDom(b);
  1449. };
  1450. var isShadowRoot = function (dos) {
  1451. return isDocumentFragment(dos);
  1452. };
  1453. var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  1454. var isSupported = constant(supported);
  1455. var getRootNode = supported ? function (e) {
  1456. return SugarElement.fromDom(e.dom.getRootNode());
  1457. } : documentOrOwner;
  1458. var getStyleContainer = function (dos) {
  1459. return isShadowRoot(dos) ? dos : getHead(documentOrOwner(dos));
  1460. };
  1461. var getShadowRoot = function (e) {
  1462. var r = getRootNode(e);
  1463. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  1464. };
  1465. var getShadowHost = function (e) {
  1466. return SugarElement.fromDom(e.dom.host);
  1467. };
  1468. var getOriginalEventTarget = function (event) {
  1469. if (isSupported() && isNonNullable(event.target)) {
  1470. var el = SugarElement.fromDom(event.target);
  1471. if (isElement(el) && isOpenShadowHost(el)) {
  1472. if (event.composed && event.composedPath) {
  1473. var composedPath = event.composedPath();
  1474. if (composedPath) {
  1475. return head(composedPath);
  1476. }
  1477. }
  1478. }
  1479. }
  1480. return Optional.from(event.target);
  1481. };
  1482. var isOpenShadowHost = function (element) {
  1483. return isNonNullable(element.dom.shadowRoot);
  1484. };
  1485. var before = function (marker, element) {
  1486. var parent$1 = parent(marker);
  1487. parent$1.each(function (v) {
  1488. v.dom.insertBefore(element.dom, marker.dom);
  1489. });
  1490. };
  1491. var after = function (marker, element) {
  1492. var sibling = nextSibling(marker);
  1493. sibling.fold(function () {
  1494. var parent$1 = parent(marker);
  1495. parent$1.each(function (v) {
  1496. append(v, element);
  1497. });
  1498. }, function (v) {
  1499. before(v, element);
  1500. });
  1501. };
  1502. var prepend = function (parent, element) {
  1503. var firstChild$1 = firstChild(parent);
  1504. firstChild$1.fold(function () {
  1505. append(parent, element);
  1506. }, function (v) {
  1507. parent.dom.insertBefore(element.dom, v.dom);
  1508. });
  1509. };
  1510. var append = function (parent, element) {
  1511. parent.dom.appendChild(element.dom);
  1512. };
  1513. var wrap = function (element, wrapper) {
  1514. before(element, wrapper);
  1515. append(wrapper, element);
  1516. };
  1517. var before$1 = function (marker, elements) {
  1518. each(elements, function (x) {
  1519. before(marker, x);
  1520. });
  1521. };
  1522. var append$1 = function (parent, elements) {
  1523. each(elements, function (x) {
  1524. append(parent, x);
  1525. });
  1526. };
  1527. var empty = function (element) {
  1528. element.dom.textContent = '';
  1529. each(children(element), function (rogue) {
  1530. remove(rogue);
  1531. });
  1532. };
  1533. var remove = function (element) {
  1534. var dom = element.dom;
  1535. if (dom.parentNode !== null) {
  1536. dom.parentNode.removeChild(dom);
  1537. }
  1538. };
  1539. var unwrap = function (wrapper) {
  1540. var children$1 = children(wrapper);
  1541. if (children$1.length > 0) {
  1542. before$1(wrapper, children$1);
  1543. }
  1544. remove(wrapper);
  1545. };
  1546. var inBody = function (element) {
  1547. var dom = isText(element) ? element.dom.parentNode : element.dom;
  1548. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1549. return false;
  1550. }
  1551. var doc = dom.ownerDocument;
  1552. return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  1553. return doc.body.contains(dom);
  1554. }, compose1(inBody, getShadowHost));
  1555. };
  1556. var r = function (left, top) {
  1557. var translate = function (x, y) {
  1558. return r(left + x, top + y);
  1559. };
  1560. return {
  1561. left: left,
  1562. top: top,
  1563. translate: translate
  1564. };
  1565. };
  1566. var SugarPosition = r;
  1567. var boxPosition = function (dom) {
  1568. var box = dom.getBoundingClientRect();
  1569. return SugarPosition(box.left, box.top);
  1570. };
  1571. var firstDefinedOrZero = function (a, b) {
  1572. if (a !== undefined) {
  1573. return a;
  1574. } else {
  1575. return b !== undefined ? b : 0;
  1576. }
  1577. };
  1578. var absolute = function (element) {
  1579. var doc = element.dom.ownerDocument;
  1580. var body = doc.body;
  1581. var win = doc.defaultView;
  1582. var html = doc.documentElement;
  1583. if (body === element.dom) {
  1584. return SugarPosition(body.offsetLeft, body.offsetTop);
  1585. }
  1586. var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
  1587. var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
  1588. var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  1589. var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  1590. return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  1591. };
  1592. var viewport = function (element) {
  1593. var dom = element.dom;
  1594. var doc = dom.ownerDocument;
  1595. var body = doc.body;
  1596. if (body === dom) {
  1597. return SugarPosition(body.offsetLeft, body.offsetTop);
  1598. }
  1599. if (!inBody(element)) {
  1600. return SugarPosition(0, 0);
  1601. }
  1602. return boxPosition(dom);
  1603. };
  1604. var get$2 = function (_DOC) {
  1605. var doc = _DOC !== undefined ? _DOC.dom : document;
  1606. var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  1607. var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  1608. return SugarPosition(x, y);
  1609. };
  1610. var to = function (x, y, _DOC) {
  1611. var doc = _DOC !== undefined ? _DOC.dom : document;
  1612. var win = doc.defaultView;
  1613. if (win) {
  1614. win.scrollTo(x, y);
  1615. }
  1616. };
  1617. var intoView = function (element, alignToTop) {
  1618. var isSafari = detect$3().browser.isSafari();
  1619. if (isSafari && isFunction(element.dom.scrollIntoViewIfNeeded)) {
  1620. element.dom.scrollIntoViewIfNeeded(false);
  1621. } else {
  1622. element.dom.scrollIntoView(alignToTop);
  1623. }
  1624. };
  1625. var get$3 = function (_win) {
  1626. var win = _win === undefined ? window : _win;
  1627. return Optional.from(win['visualViewport']);
  1628. };
  1629. var bounds = function (x, y, width, height) {
  1630. return {
  1631. x: x,
  1632. y: y,
  1633. width: width,
  1634. height: height,
  1635. right: x + width,
  1636. bottom: y + height
  1637. };
  1638. };
  1639. var getBounds = function (_win) {
  1640. var win = _win === undefined ? window : _win;
  1641. var doc = win.document;
  1642. var scroll = get$2(SugarElement.fromDom(doc));
  1643. return get$3(win).fold(function () {
  1644. var html = win.document.documentElement;
  1645. var width = html.clientWidth;
  1646. var height = html.clientHeight;
  1647. return bounds(scroll.left, scroll.top, width, height);
  1648. }, function (visualViewport) {
  1649. return bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
  1650. });
  1651. };
  1652. var isNodeType = function (type) {
  1653. return function (node) {
  1654. return !!node && node.nodeType === type;
  1655. };
  1656. };
  1657. var isRestrictedNode = function (node) {
  1658. return !!node && !Object.getPrototypeOf(node);
  1659. };
  1660. var isElement$1 = isNodeType(1);
  1661. var matchNodeNames = function (names) {
  1662. var lowercasedNames = names.map(function (s) {
  1663. return s.toLowerCase();
  1664. });
  1665. return function (node) {
  1666. if (node && node.nodeName) {
  1667. var nodeName = node.nodeName.toLowerCase();
  1668. return contains(lowercasedNames, nodeName);
  1669. }
  1670. return false;
  1671. };
  1672. };
  1673. var matchStyleValues = function (name, values) {
  1674. var items = values.toLowerCase().split(' ');
  1675. return function (node) {
  1676. var i, cssValue;
  1677. if (isElement$1(node)) {
  1678. for (i = 0; i < items.length; i++) {
  1679. var computed = node.ownerDocument.defaultView.getComputedStyle(node, null);
  1680. cssValue = computed ? computed.getPropertyValue(name) : null;
  1681. if (cssValue === items[i]) {
  1682. return true;
  1683. }
  1684. }
  1685. }
  1686. return false;
  1687. };
  1688. };
  1689. var hasAttribute = function (attrName) {
  1690. return function (node) {
  1691. return isElement$1(node) && node.hasAttribute(attrName);
  1692. };
  1693. };
  1694. var hasAttributeValue = function (attrName, attrValue) {
  1695. return function (node) {
  1696. return isElement$1(node) && node.getAttribute(attrName) === attrValue;
  1697. };
  1698. };
  1699. var isBogus = function (node) {
  1700. return isElement$1(node) && node.hasAttribute('data-mce-bogus');
  1701. };
  1702. var isBogusAll = function (node) {
  1703. return isElement$1(node) && node.getAttribute('data-mce-bogus') === 'all';
  1704. };
  1705. var isTable = function (node) {
  1706. return isElement$1(node) && node.tagName === 'TABLE';
  1707. };
  1708. var hasContentEditableState = function (value) {
  1709. return function (node) {
  1710. if (isElement$1(node)) {
  1711. if (node.contentEditable === value) {
  1712. return true;
  1713. }
  1714. if (node.getAttribute('data-mce-contenteditable') === value) {
  1715. return true;
  1716. }
  1717. }
  1718. return false;
  1719. };
  1720. };
  1721. var isTextareaOrInput = matchNodeNames([
  1722. 'textarea',
  1723. 'input'
  1724. ]);
  1725. var isText$1 = isNodeType(3);
  1726. var isComment$1 = isNodeType(8);
  1727. var isDocument$1 = isNodeType(9);
  1728. var isDocumentFragment$1 = isNodeType(11);
  1729. var isBr = matchNodeNames(['br']);
  1730. var isImg = matchNodeNames(['img']);
  1731. var isContentEditableTrue = hasContentEditableState('true');
  1732. var isContentEditableFalse = hasContentEditableState('false');
  1733. var isTableCell = matchNodeNames([
  1734. 'td',
  1735. 'th'
  1736. ]);
  1737. var isMedia = matchNodeNames([
  1738. 'video',
  1739. 'audio',
  1740. 'object',
  1741. 'embed'
  1742. ]);
  1743. var isSupported$1 = function (dom) {
  1744. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  1745. };
  1746. var rawSet = function (dom, key, value) {
  1747. if (isString(value) || isBoolean(value) || isNumber(value)) {
  1748. dom.setAttribute(key, value + '');
  1749. } else {
  1750. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1751. throw new Error('Attribute value was not simple');
  1752. }
  1753. };
  1754. var set = function (element, key, value) {
  1755. rawSet(element.dom, key, value);
  1756. };
  1757. var setAll = function (element, attrs) {
  1758. var dom = element.dom;
  1759. each$1(attrs, function (v, k) {
  1760. rawSet(dom, k, v);
  1761. });
  1762. };
  1763. var get$4 = function (element, key) {
  1764. var v = element.dom.getAttribute(key);
  1765. return v === null ? undefined : v;
  1766. };
  1767. var getOpt = function (element, key) {
  1768. return Optional.from(get$4(element, key));
  1769. };
  1770. var has$1 = function (element, key) {
  1771. var dom = element.dom;
  1772. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  1773. };
  1774. var remove$1 = function (element, key) {
  1775. element.dom.removeAttribute(key);
  1776. };
  1777. var clone = function (element) {
  1778. return foldl(element.dom.attributes, function (acc, attr) {
  1779. acc[attr.name] = attr.value;
  1780. return acc;
  1781. }, {});
  1782. };
  1783. var internalSet = function (dom, property, value) {
  1784. if (!isString(value)) {
  1785. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  1786. throw new Error('CSS value must be a string: ' + value);
  1787. }
  1788. if (isSupported$1(dom)) {
  1789. dom.style.setProperty(property, value);
  1790. }
  1791. };
  1792. var setAll$1 = function (element, css) {
  1793. var dom = element.dom;
  1794. each$1(css, function (v, k) {
  1795. internalSet(dom, k, v);
  1796. });
  1797. };
  1798. var get$5 = function (element, property) {
  1799. var dom = element.dom;
  1800. var styles = window.getComputedStyle(dom);
  1801. var r = styles.getPropertyValue(property);
  1802. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  1803. };
  1804. var getUnsafeProperty = function (dom, property) {
  1805. return isSupported$1(dom) ? dom.style.getPropertyValue(property) : '';
  1806. };
  1807. var getRaw = function (element, property) {
  1808. var dom = element.dom;
  1809. var raw = getUnsafeProperty(dom, property);
  1810. return Optional.from(raw).filter(function (r) {
  1811. return r.length > 0;
  1812. });
  1813. };
  1814. var getAllRaw = function (element) {
  1815. var css = {};
  1816. var dom = element.dom;
  1817. if (isSupported$1(dom)) {
  1818. for (var i = 0; i < dom.style.length; i++) {
  1819. var ruleName = dom.style.item(i);
  1820. css[ruleName] = dom.style[ruleName];
  1821. }
  1822. }
  1823. return css;
  1824. };
  1825. var reflow = function (e) {
  1826. return e.dom.offsetWidth;
  1827. };
  1828. var browser$1 = detect$3().browser;
  1829. var firstElement = function (nodes) {
  1830. return find(nodes, isElement);
  1831. };
  1832. var getTableCaptionDeltaY = function (elm) {
  1833. if (browser$1.isFirefox() && name(elm) === 'table') {
  1834. return firstElement(children(elm)).filter(function (elm) {
  1835. return name(elm) === 'caption';
  1836. }).bind(function (caption) {
  1837. return firstElement(nextSiblings(caption)).map(function (body) {
  1838. var bodyTop = body.dom.offsetTop;
  1839. var captionTop = caption.dom.offsetTop;
  1840. var captionHeight = caption.dom.offsetHeight;
  1841. return bodyTop <= captionTop ? -captionHeight : 0;
  1842. });
  1843. }).getOr(0);
  1844. } else {
  1845. return 0;
  1846. }
  1847. };
  1848. var hasChild = function (elm, child) {
  1849. return elm.children && contains(elm.children, child);
  1850. };
  1851. var getPos = function (body, elm, rootElm) {
  1852. var x = 0, y = 0, offsetParent;
  1853. var doc = body.ownerDocument;
  1854. var pos;
  1855. rootElm = rootElm ? rootElm : body;
  1856. if (elm) {
  1857. if (rootElm === body && elm.getBoundingClientRect && get$5(SugarElement.fromDom(body), 'position') === 'static') {
  1858. pos = elm.getBoundingClientRect();
  1859. x = pos.left + (doc.documentElement.scrollLeft || body.scrollLeft) - doc.documentElement.clientLeft;
  1860. y = pos.top + (doc.documentElement.scrollTop || body.scrollTop) - doc.documentElement.clientTop;
  1861. return {
  1862. x: x,
  1863. y: y
  1864. };
  1865. }
  1866. offsetParent = elm;
  1867. while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  1868. x += offsetParent.offsetLeft || 0;
  1869. y += offsetParent.offsetTop || 0;
  1870. offsetParent = offsetParent.offsetParent;
  1871. }
  1872. offsetParent = elm.parentNode;
  1873. while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  1874. x -= offsetParent.scrollLeft || 0;
  1875. y -= offsetParent.scrollTop || 0;
  1876. offsetParent = offsetParent.parentNode;
  1877. }
  1878. y += getTableCaptionDeltaY(SugarElement.fromDom(elm));
  1879. }
  1880. return {
  1881. x: x,
  1882. y: y
  1883. };
  1884. };
  1885. var exports$1 = {}, module$1 = { exports: exports$1 };
  1886. (function (define, exports, module, require) {
  1887. (function (f) {
  1888. if (typeof exports === 'object' && typeof module !== 'undefined') {
  1889. module.exports = f();
  1890. } else if (typeof define === 'function' && define.amd) {
  1891. define([], f);
  1892. } else {
  1893. var g;
  1894. if (typeof window !== 'undefined') {
  1895. g = window;
  1896. } else if (typeof global !== 'undefined') {
  1897. g = global;
  1898. } else if (typeof self !== 'undefined') {
  1899. g = self;
  1900. } else {
  1901. g = this;
  1902. }
  1903. g.EphoxContactWrapper = f();
  1904. }
  1905. }(function () {
  1906. return function () {
  1907. function r(e, n, t) {
  1908. function o(i, f) {
  1909. if (!n[i]) {
  1910. if (!e[i]) {
  1911. var c = 'function' == typeof require && require;
  1912. if (!f && c)
  1913. return c(i, !0);
  1914. if (u)
  1915. return u(i, !0);
  1916. var a = new Error('Cannot find module \'' + i + '\'');
  1917. throw a.code = 'MODULE_NOT_FOUND', a;
  1918. }
  1919. var p = n[i] = { exports: {} };
  1920. e[i][0].call(p.exports, function (r) {
  1921. var n = e[i][1][r];
  1922. return o(n || r);
  1923. }, p, p.exports, r, e, n, t);
  1924. }
  1925. return n[i].exports;
  1926. }
  1927. for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++)
  1928. o(t[i]);
  1929. return o;
  1930. }
  1931. return r;
  1932. }()({
  1933. 1: [
  1934. function (require, module, exports) {
  1935. var process = module.exports = {};
  1936. var cachedSetTimeout;
  1937. var cachedClearTimeout;
  1938. function defaultSetTimout() {
  1939. throw new Error('setTimeout has not been defined');
  1940. }
  1941. function defaultClearTimeout() {
  1942. throw new Error('clearTimeout has not been defined');
  1943. }
  1944. (function () {
  1945. try {
  1946. if (typeof setTimeout === 'function') {
  1947. cachedSetTimeout = setTimeout;
  1948. } else {
  1949. cachedSetTimeout = defaultSetTimout;
  1950. }
  1951. } catch (e) {
  1952. cachedSetTimeout = defaultSetTimout;
  1953. }
  1954. try {
  1955. if (typeof clearTimeout === 'function') {
  1956. cachedClearTimeout = clearTimeout;
  1957. } else {
  1958. cachedClearTimeout = defaultClearTimeout;
  1959. }
  1960. } catch (e) {
  1961. cachedClearTimeout = defaultClearTimeout;
  1962. }
  1963. }());
  1964. function runTimeout(fun) {
  1965. if (cachedSetTimeout === setTimeout) {
  1966. return setTimeout(fun, 0);
  1967. }
  1968. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  1969. cachedSetTimeout = setTimeout;
  1970. return setTimeout(fun, 0);
  1971. }
  1972. try {
  1973. return cachedSetTimeout(fun, 0);
  1974. } catch (e) {
  1975. try {
  1976. return cachedSetTimeout.call(null, fun, 0);
  1977. } catch (e) {
  1978. return cachedSetTimeout.call(this, fun, 0);
  1979. }
  1980. }
  1981. }
  1982. function runClearTimeout(marker) {
  1983. if (cachedClearTimeout === clearTimeout) {
  1984. return clearTimeout(marker);
  1985. }
  1986. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  1987. cachedClearTimeout = clearTimeout;
  1988. return clearTimeout(marker);
  1989. }
  1990. try {
  1991. return cachedClearTimeout(marker);
  1992. } catch (e) {
  1993. try {
  1994. return cachedClearTimeout.call(null, marker);
  1995. } catch (e) {
  1996. return cachedClearTimeout.call(this, marker);
  1997. }
  1998. }
  1999. }
  2000. var queue = [];
  2001. var draining = false;
  2002. var currentQueue;
  2003. var queueIndex = -1;
  2004. function cleanUpNextTick() {
  2005. if (!draining || !currentQueue) {
  2006. return;
  2007. }
  2008. draining = false;
  2009. if (currentQueue.length) {
  2010. queue = currentQueue.concat(queue);
  2011. } else {
  2012. queueIndex = -1;
  2013. }
  2014. if (queue.length) {
  2015. drainQueue();
  2016. }
  2017. }
  2018. function drainQueue() {
  2019. if (draining) {
  2020. return;
  2021. }
  2022. var timeout = runTimeout(cleanUpNextTick);
  2023. draining = true;
  2024. var len = queue.length;
  2025. while (len) {
  2026. currentQueue = queue;
  2027. queue = [];
  2028. while (++queueIndex < len) {
  2029. if (currentQueue) {
  2030. currentQueue[queueIndex].run();
  2031. }
  2032. }
  2033. queueIndex = -1;
  2034. len = queue.length;
  2035. }
  2036. currentQueue = null;
  2037. draining = false;
  2038. runClearTimeout(timeout);
  2039. }
  2040. process.nextTick = function (fun) {
  2041. var args = new Array(arguments.length - 1);
  2042. if (arguments.length > 1) {
  2043. for (var i = 1; i < arguments.length; i++) {
  2044. args[i - 1] = arguments[i];
  2045. }
  2046. }
  2047. queue.push(new Item(fun, args));
  2048. if (queue.length === 1 && !draining) {
  2049. runTimeout(drainQueue);
  2050. }
  2051. };
  2052. function Item(fun, array) {
  2053. this.fun = fun;
  2054. this.array = array;
  2055. }
  2056. Item.prototype.run = function () {
  2057. this.fun.apply(null, this.array);
  2058. };
  2059. process.title = 'browser';
  2060. process.browser = true;
  2061. process.env = {};
  2062. process.argv = [];
  2063. process.version = '';
  2064. process.versions = {};
  2065. function noop() {
  2066. }
  2067. process.on = noop;
  2068. process.addListener = noop;
  2069. process.once = noop;
  2070. process.off = noop;
  2071. process.removeListener = noop;
  2072. process.removeAllListeners = noop;
  2073. process.emit = noop;
  2074. process.prependListener = noop;
  2075. process.prependOnceListener = noop;
  2076. process.listeners = function (name) {
  2077. return [];
  2078. };
  2079. process.binding = function (name) {
  2080. throw new Error('process.binding is not supported');
  2081. };
  2082. process.cwd = function () {
  2083. return '/';
  2084. };
  2085. process.chdir = function (dir) {
  2086. throw new Error('process.chdir is not supported');
  2087. };
  2088. process.umask = function () {
  2089. return 0;
  2090. };
  2091. },
  2092. {}
  2093. ],
  2094. 2: [
  2095. function (require, module, exports) {
  2096. (function (setImmediate) {
  2097. (function (root) {
  2098. var setTimeoutFunc = setTimeout;
  2099. function noop() {
  2100. }
  2101. function bind(fn, thisArg) {
  2102. return function () {
  2103. fn.apply(thisArg, arguments);
  2104. };
  2105. }
  2106. function Promise(fn) {
  2107. if (typeof this !== 'object')
  2108. throw new TypeError('Promises must be constructed via new');
  2109. if (typeof fn !== 'function')
  2110. throw new TypeError('not a function');
  2111. this._state = 0;
  2112. this._handled = false;
  2113. this._value = undefined;
  2114. this._deferreds = [];
  2115. doResolve(fn, this);
  2116. }
  2117. function handle(self, deferred) {
  2118. while (self._state === 3) {
  2119. self = self._value;
  2120. }
  2121. if (self._state === 0) {
  2122. self._deferreds.push(deferred);
  2123. return;
  2124. }
  2125. self._handled = true;
  2126. Promise._immediateFn(function () {
  2127. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  2128. if (cb === null) {
  2129. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  2130. return;
  2131. }
  2132. var ret;
  2133. try {
  2134. ret = cb(self._value);
  2135. } catch (e) {
  2136. reject(deferred.promise, e);
  2137. return;
  2138. }
  2139. resolve(deferred.promise, ret);
  2140. });
  2141. }
  2142. function resolve(self, newValue) {
  2143. try {
  2144. if (newValue === self)
  2145. throw new TypeError('A promise cannot be resolved with itself.');
  2146. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  2147. var then = newValue.then;
  2148. if (newValue instanceof Promise) {
  2149. self._state = 3;
  2150. self._value = newValue;
  2151. finale(self);
  2152. return;
  2153. } else if (typeof then === 'function') {
  2154. doResolve(bind(then, newValue), self);
  2155. return;
  2156. }
  2157. }
  2158. self._state = 1;
  2159. self._value = newValue;
  2160. finale(self);
  2161. } catch (e) {
  2162. reject(self, e);
  2163. }
  2164. }
  2165. function reject(self, newValue) {
  2166. self._state = 2;
  2167. self._value = newValue;
  2168. finale(self);
  2169. }
  2170. function finale(self) {
  2171. if (self._state === 2 && self._deferreds.length === 0) {
  2172. Promise._immediateFn(function () {
  2173. if (!self._handled) {
  2174. Promise._unhandledRejectionFn(self._value);
  2175. }
  2176. });
  2177. }
  2178. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  2179. handle(self, self._deferreds[i]);
  2180. }
  2181. self._deferreds = null;
  2182. }
  2183. function Handler(onFulfilled, onRejected, promise) {
  2184. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  2185. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  2186. this.promise = promise;
  2187. }
  2188. function doResolve(fn, self) {
  2189. var done = false;
  2190. try {
  2191. fn(function (value) {
  2192. if (done)
  2193. return;
  2194. done = true;
  2195. resolve(self, value);
  2196. }, function (reason) {
  2197. if (done)
  2198. return;
  2199. done = true;
  2200. reject(self, reason);
  2201. });
  2202. } catch (ex) {
  2203. if (done)
  2204. return;
  2205. done = true;
  2206. reject(self, ex);
  2207. }
  2208. }
  2209. Promise.prototype['catch'] = function (onRejected) {
  2210. return this.then(null, onRejected);
  2211. };
  2212. Promise.prototype.then = function (onFulfilled, onRejected) {
  2213. var prom = new this.constructor(noop);
  2214. handle(this, new Handler(onFulfilled, onRejected, prom));
  2215. return prom;
  2216. };
  2217. Promise.all = function (arr) {
  2218. var args = Array.prototype.slice.call(arr);
  2219. return new Promise(function (resolve, reject) {
  2220. if (args.length === 0)
  2221. return resolve([]);
  2222. var remaining = args.length;
  2223. function res(i, val) {
  2224. try {
  2225. if (val && (typeof val === 'object' || typeof val === 'function')) {
  2226. var then = val.then;
  2227. if (typeof then === 'function') {
  2228. then.call(val, function (val) {
  2229. res(i, val);
  2230. }, reject);
  2231. return;
  2232. }
  2233. }
  2234. args[i] = val;
  2235. if (--remaining === 0) {
  2236. resolve(args);
  2237. }
  2238. } catch (ex) {
  2239. reject(ex);
  2240. }
  2241. }
  2242. for (var i = 0; i < args.length; i++) {
  2243. res(i, args[i]);
  2244. }
  2245. });
  2246. };
  2247. Promise.resolve = function (value) {
  2248. if (value && typeof value === 'object' && value.constructor === Promise) {
  2249. return value;
  2250. }
  2251. return new Promise(function (resolve) {
  2252. resolve(value);
  2253. });
  2254. };
  2255. Promise.reject = function (value) {
  2256. return new Promise(function (resolve, reject) {
  2257. reject(value);
  2258. });
  2259. };
  2260. Promise.race = function (values) {
  2261. return new Promise(function (resolve, reject) {
  2262. for (var i = 0, len = values.length; i < len; i++) {
  2263. values[i].then(resolve, reject);
  2264. }
  2265. });
  2266. };
  2267. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  2268. setImmediate(fn);
  2269. } : function (fn) {
  2270. setTimeoutFunc(fn, 0);
  2271. };
  2272. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  2273. if (typeof console !== 'undefined' && console) {
  2274. console.warn('Possible Unhandled Promise Rejection:', err);
  2275. }
  2276. };
  2277. Promise._setImmediateFn = function _setImmediateFn(fn) {
  2278. Promise._immediateFn = fn;
  2279. };
  2280. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  2281. Promise._unhandledRejectionFn = fn;
  2282. };
  2283. if (typeof module !== 'undefined' && module.exports) {
  2284. module.exports = Promise;
  2285. } else if (!root.Promise) {
  2286. root.Promise = Promise;
  2287. }
  2288. }(this));
  2289. }.call(this, require('timers').setImmediate));
  2290. },
  2291. { 'timers': 3 }
  2292. ],
  2293. 3: [
  2294. function (require, module, exports) {
  2295. (function (setImmediate, clearImmediate) {
  2296. var nextTick = require('process/browser.js').nextTick;
  2297. var apply = Function.prototype.apply;
  2298. var slice = Array.prototype.slice;
  2299. var immediateIds = {};
  2300. var nextImmediateId = 0;
  2301. exports.setTimeout = function () {
  2302. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  2303. };
  2304. exports.setInterval = function () {
  2305. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  2306. };
  2307. exports.clearTimeout = exports.clearInterval = function (timeout) {
  2308. timeout.close();
  2309. };
  2310. function Timeout(id, clearFn) {
  2311. this._id = id;
  2312. this._clearFn = clearFn;
  2313. }
  2314. Timeout.prototype.unref = Timeout.prototype.ref = function () {
  2315. };
  2316. Timeout.prototype.close = function () {
  2317. this._clearFn.call(window, this._id);
  2318. };
  2319. exports.enroll = function (item, msecs) {
  2320. clearTimeout(item._idleTimeoutId);
  2321. item._idleTimeout = msecs;
  2322. };
  2323. exports.unenroll = function (item) {
  2324. clearTimeout(item._idleTimeoutId);
  2325. item._idleTimeout = -1;
  2326. };
  2327. exports._unrefActive = exports.active = function (item) {
  2328. clearTimeout(item._idleTimeoutId);
  2329. var msecs = item._idleTimeout;
  2330. if (msecs >= 0) {
  2331. item._idleTimeoutId = setTimeout(function onTimeout() {
  2332. if (item._onTimeout)
  2333. item._onTimeout();
  2334. }, msecs);
  2335. }
  2336. };
  2337. exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) {
  2338. var id = nextImmediateId++;
  2339. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  2340. immediateIds[id] = true;
  2341. nextTick(function onNextTick() {
  2342. if (immediateIds[id]) {
  2343. if (args) {
  2344. fn.apply(null, args);
  2345. } else {
  2346. fn.call(null);
  2347. }
  2348. exports.clearImmediate(id);
  2349. }
  2350. });
  2351. return id;
  2352. };
  2353. exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) {
  2354. delete immediateIds[id];
  2355. };
  2356. }.call(this, require('timers').setImmediate, require('timers').clearImmediate));
  2357. },
  2358. {
  2359. 'process/browser.js': 1,
  2360. 'timers': 3
  2361. }
  2362. ],
  2363. 4: [
  2364. function (require, module, exports) {
  2365. var promisePolyfill = require('promise-polyfill');
  2366. var Global = function () {
  2367. if (typeof window !== 'undefined') {
  2368. return window;
  2369. } else {
  2370. return Function('return this;')();
  2371. }
  2372. }();
  2373. module.exports = { boltExport: Global.Promise || promisePolyfill };
  2374. },
  2375. { 'promise-polyfill': 2 }
  2376. ]
  2377. }, {}, [4])(4);
  2378. }));
  2379. }(undefined, exports$1, module$1, undefined));
  2380. var Promise = module$1.exports.boltExport;
  2381. var nu$3 = function (baseFn) {
  2382. var data = Optional.none();
  2383. var callbacks = [];
  2384. var map = function (f) {
  2385. return nu$3(function (nCallback) {
  2386. get(function (data) {
  2387. nCallback(f(data));
  2388. });
  2389. });
  2390. };
  2391. var get = function (nCallback) {
  2392. if (isReady()) {
  2393. call(nCallback);
  2394. } else {
  2395. callbacks.push(nCallback);
  2396. }
  2397. };
  2398. var set = function (x) {
  2399. if (!isReady()) {
  2400. data = Optional.some(x);
  2401. run(callbacks);
  2402. callbacks = [];
  2403. }
  2404. };
  2405. var isReady = function () {
  2406. return data.isSome();
  2407. };
  2408. var run = function (cbs) {
  2409. each(cbs, call);
  2410. };
  2411. var call = function (cb) {
  2412. data.each(function (x) {
  2413. setTimeout(function () {
  2414. cb(x);
  2415. }, 0);
  2416. });
  2417. };
  2418. baseFn(set);
  2419. return {
  2420. get: get,
  2421. map: map,
  2422. isReady: isReady
  2423. };
  2424. };
  2425. var pure = function (a) {
  2426. return nu$3(function (callback) {
  2427. callback(a);
  2428. });
  2429. };
  2430. var LazyValue = {
  2431. nu: nu$3,
  2432. pure: pure
  2433. };
  2434. var errorReporter = function (err) {
  2435. setTimeout(function () {
  2436. throw err;
  2437. }, 0);
  2438. };
  2439. var make = function (run) {
  2440. var get = function (callback) {
  2441. run().then(callback, errorReporter);
  2442. };
  2443. var map = function (fab) {
  2444. return make(function () {
  2445. return run().then(fab);
  2446. });
  2447. };
  2448. var bind = function (aFutureB) {
  2449. return make(function () {
  2450. return run().then(function (v) {
  2451. return aFutureB(v).toPromise();
  2452. });
  2453. });
  2454. };
  2455. var anonBind = function (futureB) {
  2456. return make(function () {
  2457. return run().then(function () {
  2458. return futureB.toPromise();
  2459. });
  2460. });
  2461. };
  2462. var toLazy = function () {
  2463. return LazyValue.nu(get);
  2464. };
  2465. var toCached = function () {
  2466. var cache = null;
  2467. return make(function () {
  2468. if (cache === null) {
  2469. cache = run();
  2470. }
  2471. return cache;
  2472. });
  2473. };
  2474. var toPromise = run;
  2475. return {
  2476. map: map,
  2477. bind: bind,
  2478. anonBind: anonBind,
  2479. toLazy: toLazy,
  2480. toCached: toCached,
  2481. toPromise: toPromise,
  2482. get: get
  2483. };
  2484. };
  2485. var nu$4 = function (baseFn) {
  2486. return make(function () {
  2487. return new Promise(baseFn);
  2488. });
  2489. };
  2490. var pure$1 = function (a) {
  2491. return make(function () {
  2492. return Promise.resolve(a);
  2493. });
  2494. };
  2495. var Future = {
  2496. nu: nu$4,
  2497. pure: pure$1
  2498. };
  2499. var par = function (asyncValues, nu) {
  2500. return nu(function (callback) {
  2501. var r = [];
  2502. var count = 0;
  2503. var cb = function (i) {
  2504. return function (value) {
  2505. r[i] = value;
  2506. count++;
  2507. if (count >= asyncValues.length) {
  2508. callback(r);
  2509. }
  2510. };
  2511. };
  2512. if (asyncValues.length === 0) {
  2513. callback([]);
  2514. } else {
  2515. each(asyncValues, function (asyncValue, i) {
  2516. asyncValue.get(cb(i));
  2517. });
  2518. }
  2519. });
  2520. };
  2521. var par$1 = function (futures) {
  2522. return par(futures, Future.nu);
  2523. };
  2524. var value = function (o) {
  2525. var is = function (v) {
  2526. return o === v;
  2527. };
  2528. var or = function (_opt) {
  2529. return value(o);
  2530. };
  2531. var orThunk = function (_f) {
  2532. return value(o);
  2533. };
  2534. var map = function (f) {
  2535. return value(f(o));
  2536. };
  2537. var mapError = function (_f) {
  2538. return value(o);
  2539. };
  2540. var each = function (f) {
  2541. f(o);
  2542. };
  2543. var bind = function (f) {
  2544. return f(o);
  2545. };
  2546. var fold = function (_, onValue) {
  2547. return onValue(o);
  2548. };
  2549. var exists = function (f) {
  2550. return f(o);
  2551. };
  2552. var forall = function (f) {
  2553. return f(o);
  2554. };
  2555. var toOptional = function () {
  2556. return Optional.some(o);
  2557. };
  2558. return {
  2559. is: is,
  2560. isValue: always,
  2561. isError: never,
  2562. getOr: constant(o),
  2563. getOrThunk: constant(o),
  2564. getOrDie: constant(o),
  2565. or: or,
  2566. orThunk: orThunk,
  2567. fold: fold,
  2568. map: map,
  2569. mapError: mapError,
  2570. each: each,
  2571. bind: bind,
  2572. exists: exists,
  2573. forall: forall,
  2574. toOptional: toOptional
  2575. };
  2576. };
  2577. var error = function (message) {
  2578. var getOrThunk = function (f) {
  2579. return f();
  2580. };
  2581. var getOrDie = function () {
  2582. return die(String(message))();
  2583. };
  2584. var or = function (opt) {
  2585. return opt;
  2586. };
  2587. var orThunk = function (f) {
  2588. return f();
  2589. };
  2590. var map = function (_f) {
  2591. return error(message);
  2592. };
  2593. var mapError = function (f) {
  2594. return error(f(message));
  2595. };
  2596. var bind = function (_f) {
  2597. return error(message);
  2598. };
  2599. var fold = function (onError, _) {
  2600. return onError(message);
  2601. };
  2602. return {
  2603. is: never,
  2604. isValue: never,
  2605. isError: always,
  2606. getOr: identity,
  2607. getOrThunk: getOrThunk,
  2608. getOrDie: getOrDie,
  2609. or: or,
  2610. orThunk: orThunk,
  2611. fold: fold,
  2612. map: map,
  2613. mapError: mapError,
  2614. each: noop,
  2615. bind: bind,
  2616. exists: never,
  2617. forall: always,
  2618. toOptional: Optional.none
  2619. };
  2620. };
  2621. var fromOption = function (opt, err) {
  2622. return opt.fold(function () {
  2623. return error(err);
  2624. }, value);
  2625. };
  2626. var Result = {
  2627. value: value,
  2628. error: error,
  2629. fromOption: fromOption
  2630. };
  2631. var generate = function (cases) {
  2632. if (!isArray(cases)) {
  2633. throw new Error('cases must be an array');
  2634. }
  2635. if (cases.length === 0) {
  2636. throw new Error('there must be at least one case');
  2637. }
  2638. var constructors = [];
  2639. var adt = {};
  2640. each(cases, function (acase, count) {
  2641. var keys$1 = keys(acase);
  2642. if (keys$1.length !== 1) {
  2643. throw new Error('one and only one name per case');
  2644. }
  2645. var key = keys$1[0];
  2646. var value = acase[key];
  2647. if (adt[key] !== undefined) {
  2648. throw new Error('duplicate key detected:' + key);
  2649. } else if (key === 'cata') {
  2650. throw new Error('cannot have a case named cata (sorry)');
  2651. } else if (!isArray(value)) {
  2652. throw new Error('case arguments must be an array');
  2653. }
  2654. constructors.push(key);
  2655. adt[key] = function () {
  2656. var argLength = arguments.length;
  2657. if (argLength !== value.length) {
  2658. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  2659. }
  2660. var args = new Array(argLength);
  2661. for (var i = 0; i < args.length; i++) {
  2662. args[i] = arguments[i];
  2663. }
  2664. var match = function (branches) {
  2665. var branchKeys = keys(branches);
  2666. if (constructors.length !== branchKeys.length) {
  2667. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  2668. }
  2669. var allReqd = forall(constructors, function (reqKey) {
  2670. return contains(branchKeys, reqKey);
  2671. });
  2672. if (!allReqd) {
  2673. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  2674. }
  2675. return branches[key].apply(null, args);
  2676. };
  2677. return {
  2678. fold: function () {
  2679. if (arguments.length !== cases.length) {
  2680. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
  2681. }
  2682. var target = arguments[count];
  2683. return target.apply(null, args);
  2684. },
  2685. match: match,
  2686. log: function (label) {
  2687. console.log(label, {
  2688. constructors: constructors,
  2689. constructor: key,
  2690. params: args
  2691. });
  2692. }
  2693. };
  2694. };
  2695. });
  2696. return adt;
  2697. };
  2698. var Adt = { generate: generate };
  2699. var comparison = Adt.generate([
  2700. {
  2701. bothErrors: [
  2702. 'error1',
  2703. 'error2'
  2704. ]
  2705. },
  2706. {
  2707. firstError: [
  2708. 'error1',
  2709. 'value2'
  2710. ]
  2711. },
  2712. {
  2713. secondError: [
  2714. 'value1',
  2715. 'error2'
  2716. ]
  2717. },
  2718. {
  2719. bothValues: [
  2720. 'value1',
  2721. 'value2'
  2722. ]
  2723. }
  2724. ]);
  2725. var unite = function (result) {
  2726. return result.fold(identity, identity);
  2727. };
  2728. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  2729. if (is(scope, a)) {
  2730. return Optional.some(scope);
  2731. } else if (isFunction(isRoot) && isRoot(scope)) {
  2732. return Optional.none();
  2733. } else {
  2734. return ancestor(scope, a, isRoot);
  2735. }
  2736. }
  2737. var ancestor = function (scope, predicate, isRoot) {
  2738. var element = scope.dom;
  2739. var stop = isFunction(isRoot) ? isRoot : never;
  2740. while (element.parentNode) {
  2741. element = element.parentNode;
  2742. var el = SugarElement.fromDom(element);
  2743. if (predicate(el)) {
  2744. return Optional.some(el);
  2745. } else if (stop(el)) {
  2746. break;
  2747. }
  2748. }
  2749. return Optional.none();
  2750. };
  2751. var closest = function (scope, predicate, isRoot) {
  2752. var is = function (s, test) {
  2753. return test(s);
  2754. };
  2755. return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot);
  2756. };
  2757. var sibling = function (scope, predicate) {
  2758. var element = scope.dom;
  2759. if (!element.parentNode) {
  2760. return Optional.none();
  2761. }
  2762. return child$1(SugarElement.fromDom(element.parentNode), function (x) {
  2763. return !eq$2(scope, x) && predicate(x);
  2764. });
  2765. };
  2766. var child$1 = function (scope, predicate) {
  2767. var pred = function (node) {
  2768. return predicate(SugarElement.fromDom(node));
  2769. };
  2770. var result = find(scope.dom.childNodes, pred);
  2771. return result.map(SugarElement.fromDom);
  2772. };
  2773. var ancestor$1 = function (scope, selector, isRoot) {
  2774. return ancestor(scope, function (e) {
  2775. return is$1(e, selector);
  2776. }, isRoot);
  2777. };
  2778. var descendant = function (scope, selector) {
  2779. return one(selector, scope);
  2780. };
  2781. var closest$1 = function (scope, selector, isRoot) {
  2782. var is = function (element, selector) {
  2783. return is$1(element, selector);
  2784. };
  2785. return ClosestOrAncestor(is, ancestor$1, scope, selector, isRoot);
  2786. };
  2787. var promise = function () {
  2788. function bind(fn, thisArg) {
  2789. return function () {
  2790. fn.apply(thisArg, arguments);
  2791. };
  2792. }
  2793. var isArray = Array.isArray || function (value) {
  2794. return Object.prototype.toString.call(value) === '[object Array]';
  2795. };
  2796. var Promise = function (fn) {
  2797. if (typeof this !== 'object') {
  2798. throw new TypeError('Promises must be constructed via new');
  2799. }
  2800. if (typeof fn !== 'function') {
  2801. throw new TypeError('not a function');
  2802. }
  2803. this._state = null;
  2804. this._value = null;
  2805. this._deferreds = [];
  2806. doResolve(fn, bind(resolve, this), bind(reject, this));
  2807. };
  2808. var asap = Promise.immediateFn || typeof setImmediate === 'function' && setImmediate || function (fn) {
  2809. setTimeout(fn, 1);
  2810. };
  2811. function handle(deferred) {
  2812. var me = this;
  2813. if (this._state === null) {
  2814. this._deferreds.push(deferred);
  2815. return;
  2816. }
  2817. asap(function () {
  2818. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  2819. if (cb === null) {
  2820. (me._state ? deferred.resolve : deferred.reject)(me._value);
  2821. return;
  2822. }
  2823. var ret;
  2824. try {
  2825. ret = cb(me._value);
  2826. } catch (e) {
  2827. deferred.reject(e);
  2828. return;
  2829. }
  2830. deferred.resolve(ret);
  2831. });
  2832. }
  2833. function resolve(newValue) {
  2834. try {
  2835. if (newValue === this) {
  2836. throw new TypeError('A promise cannot be resolved with itself.');
  2837. }
  2838. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  2839. var then = newValue.then;
  2840. if (typeof then === 'function') {
  2841. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  2842. return;
  2843. }
  2844. }
  2845. this._state = true;
  2846. this._value = newValue;
  2847. finale.call(this);
  2848. } catch (e) {
  2849. reject.call(this, e);
  2850. }
  2851. }
  2852. function reject(newValue) {
  2853. this._state = false;
  2854. this._value = newValue;
  2855. finale.call(this);
  2856. }
  2857. function finale() {
  2858. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  2859. handle.call(this, this._deferreds[i]);
  2860. }
  2861. this._deferreds = null;
  2862. }
  2863. function Handler(onFulfilled, onRejected, resolve, reject) {
  2864. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  2865. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  2866. this.resolve = resolve;
  2867. this.reject = reject;
  2868. }
  2869. function doResolve(fn, onFulfilled, onRejected) {
  2870. var done = false;
  2871. try {
  2872. fn(function (value) {
  2873. if (done) {
  2874. return;
  2875. }
  2876. done = true;
  2877. onFulfilled(value);
  2878. }, function (reason) {
  2879. if (done) {
  2880. return;
  2881. }
  2882. done = true;
  2883. onRejected(reason);
  2884. });
  2885. } catch (ex) {
  2886. if (done) {
  2887. return;
  2888. }
  2889. done = true;
  2890. onRejected(ex);
  2891. }
  2892. }
  2893. Promise.prototype.catch = function (onRejected) {
  2894. return this.then(null, onRejected);
  2895. };
  2896. Promise.prototype.then = function (onFulfilled, onRejected) {
  2897. var me = this;
  2898. return new Promise(function (resolve, reject) {
  2899. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  2900. });
  2901. };
  2902. Promise.all = function () {
  2903. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  2904. return new Promise(function (resolve, reject) {
  2905. if (args.length === 0) {
  2906. return resolve([]);
  2907. }
  2908. var remaining = args.length;
  2909. function res(i, val) {
  2910. try {
  2911. if (val && (typeof val === 'object' || typeof val === 'function')) {
  2912. var then = val.then;
  2913. if (typeof then === 'function') {
  2914. then.call(val, function (val) {
  2915. res(i, val);
  2916. }, reject);
  2917. return;
  2918. }
  2919. }
  2920. args[i] = val;
  2921. if (--remaining === 0) {
  2922. resolve(args);
  2923. }
  2924. } catch (ex) {
  2925. reject(ex);
  2926. }
  2927. }
  2928. for (var i = 0; i < args.length; i++) {
  2929. res(i, args[i]);
  2930. }
  2931. });
  2932. };
  2933. Promise.resolve = function (value) {
  2934. if (value && typeof value === 'object' && value.constructor === Promise) {
  2935. return value;
  2936. }
  2937. return new Promise(function (resolve) {
  2938. resolve(value);
  2939. });
  2940. };
  2941. Promise.reject = function (value) {
  2942. return new Promise(function (resolve, reject) {
  2943. reject(value);
  2944. });
  2945. };
  2946. Promise.race = function (values) {
  2947. return new Promise(function (resolve, reject) {
  2948. for (var i = 0, len = values.length; i < len; i++) {
  2949. values[i].then(resolve, reject);
  2950. }
  2951. });
  2952. };
  2953. return Promise;
  2954. };
  2955. var promiseObj = window.Promise ? window.Promise : promise();
  2956. var requestAnimationFramePromise;
  2957. var requestAnimationFrame = function (callback, element) {
  2958. var i, requestAnimationFrameFunc = window.requestAnimationFrame;
  2959. var vendors = [
  2960. 'ms',
  2961. 'moz',
  2962. 'webkit'
  2963. ];
  2964. var featurefill = function (callback) {
  2965. window.setTimeout(callback, 0);
  2966. };
  2967. for (i = 0; i < vendors.length && !requestAnimationFrameFunc; i++) {
  2968. requestAnimationFrameFunc = window[vendors[i] + 'RequestAnimationFrame'];
  2969. }
  2970. if (!requestAnimationFrameFunc) {
  2971. requestAnimationFrameFunc = featurefill;
  2972. }
  2973. requestAnimationFrameFunc(callback, element);
  2974. };
  2975. var wrappedSetTimeout = function (callback, time) {
  2976. if (typeof time !== 'number') {
  2977. time = 0;
  2978. }
  2979. return setTimeout(callback, time);
  2980. };
  2981. var wrappedSetInterval = function (callback, time) {
  2982. if (typeof time !== 'number') {
  2983. time = 1;
  2984. }
  2985. return setInterval(callback, time);
  2986. };
  2987. var wrappedClearTimeout = function (id) {
  2988. return clearTimeout(id);
  2989. };
  2990. var wrappedClearInterval = function (id) {
  2991. return clearInterval(id);
  2992. };
  2993. var debounce = function (callback, time) {
  2994. var timer;
  2995. var func = function () {
  2996. var args = [];
  2997. for (var _i = 0; _i < arguments.length; _i++) {
  2998. args[_i] = arguments[_i];
  2999. }
  3000. clearTimeout(timer);
  3001. timer = wrappedSetTimeout(function () {
  3002. callback.apply(this, args);
  3003. }, time);
  3004. };
  3005. func.stop = function () {
  3006. clearTimeout(timer);
  3007. };
  3008. return func;
  3009. };
  3010. var Delay = {
  3011. requestAnimationFrame: function (callback, element) {
  3012. if (requestAnimationFramePromise) {
  3013. requestAnimationFramePromise.then(callback);
  3014. return;
  3015. }
  3016. requestAnimationFramePromise = new promiseObj(function (resolve) {
  3017. if (!element) {
  3018. element = document.body;
  3019. }
  3020. requestAnimationFrame(resolve, element);
  3021. }).then(callback);
  3022. },
  3023. setTimeout: wrappedSetTimeout,
  3024. setInterval: wrappedSetInterval,
  3025. setEditorTimeout: function (editor, callback, time) {
  3026. return wrappedSetTimeout(function () {
  3027. if (!editor.removed) {
  3028. callback();
  3029. }
  3030. }, time);
  3031. },
  3032. setEditorInterval: function (editor, callback, time) {
  3033. var timer = wrappedSetInterval(function () {
  3034. if (!editor.removed) {
  3035. callback();
  3036. } else {
  3037. clearInterval(timer);
  3038. }
  3039. }, time);
  3040. return timer;
  3041. },
  3042. debounce: debounce,
  3043. throttle: debounce,
  3044. clearInterval: wrappedClearInterval,
  3045. clearTimeout: wrappedClearTimeout
  3046. };
  3047. function StyleSheetLoader(documentOrShadowRoot, settings) {
  3048. if (settings === void 0) {
  3049. settings = {};
  3050. }
  3051. var idCount = 0;
  3052. var loadedStates = {};
  3053. var edos = SugarElement.fromDom(documentOrShadowRoot);
  3054. var doc = documentOrOwner(edos);
  3055. var maxLoadTime = settings.maxLoadTime || 5000;
  3056. var _setReferrerPolicy = function (referrerPolicy) {
  3057. settings.referrerPolicy = referrerPolicy;
  3058. };
  3059. var addStyle = function (element) {
  3060. append(getStyleContainer(edos), element);
  3061. };
  3062. var removeStyle = function (id) {
  3063. var styleContainer = getStyleContainer(edos);
  3064. descendant(styleContainer, '#' + id).each(remove);
  3065. };
  3066. var getOrCreateState = function (url) {
  3067. return get$1(loadedStates, url).getOrThunk(function () {
  3068. return {
  3069. id: 'mce-u' + idCount++,
  3070. passed: [],
  3071. failed: [],
  3072. count: 0
  3073. };
  3074. });
  3075. };
  3076. var load = function (url, success, failure) {
  3077. var link;
  3078. var urlWithSuffix = Tools._addCacheSuffix(url);
  3079. var state = getOrCreateState(urlWithSuffix);
  3080. loadedStates[urlWithSuffix] = state;
  3081. state.count++;
  3082. var resolve = function (callbacks, status) {
  3083. var i = callbacks.length;
  3084. while (i--) {
  3085. callbacks[i]();
  3086. }
  3087. state.status = status;
  3088. state.passed = [];
  3089. state.failed = [];
  3090. if (link) {
  3091. link.onload = null;
  3092. link.onerror = null;
  3093. link = null;
  3094. }
  3095. };
  3096. var passed = function () {
  3097. return resolve(state.passed, 2);
  3098. };
  3099. var failed = function () {
  3100. return resolve(state.failed, 3);
  3101. };
  3102. var wait = function (testCallback, waitCallback) {
  3103. if (!testCallback()) {
  3104. if (Date.now() - startTime < maxLoadTime) {
  3105. Delay.setTimeout(waitCallback);
  3106. } else {
  3107. failed();
  3108. }
  3109. }
  3110. };
  3111. var waitForWebKitLinkLoaded = function () {
  3112. wait(function () {
  3113. var styleSheets = documentOrShadowRoot.styleSheets;
  3114. var i = styleSheets.length;
  3115. while (i--) {
  3116. var styleSheet = styleSheets[i];
  3117. var owner = styleSheet.ownerNode;
  3118. if (owner && owner.id === link.id) {
  3119. passed();
  3120. return true;
  3121. }
  3122. }
  3123. return false;
  3124. }, waitForWebKitLinkLoaded);
  3125. };
  3126. if (success) {
  3127. state.passed.push(success);
  3128. }
  3129. if (failure) {
  3130. state.failed.push(failure);
  3131. }
  3132. if (state.status === 1) {
  3133. return;
  3134. }
  3135. if (state.status === 2) {
  3136. passed();
  3137. return;
  3138. }
  3139. if (state.status === 3) {
  3140. failed();
  3141. return;
  3142. }
  3143. state.status = 1;
  3144. var linkElem = SugarElement.fromTag('link', doc.dom);
  3145. setAll(linkElem, {
  3146. rel: 'stylesheet',
  3147. type: 'text/css',
  3148. id: state.id
  3149. });
  3150. var startTime = Date.now();
  3151. if (settings.contentCssCors) {
  3152. set(linkElem, 'crossOrigin', 'anonymous');
  3153. }
  3154. if (settings.referrerPolicy) {
  3155. set(linkElem, 'referrerpolicy', settings.referrerPolicy);
  3156. }
  3157. link = linkElem.dom;
  3158. link.onload = waitForWebKitLinkLoaded;
  3159. link.onerror = failed;
  3160. addStyle(linkElem);
  3161. set(linkElem, 'href', urlWithSuffix);
  3162. };
  3163. var loadF = function (url) {
  3164. return Future.nu(function (resolve) {
  3165. load(url, compose(resolve, constant(Result.value(url))), compose(resolve, constant(Result.error(url))));
  3166. });
  3167. };
  3168. var loadAll = function (urls, success, failure) {
  3169. par$1(map(urls, loadF)).get(function (result) {
  3170. var parts = partition(result, function (r) {
  3171. return r.isValue();
  3172. });
  3173. if (parts.fail.length > 0) {
  3174. failure(parts.fail.map(unite));
  3175. } else {
  3176. success(parts.pass.map(unite));
  3177. }
  3178. });
  3179. };
  3180. var unload = function (url) {
  3181. var urlWithSuffix = Tools._addCacheSuffix(url);
  3182. get$1(loadedStates, urlWithSuffix).each(function (state) {
  3183. var count = --state.count;
  3184. if (count === 0) {
  3185. delete loadedStates[urlWithSuffix];
  3186. removeStyle(state.id);
  3187. }
  3188. });
  3189. };
  3190. var unloadAll = function (urls) {
  3191. each(urls, function (url) {
  3192. unload(url);
  3193. });
  3194. };
  3195. return {
  3196. load: load,
  3197. loadAll: loadAll,
  3198. unload: unload,
  3199. unloadAll: unloadAll,
  3200. _setReferrerPolicy: _setReferrerPolicy
  3201. };
  3202. }
  3203. var create$1 = function () {
  3204. var map = new WeakMap();
  3205. var forElement = function (referenceElement, settings) {
  3206. var root = getRootNode(referenceElement);
  3207. var rootDom = root.dom;
  3208. return Optional.from(map.get(rootDom)).getOrThunk(function () {
  3209. var sl = StyleSheetLoader(rootDom, settings);
  3210. map.set(rootDom, sl);
  3211. return sl;
  3212. });
  3213. };
  3214. return { forElement: forElement };
  3215. };
  3216. var instance = create$1();
  3217. var DomTreeWalker = function () {
  3218. function DomTreeWalker(startNode, rootNode) {
  3219. this.node = startNode;
  3220. this.rootNode = rootNode;
  3221. this.current = this.current.bind(this);
  3222. this.next = this.next.bind(this);
  3223. this.prev = this.prev.bind(this);
  3224. this.prev2 = this.prev2.bind(this);
  3225. }
  3226. DomTreeWalker.prototype.current = function () {
  3227. return this.node;
  3228. };
  3229. DomTreeWalker.prototype.next = function (shallow) {
  3230. this.node = this.findSibling(this.node, 'firstChild', 'nextSibling', shallow);
  3231. return this.node;
  3232. };
  3233. DomTreeWalker.prototype.prev = function (shallow) {
  3234. this.node = this.findSibling(this.node, 'lastChild', 'previousSibling', shallow);
  3235. return this.node;
  3236. };
  3237. DomTreeWalker.prototype.prev2 = function (shallow) {
  3238. this.node = this.findPreviousNode(this.node, 'lastChild', 'previousSibling', shallow);
  3239. return this.node;
  3240. };
  3241. DomTreeWalker.prototype.findSibling = function (node, startName, siblingName, shallow) {
  3242. var sibling, parent;
  3243. if (node) {
  3244. if (!shallow && node[startName]) {
  3245. return node[startName];
  3246. }
  3247. if (node !== this.rootNode) {
  3248. sibling = node[siblingName];
  3249. if (sibling) {
  3250. return sibling;
  3251. }
  3252. for (parent = node.parentNode; parent && parent !== this.rootNode; parent = parent.parentNode) {
  3253. sibling = parent[siblingName];
  3254. if (sibling) {
  3255. return sibling;
  3256. }
  3257. }
  3258. }
  3259. }
  3260. };
  3261. DomTreeWalker.prototype.findPreviousNode = function (node, startName, siblingName, shallow) {
  3262. var sibling, parent, child;
  3263. if (node) {
  3264. sibling = node[siblingName];
  3265. if (this.rootNode && sibling === this.rootNode) {
  3266. return;
  3267. }
  3268. if (sibling) {
  3269. if (!shallow) {
  3270. for (child = sibling[startName]; child; child = child[startName]) {
  3271. if (!child[startName]) {
  3272. return child;
  3273. }
  3274. }
  3275. }
  3276. return sibling;
  3277. }
  3278. parent = node.parentNode;
  3279. if (parent && parent !== this.rootNode) {
  3280. return parent;
  3281. }
  3282. }
  3283. };
  3284. return DomTreeWalker;
  3285. }();
  3286. var blocks = [
  3287. 'article',
  3288. 'aside',
  3289. 'details',
  3290. 'div',
  3291. 'dt',
  3292. 'figcaption',
  3293. 'footer',
  3294. 'form',
  3295. 'fieldset',
  3296. 'header',
  3297. 'hgroup',
  3298. 'html',
  3299. 'main',
  3300. 'nav',
  3301. 'section',
  3302. 'summary',
  3303. 'body',
  3304. 'p',
  3305. 'dl',
  3306. 'multicol',
  3307. 'dd',
  3308. 'figure',
  3309. 'address',
  3310. 'center',
  3311. 'blockquote',
  3312. 'h1',
  3313. 'h2',
  3314. 'h3',
  3315. 'h4',
  3316. 'h5',
  3317. 'h6',
  3318. 'listing',
  3319. 'xmp',
  3320. 'pre',
  3321. 'plaintext',
  3322. 'menu',
  3323. 'dir',
  3324. 'ul',
  3325. 'ol',
  3326. 'li',
  3327. 'hr',
  3328. 'table',
  3329. 'tbody',
  3330. 'thead',
  3331. 'tfoot',
  3332. 'th',
  3333. 'tr',
  3334. 'td',
  3335. 'caption'
  3336. ];
  3337. var tableCells = [
  3338. 'td',
  3339. 'th'
  3340. ];
  3341. var tableSections = [
  3342. 'thead',
  3343. 'tbody',
  3344. 'tfoot'
  3345. ];
  3346. var textBlocks = [
  3347. 'h1',
  3348. 'h2',
  3349. 'h3',
  3350. 'h4',
  3351. 'h5',
  3352. 'h6',
  3353. 'p',
  3354. 'div',
  3355. 'address',
  3356. 'pre',
  3357. 'form',
  3358. 'blockquote',
  3359. 'center',
  3360. 'dir',
  3361. 'fieldset',
  3362. 'header',
  3363. 'footer',
  3364. 'article',
  3365. 'section',
  3366. 'hgroup',
  3367. 'aside',
  3368. 'nav',
  3369. 'figure'
  3370. ];
  3371. var headings = [
  3372. 'h1',
  3373. 'h2',
  3374. 'h3',
  3375. 'h4',
  3376. 'h5',
  3377. 'h6'
  3378. ];
  3379. var listItems = [
  3380. 'li',
  3381. 'dd',
  3382. 'dt'
  3383. ];
  3384. var lists = [
  3385. 'ul',
  3386. 'ol',
  3387. 'dl'
  3388. ];
  3389. var wsElements = [
  3390. 'pre',
  3391. 'script',
  3392. 'textarea',
  3393. 'style'
  3394. ];
  3395. var lazyLookup = function (items) {
  3396. var lookup;
  3397. return function (node) {
  3398. lookup = lookup ? lookup : mapToObject(items, always);
  3399. return lookup.hasOwnProperty(name(node));
  3400. };
  3401. };
  3402. var isHeading = lazyLookup(headings);
  3403. var isBlock = lazyLookup(blocks);
  3404. var isTable$1 = function (node) {
  3405. return name(node) === 'table';
  3406. };
  3407. var isInline = function (node) {
  3408. return isElement(node) && !isBlock(node);
  3409. };
  3410. var isBr$1 = function (node) {
  3411. return isElement(node) && name(node) === 'br';
  3412. };
  3413. var isTextBlock = lazyLookup(textBlocks);
  3414. var isList = lazyLookup(lists);
  3415. var isListItem = lazyLookup(listItems);
  3416. var isTableSection = lazyLookup(tableSections);
  3417. var isTableCell$1 = lazyLookup(tableCells);
  3418. var isWsPreserveElement = lazyLookup(wsElements);
  3419. var ancestor$2 = function (scope, selector, isRoot) {
  3420. return ancestor$1(scope, selector, isRoot).isSome();
  3421. };
  3422. var zeroWidth = '\uFEFF';
  3423. var nbsp = '\xA0';
  3424. var isZwsp = function (char) {
  3425. return char === zeroWidth;
  3426. };
  3427. var removeZwsp = function (s) {
  3428. return s.replace(/\uFEFF/g, '');
  3429. };
  3430. var ZWSP = zeroWidth;
  3431. var isZwsp$1 = isZwsp;
  3432. var trim$2 = removeZwsp;
  3433. var isElement$2 = isElement$1;
  3434. var isText$2 = isText$1;
  3435. var isCaretContainerBlock = function (node) {
  3436. if (isText$2(node)) {
  3437. node = node.parentNode;
  3438. }
  3439. return isElement$2(node) && node.hasAttribute('data-mce-caret');
  3440. };
  3441. var isCaretContainerInline = function (node) {
  3442. return isText$2(node) && isZwsp$1(node.data);
  3443. };
  3444. var isCaretContainer = function (node) {
  3445. return isCaretContainerBlock(node) || isCaretContainerInline(node);
  3446. };
  3447. var hasContent = function (node) {
  3448. return node.firstChild !== node.lastChild || !isBr(node.firstChild);
  3449. };
  3450. var insertInline = function (node, before) {
  3451. var sibling;
  3452. var doc = node.ownerDocument;
  3453. var textNode = doc.createTextNode(ZWSP);
  3454. var parentNode = node.parentNode;
  3455. if (!before) {
  3456. sibling = node.nextSibling;
  3457. if (isText$2(sibling)) {
  3458. if (isCaretContainer(sibling)) {
  3459. return sibling;
  3460. }
  3461. if (startsWithCaretContainer(sibling)) {
  3462. sibling.splitText(1);
  3463. return sibling;
  3464. }
  3465. }
  3466. if (node.nextSibling) {
  3467. parentNode.insertBefore(textNode, node.nextSibling);
  3468. } else {
  3469. parentNode.appendChild(textNode);
  3470. }
  3471. } else {
  3472. sibling = node.previousSibling;
  3473. if (isText$2(sibling)) {
  3474. if (isCaretContainer(sibling)) {
  3475. return sibling;
  3476. }
  3477. if (endsWithCaretContainer(sibling)) {
  3478. return sibling.splitText(sibling.data.length - 1);
  3479. }
  3480. }
  3481. parentNode.insertBefore(textNode, node);
  3482. }
  3483. return textNode;
  3484. };
  3485. var isBeforeInline = function (pos) {
  3486. var container = pos.container();
  3487. if (!isText$1(container)) {
  3488. return false;
  3489. }
  3490. return container.data.charAt(pos.offset()) === ZWSP || pos.isAtStart() && isCaretContainerInline(container.previousSibling);
  3491. };
  3492. var isAfterInline = function (pos) {
  3493. var container = pos.container();
  3494. if (!isText$1(container)) {
  3495. return false;
  3496. }
  3497. return container.data.charAt(pos.offset() - 1) === ZWSP || pos.isAtEnd() && isCaretContainerInline(container.nextSibling);
  3498. };
  3499. var createBogusBr = function () {
  3500. var br = document.createElement('br');
  3501. br.setAttribute('data-mce-bogus', '1');
  3502. return br;
  3503. };
  3504. var insertBlock = function (blockName, node, before) {
  3505. var doc = node.ownerDocument;
  3506. var blockNode = doc.createElement(blockName);
  3507. blockNode.setAttribute('data-mce-caret', before ? 'before' : 'after');
  3508. blockNode.setAttribute('data-mce-bogus', 'all');
  3509. blockNode.appendChild(createBogusBr());
  3510. var parentNode = node.parentNode;
  3511. if (!before) {
  3512. if (node.nextSibling) {
  3513. parentNode.insertBefore(blockNode, node.nextSibling);
  3514. } else {
  3515. parentNode.appendChild(blockNode);
  3516. }
  3517. } else {
  3518. parentNode.insertBefore(blockNode, node);
  3519. }
  3520. return blockNode;
  3521. };
  3522. var startsWithCaretContainer = function (node) {
  3523. return isText$2(node) && node.data[0] === ZWSP;
  3524. };
  3525. var endsWithCaretContainer = function (node) {
  3526. return isText$2(node) && node.data[node.data.length - 1] === ZWSP;
  3527. };
  3528. var trimBogusBr = function (elm) {
  3529. var brs = elm.getElementsByTagName('br');
  3530. var lastBr = brs[brs.length - 1];
  3531. if (isBogus(lastBr)) {
  3532. lastBr.parentNode.removeChild(lastBr);
  3533. }
  3534. };
  3535. var showCaretContainerBlock = function (caretContainer) {
  3536. if (caretContainer && caretContainer.hasAttribute('data-mce-caret')) {
  3537. trimBogusBr(caretContainer);
  3538. caretContainer.removeAttribute('data-mce-caret');
  3539. caretContainer.removeAttribute('data-mce-bogus');
  3540. caretContainer.removeAttribute('style');
  3541. caretContainer.removeAttribute('_moz_abspos');
  3542. return caretContainer;
  3543. }
  3544. return null;
  3545. };
  3546. var isRangeInCaretContainerBlock = function (range) {
  3547. return isCaretContainerBlock(range.startContainer);
  3548. };
  3549. var isContentEditableTrue$1 = isContentEditableTrue;
  3550. var isContentEditableFalse$1 = isContentEditableFalse;
  3551. var isBr$2 = isBr;
  3552. var isText$3 = isText$1;
  3553. var isInvalidTextElement = matchNodeNames([
  3554. 'script',
  3555. 'style',
  3556. 'textarea'
  3557. ]);
  3558. var isAtomicInline = matchNodeNames([
  3559. 'img',
  3560. 'input',
  3561. 'textarea',
  3562. 'hr',
  3563. 'iframe',
  3564. 'video',
  3565. 'audio',
  3566. 'object',
  3567. 'embed'
  3568. ]);
  3569. var isTable$2 = matchNodeNames(['table']);
  3570. var isCaretContainer$1 = isCaretContainer;
  3571. var isCaretCandidate = function (node) {
  3572. if (isCaretContainer$1(node)) {
  3573. return false;
  3574. }
  3575. if (isText$3(node)) {
  3576. return !isInvalidTextElement(node.parentNode);
  3577. }
  3578. return isAtomicInline(node) || isBr$2(node) || isTable$2(node) || isNonUiContentEditableFalse(node);
  3579. };
  3580. var isUnselectable = function (node) {
  3581. return isElement$1(node) && node.getAttribute('unselectable') === 'true';
  3582. };
  3583. var isNonUiContentEditableFalse = function (node) {
  3584. return isUnselectable(node) === false && isContentEditableFalse$1(node);
  3585. };
  3586. var isInEditable = function (node, root) {
  3587. for (node = node.parentNode; node && node !== root; node = node.parentNode) {
  3588. if (isNonUiContentEditableFalse(node)) {
  3589. return false;
  3590. }
  3591. if (isContentEditableTrue$1(node)) {
  3592. return true;
  3593. }
  3594. }
  3595. return true;
  3596. };
  3597. var isAtomicContentEditableFalse = function (node) {
  3598. if (!isNonUiContentEditableFalse(node)) {
  3599. return false;
  3600. }
  3601. return foldl(from$1(node.getElementsByTagName('*')), function (result, elm) {
  3602. return result || isContentEditableTrue$1(elm);
  3603. }, false) !== true;
  3604. };
  3605. var isAtomic = function (node) {
  3606. return isAtomicInline(node) || isAtomicContentEditableFalse(node);
  3607. };
  3608. var isEditableCaretCandidate = function (node, root) {
  3609. return isCaretCandidate(node) && isInEditable(node, root);
  3610. };
  3611. var whiteSpaceRegExp$1 = /^[ \t\r\n]*$/;
  3612. var isWhitespaceText = function (text) {
  3613. return whiteSpaceRegExp$1.test(text);
  3614. };
  3615. var hasWhitespacePreserveParent = function (node, rootNode) {
  3616. var rootElement = SugarElement.fromDom(rootNode);
  3617. var startNode = SugarElement.fromDom(node);
  3618. return ancestor$2(startNode, 'pre,code', curry(eq$2, rootElement));
  3619. };
  3620. var isWhitespace = function (node, rootNode) {
  3621. return isText$1(node) && isWhitespaceText(node.data) && hasWhitespacePreserveParent(node, rootNode) === false;
  3622. };
  3623. var isNamedAnchor = function (node) {
  3624. return isElement$1(node) && node.nodeName === 'A' && !node.hasAttribute('href') && (node.hasAttribute('name') || node.hasAttribute('id'));
  3625. };
  3626. var isContent = function (node, rootNode) {
  3627. return isCaretCandidate(node) && isWhitespace(node, rootNode) === false || isNamedAnchor(node) || isBookmark(node);
  3628. };
  3629. var isBookmark = hasAttribute('data-mce-bookmark');
  3630. var isBogus$1 = hasAttribute('data-mce-bogus');
  3631. var isBogusAll$1 = hasAttributeValue('data-mce-bogus', 'all');
  3632. var isEmptyNode = function (targetNode, skipBogus) {
  3633. var node, brCount = 0;
  3634. if (isContent(targetNode, targetNode)) {
  3635. return false;
  3636. } else {
  3637. node = targetNode.firstChild;
  3638. if (!node) {
  3639. return true;
  3640. }
  3641. var walker = new DomTreeWalker(node, targetNode);
  3642. do {
  3643. if (skipBogus) {
  3644. if (isBogusAll$1(node)) {
  3645. node = walker.next(true);
  3646. continue;
  3647. }
  3648. if (isBogus$1(node)) {
  3649. node = walker.next();
  3650. continue;
  3651. }
  3652. }
  3653. if (isBr(node)) {
  3654. brCount++;
  3655. node = walker.next();
  3656. continue;
  3657. }
  3658. if (isContent(node, targetNode)) {
  3659. return false;
  3660. }
  3661. node = walker.next();
  3662. } while (node);
  3663. return brCount <= 1;
  3664. }
  3665. };
  3666. var isEmpty = function (elm, skipBogus) {
  3667. if (skipBogus === void 0) {
  3668. skipBogus = true;
  3669. }
  3670. return isEmptyNode(elm.dom, skipBogus);
  3671. };
  3672. var isSpan = function (node) {
  3673. return node.nodeName.toLowerCase() === 'span';
  3674. };
  3675. var isInlineContent = function (node, root) {
  3676. return isNonNullable(node) && (isContent(node, root) || isInline(SugarElement.fromDom(node)));
  3677. };
  3678. var surroundedByInlineContent = function (node, root) {
  3679. var prev = new DomTreeWalker(node, root).prev(false);
  3680. var next = new DomTreeWalker(node, root).next(false);
  3681. var prevIsInline = isUndefined(prev) || isInlineContent(prev, root);
  3682. var nextIsInline = isUndefined(next) || isInlineContent(next, root);
  3683. return prevIsInline && nextIsInline;
  3684. };
  3685. var isBookmarkNode = function (node) {
  3686. return isSpan(node) && node.getAttribute('data-mce-type') === 'bookmark';
  3687. };
  3688. var isKeepTextNode = function (node, root) {
  3689. return isText$1(node) && node.data.length > 0 && surroundedByInlineContent(node, root);
  3690. };
  3691. var isKeepElement = function (node) {
  3692. return isElement$1(node) ? node.childNodes.length > 0 : false;
  3693. };
  3694. var isDocument$2 = function (node) {
  3695. return isDocumentFragment$1(node) || isDocument$1(node);
  3696. };
  3697. var trimNode = function (dom, node, root) {
  3698. var rootNode = root || node;
  3699. if (isElement$1(node) && isBookmarkNode(node)) {
  3700. return node;
  3701. }
  3702. var children = node.childNodes;
  3703. for (var i = children.length - 1; i >= 0; i--) {
  3704. trimNode(dom, children[i], rootNode);
  3705. }
  3706. if (isElement$1(node)) {
  3707. var currentChildren = node.childNodes;
  3708. if (currentChildren.length === 1 && isBookmarkNode(currentChildren[0])) {
  3709. node.parentNode.insertBefore(currentChildren[0], node);
  3710. }
  3711. }
  3712. if (!isDocument$2(node) && !isContent(node, rootNode) && !isKeepElement(node) && !isKeepTextNode(node, rootNode)) {
  3713. dom.remove(node);
  3714. }
  3715. return node;
  3716. };
  3717. var makeMap$1 = Tools.makeMap;
  3718. var attrsCharsRegExp = /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  3719. var textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  3720. var rawCharsRegExp = /[<>&\"\']/g;
  3721. var entityRegExp = /&#([a-z0-9]+);?|&([a-z0-9]+);/gi;
  3722. var asciiMap = {
  3723. 128: '\u20AC',
  3724. 130: '\u201A',
  3725. 131: '\u0192',
  3726. 132: '\u201E',
  3727. 133: '\u2026',
  3728. 134: '\u2020',
  3729. 135: '\u2021',
  3730. 136: '\u02c6',
  3731. 137: '\u2030',
  3732. 138: '\u0160',
  3733. 139: '\u2039',
  3734. 140: '\u0152',
  3735. 142: '\u017d',
  3736. 145: '\u2018',
  3737. 146: '\u2019',
  3738. 147: '\u201C',
  3739. 148: '\u201D',
  3740. 149: '\u2022',
  3741. 150: '\u2013',
  3742. 151: '\u2014',
  3743. 152: '\u02DC',
  3744. 153: '\u2122',
  3745. 154: '\u0161',
  3746. 155: '\u203A',
  3747. 156: '\u0153',
  3748. 158: '\u017e',
  3749. 159: '\u0178'
  3750. };
  3751. var baseEntities = {
  3752. '"': '&quot;',
  3753. '\'': '&#39;',
  3754. '<': '&lt;',
  3755. '>': '&gt;',
  3756. '&': '&amp;',
  3757. '`': '&#96;'
  3758. };
  3759. var reverseEntities = {
  3760. '&lt;': '<',
  3761. '&gt;': '>',
  3762. '&amp;': '&',
  3763. '&quot;': '"',
  3764. '&apos;': '\''
  3765. };
  3766. var nativeDecode = function (text) {
  3767. var elm = SugarElement.fromTag('div').dom;
  3768. elm.innerHTML = text;
  3769. return elm.textContent || elm.innerText || text;
  3770. };
  3771. var buildEntitiesLookup = function (items, radix) {
  3772. var i, chr, entity;
  3773. var lookup = {};
  3774. if (items) {
  3775. items = items.split(',');
  3776. radix = radix || 10;
  3777. for (i = 0; i < items.length; i += 2) {
  3778. chr = String.fromCharCode(parseInt(items[i], radix));
  3779. if (!baseEntities[chr]) {
  3780. entity = '&' + items[i + 1] + ';';
  3781. lookup[chr] = entity;
  3782. lookup[entity] = chr;
  3783. }
  3784. }
  3785. return lookup;
  3786. }
  3787. };
  3788. 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);
  3789. var encodeRaw = function (text, attr) {
  3790. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3791. return baseEntities[chr] || chr;
  3792. });
  3793. };
  3794. var encodeAllRaw = function (text) {
  3795. return ('' + text).replace(rawCharsRegExp, function (chr) {
  3796. return baseEntities[chr] || chr;
  3797. });
  3798. };
  3799. var encodeNumeric = function (text, attr) {
  3800. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3801. if (chr.length > 1) {
  3802. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  3803. }
  3804. return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
  3805. });
  3806. };
  3807. var encodeNamed = function (text, attr, entities) {
  3808. entities = entities || namedEntities;
  3809. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3810. return baseEntities[chr] || entities[chr] || chr;
  3811. });
  3812. };
  3813. var getEncodeFunc = function (name, entities) {
  3814. var entitiesMap = buildEntitiesLookup(entities) || namedEntities;
  3815. var encodeNamedAndNumeric = function (text, attr) {
  3816. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3817. if (baseEntities[chr] !== undefined) {
  3818. return baseEntities[chr];
  3819. }
  3820. if (entitiesMap[chr] !== undefined) {
  3821. return entitiesMap[chr];
  3822. }
  3823. if (chr.length > 1) {
  3824. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  3825. }
  3826. return '&#' + chr.charCodeAt(0) + ';';
  3827. });
  3828. };
  3829. var encodeCustomNamed = function (text, attr) {
  3830. return encodeNamed(text, attr, entitiesMap);
  3831. };
  3832. var nameMap = makeMap$1(name.replace(/\+/g, ','));
  3833. if (nameMap.named && nameMap.numeric) {
  3834. return encodeNamedAndNumeric;
  3835. }
  3836. if (nameMap.named) {
  3837. if (entities) {
  3838. return encodeCustomNamed;
  3839. }
  3840. return encodeNamed;
  3841. }
  3842. if (nameMap.numeric) {
  3843. return encodeNumeric;
  3844. }
  3845. return encodeRaw;
  3846. };
  3847. var decode = function (text) {
  3848. return text.replace(entityRegExp, function (all, numeric) {
  3849. if (numeric) {
  3850. if (numeric.charAt(0).toLowerCase() === 'x') {
  3851. numeric = parseInt(numeric.substr(1), 16);
  3852. } else {
  3853. numeric = parseInt(numeric, 10);
  3854. }
  3855. if (numeric > 65535) {
  3856. numeric -= 65536;
  3857. return String.fromCharCode(55296 + (numeric >> 10), 56320 + (numeric & 1023));
  3858. }
  3859. return asciiMap[numeric] || String.fromCharCode(numeric);
  3860. }
  3861. return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
  3862. });
  3863. };
  3864. var Entities = {
  3865. encodeRaw: encodeRaw,
  3866. encodeAllRaw: encodeAllRaw,
  3867. encodeNumeric: encodeNumeric,
  3868. encodeNamed: encodeNamed,
  3869. getEncodeFunc: getEncodeFunc,
  3870. decode: decode
  3871. };
  3872. var mapCache = {}, dummyObj = {};
  3873. var makeMap$2 = Tools.makeMap, each$3 = Tools.each, extend$1 = Tools.extend, explode$1 = Tools.explode, inArray = Tools.inArray;
  3874. var split = function (items, delim) {
  3875. items = Tools.trim(items);
  3876. return items ? items.split(delim || ' ') : [];
  3877. };
  3878. var compileSchema = function (type) {
  3879. var schema = {};
  3880. var globalAttributes, blockContent;
  3881. var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
  3882. var add = function (name, attributes, children) {
  3883. var ni, attributesOrder, element;
  3884. var arrayToMap = function (array, obj) {
  3885. var map = {};
  3886. var i, l;
  3887. for (i = 0, l = array.length; i < l; i++) {
  3888. map[array[i]] = obj || {};
  3889. }
  3890. return map;
  3891. };
  3892. children = children || [];
  3893. attributes = attributes || '';
  3894. if (typeof children === 'string') {
  3895. children = split(children);
  3896. }
  3897. var names = split(name);
  3898. ni = names.length;
  3899. while (ni--) {
  3900. attributesOrder = split([
  3901. globalAttributes,
  3902. attributes
  3903. ].join(' '));
  3904. element = {
  3905. attributes: arrayToMap(attributesOrder),
  3906. attributesOrder: attributesOrder,
  3907. children: arrayToMap(children, dummyObj)
  3908. };
  3909. schema[names[ni]] = element;
  3910. }
  3911. };
  3912. var addAttrs = function (name, attributes) {
  3913. var ni, schemaItem, i, l;
  3914. var names = split(name);
  3915. ni = names.length;
  3916. var attrs = split(attributes);
  3917. while (ni--) {
  3918. schemaItem = schema[names[ni]];
  3919. for (i = 0, l = attrs.length; i < l; i++) {
  3920. schemaItem.attributes[attrs[i]] = {};
  3921. schemaItem.attributesOrder.push(attrs[i]);
  3922. }
  3923. }
  3924. };
  3925. if (mapCache[type]) {
  3926. return mapCache[type];
  3927. }
  3928. globalAttributes = 'id accesskey class dir lang style tabindex title role';
  3929. blockContent = 'address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul';
  3930. 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';
  3931. if (type !== 'html4') {
  3932. globalAttributes += ' contenteditable contextmenu draggable dropzone ' + 'hidden spellcheck translate';
  3933. blockContent += ' article aside details dialog figure main header footer hgroup section nav';
  3934. phrasingContent += ' audio canvas command datalist mark meter output picture ' + 'progress time wbr video ruby bdi keygen';
  3935. }
  3936. if (type !== 'html5-strict') {
  3937. globalAttributes += ' xml:lang';
  3938. html4PhrasingContent = 'acronym applet basefont big font strike tt';
  3939. phrasingContent = [
  3940. phrasingContent,
  3941. html4PhrasingContent
  3942. ].join(' ');
  3943. each$3(split(html4PhrasingContent), function (name) {
  3944. add(name, '', phrasingContent);
  3945. });
  3946. html4BlockContent = 'center dir isindex noframes';
  3947. blockContent = [
  3948. blockContent,
  3949. html4BlockContent
  3950. ].join(' ');
  3951. flowContent = [
  3952. blockContent,
  3953. phrasingContent
  3954. ].join(' ');
  3955. each$3(split(html4BlockContent), function (name) {
  3956. add(name, '', flowContent);
  3957. });
  3958. }
  3959. flowContent = flowContent || [
  3960. blockContent,
  3961. phrasingContent
  3962. ].join(' ');
  3963. add('html', 'manifest', 'head body');
  3964. add('head', '', 'base command link meta noscript script style title');
  3965. add('title hr noscript br');
  3966. add('base', 'href target');
  3967. add('link', 'href rel media hreflang type sizes hreflang');
  3968. add('meta', 'name http-equiv content charset');
  3969. add('style', 'media type scoped');
  3970. add('script', 'src async defer type charset');
  3971. add('body', 'onafterprint onbeforeprint onbeforeunload onblur onerror onfocus ' + 'onhashchange onload onmessage onoffline ononline onpagehide onpageshow ' + 'onpopstate onresize onscroll onstorage onunload', flowContent);
  3972. add('address dt dd div caption', '', flowContent);
  3973. 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);
  3974. add('blockquote', 'cite', flowContent);
  3975. add('ol', 'reversed start type', 'li');
  3976. add('ul', '', 'li');
  3977. add('li', 'value', flowContent);
  3978. add('dl', '', 'dt dd');
  3979. add('a', 'href target rel media hreflang type', phrasingContent);
  3980. add('q', 'cite', phrasingContent);
  3981. add('ins del', 'cite datetime', flowContent);
  3982. add('img', 'src sizes srcset alt usemap ismap width height');
  3983. add('iframe', 'src name width height', flowContent);
  3984. add('embed', 'src type width height');
  3985. add('object', 'data type typemustmatch name usemap form width height', [
  3986. flowContent,
  3987. 'param'
  3988. ].join(' '));
  3989. add('param', 'name value');
  3990. add('map', 'name', [
  3991. flowContent,
  3992. 'area'
  3993. ].join(' '));
  3994. add('area', 'alt coords shape href target rel media hreflang type');
  3995. add('table', 'border', 'caption colgroup thead tfoot tbody tr' + (type === 'html4' ? ' col' : ''));
  3996. add('colgroup', 'span', 'col');
  3997. add('col', 'span');
  3998. add('tbody thead tfoot', '', 'tr');
  3999. add('tr', '', 'td th');
  4000. add('td', 'colspan rowspan headers', flowContent);
  4001. add('th', 'colspan rowspan headers scope abbr', flowContent);
  4002. add('form', 'accept-charset action autocomplete enctype method name novalidate target', flowContent);
  4003. add('fieldset', 'disabled form name', [
  4004. flowContent,
  4005. 'legend'
  4006. ].join(' '));
  4007. add('label', 'form for', phrasingContent);
  4008. 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');
  4009. add('button', 'disabled form formaction formenctype formmethod formnovalidate formtarget name type value', type === 'html4' ? flowContent : phrasingContent);
  4010. add('select', 'disabled form multiple name required size', 'option optgroup');
  4011. add('optgroup', 'disabled label', 'option');
  4012. add('option', 'disabled label selected value');
  4013. add('textarea', 'cols dirname disabled form maxlength name readonly required rows wrap');
  4014. add('menu', 'type label', [
  4015. flowContent,
  4016. 'li'
  4017. ].join(' '));
  4018. add('noscript', '', flowContent);
  4019. if (type !== 'html4') {
  4020. add('wbr');
  4021. add('ruby', '', [
  4022. phrasingContent,
  4023. 'rt rp'
  4024. ].join(' '));
  4025. add('figcaption', '', flowContent);
  4026. add('mark rt rp summary bdi', '', phrasingContent);
  4027. add('canvas', 'width height', flowContent);
  4028. add('video', 'src crossorigin poster preload autoplay mediagroup loop ' + 'muted controls width height buffered', [
  4029. flowContent,
  4030. 'track source'
  4031. ].join(' '));
  4032. add('audio', 'src crossorigin preload autoplay mediagroup loop muted controls ' + 'buffered volume', [
  4033. flowContent,
  4034. 'track source'
  4035. ].join(' '));
  4036. add('picture', '', 'img source');
  4037. add('source', 'src srcset type media sizes');
  4038. add('track', 'kind src srclang label default');
  4039. add('datalist', '', [
  4040. phrasingContent,
  4041. 'option'
  4042. ].join(' '));
  4043. add('article section nav aside main header footer', '', flowContent);
  4044. add('hgroup', '', 'h1 h2 h3 h4 h5 h6');
  4045. add('figure', '', [
  4046. flowContent,
  4047. 'figcaption'
  4048. ].join(' '));
  4049. add('time', 'datetime', phrasingContent);
  4050. add('dialog', 'open', flowContent);
  4051. add('command', 'type label icon disabled checked radiogroup command');
  4052. add('output', 'for form name', phrasingContent);
  4053. add('progress', 'value max', phrasingContent);
  4054. add('meter', 'value min max low high optimum', phrasingContent);
  4055. add('details', 'open', [
  4056. flowContent,
  4057. 'summary'
  4058. ].join(' '));
  4059. add('keygen', 'autofocus challenge disabled form keytype name');
  4060. }
  4061. if (type !== 'html5-strict') {
  4062. addAttrs('script', 'language xml:space');
  4063. addAttrs('style', 'xml:space');
  4064. addAttrs('object', 'declare classid code codebase codetype archive standby align border hspace vspace');
  4065. addAttrs('embed', 'align name hspace vspace');
  4066. addAttrs('param', 'valuetype type');
  4067. addAttrs('a', 'charset name rev shape coords');
  4068. addAttrs('br', 'clear');
  4069. addAttrs('applet', 'codebase archive code object alt name width height align hspace vspace');
  4070. addAttrs('img', 'name longdesc align border hspace vspace');
  4071. addAttrs('iframe', 'longdesc frameborder marginwidth marginheight scrolling align');
  4072. addAttrs('font basefont', 'size color face');
  4073. addAttrs('input', 'usemap align');
  4074. addAttrs('select');
  4075. addAttrs('textarea');
  4076. addAttrs('h1 h2 h3 h4 h5 h6 div p legend caption', 'align');
  4077. addAttrs('ul', 'type compact');
  4078. addAttrs('li', 'type');
  4079. addAttrs('ol dl menu dir', 'compact');
  4080. addAttrs('pre', 'width xml:space');
  4081. addAttrs('hr', 'align noshade size width');
  4082. addAttrs('isindex', 'prompt');
  4083. addAttrs('table', 'summary width frame rules cellspacing cellpadding align bgcolor');
  4084. addAttrs('col', 'width align char charoff valign');
  4085. addAttrs('colgroup', 'width align char charoff valign');
  4086. addAttrs('thead', 'align char charoff valign');
  4087. addAttrs('tr', 'align char charoff valign bgcolor');
  4088. addAttrs('th', 'axis align char charoff valign nowrap bgcolor width height');
  4089. addAttrs('form', 'accept');
  4090. addAttrs('td', 'abbr axis scope align char charoff valign nowrap bgcolor width height');
  4091. addAttrs('tfoot', 'align char charoff valign');
  4092. addAttrs('tbody', 'align char charoff valign');
  4093. addAttrs('area', 'nohref');
  4094. addAttrs('body', 'background bgcolor text link vlink alink');
  4095. }
  4096. if (type !== 'html4') {
  4097. addAttrs('input button select textarea', 'autofocus');
  4098. addAttrs('input textarea', 'placeholder');
  4099. addAttrs('a', 'download');
  4100. addAttrs('link script img', 'crossorigin');
  4101. addAttrs('img', 'loading');
  4102. addAttrs('iframe', 'sandbox seamless allowfullscreen loading');
  4103. }
  4104. each$3(split('a form meter progress dfn'), function (name) {
  4105. if (schema[name]) {
  4106. delete schema[name].children[name];
  4107. }
  4108. });
  4109. delete schema.caption.children.table;
  4110. delete schema.script;
  4111. mapCache[type] = schema;
  4112. return schema;
  4113. };
  4114. var compileElementMap = function (value, mode) {
  4115. var styles;
  4116. if (value) {
  4117. styles = {};
  4118. if (typeof value === 'string') {
  4119. value = { '*': value };
  4120. }
  4121. each$3(value, function (value, key) {
  4122. styles[key] = styles[key.toUpperCase()] = mode === 'map' ? makeMap$2(value, /[, ]/) : explode$1(value, /[, ]/);
  4123. });
  4124. }
  4125. return styles;
  4126. };
  4127. function Schema(settings) {
  4128. var elements = {};
  4129. var children = {};
  4130. var patternElements = [];
  4131. var customElementsMap = {}, specialElements = {};
  4132. var createLookupTable = function (option, defaultValue, extendWith) {
  4133. var value = settings[option];
  4134. if (!value) {
  4135. value = mapCache[option];
  4136. if (!value) {
  4137. value = makeMap$2(defaultValue, ' ', makeMap$2(defaultValue.toUpperCase(), ' '));
  4138. value = extend$1(value, extendWith);
  4139. mapCache[option] = value;
  4140. }
  4141. } else {
  4142. value = makeMap$2(value, /[, ]/, makeMap$2(value.toUpperCase(), /[, ]/));
  4143. }
  4144. return value;
  4145. };
  4146. settings = settings || {};
  4147. var schemaItems = compileSchema(settings.schema);
  4148. if (settings.verify_html === false) {
  4149. settings.valid_elements = '*[*]';
  4150. }
  4151. var validStyles = compileElementMap(settings.valid_styles);
  4152. var invalidStyles = compileElementMap(settings.invalid_styles, 'map');
  4153. var validClasses = compileElementMap(settings.valid_classes, 'map');
  4154. var whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object code');
  4155. var selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
  4156. var shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link ' + 'meta param embed source wbr track');
  4157. var boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + 'noshade nowrap readonly selected autoplay loop controls');
  4158. var nonEmptyOrMoveCaretBeforeOnEnter = 'td th iframe video audio object script code';
  4159. var nonEmptyElementsMap = createLookupTable('non_empty_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' pre', shortEndedElementsMap);
  4160. var moveCaretBeforeOnEnterElementsMap = createLookupTable('move_caret_before_on_enter_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' table', shortEndedElementsMap);
  4161. 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');
  4162. 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);
  4163. var textInlineElementsMap = createLookupTable('text_inline_elements', 'span strong b em i font strike u var cite ' + 'dfn code mark q sup sub samp');
  4164. each$3((settings.special || 'script noscript iframe noframes noembed title style textarea xmp').split(' '), function (name) {
  4165. specialElements[name] = new RegExp('</' + name + '[^>]*>', 'gi');
  4166. });
  4167. var patternToRegExp = function (str) {
  4168. return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
  4169. };
  4170. var addValidElements = function (validElements) {
  4171. var ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, value;
  4172. var elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/, attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/;
  4173. if (validElements) {
  4174. var validElementsArr = split(validElements, ',');
  4175. if (elements['@']) {
  4176. globalAttributes = elements['@'].attributes;
  4177. globalAttributesOrder = elements['@'].attributesOrder;
  4178. }
  4179. for (ei = 0, el = validElementsArr.length; ei < el; ei++) {
  4180. matches = elementRuleRegExp.exec(validElementsArr[ei]);
  4181. if (matches) {
  4182. prefix = matches[1];
  4183. elementName = matches[2];
  4184. outputName = matches[3];
  4185. attrData = matches[5];
  4186. attributes = {};
  4187. attributesOrder = [];
  4188. element = {
  4189. attributes: attributes,
  4190. attributesOrder: attributesOrder
  4191. };
  4192. if (prefix === '#') {
  4193. element.paddEmpty = true;
  4194. }
  4195. if (prefix === '-') {
  4196. element.removeEmpty = true;
  4197. }
  4198. if (matches[4] === '!') {
  4199. element.removeEmptyAttrs = true;
  4200. }
  4201. if (globalAttributes) {
  4202. each$1(globalAttributes, function (value, key) {
  4203. attributes[key] = value;
  4204. });
  4205. attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
  4206. }
  4207. if (attrData) {
  4208. attrData = split(attrData, '|');
  4209. for (ai = 0, al = attrData.length; ai < al; ai++) {
  4210. matches = attrRuleRegExp.exec(attrData[ai]);
  4211. if (matches) {
  4212. attr = {};
  4213. attrType = matches[1];
  4214. attrName = matches[2].replace(/[\\:]:/g, ':');
  4215. prefix = matches[3];
  4216. value = matches[4];
  4217. if (attrType === '!') {
  4218. element.attributesRequired = element.attributesRequired || [];
  4219. element.attributesRequired.push(attrName);
  4220. attr.required = true;
  4221. }
  4222. if (attrType === '-') {
  4223. delete attributes[attrName];
  4224. attributesOrder.splice(inArray(attributesOrder, attrName), 1);
  4225. continue;
  4226. }
  4227. if (prefix) {
  4228. if (prefix === '=') {
  4229. element.attributesDefault = element.attributesDefault || [];
  4230. element.attributesDefault.push({
  4231. name: attrName,
  4232. value: value
  4233. });
  4234. attr.defaultValue = value;
  4235. }
  4236. if (prefix === ':') {
  4237. element.attributesForced = element.attributesForced || [];
  4238. element.attributesForced.push({
  4239. name: attrName,
  4240. value: value
  4241. });
  4242. attr.forcedValue = value;
  4243. }
  4244. if (prefix === '<') {
  4245. attr.validValues = makeMap$2(value, '?');
  4246. }
  4247. }
  4248. if (hasPatternsRegExp.test(attrName)) {
  4249. element.attributePatterns = element.attributePatterns || [];
  4250. attr.pattern = patternToRegExp(attrName);
  4251. element.attributePatterns.push(attr);
  4252. } else {
  4253. if (!attributes[attrName]) {
  4254. attributesOrder.push(attrName);
  4255. }
  4256. attributes[attrName] = attr;
  4257. }
  4258. }
  4259. }
  4260. }
  4261. if (!globalAttributes && elementName === '@') {
  4262. globalAttributes = attributes;
  4263. globalAttributesOrder = attributesOrder;
  4264. }
  4265. if (outputName) {
  4266. element.outputName = elementName;
  4267. elements[outputName] = element;
  4268. }
  4269. if (hasPatternsRegExp.test(elementName)) {
  4270. element.pattern = patternToRegExp(elementName);
  4271. patternElements.push(element);
  4272. } else {
  4273. elements[elementName] = element;
  4274. }
  4275. }
  4276. }
  4277. }
  4278. };
  4279. var setValidElements = function (validElements) {
  4280. elements = {};
  4281. patternElements = [];
  4282. addValidElements(validElements);
  4283. each$3(schemaItems, function (element, name) {
  4284. children[name] = element.children;
  4285. });
  4286. };
  4287. var addCustomElements = function (customElements) {
  4288. var customElementRegExp = /^(~)?(.+)$/;
  4289. if (customElements) {
  4290. mapCache.text_block_elements = mapCache.block_elements = null;
  4291. each$3(split(customElements, ','), function (rule) {
  4292. var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2];
  4293. children[name] = children[cloneName];
  4294. customElementsMap[name] = cloneName;
  4295. if (!inline) {
  4296. blockElementsMap[name.toUpperCase()] = {};
  4297. blockElementsMap[name] = {};
  4298. }
  4299. if (!elements[name]) {
  4300. var customRule = elements[cloneName];
  4301. customRule = extend$1({}, customRule);
  4302. delete customRule.removeEmptyAttrs;
  4303. delete customRule.removeEmpty;
  4304. elements[name] = customRule;
  4305. }
  4306. each$3(children, function (element, elmName) {
  4307. if (element[cloneName]) {
  4308. children[elmName] = element = extend$1({}, children[elmName]);
  4309. element[name] = element[cloneName];
  4310. }
  4311. });
  4312. });
  4313. }
  4314. };
  4315. var addValidChildren = function (validChildren) {
  4316. 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]+)\[([^\]]+)]$/;
  4317. mapCache[settings.schema] = null;
  4318. if (validChildren) {
  4319. each$3(split(validChildren, ','), function (rule) {
  4320. var matches = childRuleRegExp.exec(rule);
  4321. var parent, prefix;
  4322. if (matches) {
  4323. prefix = matches[1];
  4324. if (prefix) {
  4325. parent = children[matches[2]];
  4326. } else {
  4327. parent = children[matches[2]] = { '#comment': {} };
  4328. }
  4329. parent = children[matches[2]];
  4330. each$3(split(matches[3], '|'), function (child) {
  4331. if (prefix === '-') {
  4332. delete parent[child];
  4333. } else {
  4334. parent[child] = {};
  4335. }
  4336. });
  4337. }
  4338. });
  4339. }
  4340. };
  4341. var getElementRule = function (name) {
  4342. var element = elements[name], i;
  4343. if (element) {
  4344. return element;
  4345. }
  4346. i = patternElements.length;
  4347. while (i--) {
  4348. element = patternElements[i];
  4349. if (element.pattern.test(name)) {
  4350. return element;
  4351. }
  4352. }
  4353. };
  4354. if (!settings.valid_elements) {
  4355. each$3(schemaItems, function (element, name) {
  4356. elements[name] = {
  4357. attributes: element.attributes,
  4358. attributesOrder: element.attributesOrder
  4359. };
  4360. children[name] = element.children;
  4361. });
  4362. if (settings.schema !== 'html5') {
  4363. each$3(split('strong/b em/i'), function (item) {
  4364. var items = split(item, '/');
  4365. elements[items[1]].outputName = items[0];
  4366. });
  4367. }
  4368. each$3(split('ol ul sub sup blockquote span font a table tbody strong em b i'), function (name) {
  4369. if (elements[name]) {
  4370. elements[name].removeEmpty = true;
  4371. }
  4372. });
  4373. each$3(split('p h1 h2 h3 h4 h5 h6 th td pre div address caption li'), function (name) {
  4374. elements[name].paddEmpty = true;
  4375. });
  4376. each$3(split('span'), function (name) {
  4377. elements[name].removeEmptyAttrs = true;
  4378. });
  4379. } else {
  4380. setValidElements(settings.valid_elements);
  4381. }
  4382. addCustomElements(settings.custom_elements);
  4383. addValidChildren(settings.valid_children);
  4384. addValidElements(settings.extended_valid_elements);
  4385. addValidChildren('+ol[ul|ol],+ul[ul|ol]');
  4386. each$3({
  4387. dd: 'dl',
  4388. dt: 'dl',
  4389. li: 'ul ol',
  4390. td: 'tr',
  4391. th: 'tr',
  4392. tr: 'tbody thead tfoot',
  4393. tbody: 'table',
  4394. thead: 'table',
  4395. tfoot: 'table',
  4396. legend: 'fieldset',
  4397. area: 'map',
  4398. param: 'video audio object'
  4399. }, function (parents, item) {
  4400. if (elements[item]) {
  4401. elements[item].parentsRequired = split(parents);
  4402. }
  4403. });
  4404. if (settings.invalid_elements) {
  4405. each$3(explode$1(settings.invalid_elements), function (item) {
  4406. if (elements[item]) {
  4407. delete elements[item];
  4408. }
  4409. });
  4410. }
  4411. if (!getElementRule('span')) {
  4412. addValidElements('span[!data-mce-type|*]');
  4413. }
  4414. var getValidStyles = function () {
  4415. return validStyles;
  4416. };
  4417. var getInvalidStyles = function () {
  4418. return invalidStyles;
  4419. };
  4420. var getValidClasses = function () {
  4421. return validClasses;
  4422. };
  4423. var getBoolAttrs = function () {
  4424. return boolAttrMap;
  4425. };
  4426. var getBlockElements = function () {
  4427. return blockElementsMap;
  4428. };
  4429. var getTextBlockElements = function () {
  4430. return textBlockElementsMap;
  4431. };
  4432. var getTextInlineElements = function () {
  4433. return textInlineElementsMap;
  4434. };
  4435. var getShortEndedElements = function () {
  4436. return shortEndedElementsMap;
  4437. };
  4438. var getSelfClosingElements = function () {
  4439. return selfClosingElementsMap;
  4440. };
  4441. var getNonEmptyElements = function () {
  4442. return nonEmptyElementsMap;
  4443. };
  4444. var getMoveCaretBeforeOnEnterElements = function () {
  4445. return moveCaretBeforeOnEnterElementsMap;
  4446. };
  4447. var getWhiteSpaceElements = function () {
  4448. return whiteSpaceElementsMap;
  4449. };
  4450. var getSpecialElements = function () {
  4451. return specialElements;
  4452. };
  4453. var isValidChild = function (name, child) {
  4454. var parent = children[name.toLowerCase()];
  4455. return !!(parent && parent[child.toLowerCase()]);
  4456. };
  4457. var isValid = function (name, attr) {
  4458. var attrPatterns, i;
  4459. var rule = getElementRule(name);
  4460. if (rule) {
  4461. if (attr) {
  4462. if (rule.attributes[attr]) {
  4463. return true;
  4464. }
  4465. attrPatterns = rule.attributePatterns;
  4466. if (attrPatterns) {
  4467. i = attrPatterns.length;
  4468. while (i--) {
  4469. if (attrPatterns[i].pattern.test(name)) {
  4470. return true;
  4471. }
  4472. }
  4473. }
  4474. } else {
  4475. return true;
  4476. }
  4477. }
  4478. return false;
  4479. };
  4480. var getCustomElements = function () {
  4481. return customElementsMap;
  4482. };
  4483. return {
  4484. children: children,
  4485. elements: elements,
  4486. getValidStyles: getValidStyles,
  4487. getValidClasses: getValidClasses,
  4488. getBlockElements: getBlockElements,
  4489. getInvalidStyles: getInvalidStyles,
  4490. getShortEndedElements: getShortEndedElements,
  4491. getTextBlockElements: getTextBlockElements,
  4492. getTextInlineElements: getTextInlineElements,
  4493. getBoolAttrs: getBoolAttrs,
  4494. getElementRule: getElementRule,
  4495. getSelfClosingElements: getSelfClosingElements,
  4496. getNonEmptyElements: getNonEmptyElements,
  4497. getMoveCaretBeforeOnEnterElements: getMoveCaretBeforeOnEnterElements,
  4498. getWhiteSpaceElements: getWhiteSpaceElements,
  4499. getSpecialElements: getSpecialElements,
  4500. isValidChild: isValidChild,
  4501. isValid: isValid,
  4502. getCustomElements: getCustomElements,
  4503. addValidElements: addValidElements,
  4504. setValidElements: setValidElements,
  4505. addCustomElements: addCustomElements,
  4506. addValidChildren: addValidChildren
  4507. };
  4508. }
  4509. var toHex = function (match, r, g, b) {
  4510. var hex = function (val) {
  4511. val = parseInt(val, 10).toString(16);
  4512. return val.length > 1 ? val : '0' + val;
  4513. };
  4514. return '#' + hex(r) + hex(g) + hex(b);
  4515. };
  4516. var Styles = function (settings, schema) {
  4517. var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
  4518. var urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
  4519. var styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
  4520. var trimRightRegExp = /\s+$/;
  4521. var i;
  4522. var encodingLookup = {};
  4523. var validStyles;
  4524. var invalidStyles;
  4525. var invisibleChar = zeroWidth;
  4526. settings = settings || {};
  4527. if (schema) {
  4528. validStyles = schema.getValidStyles();
  4529. invalidStyles = schema.getInvalidStyles();
  4530. }
  4531. var encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' ');
  4532. for (i = 0; i < encodingItems.length; i++) {
  4533. encodingLookup[encodingItems[i]] = invisibleChar + i;
  4534. encodingLookup[invisibleChar + i] = encodingItems[i];
  4535. }
  4536. return {
  4537. toHex: function (color) {
  4538. return color.replace(rgbRegExp, toHex);
  4539. },
  4540. parse: function (css) {
  4541. var styles = {};
  4542. var matches, name, value, isEncoded;
  4543. var urlConverter = settings.url_converter;
  4544. var urlConverterScope = settings.url_converter_scope || this;
  4545. var compress = function (prefix, suffix, noJoin) {
  4546. var top = styles[prefix + '-top' + suffix];
  4547. if (!top) {
  4548. return;
  4549. }
  4550. var right = styles[prefix + '-right' + suffix];
  4551. if (!right) {
  4552. return;
  4553. }
  4554. var bottom = styles[prefix + '-bottom' + suffix];
  4555. if (!bottom) {
  4556. return;
  4557. }
  4558. var left = styles[prefix + '-left' + suffix];
  4559. if (!left) {
  4560. return;
  4561. }
  4562. var box = [
  4563. top,
  4564. right,
  4565. bottom,
  4566. left
  4567. ];
  4568. i = box.length - 1;
  4569. while (i--) {
  4570. if (box[i] !== box[i + 1]) {
  4571. break;
  4572. }
  4573. }
  4574. if (i > -1 && noJoin) {
  4575. return;
  4576. }
  4577. styles[prefix + suffix] = i === -1 ? box[0] : box.join(' ');
  4578. delete styles[prefix + '-top' + suffix];
  4579. delete styles[prefix + '-right' + suffix];
  4580. delete styles[prefix + '-bottom' + suffix];
  4581. delete styles[prefix + '-left' + suffix];
  4582. };
  4583. var canCompress = function (key) {
  4584. var value = styles[key], i;
  4585. if (!value) {
  4586. return;
  4587. }
  4588. value = value.split(' ');
  4589. i = value.length;
  4590. while (i--) {
  4591. if (value[i] !== value[0]) {
  4592. return false;
  4593. }
  4594. }
  4595. styles[key] = value[0];
  4596. return true;
  4597. };
  4598. var compress2 = function (target, a, b, c) {
  4599. if (!canCompress(a)) {
  4600. return;
  4601. }
  4602. if (!canCompress(b)) {
  4603. return;
  4604. }
  4605. if (!canCompress(c)) {
  4606. return;
  4607. }
  4608. styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
  4609. delete styles[a];
  4610. delete styles[b];
  4611. delete styles[c];
  4612. };
  4613. var encode = function (str) {
  4614. isEncoded = true;
  4615. return encodingLookup[str];
  4616. };
  4617. var decode = function (str, keepSlashes) {
  4618. if (isEncoded) {
  4619. str = str.replace(/\uFEFF[0-9]/g, function (str) {
  4620. return encodingLookup[str];
  4621. });
  4622. }
  4623. if (!keepSlashes) {
  4624. str = str.replace(/\\([\'\";:])/g, '$1');
  4625. }
  4626. return str;
  4627. };
  4628. var decodeSingleHexSequence = function (escSeq) {
  4629. return String.fromCharCode(parseInt(escSeq.slice(1), 16));
  4630. };
  4631. var decodeHexSequences = function (value) {
  4632. return value.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
  4633. };
  4634. var processUrl = function (match, url, url2, url3, str, str2) {
  4635. str = str || str2;
  4636. if (str) {
  4637. str = decode(str);
  4638. return '\'' + str.replace(/\'/g, '\\\'') + '\'';
  4639. }
  4640. url = decode(url || url2 || url3);
  4641. if (!settings.allow_script_urls) {
  4642. var scriptUrl = url.replace(/[\s\r\n]+/g, '');
  4643. if (/(java|vb)script:/i.test(scriptUrl)) {
  4644. return '';
  4645. }
  4646. if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
  4647. return '';
  4648. }
  4649. }
  4650. if (urlConverter) {
  4651. url = urlConverter.call(urlConverterScope, url, 'style');
  4652. }
  4653. return 'url(\'' + url.replace(/\'/g, '\\\'') + '\')';
  4654. };
  4655. if (css) {
  4656. css = css.replace(/[\u0000-\u001F]/g, '');
  4657. css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function (str) {
  4658. return str.replace(/[;:]/g, encode);
  4659. });
  4660. while (matches = styleRegExp.exec(css)) {
  4661. styleRegExp.lastIndex = matches.index + matches[0].length;
  4662. name = matches[1].replace(trimRightRegExp, '').toLowerCase();
  4663. value = matches[2].replace(trimRightRegExp, '');
  4664. if (name && value) {
  4665. name = decodeHexSequences(name);
  4666. value = decodeHexSequences(value);
  4667. if (name.indexOf(invisibleChar) !== -1 || name.indexOf('"') !== -1) {
  4668. continue;
  4669. }
  4670. if (!settings.allow_script_urls && (name === 'behavior' || /expression\s*\(|\/\*|\*\//.test(value))) {
  4671. continue;
  4672. }
  4673. if (name === 'font-weight' && value === '700') {
  4674. value = 'bold';
  4675. } else if (name === 'color' || name === 'background-color') {
  4676. value = value.toLowerCase();
  4677. }
  4678. value = value.replace(rgbRegExp, toHex);
  4679. value = value.replace(urlOrStrRegExp, processUrl);
  4680. styles[name] = isEncoded ? decode(value, true) : value;
  4681. }
  4682. }
  4683. compress('border', '', true);
  4684. compress('border', '-width');
  4685. compress('border', '-color');
  4686. compress('border', '-style');
  4687. compress('padding', '');
  4688. compress('margin', '');
  4689. compress2('border', 'border-width', 'border-style', 'border-color');
  4690. if (styles.border === 'medium none') {
  4691. delete styles.border;
  4692. }
  4693. if (styles['border-image'] === 'none') {
  4694. delete styles['border-image'];
  4695. }
  4696. }
  4697. return styles;
  4698. },
  4699. serialize: function (styles, elementName) {
  4700. var css = '';
  4701. var serializeStyles = function (name) {
  4702. var value;
  4703. var styleList = validStyles[name];
  4704. if (styleList) {
  4705. for (var i_1 = 0, l = styleList.length; i_1 < l; i_1++) {
  4706. name = styleList[i_1];
  4707. value = styles[name];
  4708. if (value) {
  4709. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4710. }
  4711. }
  4712. }
  4713. };
  4714. var isValid = function (name, elementName) {
  4715. var styleMap = invalidStyles['*'];
  4716. if (styleMap && styleMap[name]) {
  4717. return false;
  4718. }
  4719. styleMap = invalidStyles[elementName];
  4720. return !(styleMap && styleMap[name]);
  4721. };
  4722. if (elementName && validStyles) {
  4723. serializeStyles('*');
  4724. serializeStyles(elementName);
  4725. } else {
  4726. each$1(styles, function (value, name) {
  4727. if (value && (!invalidStyles || isValid(name, elementName))) {
  4728. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4729. }
  4730. });
  4731. }
  4732. return css;
  4733. }
  4734. };
  4735. };
  4736. var eventExpandoPrefix = 'mce-data-';
  4737. var mouseEventRe = /^(?:mouse|contextmenu)|click/;
  4738. var deprecated = {
  4739. keyLocation: 1,
  4740. layerX: 1,
  4741. layerY: 1,
  4742. returnValue: 1,
  4743. webkitMovementX: 1,
  4744. webkitMovementY: 1,
  4745. keyIdentifier: 1,
  4746. mozPressure: 1
  4747. };
  4748. var hasIsDefaultPrevented = function (event) {
  4749. return event.isDefaultPrevented === returnTrue || event.isDefaultPrevented === returnFalse;
  4750. };
  4751. var returnFalse = function () {
  4752. return false;
  4753. };
  4754. var returnTrue = function () {
  4755. return true;
  4756. };
  4757. var addEvent = function (target, name, callback, capture) {
  4758. if (target.addEventListener) {
  4759. target.addEventListener(name, callback, capture || false);
  4760. } else if (target.attachEvent) {
  4761. target.attachEvent('on' + name, callback);
  4762. }
  4763. };
  4764. var removeEvent = function (target, name, callback, capture) {
  4765. if (target.removeEventListener) {
  4766. target.removeEventListener(name, callback, capture || false);
  4767. } else if (target.detachEvent) {
  4768. target.detachEvent('on' + name, callback);
  4769. }
  4770. };
  4771. var isMouseEvent = function (event) {
  4772. return mouseEventRe.test(event.type);
  4773. };
  4774. var fix = function (originalEvent, data) {
  4775. var name;
  4776. var event = data || {};
  4777. for (name in originalEvent) {
  4778. if (!deprecated[name]) {
  4779. event[name] = originalEvent[name];
  4780. }
  4781. }
  4782. if (!event.target) {
  4783. event.target = event.srcElement || document;
  4784. }
  4785. if (event.composedPath) {
  4786. event.composedPath = function () {
  4787. return originalEvent.composedPath();
  4788. };
  4789. }
  4790. if (originalEvent && isMouseEvent(originalEvent) && originalEvent.pageX === undefined && originalEvent.clientX !== undefined) {
  4791. var eventDoc = event.target.ownerDocument || document;
  4792. var doc = eventDoc.documentElement;
  4793. var body = eventDoc.body;
  4794. event.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  4795. event.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  4796. }
  4797. event.preventDefault = function () {
  4798. event.isDefaultPrevented = returnTrue;
  4799. if (originalEvent) {
  4800. if (originalEvent.preventDefault) {
  4801. originalEvent.preventDefault();
  4802. } else {
  4803. originalEvent.returnValue = false;
  4804. }
  4805. }
  4806. };
  4807. event.stopPropagation = function () {
  4808. event.isPropagationStopped = returnTrue;
  4809. if (originalEvent) {
  4810. if (originalEvent.stopPropagation) {
  4811. originalEvent.stopPropagation();
  4812. } else {
  4813. originalEvent.cancelBubble = true;
  4814. }
  4815. }
  4816. };
  4817. event.stopImmediatePropagation = function () {
  4818. event.isImmediatePropagationStopped = returnTrue;
  4819. event.stopPropagation();
  4820. };
  4821. if (hasIsDefaultPrevented(event) === false) {
  4822. event.isDefaultPrevented = returnFalse;
  4823. event.isPropagationStopped = returnFalse;
  4824. event.isImmediatePropagationStopped = returnFalse;
  4825. }
  4826. if (typeof event.metaKey === 'undefined') {
  4827. event.metaKey = false;
  4828. }
  4829. return event;
  4830. };
  4831. var bindOnReady = function (win, callback, eventUtils) {
  4832. var doc = win.document, event = { type: 'ready' };
  4833. if (eventUtils.domLoaded) {
  4834. callback(event);
  4835. return;
  4836. }
  4837. var isDocReady = function () {
  4838. return doc.readyState === 'complete' || doc.readyState === 'interactive' && doc.body;
  4839. };
  4840. var readyHandler = function () {
  4841. removeEvent(win, 'DOMContentLoaded', readyHandler);
  4842. removeEvent(win, 'load', readyHandler);
  4843. if (!eventUtils.domLoaded) {
  4844. eventUtils.domLoaded = true;
  4845. callback(event);
  4846. }
  4847. win = null;
  4848. };
  4849. if (isDocReady()) {
  4850. readyHandler();
  4851. } else {
  4852. addEvent(win, 'DOMContentLoaded', readyHandler);
  4853. }
  4854. if (!eventUtils.domLoaded) {
  4855. addEvent(win, 'load', readyHandler);
  4856. }
  4857. };
  4858. var EventUtils = function () {
  4859. function EventUtils() {
  4860. this.domLoaded = false;
  4861. this.events = {};
  4862. this.count = 1;
  4863. this.expando = eventExpandoPrefix + (+new Date()).toString(32);
  4864. this.hasMouseEnterLeave = 'onmouseenter' in document.documentElement;
  4865. this.hasFocusIn = 'onfocusin' in document.documentElement;
  4866. this.count = 1;
  4867. }
  4868. EventUtils.prototype.bind = function (target, names, callback, scope) {
  4869. var self = this;
  4870. var id, callbackList, i, name, fakeName, nativeHandler, capture;
  4871. var win = window;
  4872. var defaultNativeHandler = function (evt) {
  4873. self.executeHandlers(fix(evt || win.event), id);
  4874. };
  4875. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4876. return;
  4877. }
  4878. if (!target[self.expando]) {
  4879. id = self.count++;
  4880. target[self.expando] = id;
  4881. self.events[id] = {};
  4882. } else {
  4883. id = target[self.expando];
  4884. }
  4885. scope = scope || target;
  4886. var namesList = names.split(' ');
  4887. i = namesList.length;
  4888. while (i--) {
  4889. name = namesList[i];
  4890. nativeHandler = defaultNativeHandler;
  4891. fakeName = capture = false;
  4892. if (name === 'DOMContentLoaded') {
  4893. name = 'ready';
  4894. }
  4895. if (self.domLoaded && name === 'ready' && target.readyState === 'complete') {
  4896. callback.call(scope, fix({ type: name }));
  4897. continue;
  4898. }
  4899. if (!self.hasMouseEnterLeave) {
  4900. fakeName = self.mouseEnterLeave[name];
  4901. if (fakeName) {
  4902. nativeHandler = function (evt) {
  4903. var current = evt.currentTarget;
  4904. var related = evt.relatedTarget;
  4905. if (related && current.contains) {
  4906. related = current.contains(related);
  4907. } else {
  4908. while (related && related !== current) {
  4909. related = related.parentNode;
  4910. }
  4911. }
  4912. if (!related) {
  4913. evt = fix(evt || win.event);
  4914. evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
  4915. evt.target = current;
  4916. self.executeHandlers(evt, id);
  4917. }
  4918. };
  4919. }
  4920. }
  4921. if (!self.hasFocusIn && (name === 'focusin' || name === 'focusout')) {
  4922. capture = true;
  4923. fakeName = name === 'focusin' ? 'focus' : 'blur';
  4924. nativeHandler = function (evt) {
  4925. evt = fix(evt || win.event);
  4926. evt.type = evt.type === 'focus' ? 'focusin' : 'focusout';
  4927. self.executeHandlers(evt, id);
  4928. };
  4929. }
  4930. callbackList = self.events[id][name];
  4931. if (!callbackList) {
  4932. self.events[id][name] = callbackList = [{
  4933. func: callback,
  4934. scope: scope
  4935. }];
  4936. callbackList.fakeName = fakeName;
  4937. callbackList.capture = capture;
  4938. callbackList.nativeHandler = nativeHandler;
  4939. if (name === 'ready') {
  4940. bindOnReady(target, nativeHandler, self);
  4941. } else {
  4942. addEvent(target, fakeName || name, nativeHandler, capture);
  4943. }
  4944. } else {
  4945. if (name === 'ready' && self.domLoaded) {
  4946. callback(fix({ type: name }));
  4947. } else {
  4948. callbackList.push({
  4949. func: callback,
  4950. scope: scope
  4951. });
  4952. }
  4953. }
  4954. }
  4955. target = callbackList = null;
  4956. return callback;
  4957. };
  4958. EventUtils.prototype.unbind = function (target, names, callback) {
  4959. var callbackList, i, ci, name, eventMap;
  4960. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4961. return this;
  4962. }
  4963. var id = target[this.expando];
  4964. if (id) {
  4965. eventMap = this.events[id];
  4966. if (names) {
  4967. var namesList = names.split(' ');
  4968. i = namesList.length;
  4969. while (i--) {
  4970. name = namesList[i];
  4971. callbackList = eventMap[name];
  4972. if (callbackList) {
  4973. if (callback) {
  4974. ci = callbackList.length;
  4975. while (ci--) {
  4976. if (callbackList[ci].func === callback) {
  4977. var nativeHandler = callbackList.nativeHandler;
  4978. var fakeName = callbackList.fakeName, capture = callbackList.capture;
  4979. callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
  4980. callbackList.nativeHandler = nativeHandler;
  4981. callbackList.fakeName = fakeName;
  4982. callbackList.capture = capture;
  4983. eventMap[name] = callbackList;
  4984. }
  4985. }
  4986. }
  4987. if (!callback || callbackList.length === 0) {
  4988. delete eventMap[name];
  4989. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  4990. }
  4991. }
  4992. }
  4993. } else {
  4994. each$1(eventMap, function (callbackList, name) {
  4995. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  4996. });
  4997. eventMap = {};
  4998. }
  4999. for (name in eventMap) {
  5000. if (has(eventMap, name)) {
  5001. return this;
  5002. }
  5003. }
  5004. delete this.events[id];
  5005. try {
  5006. delete target[this.expando];
  5007. } catch (ex) {
  5008. target[this.expando] = null;
  5009. }
  5010. }
  5011. return this;
  5012. };
  5013. EventUtils.prototype.fire = function (target, name, args) {
  5014. var id;
  5015. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  5016. return this;
  5017. }
  5018. var event = fix(null, args);
  5019. event.type = name;
  5020. event.target = target;
  5021. do {
  5022. id = target[this.expando];
  5023. if (id) {
  5024. this.executeHandlers(event, id);
  5025. }
  5026. target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
  5027. } while (target && !event.isPropagationStopped());
  5028. return this;
  5029. };
  5030. EventUtils.prototype.clean = function (target) {
  5031. var i, children;
  5032. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  5033. return this;
  5034. }
  5035. if (target[this.expando]) {
  5036. this.unbind(target);
  5037. }
  5038. if (!target.getElementsByTagName) {
  5039. target = target.document;
  5040. }
  5041. if (target && target.getElementsByTagName) {
  5042. this.unbind(target);
  5043. children = target.getElementsByTagName('*');
  5044. i = children.length;
  5045. while (i--) {
  5046. target = children[i];
  5047. if (target[this.expando]) {
  5048. this.unbind(target);
  5049. }
  5050. }
  5051. }
  5052. return this;
  5053. };
  5054. EventUtils.prototype.destroy = function () {
  5055. this.events = {};
  5056. };
  5057. EventUtils.prototype.cancel = function (e) {
  5058. if (e) {
  5059. e.preventDefault();
  5060. e.stopImmediatePropagation();
  5061. }
  5062. return false;
  5063. };
  5064. EventUtils.prototype.executeHandlers = function (evt, id) {
  5065. var container = this.events[id];
  5066. var callbackList = container && container[evt.type];
  5067. if (callbackList) {
  5068. for (var i = 0, l = callbackList.length; i < l; i++) {
  5069. var callback = callbackList[i];
  5070. if (callback && callback.func.call(callback.scope, evt) === false) {
  5071. evt.preventDefault();
  5072. }
  5073. if (evt.isImmediatePropagationStopped()) {
  5074. return;
  5075. }
  5076. }
  5077. }
  5078. };
  5079. EventUtils.Event = new EventUtils();
  5080. return EventUtils;
  5081. }();
  5082. 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) {
  5083. if (a === b) {
  5084. hasDuplicate = true;
  5085. }
  5086. return 0;
  5087. }, 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) {
  5088. var i = 0, len = this.length;
  5089. for (; i < len; i++) {
  5090. if (this[i] === elem) {
  5091. return i;
  5092. }
  5093. }
  5094. return -1;
  5095. }, 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 = {
  5096. ID: new RegExp('^#(' + identifier + ')'),
  5097. CLASS: new RegExp('^\\.(' + identifier + ')'),
  5098. TAG: new RegExp('^(' + identifier + '|[*])'),
  5099. ATTR: new RegExp('^' + attributes),
  5100. PSEUDO: new RegExp('^' + pseudos),
  5101. CHILD: new RegExp('^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(' + whitespace + '*(even|odd|(([+-]|)(\\d*)n|)' + whitespace + '*(?:([+-]|)' + whitespace + '*(\\d+)|))' + whitespace + '*\\)|)', 'i'),
  5102. bool: new RegExp('^(?:' + booleans + ')$', 'i'),
  5103. needsContext: new RegExp('^' + whitespace + '*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(' + whitespace + '*((?:-\\d)?\\d*)' + whitespace + '*\\)|)(?=[^-]|$)', 'i')
  5104. }, 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) {
  5105. var high = '0x' + escaped - 65536;
  5106. return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320);
  5107. };
  5108. try {
  5109. push.apply(arr = slice.call(preferredDoc.childNodes), preferredDoc.childNodes);
  5110. arr[preferredDoc.childNodes.length].nodeType;
  5111. } catch (e) {
  5112. push = {
  5113. apply: arr.length ? function (target, els) {
  5114. push_native.apply(target, slice.call(els));
  5115. } : function (target, els) {
  5116. var j = target.length, i = 0;
  5117. while (target[j++] = els[i++]) {
  5118. }
  5119. target.length = j - 1;
  5120. }
  5121. };
  5122. }
  5123. var Sizzle = function (selector, context, results, seed) {
  5124. var match, elem, m, nodeType, i, groups, old, nid, newContext, newSelector;
  5125. if ((context ? context.ownerDocument || context : preferredDoc) !== document$1) {
  5126. setDocument(context);
  5127. }
  5128. context = context || document$1;
  5129. results = results || [];
  5130. if (!selector || typeof selector !== 'string') {
  5131. return results;
  5132. }
  5133. if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) {
  5134. return [];
  5135. }
  5136. if (documentIsHTML && !seed) {
  5137. if (match = rquickExpr.exec(selector)) {
  5138. if (m = match[1]) {
  5139. if (nodeType === 9) {
  5140. elem = context.getElementById(m);
  5141. if (elem && elem.parentNode) {
  5142. if (elem.id === m) {
  5143. results.push(elem);
  5144. return results;
  5145. }
  5146. } else {
  5147. return results;
  5148. }
  5149. } else {
  5150. if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains$3(context, elem) && elem.id === m) {
  5151. results.push(elem);
  5152. return results;
  5153. }
  5154. }
  5155. } else if (match[2]) {
  5156. push.apply(results, context.getElementsByTagName(selector));
  5157. return results;
  5158. } else if ((m = match[3]) && support.getElementsByClassName) {
  5159. push.apply(results, context.getElementsByClassName(m));
  5160. return results;
  5161. }
  5162. }
  5163. if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
  5164. nid = old = expando;
  5165. newContext = context;
  5166. newSelector = nodeType === 9 && selector;
  5167. if (nodeType === 1 && context.nodeName.toLowerCase() !== 'object') {
  5168. groups = tokenize(selector);
  5169. if (old = context.getAttribute('id')) {
  5170. nid = old.replace(rescape, '\\$&');
  5171. } else {
  5172. context.setAttribute('id', nid);
  5173. }
  5174. nid = '[id=\'' + nid + '\'] ';
  5175. i = groups.length;
  5176. while (i--) {
  5177. groups[i] = nid + toSelector(groups[i]);
  5178. }
  5179. newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
  5180. newSelector = groups.join(',');
  5181. }
  5182. if (newSelector) {
  5183. try {
  5184. push.apply(results, newContext.querySelectorAll(newSelector));
  5185. return results;
  5186. } catch (qsaError) {
  5187. } finally {
  5188. if (!old) {
  5189. context.removeAttribute('id');
  5190. }
  5191. }
  5192. }
  5193. }
  5194. }
  5195. return select(selector.replace(rtrim, '$1'), context, results, seed);
  5196. };
  5197. function createCache() {
  5198. var keys = [];
  5199. function cache(key, value) {
  5200. if (keys.push(key + ' ') > Expr.cacheLength) {
  5201. delete cache[keys.shift()];
  5202. }
  5203. return cache[key + ' '] = value;
  5204. }
  5205. return cache;
  5206. }
  5207. function markFunction(fn) {
  5208. fn[expando] = true;
  5209. return fn;
  5210. }
  5211. function siblingCheck(a, b) {
  5212. var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && (~b.sourceIndex || MAX_NEGATIVE) - (~a.sourceIndex || MAX_NEGATIVE);
  5213. if (diff) {
  5214. return diff;
  5215. }
  5216. if (cur) {
  5217. while (cur = cur.nextSibling) {
  5218. if (cur === b) {
  5219. return -1;
  5220. }
  5221. }
  5222. }
  5223. return a ? 1 : -1;
  5224. }
  5225. function createInputPseudo(type) {
  5226. return function (elem) {
  5227. var name = elem.nodeName.toLowerCase();
  5228. return name === 'input' && elem.type === type;
  5229. };
  5230. }
  5231. function createButtonPseudo(type) {
  5232. return function (elem) {
  5233. var name = elem.nodeName.toLowerCase();
  5234. return (name === 'input' || name === 'button') && elem.type === type;
  5235. };
  5236. }
  5237. function createPositionalPseudo(fn) {
  5238. return markFunction(function (argument) {
  5239. argument = +argument;
  5240. return markFunction(function (seed, matches) {
  5241. var j, matchIndexes = fn([], seed.length, argument), i = matchIndexes.length;
  5242. while (i--) {
  5243. if (seed[j = matchIndexes[i]]) {
  5244. seed[j] = !(matches[j] = seed[j]);
  5245. }
  5246. }
  5247. });
  5248. });
  5249. }
  5250. function testContext(context) {
  5251. return context && typeof context.getElementsByTagName !== strundefined && context;
  5252. }
  5253. support = Sizzle.support = {};
  5254. isXML = Sizzle.isXML = function (elem) {
  5255. var documentElement = elem && (elem.ownerDocument || elem).documentElement;
  5256. return documentElement ? documentElement.nodeName !== 'HTML' : false;
  5257. };
  5258. setDocument = Sizzle.setDocument = function (node) {
  5259. var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView;
  5260. function getTop(win) {
  5261. try {
  5262. return win.top;
  5263. } catch (ex) {
  5264. }
  5265. return null;
  5266. }
  5267. if (doc === document$1 || doc.nodeType !== 9 || !doc.documentElement) {
  5268. return document$1;
  5269. }
  5270. document$1 = doc;
  5271. docElem = doc.documentElement;
  5272. documentIsHTML = !isXML(doc);
  5273. if (parent && parent !== getTop(parent)) {
  5274. if (parent.addEventListener) {
  5275. parent.addEventListener('unload', function () {
  5276. setDocument();
  5277. }, false);
  5278. } else if (parent.attachEvent) {
  5279. parent.attachEvent('onunload', function () {
  5280. setDocument();
  5281. });
  5282. }
  5283. }
  5284. support.attributes = true;
  5285. support.getElementsByTagName = true;
  5286. support.getElementsByClassName = rnative.test(doc.getElementsByClassName);
  5287. support.getById = true;
  5288. Expr.find.ID = function (id, context) {
  5289. if (typeof context.getElementById !== strundefined && documentIsHTML) {
  5290. var m = context.getElementById(id);
  5291. return m && m.parentNode ? [m] : [];
  5292. }
  5293. };
  5294. Expr.filter.ID = function (id) {
  5295. var attrId = id.replace(runescape, funescape);
  5296. return function (elem) {
  5297. return elem.getAttribute('id') === attrId;
  5298. };
  5299. };
  5300. Expr.find.TAG = support.getElementsByTagName ? function (tag, context) {
  5301. if (typeof context.getElementsByTagName !== strundefined) {
  5302. return context.getElementsByTagName(tag);
  5303. }
  5304. } : function (tag, context) {
  5305. var elem, tmp = [], i = 0, results = context.getElementsByTagName(tag);
  5306. if (tag === '*') {
  5307. while (elem = results[i++]) {
  5308. if (elem.nodeType === 1) {
  5309. tmp.push(elem);
  5310. }
  5311. }
  5312. return tmp;
  5313. }
  5314. return results;
  5315. };
  5316. Expr.find.CLASS = support.getElementsByClassName && function (className, context) {
  5317. if (documentIsHTML) {
  5318. return context.getElementsByClassName(className);
  5319. }
  5320. };
  5321. rbuggyMatches = [];
  5322. rbuggyQSA = [];
  5323. support.disconnectedMatch = true;
  5324. rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join('|'));
  5325. rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join('|'));
  5326. hasCompare = rnative.test(docElem.compareDocumentPosition);
  5327. contains$3 = hasCompare || rnative.test(docElem.contains) ? function (a, b) {
  5328. var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode;
  5329. return a === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
  5330. } : function (a, b) {
  5331. if (b) {
  5332. while (b = b.parentNode) {
  5333. if (b === a) {
  5334. return true;
  5335. }
  5336. }
  5337. }
  5338. return false;
  5339. };
  5340. sortOrder = hasCompare ? function (a, b) {
  5341. if (a === b) {
  5342. hasDuplicate = true;
  5343. return 0;
  5344. }
  5345. var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
  5346. if (compare) {
  5347. return compare;
  5348. }
  5349. compare = (a.ownerDocument || a) === (b.ownerDocument || b) ? a.compareDocumentPosition(b) : 1;
  5350. if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {
  5351. if (a === doc || a.ownerDocument === preferredDoc && contains$3(preferredDoc, a)) {
  5352. return -1;
  5353. }
  5354. if (b === doc || b.ownerDocument === preferredDoc && contains$3(preferredDoc, b)) {
  5355. return 1;
  5356. }
  5357. return sortInput ? indexOf$2.call(sortInput, a) - indexOf$2.call(sortInput, b) : 0;
  5358. }
  5359. return compare & 4 ? -1 : 1;
  5360. } : function (a, b) {
  5361. if (a === b) {
  5362. hasDuplicate = true;
  5363. return 0;
  5364. }
  5365. var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [a], bp = [b];
  5366. if (!aup || !bup) {
  5367. return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf$2.call(sortInput, a) - indexOf$2.call(sortInput, b) : 0;
  5368. } else if (aup === bup) {
  5369. return siblingCheck(a, b);
  5370. }
  5371. cur = a;
  5372. while (cur = cur.parentNode) {
  5373. ap.unshift(cur);
  5374. }
  5375. cur = b;
  5376. while (cur = cur.parentNode) {
  5377. bp.unshift(cur);
  5378. }
  5379. while (ap[i] === bp[i]) {
  5380. i++;
  5381. }
  5382. return i ? siblingCheck(ap[i], bp[i]) : ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0;
  5383. };
  5384. return doc;
  5385. };
  5386. Sizzle.matches = function (expr, elements) {
  5387. return Sizzle(expr, null, null, elements);
  5388. };
  5389. Sizzle.matchesSelector = function (elem, expr) {
  5390. if ((elem.ownerDocument || elem) !== document$1) {
  5391. setDocument(elem);
  5392. }
  5393. expr = expr.replace(rattributeQuotes, '=\'$1\']');
  5394. if (support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
  5395. try {
  5396. var ret = matches.call(elem, expr);
  5397. if (ret || support.disconnectedMatch || elem.document && elem.document.nodeType !== 11) {
  5398. return ret;
  5399. }
  5400. } catch (e) {
  5401. }
  5402. }
  5403. return Sizzle(expr, document$1, null, [elem]).length > 0;
  5404. };
  5405. Sizzle.contains = function (context, elem) {
  5406. if ((context.ownerDocument || context) !== document$1) {
  5407. setDocument(context);
  5408. }
  5409. return contains$3(context, elem);
  5410. };
  5411. Sizzle.attr = function (elem, name) {
  5412. if ((elem.ownerDocument || elem) !== document$1) {
  5413. setDocument(elem);
  5414. }
  5415. var fn = Expr.attrHandle[name.toLowerCase()], val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;
  5416. return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
  5417. };
  5418. Sizzle.error = function (msg) {
  5419. throw new Error('Syntax error, unrecognized expression: ' + msg);
  5420. };
  5421. Sizzle.uniqueSort = function (results) {
  5422. var elem, duplicates = [], j = 0, i = 0;
  5423. hasDuplicate = !support.detectDuplicates;
  5424. sortInput = !support.sortStable && results.slice(0);
  5425. results.sort(sortOrder);
  5426. if (hasDuplicate) {
  5427. while (elem = results[i++]) {
  5428. if (elem === results[i]) {
  5429. j = duplicates.push(i);
  5430. }
  5431. }
  5432. while (j--) {
  5433. results.splice(duplicates[j], 1);
  5434. }
  5435. }
  5436. sortInput = null;
  5437. return results;
  5438. };
  5439. getText = Sizzle.getText = function (elem) {
  5440. var node, ret = '', i = 0, nodeType = elem.nodeType;
  5441. if (!nodeType) {
  5442. while (node = elem[i++]) {
  5443. ret += getText(node);
  5444. }
  5445. } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
  5446. if (typeof elem.textContent === 'string') {
  5447. return elem.textContent;
  5448. } else {
  5449. for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5450. ret += getText(elem);
  5451. }
  5452. }
  5453. } else if (nodeType === 3 || nodeType === 4) {
  5454. return elem.nodeValue;
  5455. }
  5456. return ret;
  5457. };
  5458. Expr = Sizzle.selectors = {
  5459. cacheLength: 50,
  5460. createPseudo: markFunction,
  5461. match: matchExpr,
  5462. attrHandle: {},
  5463. find: {},
  5464. relative: {
  5465. '>': {
  5466. dir: 'parentNode',
  5467. first: true
  5468. },
  5469. ' ': { dir: 'parentNode' },
  5470. '+': {
  5471. dir: 'previousSibling',
  5472. first: true
  5473. },
  5474. '~': { dir: 'previousSibling' }
  5475. },
  5476. preFilter: {
  5477. ATTR: function (match) {
  5478. match[1] = match[1].replace(runescape, funescape);
  5479. match[3] = (match[3] || match[4] || match[5] || '').replace(runescape, funescape);
  5480. if (match[2] === '~=') {
  5481. match[3] = ' ' + match[3] + ' ';
  5482. }
  5483. return match.slice(0, 4);
  5484. },
  5485. CHILD: function (match) {
  5486. match[1] = match[1].toLowerCase();
  5487. if (match[1].slice(0, 3) === 'nth') {
  5488. if (!match[3]) {
  5489. Sizzle.error(match[0]);
  5490. }
  5491. match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === 'even' || match[3] === 'odd'));
  5492. match[5] = +(match[7] + match[8] || match[3] === 'odd');
  5493. } else if (match[3]) {
  5494. Sizzle.error(match[0]);
  5495. }
  5496. return match;
  5497. },
  5498. PSEUDO: function (match) {
  5499. var excess, unquoted = !match[6] && match[2];
  5500. if (matchExpr.CHILD.test(match[0])) {
  5501. return null;
  5502. }
  5503. if (match[3]) {
  5504. match[2] = match[4] || match[5] || '';
  5505. } else if (unquoted && rpseudo.test(unquoted) && (excess = tokenize(unquoted, true)) && (excess = unquoted.indexOf(')', unquoted.length - excess) - unquoted.length)) {
  5506. match[0] = match[0].slice(0, excess);
  5507. match[2] = unquoted.slice(0, excess);
  5508. }
  5509. return match.slice(0, 3);
  5510. }
  5511. },
  5512. filter: {
  5513. TAG: function (nodeNameSelector) {
  5514. var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
  5515. return nodeNameSelector === '*' ? function () {
  5516. return true;
  5517. } : function (elem) {
  5518. return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
  5519. };
  5520. },
  5521. CLASS: function (className) {
  5522. var pattern = classCache[className + ' '];
  5523. return pattern || (pattern = new RegExp('(^|' + whitespace + ')' + className + '(' + whitespace + '|$)')) && classCache(className, function (elem) {
  5524. return pattern.test(typeof elem.className === 'string' && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute('class') || '');
  5525. });
  5526. },
  5527. ATTR: function (name, operator, check) {
  5528. return function (elem) {
  5529. var result = Sizzle.attr(elem, name);
  5530. if (result == null) {
  5531. return operator === '!=';
  5532. }
  5533. if (!operator) {
  5534. return true;
  5535. }
  5536. result += '';
  5537. 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;
  5538. };
  5539. },
  5540. CHILD: function (type, what, argument, first, last) {
  5541. var simple = type.slice(0, 3) !== 'nth', forward = type.slice(-4) !== 'last', ofType = what === 'of-type';
  5542. return first === 1 && last === 0 ? function (elem) {
  5543. return !!elem.parentNode;
  5544. } : function (elem, context, xml) {
  5545. var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? 'nextSibling' : 'previousSibling', parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType;
  5546. if (parent) {
  5547. if (simple) {
  5548. while (dir) {
  5549. node = elem;
  5550. while (node = node[dir]) {
  5551. if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
  5552. return false;
  5553. }
  5554. }
  5555. start = dir = type === 'only' && !start && 'nextSibling';
  5556. }
  5557. return true;
  5558. }
  5559. start = [forward ? parent.firstChild : parent.lastChild];
  5560. if (forward && useCache) {
  5561. outerCache = parent[expando] || (parent[expando] = {});
  5562. cache = outerCache[type] || [];
  5563. nodeIndex = cache[0] === dirruns && cache[1];
  5564. diff = cache[0] === dirruns && cache[2];
  5565. node = nodeIndex && parent.childNodes[nodeIndex];
  5566. while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5567. if (node.nodeType === 1 && ++diff && node === elem) {
  5568. outerCache[type] = [
  5569. dirruns,
  5570. nodeIndex,
  5571. diff
  5572. ];
  5573. break;
  5574. }
  5575. }
  5576. } else if (useCache && (cache = (elem[expando] || (elem[expando] = {}))[type]) && cache[0] === dirruns) {
  5577. diff = cache[1];
  5578. } else {
  5579. while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5580. if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) {
  5581. if (useCache) {
  5582. (node[expando] || (node[expando] = {}))[type] = [
  5583. dirruns,
  5584. diff
  5585. ];
  5586. }
  5587. if (node === elem) {
  5588. break;
  5589. }
  5590. }
  5591. }
  5592. }
  5593. diff -= last;
  5594. return diff === first || diff % first === 0 && diff / first >= 0;
  5595. }
  5596. };
  5597. },
  5598. PSEUDO: function (pseudo, argument) {
  5599. var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error('unsupported pseudo: ' + pseudo);
  5600. if (fn[expando]) {
  5601. return fn(argument);
  5602. }
  5603. if (fn.length > 1) {
  5604. args = [
  5605. pseudo,
  5606. pseudo,
  5607. '',
  5608. argument
  5609. ];
  5610. return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) {
  5611. var idx, matched = fn(seed, argument), i = matched.length;
  5612. while (i--) {
  5613. idx = indexOf$2.call(seed, matched[i]);
  5614. seed[idx] = !(matches[idx] = matched[i]);
  5615. }
  5616. }) : function (elem) {
  5617. return fn(elem, 0, args);
  5618. };
  5619. }
  5620. return fn;
  5621. }
  5622. },
  5623. pseudos: {
  5624. not: markFunction(function (selector) {
  5625. var input = [], results = [], matcher = compile(selector.replace(rtrim, '$1'));
  5626. return matcher[expando] ? markFunction(function (seed, matches, context, xml) {
  5627. var elem, unmatched = matcher(seed, null, xml, []), i = seed.length;
  5628. while (i--) {
  5629. if (elem = unmatched[i]) {
  5630. seed[i] = !(matches[i] = elem);
  5631. }
  5632. }
  5633. }) : function (elem, context, xml) {
  5634. input[0] = elem;
  5635. matcher(input, null, xml, results);
  5636. return !results.pop();
  5637. };
  5638. }),
  5639. has: markFunction(function (selector) {
  5640. return function (elem) {
  5641. return Sizzle(selector, elem).length > 0;
  5642. };
  5643. }),
  5644. contains: markFunction(function (text) {
  5645. text = text.replace(runescape, funescape);
  5646. return function (elem) {
  5647. return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1;
  5648. };
  5649. }),
  5650. lang: markFunction(function (lang) {
  5651. if (!ridentifier.test(lang || '')) {
  5652. Sizzle.error('unsupported lang: ' + lang);
  5653. }
  5654. lang = lang.replace(runescape, funescape).toLowerCase();
  5655. return function (elem) {
  5656. var elemLang;
  5657. do {
  5658. if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute('xml:lang') || elem.getAttribute('lang')) {
  5659. elemLang = elemLang.toLowerCase();
  5660. return elemLang === lang || elemLang.indexOf(lang + '-') === 0;
  5661. }
  5662. } while ((elem = elem.parentNode) && elem.nodeType === 1);
  5663. return false;
  5664. };
  5665. }),
  5666. target: function (elem) {
  5667. var hash = window.location && window.location.hash;
  5668. return hash && hash.slice(1) === elem.id;
  5669. },
  5670. root: function (elem) {
  5671. return elem === docElem;
  5672. },
  5673. focus: function (elem) {
  5674. return elem === document$1.activeElement && (!document$1.hasFocus || document$1.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
  5675. },
  5676. enabled: function (elem) {
  5677. return elem.disabled === false;
  5678. },
  5679. disabled: function (elem) {
  5680. return elem.disabled === true;
  5681. },
  5682. checked: function (elem) {
  5683. var nodeName = elem.nodeName.toLowerCase();
  5684. return nodeName === 'input' && !!elem.checked || nodeName === 'option' && !!elem.selected;
  5685. },
  5686. selected: function (elem) {
  5687. if (elem.parentNode) {
  5688. elem.parentNode.selectedIndex;
  5689. }
  5690. return elem.selected === true;
  5691. },
  5692. empty: function (elem) {
  5693. for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5694. if (elem.nodeType < 6) {
  5695. return false;
  5696. }
  5697. }
  5698. return true;
  5699. },
  5700. parent: function (elem) {
  5701. return !Expr.pseudos.empty(elem);
  5702. },
  5703. header: function (elem) {
  5704. return rheader.test(elem.nodeName);
  5705. },
  5706. input: function (elem) {
  5707. return rinputs.test(elem.nodeName);
  5708. },
  5709. button: function (elem) {
  5710. var name = elem.nodeName.toLowerCase();
  5711. return name === 'input' && elem.type === 'button' || name === 'button';
  5712. },
  5713. text: function (elem) {
  5714. var attr;
  5715. return elem.nodeName.toLowerCase() === 'input' && elem.type === 'text' && ((attr = elem.getAttribute('type')) == null || attr.toLowerCase() === 'text');
  5716. },
  5717. first: createPositionalPseudo(function () {
  5718. return [0];
  5719. }),
  5720. last: createPositionalPseudo(function (matchIndexes, length) {
  5721. return [length - 1];
  5722. }),
  5723. eq: createPositionalPseudo(function (matchIndexes, length, argument) {
  5724. return [argument < 0 ? argument + length : argument];
  5725. }),
  5726. even: createPositionalPseudo(function (matchIndexes, length) {
  5727. var i = 0;
  5728. for (; i < length; i += 2) {
  5729. matchIndexes.push(i);
  5730. }
  5731. return matchIndexes;
  5732. }),
  5733. odd: createPositionalPseudo(function (matchIndexes, length) {
  5734. var i = 1;
  5735. for (; i < length; i += 2) {
  5736. matchIndexes.push(i);
  5737. }
  5738. return matchIndexes;
  5739. }),
  5740. lt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5741. var i = argument < 0 ? argument + length : argument;
  5742. for (; --i >= 0;) {
  5743. matchIndexes.push(i);
  5744. }
  5745. return matchIndexes;
  5746. }),
  5747. gt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5748. var i = argument < 0 ? argument + length : argument;
  5749. for (; ++i < length;) {
  5750. matchIndexes.push(i);
  5751. }
  5752. return matchIndexes;
  5753. })
  5754. }
  5755. };
  5756. Expr.pseudos.nth = Expr.pseudos.eq;
  5757. each([
  5758. 'radio',
  5759. 'checkbox',
  5760. 'file',
  5761. 'password',
  5762. 'image'
  5763. ], function (i) {
  5764. Expr.pseudos[i] = createInputPseudo(i);
  5765. });
  5766. each([
  5767. 'submit',
  5768. 'reset'
  5769. ], function (i) {
  5770. Expr.pseudos[i] = createButtonPseudo(i);
  5771. });
  5772. function setFilters() {
  5773. }
  5774. setFilters.prototype = Expr.filters = Expr.pseudos;
  5775. Expr.setFilters = new setFilters();
  5776. tokenize = Sizzle.tokenize = function (selector, parseOnly) {
  5777. var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + ' '];
  5778. if (cached) {
  5779. return parseOnly ? 0 : cached.slice(0);
  5780. }
  5781. soFar = selector;
  5782. groups = [];
  5783. preFilters = Expr.preFilter;
  5784. while (soFar) {
  5785. if (!matched || (match = rcomma.exec(soFar))) {
  5786. if (match) {
  5787. soFar = soFar.slice(match[0].length) || soFar;
  5788. }
  5789. groups.push(tokens = []);
  5790. }
  5791. matched = false;
  5792. if (match = rcombinators.exec(soFar)) {
  5793. matched = match.shift();
  5794. tokens.push({
  5795. value: matched,
  5796. type: match[0].replace(rtrim, ' ')
  5797. });
  5798. soFar = soFar.slice(matched.length);
  5799. }
  5800. for (type in Expr.filter) {
  5801. if (!Expr.filter.hasOwnProperty(type)) {
  5802. continue;
  5803. }
  5804. if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) {
  5805. matched = match.shift();
  5806. tokens.push({
  5807. value: matched,
  5808. type: type,
  5809. matches: match
  5810. });
  5811. soFar = soFar.slice(matched.length);
  5812. }
  5813. }
  5814. if (!matched) {
  5815. break;
  5816. }
  5817. }
  5818. return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : tokenCache(selector, groups).slice(0);
  5819. };
  5820. function toSelector(tokens) {
  5821. var i = 0, len = tokens.length, selector = '';
  5822. for (; i < len; i++) {
  5823. selector += tokens[i].value;
  5824. }
  5825. return selector;
  5826. }
  5827. function addCombinator(matcher, combinator, base) {
  5828. var dir = combinator.dir, checkNonElements = base && dir === 'parentNode', doneName = done++;
  5829. return combinator.first ? function (elem, context, xml) {
  5830. while (elem = elem[dir]) {
  5831. if (elem.nodeType === 1 || checkNonElements) {
  5832. return matcher(elem, context, xml);
  5833. }
  5834. }
  5835. } : function (elem, context, xml) {
  5836. var oldCache, outerCache, newCache = [
  5837. dirruns,
  5838. doneName
  5839. ];
  5840. if (xml) {
  5841. while (elem = elem[dir]) {
  5842. if (elem.nodeType === 1 || checkNonElements) {
  5843. if (matcher(elem, context, xml)) {
  5844. return true;
  5845. }
  5846. }
  5847. }
  5848. } else {
  5849. while (elem = elem[dir]) {
  5850. if (elem.nodeType === 1 || checkNonElements) {
  5851. outerCache = elem[expando] || (elem[expando] = {});
  5852. if ((oldCache = outerCache[dir]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
  5853. return newCache[2] = oldCache[2];
  5854. } else {
  5855. outerCache[dir] = newCache;
  5856. if (newCache[2] = matcher(elem, context, xml)) {
  5857. return true;
  5858. }
  5859. }
  5860. }
  5861. }
  5862. }
  5863. };
  5864. }
  5865. function elementMatcher(matchers) {
  5866. return matchers.length > 1 ? function (elem, context, xml) {
  5867. var i = matchers.length;
  5868. while (i--) {
  5869. if (!matchers[i](elem, context, xml)) {
  5870. return false;
  5871. }
  5872. }
  5873. return true;
  5874. } : matchers[0];
  5875. }
  5876. function multipleContexts(selector, contexts, results) {
  5877. var i = 0, len = contexts.length;
  5878. for (; i < len; i++) {
  5879. Sizzle(selector, contexts[i], results);
  5880. }
  5881. return results;
  5882. }
  5883. function condense(unmatched, map, filter, context, xml) {
  5884. var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null;
  5885. for (; i < len; i++) {
  5886. if (elem = unmatched[i]) {
  5887. if (!filter || filter(elem, context, xml)) {
  5888. newUnmatched.push(elem);
  5889. if (mapped) {
  5890. map.push(i);
  5891. }
  5892. }
  5893. }
  5894. }
  5895. return newUnmatched;
  5896. }
  5897. function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
  5898. if (postFilter && !postFilter[expando]) {
  5899. postFilter = setMatcher(postFilter);
  5900. }
  5901. if (postFinder && !postFinder[expando]) {
  5902. postFinder = setMatcher(postFinder, postSelector);
  5903. }
  5904. return markFunction(function (seed, results, context, xml) {
  5905. 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;
  5906. if (matcher) {
  5907. matcher(matcherIn, matcherOut, context, xml);
  5908. }
  5909. if (postFilter) {
  5910. temp = condense(matcherOut, postMap);
  5911. postFilter(temp, [], context, xml);
  5912. i = temp.length;
  5913. while (i--) {
  5914. if (elem = temp[i]) {
  5915. matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
  5916. }
  5917. }
  5918. }
  5919. if (seed) {
  5920. if (postFinder || preFilter) {
  5921. if (postFinder) {
  5922. temp = [];
  5923. i = matcherOut.length;
  5924. while (i--) {
  5925. if (elem = matcherOut[i]) {
  5926. temp.push(matcherIn[i] = elem);
  5927. }
  5928. }
  5929. postFinder(null, matcherOut = [], temp, xml);
  5930. }
  5931. i = matcherOut.length;
  5932. while (i--) {
  5933. if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf$2.call(seed, elem) : preMap[i]) > -1) {
  5934. seed[temp] = !(results[temp] = elem);
  5935. }
  5936. }
  5937. }
  5938. } else {
  5939. matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
  5940. if (postFinder) {
  5941. postFinder(null, results, matcherOut, xml);
  5942. } else {
  5943. push.apply(results, matcherOut);
  5944. }
  5945. }
  5946. });
  5947. }
  5948. function matcherFromTokens(tokens) {
  5949. 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) {
  5950. return elem === checkContext;
  5951. }, implicitRelative, true), matchAnyContext = addCombinator(function (elem) {
  5952. return indexOf$2.call(checkContext, elem) > -1;
  5953. }, implicitRelative, true), matchers = [function (elem, context, xml) {
  5954. return !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
  5955. }];
  5956. for (; i < len; i++) {
  5957. if (matcher = Expr.relative[tokens[i].type]) {
  5958. matchers = [addCombinator(elementMatcher(matchers), matcher)];
  5959. } else {
  5960. matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);
  5961. if (matcher[expando]) {
  5962. j = ++i;
  5963. for (; j < len; j++) {
  5964. if (Expr.relative[tokens[j].type]) {
  5965. break;
  5966. }
  5967. }
  5968. 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));
  5969. }
  5970. matchers.push(matcher);
  5971. }
  5972. }
  5973. return elementMatcher(matchers);
  5974. }
  5975. function matcherFromGroupMatchers(elementMatchers, setMatchers) {
  5976. var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function (seed, context, xml, results, outermost) {
  5977. 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;
  5978. if (outermost) {
  5979. outermostContext = context !== document$1 && context;
  5980. }
  5981. for (; i !== len && (elem = elems[i]) != null; i++) {
  5982. if (byElement && elem) {
  5983. j = 0;
  5984. while (matcher = elementMatchers[j++]) {
  5985. if (matcher(elem, context, xml)) {
  5986. results.push(elem);
  5987. break;
  5988. }
  5989. }
  5990. if (outermost) {
  5991. dirruns = dirrunsUnique;
  5992. }
  5993. }
  5994. if (bySet) {
  5995. if (elem = !matcher && elem) {
  5996. matchedCount--;
  5997. }
  5998. if (seed) {
  5999. unmatched.push(elem);
  6000. }
  6001. }
  6002. }
  6003. matchedCount += i;
  6004. if (bySet && i !== matchedCount) {
  6005. j = 0;
  6006. while (matcher = setMatchers[j++]) {
  6007. matcher(unmatched, setMatched, context, xml);
  6008. }
  6009. if (seed) {
  6010. if (matchedCount > 0) {
  6011. while (i--) {
  6012. if (!(unmatched[i] || setMatched[i])) {
  6013. setMatched[i] = pop.call(results);
  6014. }
  6015. }
  6016. }
  6017. setMatched = condense(setMatched);
  6018. }
  6019. push.apply(results, setMatched);
  6020. if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
  6021. Sizzle.uniqueSort(results);
  6022. }
  6023. }
  6024. if (outermost) {
  6025. dirruns = dirrunsUnique;
  6026. outermostContext = contextBackup;
  6027. }
  6028. return unmatched;
  6029. };
  6030. return bySet ? markFunction(superMatcher) : superMatcher;
  6031. }
  6032. compile = Sizzle.compile = function (selector, match) {
  6033. var i, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + ' '];
  6034. if (!cached) {
  6035. if (!match) {
  6036. match = tokenize(selector);
  6037. }
  6038. i = match.length;
  6039. while (i--) {
  6040. cached = matcherFromTokens(match[i]);
  6041. if (cached[expando]) {
  6042. setMatchers.push(cached);
  6043. } else {
  6044. elementMatchers.push(cached);
  6045. }
  6046. }
  6047. cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
  6048. cached.selector = selector;
  6049. }
  6050. return cached;
  6051. };
  6052. select = Sizzle.select = function (selector, context, results, seed) {
  6053. var i, tokens, token, type, find, compiled = typeof selector === 'function' && selector, match = !seed && tokenize(selector = compiled.selector || selector);
  6054. results = results || [];
  6055. if (match.length === 1) {
  6056. tokens = match[0] = match[0].slice(0);
  6057. if (tokens.length > 2 && (token = tokens[0]).type === 'ID' && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
  6058. context = (Expr.find.ID(token.matches[0].replace(runescape, funescape), context) || [])[0];
  6059. if (!context) {
  6060. return results;
  6061. } else if (compiled) {
  6062. context = context.parentNode;
  6063. }
  6064. selector = selector.slice(tokens.shift().value.length);
  6065. }
  6066. i = matchExpr.needsContext.test(selector) ? 0 : tokens.length;
  6067. while (i--) {
  6068. token = tokens[i];
  6069. if (Expr.relative[type = token.type]) {
  6070. break;
  6071. }
  6072. if (find = Expr.find[type]) {
  6073. if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {
  6074. tokens.splice(i, 1);
  6075. selector = seed.length && toSelector(tokens);
  6076. if (!selector) {
  6077. push.apply(results, seed);
  6078. return results;
  6079. }
  6080. break;
  6081. }
  6082. }
  6083. }
  6084. }
  6085. (compiled || compile(selector, match))(seed, context, !documentIsHTML, results, rsibling.test(selector) && testContext(context.parentNode) || context);
  6086. return results;
  6087. };
  6088. support.sortStable = expando.split('').sort(sortOrder).join('') === expando;
  6089. support.detectDuplicates = !!hasDuplicate;
  6090. setDocument();
  6091. support.sortDetached = true;
  6092. var doc = document, push$1 = Array.prototype.push, slice$1 = Array.prototype.slice;
  6093. var rquickExpr$1 = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
  6094. var Event = EventUtils.Event;
  6095. var skipUniques = Tools.makeMap('children,contents,next,prev');
  6096. var isDefined = function (obj) {
  6097. return typeof obj !== 'undefined';
  6098. };
  6099. var isString$1 = function (obj) {
  6100. return typeof obj === 'string';
  6101. };
  6102. var isWindow = function (obj) {
  6103. return obj && obj === obj.window;
  6104. };
  6105. var createFragment = function (html, fragDoc) {
  6106. fragDoc = fragDoc || doc;
  6107. var container = fragDoc.createElement('div');
  6108. var frag = fragDoc.createDocumentFragment();
  6109. container.innerHTML = html;
  6110. var node;
  6111. while (node = container.firstChild) {
  6112. frag.appendChild(node);
  6113. }
  6114. return frag;
  6115. };
  6116. var domManipulate = function (targetNodes, sourceItem, callback, reverse) {
  6117. var i;
  6118. if (isString$1(sourceItem)) {
  6119. sourceItem = createFragment(sourceItem, getElementDocument(targetNodes[0]));
  6120. } else if (sourceItem.length && !sourceItem.nodeType) {
  6121. sourceItem = DomQuery.makeArray(sourceItem);
  6122. if (reverse) {
  6123. for (i = sourceItem.length - 1; i >= 0; i--) {
  6124. domManipulate(targetNodes, sourceItem[i], callback, reverse);
  6125. }
  6126. } else {
  6127. for (i = 0; i < sourceItem.length; i++) {
  6128. domManipulate(targetNodes, sourceItem[i], callback, reverse);
  6129. }
  6130. }
  6131. return targetNodes;
  6132. }
  6133. if (sourceItem.nodeType) {
  6134. i = targetNodes.length;
  6135. while (i--) {
  6136. callback.call(targetNodes[i], sourceItem);
  6137. }
  6138. }
  6139. return targetNodes;
  6140. };
  6141. var hasClass = function (node, className) {
  6142. return node && className && (' ' + node.className + ' ').indexOf(' ' + className + ' ') !== -1;
  6143. };
  6144. var wrap$1 = function (elements, wrapper, all) {
  6145. var lastParent, newWrapper;
  6146. wrapper = DomQuery(wrapper)[0];
  6147. elements.each(function () {
  6148. var self = this;
  6149. if (!all || lastParent !== self.parentNode) {
  6150. lastParent = self.parentNode;
  6151. newWrapper = wrapper.cloneNode(false);
  6152. self.parentNode.insertBefore(newWrapper, self);
  6153. newWrapper.appendChild(self);
  6154. } else {
  6155. newWrapper.appendChild(self);
  6156. }
  6157. });
  6158. return elements;
  6159. };
  6160. var numericCssMap = Tools.makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom', ' ');
  6161. var booleanMap = Tools.makeMap('checked compact declare defer disabled ismap multiple nohref noshade nowrap readonly selected', ' ');
  6162. var propFix = {
  6163. for: 'htmlFor',
  6164. class: 'className',
  6165. readonly: 'readOnly'
  6166. };
  6167. var cssFix = { float: 'cssFloat' };
  6168. var attrHooks = {}, cssHooks = {};
  6169. var DomQueryConstructor = function (selector, context) {
  6170. return new DomQuery.fn.init(selector, context);
  6171. };
  6172. var inArray$1 = function (item, array) {
  6173. var i;
  6174. if (array.indexOf) {
  6175. return array.indexOf(item);
  6176. }
  6177. i = array.length;
  6178. while (i--) {
  6179. if (array[i] === item) {
  6180. return i;
  6181. }
  6182. }
  6183. return -1;
  6184. };
  6185. var whiteSpaceRegExp$2 = /^\s*|\s*$/g;
  6186. var trim$3 = function (str) {
  6187. return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp$2, '');
  6188. };
  6189. var each$4 = function (obj, callback) {
  6190. var length, key, i, value;
  6191. if (obj) {
  6192. length = obj.length;
  6193. if (length === undefined) {
  6194. for (key in obj) {
  6195. if (obj.hasOwnProperty(key)) {
  6196. value = obj[key];
  6197. if (callback.call(value, key, value) === false) {
  6198. break;
  6199. }
  6200. }
  6201. }
  6202. } else {
  6203. for (i = 0; i < length; i++) {
  6204. value = obj[i];
  6205. if (callback.call(value, i, value) === false) {
  6206. break;
  6207. }
  6208. }
  6209. }
  6210. }
  6211. return obj;
  6212. };
  6213. var grep = function (array, callback) {
  6214. var out = [];
  6215. each$4(array, function (i, item) {
  6216. if (callback(item, i)) {
  6217. out.push(item);
  6218. }
  6219. });
  6220. return out;
  6221. };
  6222. var getElementDocument = function (element) {
  6223. if (!element) {
  6224. return doc;
  6225. }
  6226. if (element.nodeType === 9) {
  6227. return element;
  6228. }
  6229. return element.ownerDocument;
  6230. };
  6231. DomQueryConstructor.fn = DomQueryConstructor.prototype = {
  6232. constructor: DomQueryConstructor,
  6233. selector: '',
  6234. context: null,
  6235. length: 0,
  6236. init: function (selector, context) {
  6237. var self = this;
  6238. var match, node;
  6239. if (!selector) {
  6240. return self;
  6241. }
  6242. if (selector.nodeType) {
  6243. self.context = self[0] = selector;
  6244. self.length = 1;
  6245. return self;
  6246. }
  6247. if (context && context.nodeType) {
  6248. self.context = context;
  6249. } else {
  6250. if (context) {
  6251. return DomQuery(selector).attr(context);
  6252. }
  6253. self.context = context = document;
  6254. }
  6255. if (isString$1(selector)) {
  6256. self.selector = selector;
  6257. if (selector.charAt(0) === '<' && selector.charAt(selector.length - 1) === '>' && selector.length >= 3) {
  6258. match = [
  6259. null,
  6260. selector,
  6261. null
  6262. ];
  6263. } else {
  6264. match = rquickExpr$1.exec(selector);
  6265. }
  6266. if (match) {
  6267. if (match[1]) {
  6268. node = createFragment(selector, getElementDocument(context)).firstChild;
  6269. while (node) {
  6270. push$1.call(self, node);
  6271. node = node.nextSibling;
  6272. }
  6273. } else {
  6274. node = getElementDocument(context).getElementById(match[2]);
  6275. if (!node) {
  6276. return self;
  6277. }
  6278. if (node.id !== match[2]) {
  6279. return self.find(selector);
  6280. }
  6281. self.length = 1;
  6282. self[0] = node;
  6283. }
  6284. } else {
  6285. return DomQuery(context).find(selector);
  6286. }
  6287. } else {
  6288. this.add(selector, false);
  6289. }
  6290. return self;
  6291. },
  6292. toArray: function () {
  6293. return Tools.toArray(this);
  6294. },
  6295. add: function (items, sort) {
  6296. var self = this;
  6297. var nodes, i;
  6298. if (isString$1(items)) {
  6299. return self.add(DomQuery(items));
  6300. }
  6301. if (sort !== false) {
  6302. nodes = DomQuery.unique(self.toArray().concat(DomQuery.makeArray(items)));
  6303. self.length = nodes.length;
  6304. for (i = 0; i < nodes.length; i++) {
  6305. self[i] = nodes[i];
  6306. }
  6307. } else {
  6308. push$1.apply(self, DomQuery.makeArray(items));
  6309. }
  6310. return self;
  6311. },
  6312. attr: function (name, value) {
  6313. var self = this;
  6314. var hook;
  6315. if (typeof name === 'object') {
  6316. each$4(name, function (name, value) {
  6317. self.attr(name, value);
  6318. });
  6319. } else if (isDefined(value)) {
  6320. this.each(function () {
  6321. var hook;
  6322. if (this.nodeType === 1) {
  6323. hook = attrHooks[name];
  6324. if (hook && hook.set) {
  6325. hook.set(this, value);
  6326. return;
  6327. }
  6328. if (value === null) {
  6329. this.removeAttribute(name, 2);
  6330. } else {
  6331. this.setAttribute(name, value, 2);
  6332. }
  6333. }
  6334. });
  6335. } else {
  6336. if (self[0] && self[0].nodeType === 1) {
  6337. hook = attrHooks[name];
  6338. if (hook && hook.get) {
  6339. return hook.get(self[0], name);
  6340. }
  6341. if (booleanMap[name]) {
  6342. return self.prop(name) ? name : undefined;
  6343. }
  6344. value = self[0].getAttribute(name, 2);
  6345. if (value === null) {
  6346. value = undefined;
  6347. }
  6348. }
  6349. return value;
  6350. }
  6351. return self;
  6352. },
  6353. removeAttr: function (name) {
  6354. return this.attr(name, null);
  6355. },
  6356. prop: function (name, value) {
  6357. var self = this;
  6358. name = propFix[name] || name;
  6359. if (typeof name === 'object') {
  6360. each$4(name, function (name, value) {
  6361. self.prop(name, value);
  6362. });
  6363. } else if (isDefined(value)) {
  6364. this.each(function () {
  6365. if (this.nodeType === 1) {
  6366. this[name] = value;
  6367. }
  6368. });
  6369. } else {
  6370. if (self[0] && self[0].nodeType && name in self[0]) {
  6371. return self[0][name];
  6372. }
  6373. return value;
  6374. }
  6375. return self;
  6376. },
  6377. css: function (name, value) {
  6378. var self = this;
  6379. var elm, hook;
  6380. var camel = function (name) {
  6381. return name.replace(/-(\D)/g, function (a, b) {
  6382. return b.toUpperCase();
  6383. });
  6384. };
  6385. var dashed = function (name) {
  6386. return name.replace(/[A-Z]/g, function (a) {
  6387. return '-' + a;
  6388. });
  6389. };
  6390. if (typeof name === 'object') {
  6391. each$4(name, function (name, value) {
  6392. self.css(name, value);
  6393. });
  6394. } else {
  6395. if (isDefined(value)) {
  6396. name = camel(name);
  6397. if (typeof value === 'number' && !numericCssMap[name]) {
  6398. value = value.toString() + 'px';
  6399. }
  6400. self.each(function () {
  6401. var style = this.style;
  6402. hook = cssHooks[name];
  6403. if (hook && hook.set) {
  6404. hook.set(this, value);
  6405. return;
  6406. }
  6407. try {
  6408. this.style[cssFix[name] || name] = value;
  6409. } catch (ex) {
  6410. }
  6411. if (value === null || value === '') {
  6412. if (style.removeProperty) {
  6413. style.removeProperty(dashed(name));
  6414. } else {
  6415. style.removeAttribute(name);
  6416. }
  6417. }
  6418. });
  6419. } else {
  6420. elm = self[0];
  6421. hook = cssHooks[name];
  6422. if (hook && hook.get) {
  6423. return hook.get(elm);
  6424. }
  6425. if (elm.ownerDocument.defaultView) {
  6426. try {
  6427. return elm.ownerDocument.defaultView.getComputedStyle(elm, null).getPropertyValue(dashed(name));
  6428. } catch (ex) {
  6429. return undefined;
  6430. }
  6431. } else if (elm.currentStyle) {
  6432. return elm.currentStyle[camel(name)];
  6433. } else {
  6434. return '';
  6435. }
  6436. }
  6437. }
  6438. return self;
  6439. },
  6440. remove: function () {
  6441. var self = this;
  6442. var node, i = this.length;
  6443. while (i--) {
  6444. node = self[i];
  6445. Event.clean(node);
  6446. if (node.parentNode) {
  6447. node.parentNode.removeChild(node);
  6448. }
  6449. }
  6450. return this;
  6451. },
  6452. empty: function () {
  6453. var self = this;
  6454. var node, i = this.length;
  6455. while (i--) {
  6456. node = self[i];
  6457. while (node.firstChild) {
  6458. node.removeChild(node.firstChild);
  6459. }
  6460. }
  6461. return this;
  6462. },
  6463. html: function (value) {
  6464. var self = this;
  6465. var i;
  6466. if (isDefined(value)) {
  6467. i = self.length;
  6468. try {
  6469. while (i--) {
  6470. self[i].innerHTML = value;
  6471. }
  6472. } catch (ex) {
  6473. DomQuery(self[i]).empty().append(value);
  6474. }
  6475. return self;
  6476. }
  6477. return self[0] ? self[0].innerHTML : '';
  6478. },
  6479. text: function (value) {
  6480. var self = this;
  6481. var i;
  6482. if (isDefined(value)) {
  6483. i = self.length;
  6484. while (i--) {
  6485. if ('innerText' in self[i]) {
  6486. self[i].innerText = value;
  6487. } else {
  6488. self[0].textContent = value;
  6489. }
  6490. }
  6491. return self;
  6492. }
  6493. return self[0] ? self[0].innerText || self[0].textContent : '';
  6494. },
  6495. append: function () {
  6496. return domManipulate(this, arguments, function (node) {
  6497. if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6498. this.appendChild(node);
  6499. }
  6500. });
  6501. },
  6502. prepend: function () {
  6503. return domManipulate(this, arguments, function (node) {
  6504. if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6505. this.insertBefore(node, this.firstChild);
  6506. }
  6507. }, true);
  6508. },
  6509. before: function () {
  6510. var self = this;
  6511. if (self[0] && self[0].parentNode) {
  6512. return domManipulate(self, arguments, function (node) {
  6513. this.parentNode.insertBefore(node, this);
  6514. });
  6515. }
  6516. return self;
  6517. },
  6518. after: function () {
  6519. var self = this;
  6520. if (self[0] && self[0].parentNode) {
  6521. return domManipulate(self, arguments, function (node) {
  6522. this.parentNode.insertBefore(node, this.nextSibling);
  6523. }, true);
  6524. }
  6525. return self;
  6526. },
  6527. appendTo: function (val) {
  6528. DomQuery(val).append(this);
  6529. return this;
  6530. },
  6531. prependTo: function (val) {
  6532. DomQuery(val).prepend(this);
  6533. return this;
  6534. },
  6535. replaceWith: function (content) {
  6536. return this.before(content).remove();
  6537. },
  6538. wrap: function (content) {
  6539. return wrap$1(this, content);
  6540. },
  6541. wrapAll: function (content) {
  6542. return wrap$1(this, content, true);
  6543. },
  6544. wrapInner: function (content) {
  6545. this.each(function () {
  6546. DomQuery(this).contents().wrapAll(content);
  6547. });
  6548. return this;
  6549. },
  6550. unwrap: function () {
  6551. return this.parent().each(function () {
  6552. DomQuery(this).replaceWith(this.childNodes);
  6553. });
  6554. },
  6555. clone: function () {
  6556. var result = [];
  6557. this.each(function () {
  6558. result.push(this.cloneNode(true));
  6559. });
  6560. return DomQuery(result);
  6561. },
  6562. addClass: function (className) {
  6563. return this.toggleClass(className, true);
  6564. },
  6565. removeClass: function (className) {
  6566. return this.toggleClass(className, false);
  6567. },
  6568. toggleClass: function (className, state) {
  6569. var self = this;
  6570. if (typeof className !== 'string') {
  6571. return self;
  6572. }
  6573. if (className.indexOf(' ') !== -1) {
  6574. each$4(className.split(' '), function () {
  6575. self.toggleClass(this, state);
  6576. });
  6577. } else {
  6578. self.each(function (index, node) {
  6579. var classState = hasClass(node, className);
  6580. if (classState !== state) {
  6581. var existingClassName = node.className;
  6582. if (classState) {
  6583. node.className = trim$3((' ' + existingClassName + ' ').replace(' ' + className + ' ', ' '));
  6584. } else {
  6585. node.className += existingClassName ? ' ' + className : className;
  6586. }
  6587. }
  6588. });
  6589. }
  6590. return self;
  6591. },
  6592. hasClass: function (className) {
  6593. return hasClass(this[0], className);
  6594. },
  6595. each: function (callback) {
  6596. return each$4(this, callback);
  6597. },
  6598. on: function (name, callback) {
  6599. return this.each(function () {
  6600. Event.bind(this, name, callback);
  6601. });
  6602. },
  6603. off: function (name, callback) {
  6604. return this.each(function () {
  6605. Event.unbind(this, name, callback);
  6606. });
  6607. },
  6608. trigger: function (name) {
  6609. return this.each(function () {
  6610. if (typeof name === 'object') {
  6611. Event.fire(this, name.type, name);
  6612. } else {
  6613. Event.fire(this, name);
  6614. }
  6615. });
  6616. },
  6617. show: function () {
  6618. return this.css('display', '');
  6619. },
  6620. hide: function () {
  6621. return this.css('display', 'none');
  6622. },
  6623. slice: function () {
  6624. return new DomQuery(slice$1.apply(this, arguments));
  6625. },
  6626. eq: function (index) {
  6627. return index === -1 ? this.slice(index) : this.slice(index, +index + 1);
  6628. },
  6629. first: function () {
  6630. return this.eq(0);
  6631. },
  6632. last: function () {
  6633. return this.eq(-1);
  6634. },
  6635. find: function (selector) {
  6636. var i, l;
  6637. var ret = [];
  6638. for (i = 0, l = this.length; i < l; i++) {
  6639. DomQuery.find(selector, this[i], ret);
  6640. }
  6641. return DomQuery(ret);
  6642. },
  6643. filter: function (selector) {
  6644. if (typeof selector === 'function') {
  6645. return DomQuery(grep(this.toArray(), function (item, i) {
  6646. return selector(i, item);
  6647. }));
  6648. }
  6649. return DomQuery(DomQuery.filter(selector, this.toArray()));
  6650. },
  6651. closest: function (selector) {
  6652. var result = [];
  6653. if (selector instanceof DomQuery) {
  6654. selector = selector[0];
  6655. }
  6656. this.each(function (i, node) {
  6657. while (node) {
  6658. if (typeof selector === 'string' && DomQuery(node).is(selector)) {
  6659. result.push(node);
  6660. break;
  6661. } else if (node === selector) {
  6662. result.push(node);
  6663. break;
  6664. }
  6665. node = node.parentNode;
  6666. }
  6667. });
  6668. return DomQuery(result);
  6669. },
  6670. offset: function (offset) {
  6671. var elm, doc, docElm;
  6672. var x = 0, y = 0, pos;
  6673. if (!offset) {
  6674. elm = this[0];
  6675. if (elm) {
  6676. doc = elm.ownerDocument;
  6677. docElm = doc.documentElement;
  6678. if (elm.getBoundingClientRect) {
  6679. pos = elm.getBoundingClientRect();
  6680. x = pos.left + (docElm.scrollLeft || doc.body.scrollLeft) - docElm.clientLeft;
  6681. y = pos.top + (docElm.scrollTop || doc.body.scrollTop) - docElm.clientTop;
  6682. }
  6683. }
  6684. return {
  6685. left: x,
  6686. top: y
  6687. };
  6688. }
  6689. return this.css(offset);
  6690. },
  6691. push: push$1,
  6692. sort: Array.prototype.sort,
  6693. splice: Array.prototype.splice
  6694. };
  6695. Tools.extend(DomQueryConstructor, {
  6696. extend: Tools.extend,
  6697. makeArray: function (object) {
  6698. if (isWindow(object) || object.nodeType) {
  6699. return [object];
  6700. }
  6701. return Tools.toArray(object);
  6702. },
  6703. inArray: inArray$1,
  6704. isArray: Tools.isArray,
  6705. each: each$4,
  6706. trim: trim$3,
  6707. grep: grep,
  6708. find: Sizzle,
  6709. expr: Sizzle.selectors,
  6710. unique: Sizzle.uniqueSort,
  6711. text: Sizzle.getText,
  6712. contains: Sizzle.contains,
  6713. filter: function (expr, elems, not) {
  6714. var i = elems.length;
  6715. if (not) {
  6716. expr = ':not(' + expr + ')';
  6717. }
  6718. while (i--) {
  6719. if (elems[i].nodeType !== 1) {
  6720. elems.splice(i, 1);
  6721. }
  6722. }
  6723. if (elems.length === 1) {
  6724. elems = DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [];
  6725. } else {
  6726. elems = DomQuery.find.matches(expr, elems);
  6727. }
  6728. return elems;
  6729. }
  6730. });
  6731. var dir = function (el, prop, until) {
  6732. var matched = [];
  6733. var cur = el[prop];
  6734. if (typeof until !== 'string' && until instanceof DomQuery) {
  6735. until = until[0];
  6736. }
  6737. while (cur && cur.nodeType !== 9) {
  6738. if (until !== undefined) {
  6739. if (cur === until) {
  6740. break;
  6741. }
  6742. if (typeof until === 'string' && DomQuery(cur).is(until)) {
  6743. break;
  6744. }
  6745. }
  6746. if (cur.nodeType === 1) {
  6747. matched.push(cur);
  6748. }
  6749. cur = cur[prop];
  6750. }
  6751. return matched;
  6752. };
  6753. var sibling$1 = function (node, siblingName, nodeType, until) {
  6754. var result = [];
  6755. if (until instanceof DomQuery) {
  6756. until = until[0];
  6757. }
  6758. for (; node; node = node[siblingName]) {
  6759. if (nodeType && node.nodeType !== nodeType) {
  6760. continue;
  6761. }
  6762. if (until !== undefined) {
  6763. if (node === until) {
  6764. break;
  6765. }
  6766. if (typeof until === 'string' && DomQuery(node).is(until)) {
  6767. break;
  6768. }
  6769. }
  6770. result.push(node);
  6771. }
  6772. return result;
  6773. };
  6774. var firstSibling = function (node, siblingName, nodeType) {
  6775. for (node = node[siblingName]; node; node = node[siblingName]) {
  6776. if (node.nodeType === nodeType) {
  6777. return node;
  6778. }
  6779. }
  6780. return null;
  6781. };
  6782. each$4({
  6783. parent: function (node) {
  6784. var parent = node.parentNode;
  6785. return parent && parent.nodeType !== 11 ? parent : null;
  6786. },
  6787. parents: function (node) {
  6788. return dir(node, 'parentNode');
  6789. },
  6790. next: function (node) {
  6791. return firstSibling(node, 'nextSibling', 1);
  6792. },
  6793. prev: function (node) {
  6794. return firstSibling(node, 'previousSibling', 1);
  6795. },
  6796. children: function (node) {
  6797. return sibling$1(node.firstChild, 'nextSibling', 1);
  6798. },
  6799. contents: function (node) {
  6800. return Tools.toArray((node.nodeName === 'iframe' ? node.contentDocument || node.contentWindow.document : node).childNodes);
  6801. }
  6802. }, function (name, fn) {
  6803. DomQueryConstructor.fn[name] = function (selector) {
  6804. var self = this;
  6805. var result = [];
  6806. self.each(function () {
  6807. var nodes = fn.call(result, this, selector, result);
  6808. if (nodes) {
  6809. if (DomQuery.isArray(nodes)) {
  6810. result.push.apply(result, nodes);
  6811. } else {
  6812. result.push(nodes);
  6813. }
  6814. }
  6815. });
  6816. if (this.length > 1) {
  6817. if (!skipUniques[name]) {
  6818. result = DomQuery.unique(result);
  6819. }
  6820. if (name.indexOf('parents') === 0) {
  6821. result = result.reverse();
  6822. }
  6823. }
  6824. var wrappedResult = DomQuery(result);
  6825. if (selector) {
  6826. return wrappedResult.filter(selector);
  6827. }
  6828. return wrappedResult;
  6829. };
  6830. });
  6831. each$4({
  6832. parentsUntil: function (node, until) {
  6833. return dir(node, 'parentNode', until);
  6834. },
  6835. nextUntil: function (node, until) {
  6836. return sibling$1(node, 'nextSibling', 1, until).slice(1);
  6837. },
  6838. prevUntil: function (node, until) {
  6839. return sibling$1(node, 'previousSibling', 1, until).slice(1);
  6840. }
  6841. }, function (name, fn) {
  6842. DomQueryConstructor.fn[name] = function (selector, filter) {
  6843. var self = this;
  6844. var result = [];
  6845. self.each(function () {
  6846. var nodes = fn.call(result, this, selector, result);
  6847. if (nodes) {
  6848. if (DomQuery.isArray(nodes)) {
  6849. result.push.apply(result, nodes);
  6850. } else {
  6851. result.push(nodes);
  6852. }
  6853. }
  6854. });
  6855. if (this.length > 1) {
  6856. result = DomQuery.unique(result);
  6857. if (name.indexOf('parents') === 0 || name === 'prevUntil') {
  6858. result = result.reverse();
  6859. }
  6860. }
  6861. var wrappedResult = DomQuery(result);
  6862. if (filter) {
  6863. return wrappedResult.filter(filter);
  6864. }
  6865. return wrappedResult;
  6866. };
  6867. });
  6868. DomQueryConstructor.fn.is = function (selector) {
  6869. return !!selector && this.filter(selector).length > 0;
  6870. };
  6871. DomQueryConstructor.fn.init.prototype = DomQueryConstructor.fn;
  6872. DomQueryConstructor.overrideDefaults = function (callback) {
  6873. var defaults;
  6874. var sub = function (selector, context) {
  6875. defaults = defaults || callback();
  6876. if (arguments.length === 0) {
  6877. selector = defaults.element;
  6878. }
  6879. if (!context) {
  6880. context = defaults.context;
  6881. }
  6882. return new sub.fn.init(selector, context);
  6883. };
  6884. DomQuery.extend(sub, this);
  6885. return sub;
  6886. };
  6887. DomQueryConstructor.attrHooks = attrHooks;
  6888. DomQueryConstructor.cssHooks = cssHooks;
  6889. var DomQuery = DomQueryConstructor;
  6890. var each$5 = Tools.each;
  6891. var grep$1 = Tools.grep;
  6892. var isIE = Env.ie;
  6893. var simpleSelectorRe = /^([a-z0-9],?)+$/i;
  6894. var setupAttrHooks = function (styles, settings, getContext) {
  6895. var keepValues = settings.keep_values;
  6896. var keepUrlHook = {
  6897. set: function ($elm, value, name) {
  6898. if (settings.url_converter) {
  6899. value = settings.url_converter.call(settings.url_converter_scope || getContext(), value, name, $elm[0]);
  6900. }
  6901. $elm.attr('data-mce-' + name, value).attr(name, value);
  6902. },
  6903. get: function ($elm, name) {
  6904. return $elm.attr('data-mce-' + name) || $elm.attr(name);
  6905. }
  6906. };
  6907. var attrHooks = {
  6908. style: {
  6909. set: function ($elm, value) {
  6910. if (value !== null && typeof value === 'object') {
  6911. $elm.css(value);
  6912. return;
  6913. }
  6914. if (keepValues) {
  6915. $elm.attr('data-mce-style', value);
  6916. }
  6917. if (value !== null && typeof value === 'string') {
  6918. $elm.removeAttr('style');
  6919. $elm.css(styles.parse(value));
  6920. } else {
  6921. $elm.attr('style', value);
  6922. }
  6923. },
  6924. get: function ($elm) {
  6925. var value = $elm.attr('data-mce-style') || $elm.attr('style');
  6926. value = styles.serialize(styles.parse(value), $elm[0].nodeName);
  6927. return value;
  6928. }
  6929. }
  6930. };
  6931. if (keepValues) {
  6932. attrHooks.href = attrHooks.src = keepUrlHook;
  6933. }
  6934. return attrHooks;
  6935. };
  6936. var updateInternalStyleAttr = function (styles, $elm) {
  6937. var rawValue = $elm.attr('style');
  6938. var value = styles.serialize(styles.parse(rawValue), $elm[0].nodeName);
  6939. if (!value) {
  6940. value = null;
  6941. }
  6942. $elm.attr('data-mce-style', value);
  6943. };
  6944. var findNodeIndex = function (node, normalized) {
  6945. var idx = 0, lastNodeType, nodeType;
  6946. if (node) {
  6947. for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
  6948. nodeType = node.nodeType;
  6949. if (normalized && nodeType === 3) {
  6950. if (nodeType === lastNodeType || !node.nodeValue.length) {
  6951. continue;
  6952. }
  6953. }
  6954. idx++;
  6955. lastNodeType = nodeType;
  6956. }
  6957. }
  6958. return idx;
  6959. };
  6960. function DOMUtils(doc, settings) {
  6961. var _this = this;
  6962. if (settings === void 0) {
  6963. settings = {};
  6964. }
  6965. var addedStyles = {};
  6966. var win = window;
  6967. var files = {};
  6968. var counter = 0;
  6969. var stdMode = true;
  6970. var boxModel = true;
  6971. var styleSheetLoader = instance.forElement(SugarElement.fromDom(doc), {
  6972. contentCssCors: settings.contentCssCors,
  6973. referrerPolicy: settings.referrerPolicy
  6974. });
  6975. var boundEvents = [];
  6976. var schema = settings.schema ? settings.schema : Schema({});
  6977. var styles = Styles({
  6978. url_converter: settings.url_converter,
  6979. url_converter_scope: settings.url_converter_scope
  6980. }, settings.schema);
  6981. var events = settings.ownEvents ? new EventUtils() : EventUtils.Event;
  6982. var blockElementsMap = schema.getBlockElements();
  6983. var $ = DomQuery.overrideDefaults(function () {
  6984. return {
  6985. context: doc,
  6986. element: self.getRoot()
  6987. };
  6988. });
  6989. var isBlock = function (node) {
  6990. if (typeof node === 'string') {
  6991. return !!blockElementsMap[node];
  6992. } else if (node) {
  6993. var type = node.nodeType;
  6994. if (type) {
  6995. return !!(type === 1 && blockElementsMap[node.nodeName]);
  6996. }
  6997. }
  6998. return false;
  6999. };
  7000. var get = function (elm) {
  7001. return elm && doc && isString(elm) ? doc.getElementById(elm) : elm;
  7002. };
  7003. var $$ = function (elm) {
  7004. return $(typeof elm === 'string' ? get(elm) : elm);
  7005. };
  7006. var getAttrib = function (elm, name, defaultVal) {
  7007. var hook, value;
  7008. var $elm = $$(elm);
  7009. if ($elm.length) {
  7010. hook = attrHooks[name];
  7011. if (hook && hook.get) {
  7012. value = hook.get($elm, name);
  7013. } else {
  7014. value = $elm.attr(name);
  7015. }
  7016. }
  7017. if (typeof value === 'undefined') {
  7018. value = defaultVal || '';
  7019. }
  7020. return value;
  7021. };
  7022. var getAttribs = function (elm) {
  7023. var node = get(elm);
  7024. if (!node) {
  7025. return [];
  7026. }
  7027. return node.attributes;
  7028. };
  7029. var setAttrib = function (elm, name, value) {
  7030. if (value === '') {
  7031. value = null;
  7032. }
  7033. var $elm = $$(elm);
  7034. var originalValue = $elm.attr(name);
  7035. if (!$elm.length) {
  7036. return;
  7037. }
  7038. var hook = attrHooks[name];
  7039. if (hook && hook.set) {
  7040. hook.set($elm, value, name);
  7041. } else {
  7042. $elm.attr(name, value);
  7043. }
  7044. if (originalValue !== value && settings.onSetAttrib) {
  7045. settings.onSetAttrib({
  7046. attrElm: $elm,
  7047. attrName: name,
  7048. attrValue: value
  7049. });
  7050. }
  7051. };
  7052. var clone = function (node, deep) {
  7053. if (!isIE || node.nodeType !== 1 || deep) {
  7054. return node.cloneNode(deep);
  7055. } else {
  7056. var clone_1 = doc.createElement(node.nodeName);
  7057. each$5(getAttribs(node), function (attr) {
  7058. setAttrib(clone_1, attr.nodeName, getAttrib(node, attr.nodeName));
  7059. });
  7060. return clone_1;
  7061. }
  7062. };
  7063. var getRoot = function () {
  7064. return settings.root_element || doc.body;
  7065. };
  7066. var getViewPort = function (argWin) {
  7067. var vp = getBounds(argWin);
  7068. return {
  7069. x: vp.x,
  7070. y: vp.y,
  7071. w: vp.width,
  7072. h: vp.height
  7073. };
  7074. };
  7075. var getPos$1 = function (elm, rootElm) {
  7076. return getPos(doc.body, get(elm), rootElm);
  7077. };
  7078. var setStyle = function (elm, name, value) {
  7079. var $elm = isString(name) ? $$(elm).css(name, value) : $$(elm).css(name);
  7080. if (settings.update_styles) {
  7081. updateInternalStyleAttr(styles, $elm);
  7082. }
  7083. };
  7084. var setStyles = function (elm, stylesArg) {
  7085. var $elm = $$(elm).css(stylesArg);
  7086. if (settings.update_styles) {
  7087. updateInternalStyleAttr(styles, $elm);
  7088. }
  7089. };
  7090. var getStyle = function (elm, name, computed) {
  7091. var $elm = $$(elm);
  7092. if (computed) {
  7093. return $elm.css(name);
  7094. }
  7095. name = name.replace(/-(\D)/g, function (a, b) {
  7096. return b.toUpperCase();
  7097. });
  7098. if (name === 'float') {
  7099. name = Env.browser.isIE() ? 'styleFloat' : 'cssFloat';
  7100. }
  7101. return $elm[0] && $elm[0].style ? $elm[0].style[name] : undefined;
  7102. };
  7103. var getSize = function (elm) {
  7104. var w, h;
  7105. elm = get(elm);
  7106. w = getStyle(elm, 'width');
  7107. h = getStyle(elm, 'height');
  7108. if (w.indexOf('px') === -1) {
  7109. w = 0;
  7110. }
  7111. if (h.indexOf('px') === -1) {
  7112. h = 0;
  7113. }
  7114. return {
  7115. w: parseInt(w, 10) || elm.offsetWidth || elm.clientWidth,
  7116. h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight
  7117. };
  7118. };
  7119. var getRect = function (elm) {
  7120. elm = get(elm);
  7121. var pos = getPos$1(elm);
  7122. var size = getSize(elm);
  7123. return {
  7124. x: pos.x,
  7125. y: pos.y,
  7126. w: size.w,
  7127. h: size.h
  7128. };
  7129. };
  7130. var is = function (elm, selector) {
  7131. var i;
  7132. if (!elm) {
  7133. return false;
  7134. }
  7135. if (!Array.isArray(elm)) {
  7136. if (selector === '*') {
  7137. return elm.nodeType === 1;
  7138. }
  7139. if (simpleSelectorRe.test(selector)) {
  7140. var selectors = selector.toLowerCase().split(/,/);
  7141. var elmName = elm.nodeName.toLowerCase();
  7142. for (i = selectors.length - 1; i >= 0; i--) {
  7143. if (selectors[i] === elmName) {
  7144. return true;
  7145. }
  7146. }
  7147. return false;
  7148. }
  7149. if (elm.nodeType && elm.nodeType !== 1) {
  7150. return false;
  7151. }
  7152. }
  7153. var elms = !Array.isArray(elm) ? [elm] : elm;
  7154. return Sizzle(selector, elms[0].ownerDocument || elms[0], null, elms).length > 0;
  7155. };
  7156. var getParents = function (elm, selector, root, collect) {
  7157. var result = [];
  7158. var selectorVal;
  7159. var node = get(elm);
  7160. collect = collect === undefined;
  7161. root = root || (getRoot().nodeName !== 'BODY' ? getRoot().parentNode : null);
  7162. if (Tools.is(selector, 'string')) {
  7163. selectorVal = selector;
  7164. if (selector === '*') {
  7165. selector = function (node) {
  7166. return node.nodeType === 1;
  7167. };
  7168. } else {
  7169. selector = function (node) {
  7170. return is(node, selectorVal);
  7171. };
  7172. }
  7173. }
  7174. while (node) {
  7175. if (node === root || isNullable(node.nodeType) || isDocument$1(node) || isDocumentFragment$1(node)) {
  7176. break;
  7177. }
  7178. if (!selector || typeof selector === 'function' && selector(node)) {
  7179. if (collect) {
  7180. result.push(node);
  7181. } else {
  7182. return [node];
  7183. }
  7184. }
  7185. node = node.parentNode;
  7186. }
  7187. return collect ? result : null;
  7188. };
  7189. var getParent = function (node, selector, root) {
  7190. var parents = getParents(node, selector, root, false);
  7191. return parents && parents.length > 0 ? parents[0] : null;
  7192. };
  7193. var _findSib = function (node, selector, name) {
  7194. var func = selector;
  7195. if (node) {
  7196. if (typeof selector === 'string') {
  7197. func = function (node) {
  7198. return is(node, selector);
  7199. };
  7200. }
  7201. for (node = node[name]; node; node = node[name]) {
  7202. if (typeof func === 'function' && func(node)) {
  7203. return node;
  7204. }
  7205. }
  7206. }
  7207. return null;
  7208. };
  7209. var getNext = function (node, selector) {
  7210. return _findSib(node, selector, 'nextSibling');
  7211. };
  7212. var getPrev = function (node, selector) {
  7213. return _findSib(node, selector, 'previousSibling');
  7214. };
  7215. var select = function (selector, scope) {
  7216. return Sizzle(selector, get(scope) || settings.root_element || doc, []);
  7217. };
  7218. var run = function (elm, func, scope) {
  7219. var result;
  7220. var node = typeof elm === 'string' ? get(elm) : elm;
  7221. if (!node) {
  7222. return false;
  7223. }
  7224. if (Tools.isArray(node) && (node.length || node.length === 0)) {
  7225. result = [];
  7226. each$5(node, function (elm, i) {
  7227. if (elm) {
  7228. result.push(func.call(scope, typeof elm === 'string' ? get(elm) : elm, i));
  7229. }
  7230. });
  7231. return result;
  7232. }
  7233. var context = scope ? scope : _this;
  7234. return func.call(context, node);
  7235. };
  7236. var setAttribs = function (elm, attrs) {
  7237. $$(elm).each(function (i, node) {
  7238. each$5(attrs, function (value, name) {
  7239. setAttrib(node, name, value);
  7240. });
  7241. });
  7242. };
  7243. var setHTML = function (elm, html) {
  7244. var $elm = $$(elm);
  7245. if (isIE) {
  7246. $elm.each(function (i, target) {
  7247. if (target.canHaveHTML === false) {
  7248. return;
  7249. }
  7250. while (target.firstChild) {
  7251. target.removeChild(target.firstChild);
  7252. }
  7253. try {
  7254. target.innerHTML = '<br>' + html;
  7255. target.removeChild(target.firstChild);
  7256. } catch (ex) {
  7257. DomQuery('<div></div>').html('<br>' + html).contents().slice(1).appendTo(target);
  7258. }
  7259. return html;
  7260. });
  7261. } else {
  7262. $elm.html(html);
  7263. }
  7264. };
  7265. var add = function (parentElm, name, attrs, html, create) {
  7266. return run(parentElm, function (parentElm) {
  7267. var newElm = typeof name === 'string' ? doc.createElement(name) : name;
  7268. setAttribs(newElm, attrs);
  7269. if (html) {
  7270. if (typeof html !== 'string' && html.nodeType) {
  7271. newElm.appendChild(html);
  7272. } else if (typeof html === 'string') {
  7273. setHTML(newElm, html);
  7274. }
  7275. }
  7276. return !create ? parentElm.appendChild(newElm) : newElm;
  7277. });
  7278. };
  7279. var create = function (name, attrs, html) {
  7280. return add(doc.createElement(name), name, attrs, html, true);
  7281. };
  7282. var decode = Entities.decode;
  7283. var encode = Entities.encodeAllRaw;
  7284. var createHTML = function (name, attrs, html) {
  7285. var outHtml = '', key;
  7286. outHtml += '<' + name;
  7287. for (key in attrs) {
  7288. if (attrs.hasOwnProperty(key) && attrs[key] !== null && typeof attrs[key] !== 'undefined') {
  7289. outHtml += ' ' + key + '="' + encode(attrs[key]) + '"';
  7290. }
  7291. }
  7292. if (typeof html !== 'undefined') {
  7293. return outHtml + '>' + html + '</' + name + '>';
  7294. }
  7295. return outHtml + ' />';
  7296. };
  7297. var createFragment = function (html) {
  7298. var node;
  7299. var container = doc.createElement('div');
  7300. var frag = doc.createDocumentFragment();
  7301. frag.appendChild(container);
  7302. if (html) {
  7303. container.innerHTML = html;
  7304. }
  7305. while (node = container.firstChild) {
  7306. frag.appendChild(node);
  7307. }
  7308. frag.removeChild(container);
  7309. return frag;
  7310. };
  7311. var remove = function (node, keepChildren) {
  7312. var $node = $$(node);
  7313. if (keepChildren) {
  7314. $node.each(function () {
  7315. var child;
  7316. while (child = this.firstChild) {
  7317. if (child.nodeType === 3 && child.data.length === 0) {
  7318. this.removeChild(child);
  7319. } else {
  7320. this.parentNode.insertBefore(child, this);
  7321. }
  7322. }
  7323. }).remove();
  7324. } else {
  7325. $node.remove();
  7326. }
  7327. return $node.length > 1 ? $node.toArray() : $node[0];
  7328. };
  7329. var removeAllAttribs = function (e) {
  7330. return run(e, function (e) {
  7331. var i;
  7332. var attrs = e.attributes;
  7333. for (i = attrs.length - 1; i >= 0; i--) {
  7334. e.removeAttributeNode(attrs.item(i));
  7335. }
  7336. });
  7337. };
  7338. var parseStyle = function (cssText) {
  7339. return styles.parse(cssText);
  7340. };
  7341. var serializeStyle = function (stylesArg, name) {
  7342. return styles.serialize(stylesArg, name);
  7343. };
  7344. var addStyle = function (cssText) {
  7345. var head, styleElm;
  7346. if (self !== DOMUtils.DOM && doc === document) {
  7347. if (addedStyles[cssText]) {
  7348. return;
  7349. }
  7350. addedStyles[cssText] = true;
  7351. }
  7352. styleElm = doc.getElementById('mceDefaultStyles');
  7353. if (!styleElm) {
  7354. styleElm = doc.createElement('style');
  7355. styleElm.id = 'mceDefaultStyles';
  7356. styleElm.type = 'text/css';
  7357. head = doc.getElementsByTagName('head')[0];
  7358. if (head.firstChild) {
  7359. head.insertBefore(styleElm, head.firstChild);
  7360. } else {
  7361. head.appendChild(styleElm);
  7362. }
  7363. }
  7364. if (styleElm.styleSheet) {
  7365. styleElm.styleSheet.cssText += cssText;
  7366. } else {
  7367. styleElm.appendChild(doc.createTextNode(cssText));
  7368. }
  7369. };
  7370. var loadCSS = function (urls) {
  7371. if (!urls) {
  7372. urls = '';
  7373. }
  7374. each(urls.split(','), function (url) {
  7375. files[url] = true;
  7376. styleSheetLoader.load(url, noop);
  7377. });
  7378. };
  7379. var toggleClass = function (elm, cls, state) {
  7380. $$(elm).toggleClass(cls, state).each(function () {
  7381. if (this.className === '') {
  7382. DomQuery(this).attr('class', null);
  7383. }
  7384. });
  7385. };
  7386. var addClass = function (elm, cls) {
  7387. $$(elm).addClass(cls);
  7388. };
  7389. var removeClass = function (elm, cls) {
  7390. toggleClass(elm, cls, false);
  7391. };
  7392. var hasClass = function (elm, cls) {
  7393. return $$(elm).hasClass(cls);
  7394. };
  7395. var show = function (elm) {
  7396. $$(elm).show();
  7397. };
  7398. var hide = function (elm) {
  7399. $$(elm).hide();
  7400. };
  7401. var isHidden = function (elm) {
  7402. return $$(elm).css('display') === 'none';
  7403. };
  7404. var uniqueId = function (prefix) {
  7405. return (!prefix ? 'mce_' : prefix) + counter++;
  7406. };
  7407. var getOuterHTML = function (elm) {
  7408. var node = typeof elm === 'string' ? get(elm) : elm;
  7409. return isElement$1(node) ? node.outerHTML : DomQuery('<div></div>').append(DomQuery(node).clone()).html();
  7410. };
  7411. var setOuterHTML = function (elm, html) {
  7412. $$(elm).each(function () {
  7413. try {
  7414. if ('outerHTML' in this) {
  7415. this.outerHTML = html;
  7416. return;
  7417. }
  7418. } catch (ex) {
  7419. }
  7420. remove(DomQuery(this).html(html), true);
  7421. });
  7422. };
  7423. var insertAfter = function (node, reference) {
  7424. var referenceNode = get(reference);
  7425. return run(node, function (node) {
  7426. var parent = referenceNode.parentNode;
  7427. var nextSibling = referenceNode.nextSibling;
  7428. if (nextSibling) {
  7429. parent.insertBefore(node, nextSibling);
  7430. } else {
  7431. parent.appendChild(node);
  7432. }
  7433. return node;
  7434. });
  7435. };
  7436. var replace = function (newElm, oldElm, keepChildren) {
  7437. return run(oldElm, function (oldElm) {
  7438. if (Tools.is(oldElm, 'array')) {
  7439. newElm = newElm.cloneNode(true);
  7440. }
  7441. if (keepChildren) {
  7442. each$5(grep$1(oldElm.childNodes), function (node) {
  7443. newElm.appendChild(node);
  7444. });
  7445. }
  7446. return oldElm.parentNode.replaceChild(newElm, oldElm);
  7447. });
  7448. };
  7449. var rename = function (elm, name) {
  7450. var newElm;
  7451. if (elm.nodeName !== name.toUpperCase()) {
  7452. newElm = create(name);
  7453. each$5(getAttribs(elm), function (attrNode) {
  7454. setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
  7455. });
  7456. replace(newElm, elm, true);
  7457. }
  7458. return newElm || elm;
  7459. };
  7460. var findCommonAncestor = function (a, b) {
  7461. var ps = a, pe;
  7462. while (ps) {
  7463. pe = b;
  7464. while (pe && ps !== pe) {
  7465. pe = pe.parentNode;
  7466. }
  7467. if (ps === pe) {
  7468. break;
  7469. }
  7470. ps = ps.parentNode;
  7471. }
  7472. if (!ps && a.ownerDocument) {
  7473. return a.ownerDocument.documentElement;
  7474. }
  7475. return ps;
  7476. };
  7477. var toHex = function (rgbVal) {
  7478. return styles.toHex(Tools.trim(rgbVal));
  7479. };
  7480. var isNonEmptyElement = function (node) {
  7481. if (isElement$1(node)) {
  7482. var isNamedAnchor = node.nodeName.toLowerCase() === 'a' && !getAttrib(node, 'href') && getAttrib(node, 'id');
  7483. if (getAttrib(node, 'name') || getAttrib(node, 'data-mce-bookmark') || isNamedAnchor) {
  7484. return true;
  7485. }
  7486. }
  7487. return false;
  7488. };
  7489. var isEmpty = function (node, elements) {
  7490. var type, name, brCount = 0;
  7491. if (isNonEmptyElement(node)) {
  7492. return false;
  7493. }
  7494. node = node.firstChild;
  7495. if (node) {
  7496. var walker = new DomTreeWalker(node, node.parentNode);
  7497. var whitespace = schema ? schema.getWhiteSpaceElements() : {};
  7498. elements = elements || (schema ? schema.getNonEmptyElements() : null);
  7499. do {
  7500. type = node.nodeType;
  7501. if (isElement$1(node)) {
  7502. var bogusVal = node.getAttribute('data-mce-bogus');
  7503. if (bogusVal) {
  7504. node = walker.next(bogusVal === 'all');
  7505. continue;
  7506. }
  7507. name = node.nodeName.toLowerCase();
  7508. if (elements && elements[name]) {
  7509. if (name === 'br') {
  7510. brCount++;
  7511. node = walker.next();
  7512. continue;
  7513. }
  7514. return false;
  7515. }
  7516. if (isNonEmptyElement(node)) {
  7517. return false;
  7518. }
  7519. }
  7520. if (type === 8) {
  7521. return false;
  7522. }
  7523. if (type === 3 && !isWhitespaceText(node.nodeValue)) {
  7524. return false;
  7525. }
  7526. if (type === 3 && node.parentNode && whitespace[node.parentNode.nodeName] && isWhitespaceText(node.nodeValue)) {
  7527. return false;
  7528. }
  7529. node = walker.next();
  7530. } while (node);
  7531. }
  7532. return brCount <= 1;
  7533. };
  7534. var createRng = function () {
  7535. return doc.createRange();
  7536. };
  7537. var split = function (parentElm, splitElm, replacementElm) {
  7538. var range = createRng();
  7539. var beforeFragment;
  7540. var afterFragment;
  7541. var parentNode;
  7542. if (parentElm && splitElm) {
  7543. range.setStart(parentElm.parentNode, findNodeIndex(parentElm));
  7544. range.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
  7545. beforeFragment = range.extractContents();
  7546. range = createRng();
  7547. range.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
  7548. range.setEnd(parentElm.parentNode, findNodeIndex(parentElm) + 1);
  7549. afterFragment = range.extractContents();
  7550. parentNode = parentElm.parentNode;
  7551. parentNode.insertBefore(trimNode(self, beforeFragment), parentElm);
  7552. if (replacementElm) {
  7553. parentNode.insertBefore(replacementElm, parentElm);
  7554. } else {
  7555. parentNode.insertBefore(splitElm, parentElm);
  7556. }
  7557. parentNode.insertBefore(trimNode(self, afterFragment), parentElm);
  7558. remove(parentElm);
  7559. return replacementElm || splitElm;
  7560. }
  7561. };
  7562. var bind = function (target, name, func, scope) {
  7563. if (Tools.isArray(target)) {
  7564. var i = target.length;
  7565. var rv = [];
  7566. while (i--) {
  7567. rv[i] = bind(target[i], name, func, scope);
  7568. }
  7569. return rv;
  7570. }
  7571. if (settings.collect && (target === doc || target === win)) {
  7572. boundEvents.push([
  7573. target,
  7574. name,
  7575. func,
  7576. scope
  7577. ]);
  7578. }
  7579. var output = events.bind(target, name, func, scope || self);
  7580. return output;
  7581. };
  7582. var unbind = function (target, name, func) {
  7583. if (Tools.isArray(target)) {
  7584. var i = target.length;
  7585. var rv = [];
  7586. while (i--) {
  7587. rv[i] = unbind(target[i], name, func);
  7588. }
  7589. return rv;
  7590. } else {
  7591. if (boundEvents.length > 0 && (target === doc || target === win)) {
  7592. var i = boundEvents.length;
  7593. while (i--) {
  7594. var item = boundEvents[i];
  7595. if (target === item[0] && (!name || name === item[1]) && (!func || func === item[2])) {
  7596. events.unbind(item[0], item[1], item[2]);
  7597. }
  7598. }
  7599. }
  7600. return events.unbind(target, name, func);
  7601. }
  7602. };
  7603. var fire = function (target, name, evt) {
  7604. return events.fire(target, name, evt);
  7605. };
  7606. var getContentEditable = function (node) {
  7607. if (node && isElement$1(node)) {
  7608. var contentEditable = node.getAttribute('data-mce-contenteditable');
  7609. if (contentEditable && contentEditable !== 'inherit') {
  7610. return contentEditable;
  7611. }
  7612. return node.contentEditable !== 'inherit' ? node.contentEditable : null;
  7613. } else {
  7614. return null;
  7615. }
  7616. };
  7617. var getContentEditableParent = function (node) {
  7618. var root = getRoot();
  7619. var state = null;
  7620. for (; node && node !== root; node = node.parentNode) {
  7621. state = getContentEditable(node);
  7622. if (state !== null) {
  7623. break;
  7624. }
  7625. }
  7626. return state;
  7627. };
  7628. var destroy = function () {
  7629. if (boundEvents.length > 0) {
  7630. var i = boundEvents.length;
  7631. while (i--) {
  7632. var item = boundEvents[i];
  7633. events.unbind(item[0], item[1], item[2]);
  7634. }
  7635. }
  7636. each$1(files, function (_, url) {
  7637. styleSheetLoader.unload(url);
  7638. delete files[url];
  7639. });
  7640. if (Sizzle.setDocument) {
  7641. Sizzle.setDocument();
  7642. }
  7643. };
  7644. var isChildOf = function (node, parent) {
  7645. while (node) {
  7646. if (parent === node) {
  7647. return true;
  7648. }
  7649. node = node.parentNode;
  7650. }
  7651. return false;
  7652. };
  7653. var dumpRng = function (r) {
  7654. return 'startContainer: ' + r.startContainer.nodeName + ', startOffset: ' + r.startOffset + ', endContainer: ' + r.endContainer.nodeName + ', endOffset: ' + r.endOffset;
  7655. };
  7656. var self = {
  7657. doc: doc,
  7658. settings: settings,
  7659. win: win,
  7660. files: files,
  7661. stdMode: stdMode,
  7662. boxModel: boxModel,
  7663. styleSheetLoader: styleSheetLoader,
  7664. boundEvents: boundEvents,
  7665. styles: styles,
  7666. schema: schema,
  7667. events: events,
  7668. isBlock: isBlock,
  7669. $: $,
  7670. $$: $$,
  7671. root: null,
  7672. clone: clone,
  7673. getRoot: getRoot,
  7674. getViewPort: getViewPort,
  7675. getRect: getRect,
  7676. getSize: getSize,
  7677. getParent: getParent,
  7678. getParents: getParents,
  7679. get: get,
  7680. getNext: getNext,
  7681. getPrev: getPrev,
  7682. select: select,
  7683. is: is,
  7684. add: add,
  7685. create: create,
  7686. createHTML: createHTML,
  7687. createFragment: createFragment,
  7688. remove: remove,
  7689. setStyle: setStyle,
  7690. getStyle: getStyle,
  7691. setStyles: setStyles,
  7692. removeAllAttribs: removeAllAttribs,
  7693. setAttrib: setAttrib,
  7694. setAttribs: setAttribs,
  7695. getAttrib: getAttrib,
  7696. getPos: getPos$1,
  7697. parseStyle: parseStyle,
  7698. serializeStyle: serializeStyle,
  7699. addStyle: addStyle,
  7700. loadCSS: loadCSS,
  7701. addClass: addClass,
  7702. removeClass: removeClass,
  7703. hasClass: hasClass,
  7704. toggleClass: toggleClass,
  7705. show: show,
  7706. hide: hide,
  7707. isHidden: isHidden,
  7708. uniqueId: uniqueId,
  7709. setHTML: setHTML,
  7710. getOuterHTML: getOuterHTML,
  7711. setOuterHTML: setOuterHTML,
  7712. decode: decode,
  7713. encode: encode,
  7714. insertAfter: insertAfter,
  7715. replace: replace,
  7716. rename: rename,
  7717. findCommonAncestor: findCommonAncestor,
  7718. toHex: toHex,
  7719. run: run,
  7720. getAttribs: getAttribs,
  7721. isEmpty: isEmpty,
  7722. createRng: createRng,
  7723. nodeIndex: findNodeIndex,
  7724. split: split,
  7725. bind: bind,
  7726. unbind: unbind,
  7727. fire: fire,
  7728. getContentEditable: getContentEditable,
  7729. getContentEditableParent: getContentEditableParent,
  7730. destroy: destroy,
  7731. isChildOf: isChildOf,
  7732. dumpRng: dumpRng
  7733. };
  7734. var attrHooks = setupAttrHooks(styles, settings, function () {
  7735. return self;
  7736. });
  7737. return self;
  7738. }
  7739. (function (DOMUtils) {
  7740. DOMUtils.DOM = DOMUtils(document);
  7741. DOMUtils.nodeIndex = findNodeIndex;
  7742. }(DOMUtils || (DOMUtils = {})));
  7743. var DOMUtils$1 = DOMUtils;
  7744. var DOM = DOMUtils$1.DOM;
  7745. var each$6 = Tools.each, grep$2 = Tools.grep;
  7746. var QUEUED = 0;
  7747. var LOADING = 1;
  7748. var LOADED = 2;
  7749. var FAILED = 3;
  7750. var ScriptLoader = function () {
  7751. function ScriptLoader(settings) {
  7752. if (settings === void 0) {
  7753. settings = {};
  7754. }
  7755. this.states = {};
  7756. this.queue = [];
  7757. this.scriptLoadedCallbacks = {};
  7758. this.queueLoadedCallbacks = [];
  7759. this.loading = 0;
  7760. this.settings = settings;
  7761. }
  7762. ScriptLoader.prototype._setReferrerPolicy = function (referrerPolicy) {
  7763. this.settings.referrerPolicy = referrerPolicy;
  7764. };
  7765. ScriptLoader.prototype.loadScript = function (url, success, failure) {
  7766. var dom = DOM;
  7767. var elm;
  7768. var cleanup = function () {
  7769. dom.remove(id);
  7770. if (elm) {
  7771. elm.onerror = elm.onload = elm = null;
  7772. }
  7773. };
  7774. var done = function () {
  7775. cleanup();
  7776. success();
  7777. };
  7778. var error = function () {
  7779. cleanup();
  7780. if (isFunction(failure)) {
  7781. failure();
  7782. } else {
  7783. if (typeof console !== 'undefined' && console.log) {
  7784. console.log('Failed to load script: ' + url);
  7785. }
  7786. }
  7787. };
  7788. var id = dom.uniqueId();
  7789. elm = document.createElement('script');
  7790. elm.id = id;
  7791. elm.type = 'text/javascript';
  7792. elm.src = Tools._addCacheSuffix(url);
  7793. if (this.settings.referrerPolicy) {
  7794. dom.setAttrib(elm, 'referrerpolicy', this.settings.referrerPolicy);
  7795. }
  7796. elm.onload = done;
  7797. elm.onerror = error;
  7798. (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
  7799. };
  7800. ScriptLoader.prototype.isDone = function (url) {
  7801. return this.states[url] === LOADED;
  7802. };
  7803. ScriptLoader.prototype.markDone = function (url) {
  7804. this.states[url] = LOADED;
  7805. };
  7806. ScriptLoader.prototype.add = function (url, success, scope, failure) {
  7807. var state = this.states[url];
  7808. this.queue.push(url);
  7809. if (state === undefined) {
  7810. this.states[url] = QUEUED;
  7811. }
  7812. if (success) {
  7813. if (!this.scriptLoadedCallbacks[url]) {
  7814. this.scriptLoadedCallbacks[url] = [];
  7815. }
  7816. this.scriptLoadedCallbacks[url].push({
  7817. success: success,
  7818. failure: failure,
  7819. scope: scope || this
  7820. });
  7821. }
  7822. };
  7823. ScriptLoader.prototype.load = function (url, success, scope, failure) {
  7824. return this.add(url, success, scope, failure);
  7825. };
  7826. ScriptLoader.prototype.remove = function (url) {
  7827. delete this.states[url];
  7828. delete this.scriptLoadedCallbacks[url];
  7829. };
  7830. ScriptLoader.prototype.loadQueue = function (success, scope, failure) {
  7831. this.loadScripts(this.queue, success, scope, failure);
  7832. };
  7833. ScriptLoader.prototype.loadScripts = function (scripts, success, scope, failure) {
  7834. var self = this;
  7835. var failures = [];
  7836. var execCallbacks = function (name, url) {
  7837. each$6(self.scriptLoadedCallbacks[url], function (callback) {
  7838. if (isFunction(callback[name])) {
  7839. callback[name].call(callback.scope);
  7840. }
  7841. });
  7842. self.scriptLoadedCallbacks[url] = undefined;
  7843. };
  7844. self.queueLoadedCallbacks.push({
  7845. success: success,
  7846. failure: failure,
  7847. scope: scope || this
  7848. });
  7849. var loadScripts = function () {
  7850. var loadingScripts = grep$2(scripts);
  7851. scripts.length = 0;
  7852. each$6(loadingScripts, function (url) {
  7853. if (self.states[url] === LOADED) {
  7854. execCallbacks('success', url);
  7855. return;
  7856. }
  7857. if (self.states[url] === FAILED) {
  7858. execCallbacks('failure', url);
  7859. return;
  7860. }
  7861. if (self.states[url] !== LOADING) {
  7862. self.states[url] = LOADING;
  7863. self.loading++;
  7864. self.loadScript(url, function () {
  7865. self.states[url] = LOADED;
  7866. self.loading--;
  7867. execCallbacks('success', url);
  7868. loadScripts();
  7869. }, function () {
  7870. self.states[url] = FAILED;
  7871. self.loading--;
  7872. failures.push(url);
  7873. execCallbacks('failure', url);
  7874. loadScripts();
  7875. });
  7876. }
  7877. });
  7878. if (!self.loading) {
  7879. var notifyCallbacks = self.queueLoadedCallbacks.slice(0);
  7880. self.queueLoadedCallbacks.length = 0;
  7881. each$6(notifyCallbacks, function (callback) {
  7882. if (failures.length === 0) {
  7883. if (isFunction(callback.success)) {
  7884. callback.success.call(callback.scope);
  7885. }
  7886. } else {
  7887. if (isFunction(callback.failure)) {
  7888. callback.failure.call(callback.scope, failures);
  7889. }
  7890. }
  7891. });
  7892. }
  7893. };
  7894. loadScripts();
  7895. };
  7896. ScriptLoader.ScriptLoader = new ScriptLoader();
  7897. return ScriptLoader;
  7898. }();
  7899. var Cell = function (initial) {
  7900. var value = initial;
  7901. var get = function () {
  7902. return value;
  7903. };
  7904. var set = function (v) {
  7905. value = v;
  7906. };
  7907. return {
  7908. get: get,
  7909. set: set
  7910. };
  7911. };
  7912. var isRaw = function (str) {
  7913. return isObject(str) && has(str, 'raw');
  7914. };
  7915. var isTokenised = function (str) {
  7916. return isArray(str) && str.length > 1;
  7917. };
  7918. var data = {};
  7919. var currentCode = Cell('en');
  7920. var getLanguageData = function () {
  7921. return get$1(data, currentCode.get());
  7922. };
  7923. var getData = function () {
  7924. return map$1(data, function (value) {
  7925. return __assign({}, value);
  7926. });
  7927. };
  7928. var setCode = function (newCode) {
  7929. if (newCode) {
  7930. currentCode.set(newCode);
  7931. }
  7932. };
  7933. var getCode = function () {
  7934. return currentCode.get();
  7935. };
  7936. var add = function (code, items) {
  7937. var langData = data[code];
  7938. if (!langData) {
  7939. data[code] = langData = {};
  7940. }
  7941. each$1(items, function (translation, name) {
  7942. langData[name.toLowerCase()] = translation;
  7943. });
  7944. };
  7945. var translate = function (text) {
  7946. var langData = getLanguageData().getOr({});
  7947. var toString = function (obj) {
  7948. if (isFunction(obj)) {
  7949. return Object.prototype.toString.call(obj);
  7950. }
  7951. return !isEmpty(obj) ? '' + obj : '';
  7952. };
  7953. var isEmpty = function (text) {
  7954. return text === '' || text === null || text === undefined;
  7955. };
  7956. var getLangData = function (text) {
  7957. var textstr = toString(text);
  7958. return get$1(langData, textstr.toLowerCase()).map(toString).getOr(textstr);
  7959. };
  7960. var removeContext = function (str) {
  7961. return str.replace(/{context:\w+}$/, '');
  7962. };
  7963. if (isEmpty(text)) {
  7964. return '';
  7965. }
  7966. if (isRaw(text)) {
  7967. return toString(text.raw);
  7968. }
  7969. if (isTokenised(text)) {
  7970. var values_1 = text.slice(1);
  7971. var substitued = getLangData(text[0]).replace(/\{([0-9]+)\}/g, function ($1, $2) {
  7972. return has(values_1, $2) ? toString(values_1[$2]) : $1;
  7973. });
  7974. return removeContext(substitued);
  7975. }
  7976. return removeContext(getLangData(text));
  7977. };
  7978. var isRtl = function () {
  7979. return getLanguageData().bind(function (items) {
  7980. return get$1(items, '_dir');
  7981. }).exists(function (dir) {
  7982. return dir === 'rtl';
  7983. });
  7984. };
  7985. var hasCode = function (code) {
  7986. return has(data, code);
  7987. };
  7988. var I18n = {
  7989. getData: getData,
  7990. setCode: setCode,
  7991. getCode: getCode,
  7992. add: add,
  7993. translate: translate,
  7994. isRtl: isRtl,
  7995. hasCode: hasCode
  7996. };
  7997. function AddOnManager() {
  7998. var _this = this;
  7999. var items = [];
  8000. var urls = {};
  8001. var lookup = {};
  8002. var _listeners = [];
  8003. var runListeners = function (name, state) {
  8004. var matchedListeners = filter(_listeners, function (listener) {
  8005. return listener.name === name && listener.state === state;
  8006. });
  8007. each(matchedListeners, function (listener) {
  8008. return listener.callback();
  8009. });
  8010. };
  8011. var get = function (name) {
  8012. if (lookup[name]) {
  8013. return lookup[name].instance;
  8014. }
  8015. return undefined;
  8016. };
  8017. var dependencies = function (name) {
  8018. var result;
  8019. if (lookup[name]) {
  8020. result = lookup[name].dependencies;
  8021. }
  8022. return result || [];
  8023. };
  8024. var requireLangPack = function (name, languages) {
  8025. if (AddOnManager.languageLoad !== false) {
  8026. waitFor(name, function () {
  8027. var language = I18n.getCode();
  8028. var wrappedLanguages = ',' + (languages || '') + ',';
  8029. if (!language || languages && wrappedLanguages.indexOf(',' + language + ',') === -1) {
  8030. return;
  8031. }
  8032. ScriptLoader.ScriptLoader.add(urls[name] + '/langs/' + language + '.js');
  8033. }, 'loaded');
  8034. }
  8035. };
  8036. var add = function (id, addOn, dependencies) {
  8037. var addOnConstructor = addOn;
  8038. items.push(addOnConstructor);
  8039. lookup[id] = {
  8040. instance: addOnConstructor,
  8041. dependencies: dependencies
  8042. };
  8043. runListeners(id, 'added');
  8044. return addOnConstructor;
  8045. };
  8046. var remove = function (name) {
  8047. delete urls[name];
  8048. delete lookup[name];
  8049. };
  8050. var createUrl = function (baseUrl, dep) {
  8051. if (typeof dep === 'object') {
  8052. return dep;
  8053. }
  8054. return typeof baseUrl === 'string' ? {
  8055. prefix: '',
  8056. resource: dep,
  8057. suffix: ''
  8058. } : {
  8059. prefix: baseUrl.prefix,
  8060. resource: dep,
  8061. suffix: baseUrl.suffix
  8062. };
  8063. };
  8064. var addComponents = function (pluginName, scripts) {
  8065. var pluginUrl = _this.urls[pluginName];
  8066. each(scripts, function (script) {
  8067. ScriptLoader.ScriptLoader.add(pluginUrl + '/' + script);
  8068. });
  8069. };
  8070. var loadDependencies = function (name, addOnUrl, success, scope) {
  8071. var deps = dependencies(name);
  8072. each(deps, function (dep) {
  8073. var newUrl = createUrl(addOnUrl, dep);
  8074. load(newUrl.resource, newUrl, undefined, undefined);
  8075. });
  8076. if (success) {
  8077. if (scope) {
  8078. success.call(scope);
  8079. } else {
  8080. success.call(ScriptLoader);
  8081. }
  8082. }
  8083. };
  8084. var load = function (name, addOnUrl, success, scope, failure) {
  8085. if (urls[name]) {
  8086. return;
  8087. }
  8088. var urlString = typeof addOnUrl === 'string' ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
  8089. if (urlString.indexOf('/') !== 0 && urlString.indexOf('://') === -1) {
  8090. urlString = AddOnManager.baseURL + '/' + urlString;
  8091. }
  8092. urls[name] = urlString.substring(0, urlString.lastIndexOf('/'));
  8093. var done = function () {
  8094. runListeners(name, 'loaded');
  8095. loadDependencies(name, addOnUrl, success, scope);
  8096. };
  8097. if (lookup[name]) {
  8098. done();
  8099. } else {
  8100. ScriptLoader.ScriptLoader.add(urlString, done, scope, failure);
  8101. }
  8102. };
  8103. var waitFor = function (name, callback, state) {
  8104. if (state === void 0) {
  8105. state = 'added';
  8106. }
  8107. if (has(lookup, name) && state === 'added') {
  8108. callback();
  8109. } else if (has(urls, name) && state === 'loaded') {
  8110. callback();
  8111. } else {
  8112. _listeners.push({
  8113. name: name,
  8114. state: state,
  8115. callback: callback
  8116. });
  8117. }
  8118. };
  8119. return {
  8120. items: items,
  8121. urls: urls,
  8122. lookup: lookup,
  8123. _listeners: _listeners,
  8124. get: get,
  8125. dependencies: dependencies,
  8126. requireLangPack: requireLangPack,
  8127. add: add,
  8128. remove: remove,
  8129. createUrl: createUrl,
  8130. addComponents: addComponents,
  8131. load: load,
  8132. waitFor: waitFor
  8133. };
  8134. }
  8135. (function (AddOnManager) {
  8136. AddOnManager.PluginManager = AddOnManager();
  8137. AddOnManager.ThemeManager = AddOnManager();
  8138. }(AddOnManager || (AddOnManager = {})));
  8139. var AddOnManager$1 = AddOnManager;
  8140. var first = function (fn, rate) {
  8141. var timer = null;
  8142. var cancel = function () {
  8143. if (timer !== null) {
  8144. clearTimeout(timer);
  8145. timer = null;
  8146. }
  8147. };
  8148. var throttle = function () {
  8149. var args = [];
  8150. for (var _i = 0; _i < arguments.length; _i++) {
  8151. args[_i] = arguments[_i];
  8152. }
  8153. if (timer === null) {
  8154. timer = setTimeout(function () {
  8155. fn.apply(null, args);
  8156. timer = null;
  8157. }, rate);
  8158. }
  8159. };
  8160. return {
  8161. cancel: cancel,
  8162. throttle: throttle
  8163. };
  8164. };
  8165. var last$2 = function (fn, rate) {
  8166. var timer = null;
  8167. var cancel = function () {
  8168. if (timer !== null) {
  8169. clearTimeout(timer);
  8170. timer = null;
  8171. }
  8172. };
  8173. var throttle = function () {
  8174. var args = [];
  8175. for (var _i = 0; _i < arguments.length; _i++) {
  8176. args[_i] = arguments[_i];
  8177. }
  8178. if (timer !== null) {
  8179. clearTimeout(timer);
  8180. }
  8181. timer = setTimeout(function () {
  8182. fn.apply(null, args);
  8183. timer = null;
  8184. }, rate);
  8185. };
  8186. return {
  8187. cancel: cancel,
  8188. throttle: throttle
  8189. };
  8190. };
  8191. var read = function (element, attr) {
  8192. var value = get$4(element, attr);
  8193. return value === undefined || value === '' ? [] : value.split(' ');
  8194. };
  8195. var add$1 = function (element, attr, id) {
  8196. var old = read(element, attr);
  8197. var nu = old.concat([id]);
  8198. set(element, attr, nu.join(' '));
  8199. return true;
  8200. };
  8201. var remove$2 = function (element, attr, id) {
  8202. var nu = filter(read(element, attr), function (v) {
  8203. return v !== id;
  8204. });
  8205. if (nu.length > 0) {
  8206. set(element, attr, nu.join(' '));
  8207. } else {
  8208. remove$1(element, attr);
  8209. }
  8210. return false;
  8211. };
  8212. var supports = function (element) {
  8213. return element.dom.classList !== undefined;
  8214. };
  8215. var get$6 = function (element) {
  8216. return read(element, 'class');
  8217. };
  8218. var add$2 = function (element, clazz) {
  8219. return add$1(element, 'class', clazz);
  8220. };
  8221. var remove$3 = function (element, clazz) {
  8222. return remove$2(element, 'class', clazz);
  8223. };
  8224. var add$3 = function (element, clazz) {
  8225. if (supports(element)) {
  8226. element.dom.classList.add(clazz);
  8227. } else {
  8228. add$2(element, clazz);
  8229. }
  8230. };
  8231. var cleanClass = function (element) {
  8232. var classList = supports(element) ? element.dom.classList : get$6(element);
  8233. if (classList.length === 0) {
  8234. remove$1(element, 'class');
  8235. }
  8236. };
  8237. var remove$4 = function (element, clazz) {
  8238. if (supports(element)) {
  8239. var classList = element.dom.classList;
  8240. classList.remove(clazz);
  8241. } else {
  8242. remove$3(element, clazz);
  8243. }
  8244. cleanClass(element);
  8245. };
  8246. var has$2 = function (element, clazz) {
  8247. return supports(element) && element.dom.classList.contains(clazz);
  8248. };
  8249. var descendants = function (scope, predicate) {
  8250. var result = [];
  8251. each(children(scope), function (x) {
  8252. if (predicate(x)) {
  8253. result = result.concat([x]);
  8254. }
  8255. result = result.concat(descendants(x, predicate));
  8256. });
  8257. return result;
  8258. };
  8259. var descendants$1 = function (scope, selector) {
  8260. return all(selector, scope);
  8261. };
  8262. var annotation = constant('mce-annotation');
  8263. var dataAnnotation = constant('data-mce-annotation');
  8264. var dataAnnotationId = constant('data-mce-annotation-uid');
  8265. var identify = function (editor, annotationName) {
  8266. var rng = editor.selection.getRng();
  8267. var start = SugarElement.fromDom(rng.startContainer);
  8268. var root = SugarElement.fromDom(editor.getBody());
  8269. var selector = annotationName.fold(function () {
  8270. return '.' + annotation();
  8271. }, function (an) {
  8272. return '[' + dataAnnotation() + '="' + an + '"]';
  8273. });
  8274. var newStart = child(start, rng.startOffset).getOr(start);
  8275. var closest = closest$1(newStart, selector, function (n) {
  8276. return eq$2(n, root);
  8277. });
  8278. var getAttr = function (c, property) {
  8279. if (has$1(c, property)) {
  8280. return Optional.some(get$4(c, property));
  8281. } else {
  8282. return Optional.none();
  8283. }
  8284. };
  8285. return closest.bind(function (c) {
  8286. return getAttr(c, '' + dataAnnotationId()).bind(function (uid) {
  8287. return getAttr(c, '' + dataAnnotation()).map(function (name) {
  8288. var elements = findMarkers(editor, uid);
  8289. return {
  8290. uid: uid,
  8291. name: name,
  8292. elements: elements
  8293. };
  8294. });
  8295. });
  8296. });
  8297. };
  8298. var isAnnotation = function (elem) {
  8299. return isElement(elem) && has$2(elem, annotation());
  8300. };
  8301. var findMarkers = function (editor, uid) {
  8302. var body = SugarElement.fromDom(editor.getBody());
  8303. return descendants$1(body, '[' + dataAnnotationId() + '="' + uid + '"]');
  8304. };
  8305. var findAll = function (editor, name) {
  8306. var body = SugarElement.fromDom(editor.getBody());
  8307. var markers = descendants$1(body, '[' + dataAnnotation() + '="' + name + '"]');
  8308. var directory = {};
  8309. each(markers, function (m) {
  8310. var uid = get$4(m, dataAnnotationId());
  8311. var nodesAlready = directory.hasOwnProperty(uid) ? directory[uid] : [];
  8312. directory[uid] = nodesAlready.concat([m]);
  8313. });
  8314. return directory;
  8315. };
  8316. var setup = function (editor, _registry) {
  8317. var changeCallbacks = Cell({});
  8318. var initData = function () {
  8319. return {
  8320. listeners: [],
  8321. previous: Cell(Optional.none())
  8322. };
  8323. };
  8324. var withCallbacks = function (name, f) {
  8325. updateCallbacks(name, function (data) {
  8326. f(data);
  8327. return data;
  8328. });
  8329. };
  8330. var updateCallbacks = function (name, f) {
  8331. var callbackMap = changeCallbacks.get();
  8332. var data = callbackMap.hasOwnProperty(name) ? callbackMap[name] : initData();
  8333. var outputData = f(data);
  8334. callbackMap[name] = outputData;
  8335. changeCallbacks.set(callbackMap);
  8336. };
  8337. var fireCallbacks = function (name, uid, elements) {
  8338. withCallbacks(name, function (data) {
  8339. each(data.listeners, function (f) {
  8340. return f(true, name, {
  8341. uid: uid,
  8342. nodes: map(elements, function (elem) {
  8343. return elem.dom;
  8344. })
  8345. });
  8346. });
  8347. });
  8348. };
  8349. var fireNoAnnotation = function (name) {
  8350. withCallbacks(name, function (data) {
  8351. each(data.listeners, function (f) {
  8352. return f(false, name);
  8353. });
  8354. });
  8355. };
  8356. var onNodeChange = last$2(function () {
  8357. var callbackMap = changeCallbacks.get();
  8358. var annotations = sort$1(keys(callbackMap));
  8359. each(annotations, function (name) {
  8360. updateCallbacks(name, function (data) {
  8361. var prev = data.previous.get();
  8362. identify(editor, Optional.some(name)).fold(function () {
  8363. if (prev.isSome()) {
  8364. fireNoAnnotation(name);
  8365. data.previous.set(Optional.none());
  8366. }
  8367. }, function (_a) {
  8368. var uid = _a.uid, name = _a.name, elements = _a.elements;
  8369. if (!prev.is(uid)) {
  8370. fireCallbacks(name, uid, elements);
  8371. data.previous.set(Optional.some(uid));
  8372. }
  8373. });
  8374. return {
  8375. previous: data.previous,
  8376. listeners: data.listeners
  8377. };
  8378. });
  8379. });
  8380. }, 30);
  8381. editor.on('remove', function () {
  8382. onNodeChange.cancel();
  8383. });
  8384. editor.on('NodeChange', function () {
  8385. onNodeChange.throttle();
  8386. });
  8387. var addListener = function (name, f) {
  8388. updateCallbacks(name, function (data) {
  8389. return {
  8390. previous: data.previous,
  8391. listeners: data.listeners.concat([f])
  8392. };
  8393. });
  8394. };
  8395. return { addListener: addListener };
  8396. };
  8397. var setup$1 = function (editor, registry) {
  8398. var identifyParserNode = function (span) {
  8399. return Optional.from(span.attr(dataAnnotation())).bind(registry.lookup);
  8400. };
  8401. editor.on('init', function () {
  8402. editor.serializer.addNodeFilter('span', function (spans) {
  8403. each(spans, function (span) {
  8404. identifyParserNode(span).each(function (settings) {
  8405. if (settings.persistent === false) {
  8406. span.unwrap();
  8407. }
  8408. });
  8409. });
  8410. });
  8411. });
  8412. };
  8413. var create$2 = function () {
  8414. var annotations = {};
  8415. var register = function (name, settings) {
  8416. annotations[name] = {
  8417. name: name,
  8418. settings: settings
  8419. };
  8420. };
  8421. var lookup = function (name) {
  8422. return annotations.hasOwnProperty(name) ? Optional.from(annotations[name]).map(function (a) {
  8423. return a.settings;
  8424. }) : Optional.none();
  8425. };
  8426. return {
  8427. register: register,
  8428. lookup: lookup
  8429. };
  8430. };
  8431. var unique = 0;
  8432. var generate$1 = function (prefix) {
  8433. var date = new Date();
  8434. var time = date.getTime();
  8435. var random = Math.floor(Math.random() * 1000000000);
  8436. unique++;
  8437. return prefix + '_' + random + unique + String(time);
  8438. };
  8439. var add$4 = function (element, classes) {
  8440. each(classes, function (x) {
  8441. add$3(element, x);
  8442. });
  8443. };
  8444. var fromHtml$1 = function (html, scope) {
  8445. var doc = scope || document;
  8446. var div = doc.createElement('div');
  8447. div.innerHTML = html;
  8448. return children(SugarElement.fromDom(div));
  8449. };
  8450. var get$7 = function (element) {
  8451. return element.dom.innerHTML;
  8452. };
  8453. var set$1 = function (element, content) {
  8454. var owner$1 = owner(element);
  8455. var docDom = owner$1.dom;
  8456. var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  8457. var contentElements = fromHtml$1(content, docDom);
  8458. append$1(fragment, contentElements);
  8459. empty(element);
  8460. append(element, fragment);
  8461. };
  8462. var clone$1 = function (original, isDeep) {
  8463. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  8464. };
  8465. var shallow = function (original) {
  8466. return clone$1(original, false);
  8467. };
  8468. var deep = function (original) {
  8469. return clone$1(original, true);
  8470. };
  8471. var TextWalker = function (startNode, rootNode, isBoundary) {
  8472. if (isBoundary === void 0) {
  8473. isBoundary = never;
  8474. }
  8475. var walker = new DomTreeWalker(startNode, rootNode);
  8476. var walk = function (direction) {
  8477. var next;
  8478. do {
  8479. next = walker[direction]();
  8480. } while (next && !isText$1(next) && !isBoundary(next));
  8481. return Optional.from(next).filter(isText$1);
  8482. };
  8483. return {
  8484. current: function () {
  8485. return Optional.from(walker.current()).filter(isText$1);
  8486. },
  8487. next: function () {
  8488. return walk('next');
  8489. },
  8490. prev: function () {
  8491. return walk('prev');
  8492. },
  8493. prev2: function () {
  8494. return walk('prev2');
  8495. }
  8496. };
  8497. };
  8498. var TextSeeker = function (dom, isBoundary) {
  8499. var isBlockBoundary = isBoundary ? isBoundary : function (node) {
  8500. return dom.isBlock(node) || isBr(node) || isContentEditableFalse(node);
  8501. };
  8502. var walk = function (node, offset, walker, process) {
  8503. if (isText$1(node)) {
  8504. var newOffset = process(node, offset, node.data);
  8505. if (newOffset !== -1) {
  8506. return Optional.some({
  8507. container: node,
  8508. offset: newOffset
  8509. });
  8510. }
  8511. }
  8512. return walker().bind(function (next) {
  8513. return walk(next.container, next.offset, walker, process);
  8514. });
  8515. };
  8516. var backwards = function (node, offset, process, root) {
  8517. var walker = TextWalker(node, root, isBlockBoundary);
  8518. return walk(node, offset, function () {
  8519. return walker.prev().map(function (prev) {
  8520. return {
  8521. container: prev,
  8522. offset: prev.length
  8523. };
  8524. });
  8525. }, process).getOrNull();
  8526. };
  8527. var forwards = function (node, offset, process, root) {
  8528. var walker = TextWalker(node, root, isBlockBoundary);
  8529. return walk(node, offset, function () {
  8530. return walker.next().map(function (next) {
  8531. return {
  8532. container: next,
  8533. offset: 0
  8534. };
  8535. });
  8536. }, process).getOrNull();
  8537. };
  8538. return {
  8539. backwards: backwards,
  8540. forwards: forwards
  8541. };
  8542. };
  8543. var cat = function (arr) {
  8544. var r = [];
  8545. var push = function (x) {
  8546. r.push(x);
  8547. };
  8548. for (var i = 0; i < arr.length; i++) {
  8549. arr[i].each(push);
  8550. }
  8551. return r;
  8552. };
  8553. var lift2 = function (oa, ob, f) {
  8554. return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  8555. };
  8556. var lift3 = function (oa, ob, oc, f) {
  8557. return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
  8558. };
  8559. var someIf = function (b, a) {
  8560. return b ? Optional.some(a) : Optional.none();
  8561. };
  8562. var round = Math.round;
  8563. var clone$2 = function (rect) {
  8564. if (!rect) {
  8565. return {
  8566. left: 0,
  8567. top: 0,
  8568. bottom: 0,
  8569. right: 0,
  8570. width: 0,
  8571. height: 0
  8572. };
  8573. }
  8574. return {
  8575. left: round(rect.left),
  8576. top: round(rect.top),
  8577. bottom: round(rect.bottom),
  8578. right: round(rect.right),
  8579. width: round(rect.width),
  8580. height: round(rect.height)
  8581. };
  8582. };
  8583. var collapse = function (rect, toStart) {
  8584. rect = clone$2(rect);
  8585. if (toStart) {
  8586. rect.right = rect.left;
  8587. } else {
  8588. rect.left = rect.left + rect.width;
  8589. rect.right = rect.left;
  8590. }
  8591. rect.width = 0;
  8592. return rect;
  8593. };
  8594. var isEqual = function (rect1, rect2) {
  8595. return rect1.left === rect2.left && rect1.top === rect2.top && rect1.bottom === rect2.bottom && rect1.right === rect2.right;
  8596. };
  8597. var isValidOverflow = function (overflowY, rect1, rect2) {
  8598. return overflowY >= 0 && overflowY <= Math.min(rect1.height, rect2.height) / 2;
  8599. };
  8600. var isAbove = function (rect1, rect2) {
  8601. var halfHeight = Math.min(rect2.height / 2, rect1.height / 2);
  8602. if (rect1.bottom - halfHeight < rect2.top) {
  8603. return true;
  8604. }
  8605. if (rect1.top > rect2.bottom) {
  8606. return false;
  8607. }
  8608. return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
  8609. };
  8610. var isBelow = function (rect1, rect2) {
  8611. if (rect1.top > rect2.bottom) {
  8612. return true;
  8613. }
  8614. if (rect1.bottom < rect2.top) {
  8615. return false;
  8616. }
  8617. return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
  8618. };
  8619. var containsXY = function (rect, clientX, clientY) {
  8620. return clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
  8621. };
  8622. var getSelectedNode = function (range) {
  8623. var startContainer = range.startContainer, startOffset = range.startOffset;
  8624. if (startContainer.hasChildNodes() && range.endOffset === startOffset + 1) {
  8625. return startContainer.childNodes[startOffset];
  8626. }
  8627. return null;
  8628. };
  8629. var getNode = function (container, offset) {
  8630. if (container.nodeType === 1 && container.hasChildNodes()) {
  8631. if (offset >= container.childNodes.length) {
  8632. offset = container.childNodes.length - 1;
  8633. }
  8634. container = container.childNodes[offset];
  8635. }
  8636. return container;
  8637. };
  8638. 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]');
  8639. var isExtendingChar = function (ch) {
  8640. return typeof ch === 'string' && ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
  8641. };
  8642. var or = function () {
  8643. var args = [];
  8644. for (var _i = 0; _i < arguments.length; _i++) {
  8645. args[_i] = arguments[_i];
  8646. }
  8647. return function (x) {
  8648. for (var i = 0; i < args.length; i++) {
  8649. if (args[i](x)) {
  8650. return true;
  8651. }
  8652. }
  8653. return false;
  8654. };
  8655. };
  8656. var and = function () {
  8657. var args = [];
  8658. for (var _i = 0; _i < arguments.length; _i++) {
  8659. args[_i] = arguments[_i];
  8660. }
  8661. return function (x) {
  8662. for (var i = 0; i < args.length; i++) {
  8663. if (!args[i](x)) {
  8664. return false;
  8665. }
  8666. }
  8667. return true;
  8668. };
  8669. };
  8670. var isElement$3 = isElement$1;
  8671. var isCaretCandidate$1 = isCaretCandidate;
  8672. var isBlock$1 = matchStyleValues('display', 'block table');
  8673. var isFloated = matchStyleValues('float', 'left right');
  8674. var isValidElementCaretCandidate = and(isElement$3, isCaretCandidate$1, not(isFloated));
  8675. var isNotPre = not(matchStyleValues('white-space', 'pre pre-line pre-wrap'));
  8676. var isText$4 = isText$1;
  8677. var isBr$3 = isBr;
  8678. var nodeIndex = DOMUtils$1.nodeIndex;
  8679. var resolveIndex = getNode;
  8680. var createRange = function (doc) {
  8681. return 'createRange' in doc ? doc.createRange() : DOMUtils$1.DOM.createRng();
  8682. };
  8683. var isWhiteSpace = function (chr) {
  8684. return chr && /[\r\n\t ]/.test(chr);
  8685. };
  8686. var isRange = function (rng) {
  8687. return !!rng.setStart && !!rng.setEnd;
  8688. };
  8689. var isHiddenWhiteSpaceRange = function (range) {
  8690. var container = range.startContainer;
  8691. var offset = range.startOffset;
  8692. var text;
  8693. if (isWhiteSpace(range.toString()) && isNotPre(container.parentNode) && isText$1(container)) {
  8694. text = container.data;
  8695. if (isWhiteSpace(text[offset - 1]) || isWhiteSpace(text[offset + 1])) {
  8696. return true;
  8697. }
  8698. }
  8699. return false;
  8700. };
  8701. var getBrClientRect = function (brNode) {
  8702. var doc = brNode.ownerDocument;
  8703. var rng = createRange(doc);
  8704. var nbsp$1 = doc.createTextNode(nbsp);
  8705. var parentNode = brNode.parentNode;
  8706. parentNode.insertBefore(nbsp$1, brNode);
  8707. rng.setStart(nbsp$1, 0);
  8708. rng.setEnd(nbsp$1, 1);
  8709. var clientRect = clone$2(rng.getBoundingClientRect());
  8710. parentNode.removeChild(nbsp$1);
  8711. return clientRect;
  8712. };
  8713. var getBoundingClientRectWebKitText = function (rng) {
  8714. var sc = rng.startContainer;
  8715. var ec = rng.endContainer;
  8716. var so = rng.startOffset;
  8717. var eo = rng.endOffset;
  8718. if (sc === ec && isText$1(ec) && so === 0 && eo === 1) {
  8719. var newRng = rng.cloneRange();
  8720. newRng.setEndAfter(ec);
  8721. return getBoundingClientRect(newRng);
  8722. } else {
  8723. return null;
  8724. }
  8725. };
  8726. var isZeroRect = function (r) {
  8727. return r.left === 0 && r.right === 0 && r.top === 0 && r.bottom === 0;
  8728. };
  8729. var getBoundingClientRect = function (item) {
  8730. var clientRect;
  8731. var clientRects = item.getClientRects();
  8732. if (clientRects.length > 0) {
  8733. clientRect = clone$2(clientRects[0]);
  8734. } else {
  8735. clientRect = clone$2(item.getBoundingClientRect());
  8736. }
  8737. if (!isRange(item) && isBr$3(item) && isZeroRect(clientRect)) {
  8738. return getBrClientRect(item);
  8739. }
  8740. if (isZeroRect(clientRect) && isRange(item)) {
  8741. return getBoundingClientRectWebKitText(item);
  8742. }
  8743. return clientRect;
  8744. };
  8745. var collapseAndInflateWidth = function (clientRect, toStart) {
  8746. var newClientRect = collapse(clientRect, toStart);
  8747. newClientRect.width = 1;
  8748. newClientRect.right = newClientRect.left + 1;
  8749. return newClientRect;
  8750. };
  8751. var getCaretPositionClientRects = function (caretPosition) {
  8752. var clientRects = [];
  8753. var beforeNode, node;
  8754. var addUniqueAndValidRect = function (clientRect) {
  8755. if (clientRect.height === 0) {
  8756. return;
  8757. }
  8758. if (clientRects.length > 0) {
  8759. if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
  8760. return;
  8761. }
  8762. }
  8763. clientRects.push(clientRect);
  8764. };
  8765. var addCharacterOffset = function (container, offset) {
  8766. var range = createRange(container.ownerDocument);
  8767. if (offset < container.data.length) {
  8768. if (isExtendingChar(container.data[offset])) {
  8769. return clientRects;
  8770. }
  8771. if (isExtendingChar(container.data[offset - 1])) {
  8772. range.setStart(container, offset);
  8773. range.setEnd(container, offset + 1);
  8774. if (!isHiddenWhiteSpaceRange(range)) {
  8775. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(range), false));
  8776. return clientRects;
  8777. }
  8778. }
  8779. }
  8780. if (offset > 0) {
  8781. range.setStart(container, offset - 1);
  8782. range.setEnd(container, offset);
  8783. if (!isHiddenWhiteSpaceRange(range)) {
  8784. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(range), false));
  8785. }
  8786. }
  8787. if (offset < container.data.length) {
  8788. range.setStart(container, offset);
  8789. range.setEnd(container, offset + 1);
  8790. if (!isHiddenWhiteSpaceRange(range)) {
  8791. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(range), true));
  8792. }
  8793. }
  8794. };
  8795. if (isText$4(caretPosition.container())) {
  8796. addCharacterOffset(caretPosition.container(), caretPosition.offset());
  8797. return clientRects;
  8798. }
  8799. if (isElement$3(caretPosition.container())) {
  8800. if (caretPosition.isAtEnd()) {
  8801. node = resolveIndex(caretPosition.container(), caretPosition.offset());
  8802. if (isText$4(node)) {
  8803. addCharacterOffset(node, node.data.length);
  8804. }
  8805. if (isValidElementCaretCandidate(node) && !isBr$3(node)) {
  8806. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(node), false));
  8807. }
  8808. } else {
  8809. node = resolveIndex(caretPosition.container(), caretPosition.offset());
  8810. if (isText$4(node)) {
  8811. addCharacterOffset(node, 0);
  8812. }
  8813. if (isValidElementCaretCandidate(node) && caretPosition.isAtEnd()) {
  8814. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(node), false));
  8815. return clientRects;
  8816. }
  8817. beforeNode = resolveIndex(caretPosition.container(), caretPosition.offset() - 1);
  8818. if (isValidElementCaretCandidate(beforeNode) && !isBr$3(beforeNode)) {
  8819. if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
  8820. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(beforeNode), false));
  8821. }
  8822. }
  8823. if (isValidElementCaretCandidate(node)) {
  8824. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(node), true));
  8825. }
  8826. }
  8827. }
  8828. return clientRects;
  8829. };
  8830. function CaretPosition(container, offset, clientRects) {
  8831. var isAtStart = function () {
  8832. if (isText$4(container)) {
  8833. return offset === 0;
  8834. }
  8835. return offset === 0;
  8836. };
  8837. var isAtEnd = function () {
  8838. if (isText$4(container)) {
  8839. return offset >= container.data.length;
  8840. }
  8841. return offset >= container.childNodes.length;
  8842. };
  8843. var toRange = function () {
  8844. var range = createRange(container.ownerDocument);
  8845. range.setStart(container, offset);
  8846. range.setEnd(container, offset);
  8847. return range;
  8848. };
  8849. var getClientRects = function () {
  8850. if (!clientRects) {
  8851. clientRects = getCaretPositionClientRects(CaretPosition(container, offset));
  8852. }
  8853. return clientRects;
  8854. };
  8855. var isVisible = function () {
  8856. return getClientRects().length > 0;
  8857. };
  8858. var isEqual = function (caretPosition) {
  8859. return caretPosition && container === caretPosition.container() && offset === caretPosition.offset();
  8860. };
  8861. var getNode = function (before) {
  8862. return resolveIndex(container, before ? offset - 1 : offset);
  8863. };
  8864. return {
  8865. container: constant(container),
  8866. offset: constant(offset),
  8867. toRange: toRange,
  8868. getClientRects: getClientRects,
  8869. isVisible: isVisible,
  8870. isAtStart: isAtStart,
  8871. isAtEnd: isAtEnd,
  8872. isEqual: isEqual,
  8873. getNode: getNode
  8874. };
  8875. }
  8876. (function (CaretPosition) {
  8877. CaretPosition.fromRangeStart = function (range) {
  8878. return CaretPosition(range.startContainer, range.startOffset);
  8879. };
  8880. CaretPosition.fromRangeEnd = function (range) {
  8881. return CaretPosition(range.endContainer, range.endOffset);
  8882. };
  8883. CaretPosition.after = function (node) {
  8884. return CaretPosition(node.parentNode, nodeIndex(node) + 1);
  8885. };
  8886. CaretPosition.before = function (node) {
  8887. return CaretPosition(node.parentNode, nodeIndex(node));
  8888. };
  8889. CaretPosition.isAbove = function (pos1, pos2) {
  8890. return lift2(head(pos2.getClientRects()), last(pos1.getClientRects()), isAbove).getOr(false);
  8891. };
  8892. CaretPosition.isBelow = function (pos1, pos2) {
  8893. return lift2(last(pos2.getClientRects()), head(pos1.getClientRects()), isBelow).getOr(false);
  8894. };
  8895. CaretPosition.isAtStart = function (pos) {
  8896. return pos ? pos.isAtStart() : false;
  8897. };
  8898. CaretPosition.isAtEnd = function (pos) {
  8899. return pos ? pos.isAtEnd() : false;
  8900. };
  8901. CaretPosition.isTextPosition = function (pos) {
  8902. return pos ? isText$1(pos.container()) : false;
  8903. };
  8904. CaretPosition.isElementPosition = function (pos) {
  8905. return CaretPosition.isTextPosition(pos) === false;
  8906. };
  8907. }(CaretPosition || (CaretPosition = {})));
  8908. var CaretPosition$1 = CaretPosition;
  8909. var trimEmptyTextNode = function (dom, node) {
  8910. if (isText$1(node) && node.data.length === 0) {
  8911. dom.remove(node);
  8912. }
  8913. };
  8914. var insertNode = function (dom, rng, node) {
  8915. rng.insertNode(node);
  8916. trimEmptyTextNode(dom, node.previousSibling);
  8917. trimEmptyTextNode(dom, node.nextSibling);
  8918. };
  8919. var insertFragment = function (dom, rng, frag) {
  8920. var firstChild = Optional.from(frag.firstChild);
  8921. var lastChild = Optional.from(frag.lastChild);
  8922. rng.insertNode(frag);
  8923. firstChild.each(function (child) {
  8924. return trimEmptyTextNode(dom, child.previousSibling);
  8925. });
  8926. lastChild.each(function (child) {
  8927. return trimEmptyTextNode(dom, child.nextSibling);
  8928. });
  8929. };
  8930. var rangeInsertNode = function (dom, rng, node) {
  8931. if (isDocumentFragment$1(node)) {
  8932. insertFragment(dom, rng, node);
  8933. } else {
  8934. insertNode(dom, rng, node);
  8935. }
  8936. };
  8937. var isText$5 = isText$1;
  8938. var isBogus$2 = isBogus;
  8939. var nodeIndex$1 = DOMUtils$1.nodeIndex;
  8940. var normalizedParent = function (node) {
  8941. var parentNode = node.parentNode;
  8942. if (isBogus$2(parentNode)) {
  8943. return normalizedParent(parentNode);
  8944. }
  8945. return parentNode;
  8946. };
  8947. var getChildNodes = function (node) {
  8948. if (!node) {
  8949. return [];
  8950. }
  8951. return reduce(node.childNodes, function (result, node) {
  8952. if (isBogus$2(node) && node.nodeName !== 'BR') {
  8953. result = result.concat(getChildNodes(node));
  8954. } else {
  8955. result.push(node);
  8956. }
  8957. return result;
  8958. }, []);
  8959. };
  8960. var normalizedTextOffset = function (node, offset) {
  8961. while (node = node.previousSibling) {
  8962. if (!isText$5(node)) {
  8963. break;
  8964. }
  8965. offset += node.data.length;
  8966. }
  8967. return offset;
  8968. };
  8969. var equal$1 = function (a) {
  8970. return function (b) {
  8971. return a === b;
  8972. };
  8973. };
  8974. var normalizedNodeIndex = function (node) {
  8975. var nodes, index;
  8976. nodes = getChildNodes(normalizedParent(node));
  8977. index = findIndex$1(nodes, equal$1(node), node);
  8978. nodes = nodes.slice(0, index + 1);
  8979. var numTextFragments = reduce(nodes, function (result, node, i) {
  8980. if (isText$5(node) && isText$5(nodes[i - 1])) {
  8981. result++;
  8982. }
  8983. return result;
  8984. }, 0);
  8985. nodes = filter$2(nodes, matchNodeNames([node.nodeName]));
  8986. index = findIndex$1(nodes, equal$1(node), node);
  8987. return index - numTextFragments;
  8988. };
  8989. var createPathItem = function (node) {
  8990. var name;
  8991. if (isText$5(node)) {
  8992. name = 'text()';
  8993. } else {
  8994. name = node.nodeName.toLowerCase();
  8995. }
  8996. return name + '[' + normalizedNodeIndex(node) + ']';
  8997. };
  8998. var parentsUntil = function (root, node, predicate) {
  8999. var parents = [];
  9000. for (node = node.parentNode; node !== root; node = node.parentNode) {
  9001. if (predicate && predicate(node)) {
  9002. break;
  9003. }
  9004. parents.push(node);
  9005. }
  9006. return parents;
  9007. };
  9008. var create$3 = function (root, caretPosition) {
  9009. var container, offset, path = [], outputOffset, childNodes, parents;
  9010. container = caretPosition.container();
  9011. offset = caretPosition.offset();
  9012. if (isText$5(container)) {
  9013. outputOffset = normalizedTextOffset(container, offset);
  9014. } else {
  9015. childNodes = container.childNodes;
  9016. if (offset >= childNodes.length) {
  9017. outputOffset = 'after';
  9018. offset = childNodes.length - 1;
  9019. } else {
  9020. outputOffset = 'before';
  9021. }
  9022. container = childNodes[offset];
  9023. }
  9024. path.push(createPathItem(container));
  9025. parents = parentsUntil(root, container);
  9026. parents = filter$2(parents, not(isBogus));
  9027. path = path.concat(map$2(parents, function (node) {
  9028. return createPathItem(node);
  9029. }));
  9030. return path.reverse().join('/') + ',' + outputOffset;
  9031. };
  9032. var resolvePathItem = function (node, name, index) {
  9033. var nodes = getChildNodes(node);
  9034. nodes = filter$2(nodes, function (node, index) {
  9035. return !isText$5(node) || !isText$5(nodes[index - 1]);
  9036. });
  9037. nodes = filter$2(nodes, matchNodeNames([name]));
  9038. return nodes[index];
  9039. };
  9040. var findTextPosition = function (container, offset) {
  9041. var node = container, targetOffset = 0, dataLen;
  9042. while (isText$5(node)) {
  9043. dataLen = node.data.length;
  9044. if (offset >= targetOffset && offset <= targetOffset + dataLen) {
  9045. container = node;
  9046. offset = offset - targetOffset;
  9047. break;
  9048. }
  9049. if (!isText$5(node.nextSibling)) {
  9050. container = node;
  9051. offset = dataLen;
  9052. break;
  9053. }
  9054. targetOffset += dataLen;
  9055. node = node.nextSibling;
  9056. }
  9057. if (isText$5(container) && offset > container.data.length) {
  9058. offset = container.data.length;
  9059. }
  9060. return CaretPosition$1(container, offset);
  9061. };
  9062. var resolve$1 = function (root, path) {
  9063. var offset;
  9064. if (!path) {
  9065. return null;
  9066. }
  9067. var parts = path.split(',');
  9068. var paths = parts[0].split('/');
  9069. offset = parts.length > 1 ? parts[1] : 'before';
  9070. var container = reduce(paths, function (result, value) {
  9071. var match = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value);
  9072. if (!match) {
  9073. return null;
  9074. }
  9075. if (match[1] === 'text()') {
  9076. match[1] = '#text';
  9077. }
  9078. return resolvePathItem(result, match[1], parseInt(match[2], 10));
  9079. }, root);
  9080. if (!container) {
  9081. return null;
  9082. }
  9083. if (!isText$5(container)) {
  9084. if (offset === 'after') {
  9085. offset = nodeIndex$1(container) + 1;
  9086. } else {
  9087. offset = nodeIndex$1(container);
  9088. }
  9089. return CaretPosition$1(container.parentNode, offset);
  9090. }
  9091. return findTextPosition(container, parseInt(offset, 10));
  9092. };
  9093. var isContentEditableFalse$2 = isContentEditableFalse;
  9094. var getNormalizedTextOffset = function (trim, container, offset) {
  9095. var node, trimmedOffset;
  9096. trimmedOffset = trim(container.data.slice(0, offset)).length;
  9097. for (node = container.previousSibling; node && isText$1(node); node = node.previousSibling) {
  9098. trimmedOffset += trim(node.data).length;
  9099. }
  9100. return trimmedOffset;
  9101. };
  9102. var getPoint = function (dom, trim, normalized, rng, start) {
  9103. var container = rng[start ? 'startContainer' : 'endContainer'];
  9104. var offset = rng[start ? 'startOffset' : 'endOffset'];
  9105. var point = [];
  9106. var childNodes, after = 0;
  9107. var root = dom.getRoot();
  9108. if (isText$1(container)) {
  9109. point.push(normalized ? getNormalizedTextOffset(trim, container, offset) : offset);
  9110. } else {
  9111. childNodes = container.childNodes;
  9112. if (offset >= childNodes.length && childNodes.length) {
  9113. after = 1;
  9114. offset = Math.max(0, childNodes.length - 1);
  9115. }
  9116. point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
  9117. }
  9118. for (; container && container !== root; container = container.parentNode) {
  9119. point.push(dom.nodeIndex(container, normalized));
  9120. }
  9121. return point;
  9122. };
  9123. var getLocation = function (trim, selection, normalized, rng) {
  9124. var dom = selection.dom, bookmark = {};
  9125. bookmark.start = getPoint(dom, trim, normalized, rng, true);
  9126. if (!selection.isCollapsed()) {
  9127. bookmark.end = getPoint(dom, trim, normalized, rng, false);
  9128. }
  9129. return bookmark;
  9130. };
  9131. var findIndex$2 = function (dom, name, element) {
  9132. var count = 0;
  9133. Tools.each(dom.select(name), function (node) {
  9134. if (node.getAttribute('data-mce-bogus') === 'all') {
  9135. return;
  9136. }
  9137. if (node === element) {
  9138. return false;
  9139. }
  9140. count++;
  9141. });
  9142. return count;
  9143. };
  9144. var moveEndPoint = function (rng, start) {
  9145. var container, offset, childNodes;
  9146. var prefix = start ? 'start' : 'end';
  9147. container = rng[prefix + 'Container'];
  9148. offset = rng[prefix + 'Offset'];
  9149. if (isElement$1(container) && container.nodeName === 'TR') {
  9150. childNodes = container.childNodes;
  9151. container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
  9152. if (container) {
  9153. offset = start ? 0 : container.childNodes.length;
  9154. rng['set' + (start ? 'Start' : 'End')](container, offset);
  9155. }
  9156. }
  9157. };
  9158. var normalizeTableCellSelection = function (rng) {
  9159. moveEndPoint(rng, true);
  9160. moveEndPoint(rng, false);
  9161. return rng;
  9162. };
  9163. var findSibling = function (node, offset) {
  9164. var sibling;
  9165. if (isElement$1(node)) {
  9166. node = getNode(node, offset);
  9167. if (isContentEditableFalse$2(node)) {
  9168. return node;
  9169. }
  9170. }
  9171. if (isCaretContainer(node)) {
  9172. if (isText$1(node) && isCaretContainerBlock(node)) {
  9173. node = node.parentNode;
  9174. }
  9175. sibling = node.previousSibling;
  9176. if (isContentEditableFalse$2(sibling)) {
  9177. return sibling;
  9178. }
  9179. sibling = node.nextSibling;
  9180. if (isContentEditableFalse$2(sibling)) {
  9181. return sibling;
  9182. }
  9183. }
  9184. };
  9185. var findAdjacentContentEditableFalseElm = function (rng) {
  9186. return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
  9187. };
  9188. var getOffsetBookmark = function (trim, normalized, selection) {
  9189. var element = selection.getNode();
  9190. var name = element ? element.nodeName : null;
  9191. var rng = selection.getRng();
  9192. if (isContentEditableFalse$2(element) || name === 'IMG') {
  9193. return {
  9194. name: name,
  9195. index: findIndex$2(selection.dom, name, element)
  9196. };
  9197. }
  9198. var sibling = findAdjacentContentEditableFalseElm(rng);
  9199. if (sibling) {
  9200. name = sibling.tagName;
  9201. return {
  9202. name: name,
  9203. index: findIndex$2(selection.dom, name, sibling)
  9204. };
  9205. }
  9206. return getLocation(trim, selection, normalized, rng);
  9207. };
  9208. var getCaretBookmark = function (selection) {
  9209. var rng = selection.getRng();
  9210. return {
  9211. start: create$3(selection.dom.getRoot(), CaretPosition$1.fromRangeStart(rng)),
  9212. end: create$3(selection.dom.getRoot(), CaretPosition$1.fromRangeEnd(rng))
  9213. };
  9214. };
  9215. var getRangeBookmark = function (selection) {
  9216. return { rng: selection.getRng() };
  9217. };
  9218. var createBookmarkSpan = function (dom, id, filled) {
  9219. var args = {
  9220. 'data-mce-type': 'bookmark',
  9221. id: id,
  9222. 'style': 'overflow:hidden;line-height:0px'
  9223. };
  9224. return filled ? dom.create('span', args, '&#xFEFF;') : dom.create('span', args);
  9225. };
  9226. var getPersistentBookmark = function (selection, filled) {
  9227. var dom = selection.dom;
  9228. var rng = selection.getRng();
  9229. var id = dom.uniqueId();
  9230. var collapsed = selection.isCollapsed();
  9231. var element = selection.getNode();
  9232. var name = element.nodeName;
  9233. if (name === 'IMG') {
  9234. return {
  9235. name: name,
  9236. index: findIndex$2(dom, name, element)
  9237. };
  9238. }
  9239. var rng2 = normalizeTableCellSelection(rng.cloneRange());
  9240. if (!collapsed) {
  9241. rng2.collapse(false);
  9242. var endBookmarkNode = createBookmarkSpan(dom, id + '_end', filled);
  9243. rangeInsertNode(dom, rng2, endBookmarkNode);
  9244. }
  9245. rng = normalizeTableCellSelection(rng);
  9246. rng.collapse(true);
  9247. var startBookmarkNode = createBookmarkSpan(dom, id + '_start', filled);
  9248. rangeInsertNode(dom, rng, startBookmarkNode);
  9249. selection.moveToBookmark({
  9250. id: id,
  9251. keep: true
  9252. });
  9253. return { id: id };
  9254. };
  9255. var getBookmark = function (selection, type, normalized) {
  9256. if (type === 2) {
  9257. return getOffsetBookmark(trim$2, normalized, selection);
  9258. } else if (type === 3) {
  9259. return getCaretBookmark(selection);
  9260. } else if (type) {
  9261. return getRangeBookmark(selection);
  9262. } else {
  9263. return getPersistentBookmark(selection, false);
  9264. }
  9265. };
  9266. var getUndoBookmark = curry(getOffsetBookmark, identity, true);
  9267. var DOM$1 = DOMUtils$1.DOM;
  9268. var defaultPreviewStyles = 'font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow';
  9269. var getBodySetting = function (editor, name, defaultValue) {
  9270. var value = editor.getParam(name, defaultValue);
  9271. if (value.indexOf('=') !== -1) {
  9272. var bodyObj = editor.getParam(name, '', 'hash');
  9273. return bodyObj.hasOwnProperty(editor.id) ? bodyObj[editor.id] : defaultValue;
  9274. } else {
  9275. return value;
  9276. }
  9277. };
  9278. var getIframeAttrs = function (editor) {
  9279. return editor.getParam('iframe_attrs', {});
  9280. };
  9281. var getDocType = function (editor) {
  9282. return editor.getParam('doctype', '<!DOCTYPE html>');
  9283. };
  9284. var getDocumentBaseUrl = function (editor) {
  9285. return editor.getParam('document_base_url', '');
  9286. };
  9287. var getBodyId = function (editor) {
  9288. return getBodySetting(editor, 'body_id', 'tinymce');
  9289. };
  9290. var getBodyClass = function (editor) {
  9291. return getBodySetting(editor, 'body_class', '');
  9292. };
  9293. var getContentSecurityPolicy = function (editor) {
  9294. return editor.getParam('content_security_policy', '');
  9295. };
  9296. var shouldPutBrInPre = function (editor) {
  9297. return editor.getParam('br_in_pre', true);
  9298. };
  9299. var getForcedRootBlock = function (editor) {
  9300. if (editor.getParam('force_p_newlines', false)) {
  9301. return 'p';
  9302. }
  9303. var block = editor.getParam('forced_root_block', 'p');
  9304. if (block === false) {
  9305. return '';
  9306. } else if (block === true) {
  9307. return 'p';
  9308. } else {
  9309. return block;
  9310. }
  9311. };
  9312. var getForcedRootBlockAttrs = function (editor) {
  9313. return editor.getParam('forced_root_block_attrs', {});
  9314. };
  9315. var getBrNewLineSelector = function (editor) {
  9316. return editor.getParam('br_newline_selector', '.mce-toc h2,figcaption,caption');
  9317. };
  9318. var getNoNewLineSelector = function (editor) {
  9319. return editor.getParam('no_newline_selector', '');
  9320. };
  9321. var shouldKeepStyles = function (editor) {
  9322. return editor.getParam('keep_styles', true);
  9323. };
  9324. var shouldEndContainerOnEmptyBlock = function (editor) {
  9325. return editor.getParam('end_container_on_empty_block', false);
  9326. };
  9327. var getFontStyleValues = function (editor) {
  9328. return Tools.explode(editor.getParam('font_size_style_values', 'xx-small,x-small,small,medium,large,x-large,xx-large'));
  9329. };
  9330. var getFontSizeClasses = function (editor) {
  9331. return Tools.explode(editor.getParam('font_size_classes', ''));
  9332. };
  9333. var getImagesDataImgFilter = function (editor) {
  9334. return editor.getParam('images_dataimg_filter', always, 'function');
  9335. };
  9336. var isAutomaticUploadsEnabled = function (editor) {
  9337. return editor.getParam('automatic_uploads', true, 'boolean');
  9338. };
  9339. var shouldReuseFileName = function (editor) {
  9340. return editor.getParam('images_reuse_filename', false, 'boolean');
  9341. };
  9342. var shouldReplaceBlobUris = function (editor) {
  9343. return editor.getParam('images_replace_blob_uris', true, 'boolean');
  9344. };
  9345. var getIconPackName = function (editor) {
  9346. return editor.getParam('icons', '', 'string');
  9347. };
  9348. var getIconsUrl = function (editor) {
  9349. return editor.getParam('icons_url', '', 'string');
  9350. };
  9351. var getImageUploadUrl = function (editor) {
  9352. return editor.getParam('images_upload_url', '', 'string');
  9353. };
  9354. var getImageUploadBasePath = function (editor) {
  9355. return editor.getParam('images_upload_base_path', '', 'string');
  9356. };
  9357. var getImagesUploadCredentials = function (editor) {
  9358. return editor.getParam('images_upload_credentials', false, 'boolean');
  9359. };
  9360. var getImagesUploadHandler = function (editor) {
  9361. return editor.getParam('images_upload_handler', null, 'function');
  9362. };
  9363. var shouldUseContentCssCors = function (editor) {
  9364. return editor.getParam('content_css_cors', false, 'boolean');
  9365. };
  9366. var getReferrerPolicy = function (editor) {
  9367. return editor.getParam('referrer_policy', '', 'string');
  9368. };
  9369. var getLanguageCode = function (editor) {
  9370. return editor.getParam('language', 'en', 'string');
  9371. };
  9372. var getLanguageUrl = function (editor) {
  9373. return editor.getParam('language_url', '', 'string');
  9374. };
  9375. var shouldIndentUseMargin = function (editor) {
  9376. return editor.getParam('indent_use_margin', false);
  9377. };
  9378. var getIndentation = function (editor) {
  9379. return editor.getParam('indentation', '40px', 'string');
  9380. };
  9381. var getContentCss = function (editor) {
  9382. var contentCss = editor.getParam('content_css');
  9383. if (isString(contentCss)) {
  9384. return map(contentCss.split(','), trim);
  9385. } else if (isArray(contentCss)) {
  9386. return contentCss;
  9387. } else if (contentCss === false || editor.inline) {
  9388. return [];
  9389. } else {
  9390. return ['default'];
  9391. }
  9392. };
  9393. var getDirectionality = function (editor) {
  9394. return editor.getParam('directionality', I18n.isRtl() ? 'rtl' : undefined);
  9395. };
  9396. var getInlineBoundarySelector = function (editor) {
  9397. return editor.getParam('inline_boundaries_selector', 'a[href],code,.mce-annotation', 'string');
  9398. };
  9399. var getObjectResizing = function (editor) {
  9400. var selector = editor.getParam('object_resizing');
  9401. if (selector === false || Env.iOS) {
  9402. return false;
  9403. } else {
  9404. return isString(selector) ? selector : 'table,img,figure.image,div';
  9405. }
  9406. };
  9407. var getResizeImgProportional = function (editor) {
  9408. return editor.getParam('resize_img_proportional', true, 'boolean');
  9409. };
  9410. var getPlaceholder = function (editor) {
  9411. return editor.getParam('placeholder', DOM$1.getAttrib(editor.getElement(), 'placeholder'), 'string');
  9412. };
  9413. var getEventRoot = function (editor) {
  9414. return editor.getParam('event_root');
  9415. };
  9416. var getServiceMessage = function (editor) {
  9417. return editor.getParam('service_message');
  9418. };
  9419. var getTheme = function (editor) {
  9420. return editor.getParam('theme');
  9421. };
  9422. var shouldValidate = function (editor) {
  9423. return editor.getParam('validate');
  9424. };
  9425. var isInlineBoundariesEnabled = function (editor) {
  9426. return editor.getParam('inline_boundaries') !== false;
  9427. };
  9428. var getFormats = function (editor) {
  9429. return editor.getParam('formats');
  9430. };
  9431. var getPreviewStyles = function (editor) {
  9432. var style = editor.getParam('preview_styles', defaultPreviewStyles);
  9433. if (isString(style)) {
  9434. return style;
  9435. } else {
  9436. return '';
  9437. }
  9438. };
  9439. var canFormatEmptyLines = function (editor) {
  9440. return editor.getParam('format_empty_lines', false, 'boolean');
  9441. };
  9442. var getCustomUiSelector = function (editor) {
  9443. return editor.getParam('custom_ui_selector', '', 'string');
  9444. };
  9445. var getThemeUrl = function (editor) {
  9446. return editor.getParam('theme_url');
  9447. };
  9448. var isInline$1 = function (editor) {
  9449. return editor.getParam('inline');
  9450. };
  9451. var hasHiddenInput = function (editor) {
  9452. return editor.getParam('hidden_input');
  9453. };
  9454. var shouldPatchSubmit = function (editor) {
  9455. return editor.getParam('submit_patch');
  9456. };
  9457. var isEncodingXml = function (editor) {
  9458. return editor.getParam('encoding') === 'xml';
  9459. };
  9460. var shouldAddFormSubmitTrigger = function (editor) {
  9461. return editor.getParam('add_form_submit_trigger');
  9462. };
  9463. var shouldAddUnloadTrigger = function (editor) {
  9464. return editor.getParam('add_unload_trigger');
  9465. };
  9466. var hasForcedRootBlock = function (editor) {
  9467. return getForcedRootBlock(editor) !== '';
  9468. };
  9469. var getCustomUndoRedoLevels = function (editor) {
  9470. return editor.getParam('custom_undo_redo_levels', 0, 'number');
  9471. };
  9472. var shouldDisableNodeChange = function (editor) {
  9473. return editor.getParam('disable_nodechange');
  9474. };
  9475. var isReadOnly = function (editor) {
  9476. return editor.getParam('readonly');
  9477. };
  9478. var hasContentCssCors = function (editor) {
  9479. return editor.getParam('content_css_cors');
  9480. };
  9481. var getPlugins = function (editor) {
  9482. return editor.getParam('plugins', '', 'string');
  9483. };
  9484. var getExternalPlugins = function (editor) {
  9485. return editor.getParam('external_plugins');
  9486. };
  9487. var shouldBlockUnsupportedDrop = function (editor) {
  9488. return editor.getParam('block_unsupported_drop', true, 'boolean');
  9489. };
  9490. var isVisualAidsEnabled = function (editor) {
  9491. return editor.getParam('visual', true, 'boolean');
  9492. };
  9493. var getVisualAidsTableClass = function (editor) {
  9494. return editor.getParam('visual_table_class', 'mce-item-table', 'string');
  9495. };
  9496. var getVisualAidsAnchorClass = function (editor) {
  9497. return editor.getParam('visual_anchor_class', 'mce-item-anchor', 'string');
  9498. };
  9499. var isElement$4 = isElement$1;
  9500. var isText$6 = isText$1;
  9501. var removeNode = function (node) {
  9502. var parentNode = node.parentNode;
  9503. if (parentNode) {
  9504. parentNode.removeChild(node);
  9505. }
  9506. };
  9507. var trimCount = function (text) {
  9508. var trimmedText = trim$2(text);
  9509. return {
  9510. count: text.length - trimmedText.length,
  9511. text: trimmedText
  9512. };
  9513. };
  9514. var deleteZwspChars = function (caretContainer) {
  9515. var idx;
  9516. while ((idx = caretContainer.data.lastIndexOf(ZWSP)) !== -1) {
  9517. caretContainer.deleteData(idx, 1);
  9518. }
  9519. };
  9520. var removeUnchanged = function (caretContainer, pos) {
  9521. remove$5(caretContainer);
  9522. return pos;
  9523. };
  9524. var removeTextAndReposition = function (caretContainer, pos) {
  9525. var before = trimCount(caretContainer.data.substr(0, pos.offset()));
  9526. var after = trimCount(caretContainer.data.substr(pos.offset()));
  9527. var text = before.text + after.text;
  9528. if (text.length > 0) {
  9529. deleteZwspChars(caretContainer);
  9530. return CaretPosition$1(caretContainer, pos.offset() - before.count);
  9531. } else {
  9532. return pos;
  9533. }
  9534. };
  9535. var removeElementAndReposition = function (caretContainer, pos) {
  9536. var parentNode = pos.container();
  9537. var newPosition = indexOf(from$1(parentNode.childNodes), caretContainer).map(function (index) {
  9538. return index < pos.offset() ? CaretPosition$1(parentNode, pos.offset() - 1) : pos;
  9539. }).getOr(pos);
  9540. remove$5(caretContainer);
  9541. return newPosition;
  9542. };
  9543. var removeTextCaretContainer = function (caretContainer, pos) {
  9544. return isText$6(caretContainer) && pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9545. };
  9546. var removeElementCaretContainer = function (caretContainer, pos) {
  9547. return pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9548. };
  9549. var removeAndReposition = function (container, pos) {
  9550. return CaretPosition$1.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
  9551. };
  9552. var remove$5 = function (caretContainerNode) {
  9553. if (isElement$4(caretContainerNode) && isCaretContainer(caretContainerNode)) {
  9554. if (hasContent(caretContainerNode)) {
  9555. caretContainerNode.removeAttribute('data-mce-caret');
  9556. } else {
  9557. removeNode(caretContainerNode);
  9558. }
  9559. }
  9560. if (isText$6(caretContainerNode)) {
  9561. deleteZwspChars(caretContainerNode);
  9562. if (caretContainerNode.data.length === 0) {
  9563. removeNode(caretContainerNode);
  9564. }
  9565. }
  9566. };
  9567. var browser$2 = detect$3().browser;
  9568. var isContentEditableFalse$3 = isContentEditableFalse;
  9569. var isMedia$1 = isMedia;
  9570. var isTableCell$2 = isTableCell;
  9571. var inlineFakeCaretSelector = '*[contentEditable=false],video,audio,embed,object';
  9572. var getAbsoluteClientRect = function (root, element, before) {
  9573. var clientRect = collapse(element.getBoundingClientRect(), before);
  9574. var docElm, scrollX, scrollY, margin, rootRect;
  9575. if (root.tagName === 'BODY') {
  9576. docElm = root.ownerDocument.documentElement;
  9577. scrollX = root.scrollLeft || docElm.scrollLeft;
  9578. scrollY = root.scrollTop || docElm.scrollTop;
  9579. } else {
  9580. rootRect = root.getBoundingClientRect();
  9581. scrollX = root.scrollLeft - rootRect.left;
  9582. scrollY = root.scrollTop - rootRect.top;
  9583. }
  9584. clientRect.left += scrollX;
  9585. clientRect.right += scrollX;
  9586. clientRect.top += scrollY;
  9587. clientRect.bottom += scrollY;
  9588. clientRect.width = 1;
  9589. margin = element.offsetWidth - element.clientWidth;
  9590. if (margin > 0) {
  9591. if (before) {
  9592. margin *= -1;
  9593. }
  9594. clientRect.left += margin;
  9595. clientRect.right += margin;
  9596. }
  9597. return clientRect;
  9598. };
  9599. var trimInlineCaretContainers = function (root) {
  9600. var fakeCaretTargetNodes = descendants$1(SugarElement.fromDom(root), inlineFakeCaretSelector);
  9601. for (var i = 0; i < fakeCaretTargetNodes.length; i++) {
  9602. var node = fakeCaretTargetNodes[i].dom;
  9603. var sibling = node.previousSibling;
  9604. if (endsWithCaretContainer(sibling)) {
  9605. var data = sibling.data;
  9606. if (data.length === 1) {
  9607. sibling.parentNode.removeChild(sibling);
  9608. } else {
  9609. sibling.deleteData(data.length - 1, 1);
  9610. }
  9611. }
  9612. sibling = node.nextSibling;
  9613. if (startsWithCaretContainer(sibling)) {
  9614. var data = sibling.data;
  9615. if (data.length === 1) {
  9616. sibling.parentNode.removeChild(sibling);
  9617. } else {
  9618. sibling.deleteData(0, 1);
  9619. }
  9620. }
  9621. }
  9622. };
  9623. var FakeCaret = function (editor, root, isBlock, hasFocus) {
  9624. var lastVisualCaret = Cell(Optional.none());
  9625. var cursorInterval, caretContainerNode;
  9626. var rootBlock = getForcedRootBlock(editor);
  9627. var caretBlock = rootBlock.length > 0 ? rootBlock : 'p';
  9628. var show = function (before, element) {
  9629. var clientRect, rng;
  9630. hide();
  9631. if (isTableCell$2(element)) {
  9632. return null;
  9633. }
  9634. if (isBlock(element)) {
  9635. caretContainerNode = insertBlock(caretBlock, element, before);
  9636. clientRect = getAbsoluteClientRect(root, element, before);
  9637. DomQuery(caretContainerNode).css('top', clientRect.top);
  9638. var caret = DomQuery('<div class="mce-visual-caret" data-mce-bogus="all"></div>').css(clientRect).appendTo(root)[0];
  9639. lastVisualCaret.set(Optional.some({
  9640. caret: caret,
  9641. element: element,
  9642. before: before
  9643. }));
  9644. lastVisualCaret.get().each(function (caretState) {
  9645. if (before) {
  9646. DomQuery(caretState.caret).addClass('mce-visual-caret-before');
  9647. }
  9648. });
  9649. startBlink();
  9650. rng = element.ownerDocument.createRange();
  9651. rng.setStart(caretContainerNode, 0);
  9652. rng.setEnd(caretContainerNode, 0);
  9653. } else {
  9654. caretContainerNode = insertInline(element, before);
  9655. rng = element.ownerDocument.createRange();
  9656. if (isInlineFakeCaretTarget(caretContainerNode.nextSibling)) {
  9657. rng.setStart(caretContainerNode, 0);
  9658. rng.setEnd(caretContainerNode, 0);
  9659. } else {
  9660. rng.setStart(caretContainerNode, 1);
  9661. rng.setEnd(caretContainerNode, 1);
  9662. }
  9663. return rng;
  9664. }
  9665. return rng;
  9666. };
  9667. var hide = function () {
  9668. trimInlineCaretContainers(root);
  9669. if (caretContainerNode) {
  9670. remove$5(caretContainerNode);
  9671. caretContainerNode = null;
  9672. }
  9673. lastVisualCaret.get().each(function (caretState) {
  9674. DomQuery(caretState.caret).remove();
  9675. lastVisualCaret.set(Optional.none());
  9676. });
  9677. if (cursorInterval) {
  9678. Delay.clearInterval(cursorInterval);
  9679. cursorInterval = null;
  9680. }
  9681. };
  9682. var startBlink = function () {
  9683. cursorInterval = Delay.setInterval(function () {
  9684. if (hasFocus()) {
  9685. DomQuery('div.mce-visual-caret', root).toggleClass('mce-visual-caret-hidden');
  9686. } else {
  9687. DomQuery('div.mce-visual-caret', root).addClass('mce-visual-caret-hidden');
  9688. }
  9689. }, 500);
  9690. };
  9691. var reposition = function () {
  9692. lastVisualCaret.get().each(function (caretState) {
  9693. var clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
  9694. DomQuery(caretState.caret).css(__assign({}, clientRect));
  9695. });
  9696. };
  9697. var destroy = function () {
  9698. return Delay.clearInterval(cursorInterval);
  9699. };
  9700. var getCss = function () {
  9701. 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;' + '}';
  9702. };
  9703. return {
  9704. show: show,
  9705. hide: hide,
  9706. getCss: getCss,
  9707. reposition: reposition,
  9708. destroy: destroy
  9709. };
  9710. };
  9711. var isFakeCaretTableBrowser = function () {
  9712. return browser$2.isIE() || browser$2.isEdge() || browser$2.isFirefox();
  9713. };
  9714. var isInlineFakeCaretTarget = function (node) {
  9715. return isContentEditableFalse$3(node) || isMedia$1(node);
  9716. };
  9717. var isFakeCaretTarget = function (node) {
  9718. return isInlineFakeCaretTarget(node) || isTable(node) && isFakeCaretTableBrowser();
  9719. };
  9720. var isContentEditableFalse$4 = isContentEditableFalse;
  9721. var isMedia$2 = isMedia;
  9722. var isBlockLike = matchStyleValues('display', 'block table table-cell table-caption list-item');
  9723. var isCaretContainer$2 = isCaretContainer;
  9724. var isCaretContainerBlock$1 = isCaretContainerBlock;
  9725. var isElement$5 = isElement$1;
  9726. var isCaretCandidate$2 = isCaretCandidate;
  9727. var isForwards = function (direction) {
  9728. return direction > 0;
  9729. };
  9730. var isBackwards = function (direction) {
  9731. return direction < 0;
  9732. };
  9733. var skipCaretContainers = function (walk, shallow) {
  9734. var node;
  9735. while (node = walk(shallow)) {
  9736. if (!isCaretContainerBlock$1(node)) {
  9737. return node;
  9738. }
  9739. }
  9740. return null;
  9741. };
  9742. var findNode = function (node, direction, predicateFn, rootNode, shallow) {
  9743. var walker = new DomTreeWalker(node, rootNode);
  9744. var isCefOrCaretContainer = isContentEditableFalse$4(node) || isCaretContainerBlock$1(node);
  9745. if (isBackwards(direction)) {
  9746. if (isCefOrCaretContainer) {
  9747. node = skipCaretContainers(walker.prev, true);
  9748. if (predicateFn(node)) {
  9749. return node;
  9750. }
  9751. }
  9752. while (node = skipCaretContainers(walker.prev, shallow)) {
  9753. if (predicateFn(node)) {
  9754. return node;
  9755. }
  9756. }
  9757. }
  9758. if (isForwards(direction)) {
  9759. if (isCefOrCaretContainer) {
  9760. node = skipCaretContainers(walker.next, true);
  9761. if (predicateFn(node)) {
  9762. return node;
  9763. }
  9764. }
  9765. while (node = skipCaretContainers(walker.next, shallow)) {
  9766. if (predicateFn(node)) {
  9767. return node;
  9768. }
  9769. }
  9770. }
  9771. return null;
  9772. };
  9773. var getParentBlock = function (node, rootNode) {
  9774. while (node && node !== rootNode) {
  9775. if (isBlockLike(node)) {
  9776. return node;
  9777. }
  9778. node = node.parentNode;
  9779. }
  9780. return null;
  9781. };
  9782. var isInSameBlock = function (caretPosition1, caretPosition2, rootNode) {
  9783. return getParentBlock(caretPosition1.container(), rootNode) === getParentBlock(caretPosition2.container(), rootNode);
  9784. };
  9785. var getChildNodeAtRelativeOffset = function (relativeOffset, caretPosition) {
  9786. if (!caretPosition) {
  9787. return null;
  9788. }
  9789. var container = caretPosition.container();
  9790. var offset = caretPosition.offset();
  9791. if (!isElement$5(container)) {
  9792. return null;
  9793. }
  9794. return container.childNodes[offset + relativeOffset];
  9795. };
  9796. var beforeAfter = function (before, node) {
  9797. var range = node.ownerDocument.createRange();
  9798. if (before) {
  9799. range.setStartBefore(node);
  9800. range.setEndBefore(node);
  9801. } else {
  9802. range.setStartAfter(node);
  9803. range.setEndAfter(node);
  9804. }
  9805. return range;
  9806. };
  9807. var isNodesInSameBlock = function (root, node1, node2) {
  9808. return getParentBlock(node1, root) === getParentBlock(node2, root);
  9809. };
  9810. var lean = function (left, root, node) {
  9811. var sibling, siblingName;
  9812. if (left) {
  9813. siblingName = 'previousSibling';
  9814. } else {
  9815. siblingName = 'nextSibling';
  9816. }
  9817. while (node && node !== root) {
  9818. sibling = node[siblingName];
  9819. if (isCaretContainer$2(sibling)) {
  9820. sibling = sibling[siblingName];
  9821. }
  9822. if (isContentEditableFalse$4(sibling) || isMedia$2(sibling)) {
  9823. if (isNodesInSameBlock(root, sibling, node)) {
  9824. return sibling;
  9825. }
  9826. break;
  9827. }
  9828. if (isCaretCandidate$2(sibling)) {
  9829. break;
  9830. }
  9831. node = node.parentNode;
  9832. }
  9833. return null;
  9834. };
  9835. var before$2 = curry(beforeAfter, true);
  9836. var after$1 = curry(beforeAfter, false);
  9837. var normalizeRange = function (direction, root, range) {
  9838. var node, container, location;
  9839. var leanLeft = curry(lean, true, root);
  9840. var leanRight = curry(lean, false, root);
  9841. container = range.startContainer;
  9842. var offset = range.startOffset;
  9843. if (isCaretContainerBlock(container)) {
  9844. if (!isElement$5(container)) {
  9845. container = container.parentNode;
  9846. }
  9847. location = container.getAttribute('data-mce-caret');
  9848. if (location === 'before') {
  9849. node = container.nextSibling;
  9850. if (isFakeCaretTarget(node)) {
  9851. return before$2(node);
  9852. }
  9853. }
  9854. if (location === 'after') {
  9855. node = container.previousSibling;
  9856. if (isFakeCaretTarget(node)) {
  9857. return after$1(node);
  9858. }
  9859. }
  9860. }
  9861. if (!range.collapsed) {
  9862. return range;
  9863. }
  9864. if (isText$1(container)) {
  9865. if (isCaretContainer$2(container)) {
  9866. if (direction === 1) {
  9867. node = leanRight(container);
  9868. if (node) {
  9869. return before$2(node);
  9870. }
  9871. node = leanLeft(container);
  9872. if (node) {
  9873. return after$1(node);
  9874. }
  9875. }
  9876. if (direction === -1) {
  9877. node = leanLeft(container);
  9878. if (node) {
  9879. return after$1(node);
  9880. }
  9881. node = leanRight(container);
  9882. if (node) {
  9883. return before$2(node);
  9884. }
  9885. }
  9886. return range;
  9887. }
  9888. if (endsWithCaretContainer(container) && offset >= container.data.length - 1) {
  9889. if (direction === 1) {
  9890. node = leanRight(container);
  9891. if (node) {
  9892. return before$2(node);
  9893. }
  9894. }
  9895. return range;
  9896. }
  9897. if (startsWithCaretContainer(container) && offset <= 1) {
  9898. if (direction === -1) {
  9899. node = leanLeft(container);
  9900. if (node) {
  9901. return after$1(node);
  9902. }
  9903. }
  9904. return range;
  9905. }
  9906. if (offset === container.data.length) {
  9907. node = leanRight(container);
  9908. if (node) {
  9909. return before$2(node);
  9910. }
  9911. return range;
  9912. }
  9913. if (offset === 0) {
  9914. node = leanLeft(container);
  9915. if (node) {
  9916. return after$1(node);
  9917. }
  9918. return range;
  9919. }
  9920. }
  9921. return range;
  9922. };
  9923. var getRelativeCefElm = function (forward, caretPosition) {
  9924. return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition)).filter(isContentEditableFalse$4);
  9925. };
  9926. var getNormalizedRangeEndPoint = function (direction, root, range) {
  9927. var normalizedRange = normalizeRange(direction, root, range);
  9928. if (direction === -1) {
  9929. return CaretPosition.fromRangeStart(normalizedRange);
  9930. }
  9931. return CaretPosition.fromRangeEnd(normalizedRange);
  9932. };
  9933. var getElementFromPosition = function (pos) {
  9934. return Optional.from(pos.getNode()).map(SugarElement.fromDom);
  9935. };
  9936. var getElementFromPrevPosition = function (pos) {
  9937. return Optional.from(pos.getNode(true)).map(SugarElement.fromDom);
  9938. };
  9939. var getVisualCaretPosition = function (walkFn, caretPosition) {
  9940. while (caretPosition = walkFn(caretPosition)) {
  9941. if (caretPosition.isVisible()) {
  9942. return caretPosition;
  9943. }
  9944. }
  9945. return caretPosition;
  9946. };
  9947. var isMoveInsideSameBlock = function (from, to) {
  9948. var inSameBlock = isInSameBlock(from, to);
  9949. if (!inSameBlock && isBr(from.getNode())) {
  9950. return true;
  9951. }
  9952. return inSameBlock;
  9953. };
  9954. var HDirection;
  9955. (function (HDirection) {
  9956. HDirection[HDirection['Backwards'] = -1] = 'Backwards';
  9957. HDirection[HDirection['Forwards'] = 1] = 'Forwards';
  9958. }(HDirection || (HDirection = {})));
  9959. var isContentEditableFalse$5 = isContentEditableFalse;
  9960. var isText$7 = isText$1;
  9961. var isElement$6 = isElement$1;
  9962. var isBr$4 = isBr;
  9963. var isCaretCandidate$3 = isCaretCandidate;
  9964. var isAtomic$1 = isAtomic;
  9965. var isEditableCaretCandidate$1 = isEditableCaretCandidate;
  9966. var getParents = function (node, root) {
  9967. var parents = [];
  9968. while (node && node !== root) {
  9969. parents.push(node);
  9970. node = node.parentNode;
  9971. }
  9972. return parents;
  9973. };
  9974. var nodeAtIndex = function (container, offset) {
  9975. if (container.hasChildNodes() && offset < container.childNodes.length) {
  9976. return container.childNodes[offset];
  9977. }
  9978. return null;
  9979. };
  9980. var getCaretCandidatePosition = function (direction, node) {
  9981. if (isForwards(direction)) {
  9982. if (isCaretCandidate$3(node.previousSibling) && !isText$7(node.previousSibling)) {
  9983. return CaretPosition$1.before(node);
  9984. }
  9985. if (isText$7(node)) {
  9986. return CaretPosition$1(node, 0);
  9987. }
  9988. }
  9989. if (isBackwards(direction)) {
  9990. if (isCaretCandidate$3(node.nextSibling) && !isText$7(node.nextSibling)) {
  9991. return CaretPosition$1.after(node);
  9992. }
  9993. if (isText$7(node)) {
  9994. return CaretPosition$1(node, node.data.length);
  9995. }
  9996. }
  9997. if (isBackwards(direction)) {
  9998. if (isBr$4(node)) {
  9999. return CaretPosition$1.before(node);
  10000. }
  10001. return CaretPosition$1.after(node);
  10002. }
  10003. return CaretPosition$1.before(node);
  10004. };
  10005. var moveForwardFromBr = function (root, nextNode) {
  10006. var nextSibling = nextNode.nextSibling;
  10007. if (nextSibling && isCaretCandidate$3(nextSibling)) {
  10008. if (isText$7(nextSibling)) {
  10009. return CaretPosition$1(nextSibling, 0);
  10010. } else {
  10011. return CaretPosition$1.before(nextSibling);
  10012. }
  10013. } else {
  10014. return findCaretPosition(HDirection.Forwards, CaretPosition$1.after(nextNode), root);
  10015. }
  10016. };
  10017. var findCaretPosition = function (direction, startPos, root) {
  10018. var node, nextNode, innerNode;
  10019. var caretPosition;
  10020. if (!isElement$6(root) || !startPos) {
  10021. return null;
  10022. }
  10023. if (startPos.isEqual(CaretPosition$1.after(root)) && root.lastChild) {
  10024. caretPosition = CaretPosition$1.after(root.lastChild);
  10025. if (isBackwards(direction) && isCaretCandidate$3(root.lastChild) && isElement$6(root.lastChild)) {
  10026. return isBr$4(root.lastChild) ? CaretPosition$1.before(root.lastChild) : caretPosition;
  10027. }
  10028. } else {
  10029. caretPosition = startPos;
  10030. }
  10031. var container = caretPosition.container();
  10032. var offset = caretPosition.offset();
  10033. if (isText$7(container)) {
  10034. if (isBackwards(direction) && offset > 0) {
  10035. return CaretPosition$1(container, --offset);
  10036. }
  10037. if (isForwards(direction) && offset < container.length) {
  10038. return CaretPosition$1(container, ++offset);
  10039. }
  10040. node = container;
  10041. } else {
  10042. if (isBackwards(direction) && offset > 0) {
  10043. nextNode = nodeAtIndex(container, offset - 1);
  10044. if (isCaretCandidate$3(nextNode)) {
  10045. if (!isAtomic$1(nextNode)) {
  10046. innerNode = findNode(nextNode, direction, isEditableCaretCandidate$1, nextNode);
  10047. if (innerNode) {
  10048. if (isText$7(innerNode)) {
  10049. return CaretPosition$1(innerNode, innerNode.data.length);
  10050. }
  10051. return CaretPosition$1.after(innerNode);
  10052. }
  10053. }
  10054. if (isText$7(nextNode)) {
  10055. return CaretPosition$1(nextNode, nextNode.data.length);
  10056. }
  10057. return CaretPosition$1.before(nextNode);
  10058. }
  10059. }
  10060. if (isForwards(direction) && offset < container.childNodes.length) {
  10061. nextNode = nodeAtIndex(container, offset);
  10062. if (isCaretCandidate$3(nextNode)) {
  10063. if (isBr$4(nextNode)) {
  10064. return moveForwardFromBr(root, nextNode);
  10065. }
  10066. if (!isAtomic$1(nextNode)) {
  10067. innerNode = findNode(nextNode, direction, isEditableCaretCandidate$1, nextNode);
  10068. if (innerNode) {
  10069. if (isText$7(innerNode)) {
  10070. return CaretPosition$1(innerNode, 0);
  10071. }
  10072. return CaretPosition$1.before(innerNode);
  10073. }
  10074. }
  10075. if (isText$7(nextNode)) {
  10076. return CaretPosition$1(nextNode, 0);
  10077. }
  10078. return CaretPosition$1.after(nextNode);
  10079. }
  10080. }
  10081. node = nextNode ? nextNode : caretPosition.getNode();
  10082. }
  10083. if (isForwards(direction) && caretPosition.isAtEnd() || isBackwards(direction) && caretPosition.isAtStart()) {
  10084. node = findNode(node, direction, always, root, true);
  10085. if (isEditableCaretCandidate$1(node, root)) {
  10086. return getCaretCandidatePosition(direction, node);
  10087. }
  10088. }
  10089. nextNode = findNode(node, direction, isEditableCaretCandidate$1, root);
  10090. var rootContentEditableFalseElm = last$1(filter(getParents(container, root), isContentEditableFalse$5));
  10091. if (rootContentEditableFalseElm && (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
  10092. if (isForwards(direction)) {
  10093. caretPosition = CaretPosition$1.after(rootContentEditableFalseElm);
  10094. } else {
  10095. caretPosition = CaretPosition$1.before(rootContentEditableFalseElm);
  10096. }
  10097. return caretPosition;
  10098. }
  10099. if (nextNode) {
  10100. return getCaretCandidatePosition(direction, nextNode);
  10101. }
  10102. return null;
  10103. };
  10104. var CaretWalker = function (root) {
  10105. return {
  10106. next: function (caretPosition) {
  10107. return findCaretPosition(HDirection.Forwards, caretPosition, root);
  10108. },
  10109. prev: function (caretPosition) {
  10110. return findCaretPosition(HDirection.Backwards, caretPosition, root);
  10111. }
  10112. };
  10113. };
  10114. var walkToPositionIn = function (forward, root, start) {
  10115. var position = forward ? CaretPosition$1.before(start) : CaretPosition$1.after(start);
  10116. return fromPosition(forward, root, position);
  10117. };
  10118. var afterElement = function (node) {
  10119. return isBr(node) ? CaretPosition$1.before(node) : CaretPosition$1.after(node);
  10120. };
  10121. var isBeforeOrStart = function (position) {
  10122. if (CaretPosition$1.isTextPosition(position)) {
  10123. return position.offset() === 0;
  10124. } else {
  10125. return isCaretCandidate(position.getNode());
  10126. }
  10127. };
  10128. var isAfterOrEnd = function (position) {
  10129. if (CaretPosition$1.isTextPosition(position)) {
  10130. var container = position.container();
  10131. return position.offset() === container.data.length;
  10132. } else {
  10133. return isCaretCandidate(position.getNode(true));
  10134. }
  10135. };
  10136. var isBeforeAfterSameElement = function (from, to) {
  10137. return !CaretPosition$1.isTextPosition(from) && !CaretPosition$1.isTextPosition(to) && from.getNode() === to.getNode(true);
  10138. };
  10139. var isAtBr = function (position) {
  10140. return !CaretPosition$1.isTextPosition(position) && isBr(position.getNode());
  10141. };
  10142. var shouldSkipPosition = function (forward, from, to) {
  10143. if (forward) {
  10144. return !isBeforeAfterSameElement(from, to) && !isAtBr(from) && isAfterOrEnd(from) && isBeforeOrStart(to);
  10145. } else {
  10146. return !isBeforeAfterSameElement(to, from) && isBeforeOrStart(from) && isAfterOrEnd(to);
  10147. }
  10148. };
  10149. var fromPosition = function (forward, root, pos) {
  10150. var walker = CaretWalker(root);
  10151. return Optional.from(forward ? walker.next(pos) : walker.prev(pos));
  10152. };
  10153. var navigate = function (forward, root, from) {
  10154. return fromPosition(forward, root, from).bind(function (to) {
  10155. if (isInSameBlock(from, to, root) && shouldSkipPosition(forward, from, to)) {
  10156. return fromPosition(forward, root, to);
  10157. } else {
  10158. return Optional.some(to);
  10159. }
  10160. });
  10161. };
  10162. var navigateIgnore = function (forward, root, from, ignoreFilter) {
  10163. return navigate(forward, root, from).bind(function (pos) {
  10164. return ignoreFilter(pos) ? navigateIgnore(forward, root, pos, ignoreFilter) : Optional.some(pos);
  10165. });
  10166. };
  10167. var positionIn = function (forward, element) {
  10168. var startNode = forward ? element.firstChild : element.lastChild;
  10169. if (isText$1(startNode)) {
  10170. return Optional.some(CaretPosition$1(startNode, forward ? 0 : startNode.data.length));
  10171. } else if (startNode) {
  10172. if (isCaretCandidate(startNode)) {
  10173. return Optional.some(forward ? CaretPosition$1.before(startNode) : afterElement(startNode));
  10174. } else {
  10175. return walkToPositionIn(forward, element, startNode);
  10176. }
  10177. } else {
  10178. return Optional.none();
  10179. }
  10180. };
  10181. var nextPosition = curry(fromPosition, true);
  10182. var prevPosition = curry(fromPosition, false);
  10183. var firstPositionIn = curry(positionIn, true);
  10184. var lastPositionIn = curry(positionIn, false);
  10185. var CARET_ID = '_mce_caret';
  10186. var isCaretNode = function (node) {
  10187. return isElement$1(node) && node.id === CARET_ID;
  10188. };
  10189. var getParentCaretContainer = function (body, node) {
  10190. while (node && node !== body) {
  10191. if (node.id === CARET_ID) {
  10192. return node;
  10193. }
  10194. node = node.parentNode;
  10195. }
  10196. return null;
  10197. };
  10198. var isStringPathBookmark = function (bookmark) {
  10199. return typeof bookmark.start === 'string';
  10200. };
  10201. var isRangeBookmark = function (bookmark) {
  10202. return bookmark.hasOwnProperty('rng');
  10203. };
  10204. var isIdBookmark = function (bookmark) {
  10205. return bookmark.hasOwnProperty('id');
  10206. };
  10207. var isIndexBookmark = function (bookmark) {
  10208. return bookmark.hasOwnProperty('name');
  10209. };
  10210. var isPathBookmark = function (bookmark) {
  10211. return Tools.isArray(bookmark.start);
  10212. };
  10213. var addBogus = function (dom, node) {
  10214. if (isElement$1(node) && dom.isBlock(node) && !node.innerHTML && !Env.ie) {
  10215. node.innerHTML = '<br data-mce-bogus="1" />';
  10216. }
  10217. return node;
  10218. };
  10219. var resolveCaretPositionBookmark = function (dom, bookmark) {
  10220. var pos;
  10221. var rng = dom.createRng();
  10222. pos = resolve$1(dom.getRoot(), bookmark.start);
  10223. rng.setStart(pos.container(), pos.offset());
  10224. pos = resolve$1(dom.getRoot(), bookmark.end);
  10225. rng.setEnd(pos.container(), pos.offset());
  10226. return rng;
  10227. };
  10228. var insertZwsp = function (node, rng) {
  10229. var textNode = node.ownerDocument.createTextNode(ZWSP);
  10230. node.appendChild(textNode);
  10231. rng.setStart(textNode, 0);
  10232. rng.setEnd(textNode, 0);
  10233. };
  10234. var isEmpty$1 = function (node) {
  10235. return node.hasChildNodes() === false;
  10236. };
  10237. var tryFindRangePosition = function (node, rng) {
  10238. return lastPositionIn(node).fold(function () {
  10239. return false;
  10240. }, function (pos) {
  10241. rng.setStart(pos.container(), pos.offset());
  10242. rng.setEnd(pos.container(), pos.offset());
  10243. return true;
  10244. });
  10245. };
  10246. var padEmptyCaretContainer = function (root, node, rng) {
  10247. if (isEmpty$1(node) && getParentCaretContainer(root, node)) {
  10248. insertZwsp(node, rng);
  10249. return true;
  10250. } else {
  10251. return false;
  10252. }
  10253. };
  10254. var setEndPoint = function (dom, start, bookmark, rng) {
  10255. var point = bookmark[start ? 'start' : 'end'];
  10256. var i, node, offset, children;
  10257. var root = dom.getRoot();
  10258. if (point) {
  10259. offset = point[0];
  10260. for (node = root, i = point.length - 1; i >= 1; i--) {
  10261. children = node.childNodes;
  10262. if (padEmptyCaretContainer(root, node, rng)) {
  10263. return true;
  10264. }
  10265. if (point[i] > children.length - 1) {
  10266. if (padEmptyCaretContainer(root, node, rng)) {
  10267. return true;
  10268. }
  10269. return tryFindRangePosition(node, rng);
  10270. }
  10271. node = children[point[i]];
  10272. }
  10273. if (node.nodeType === 3) {
  10274. offset = Math.min(point[0], node.nodeValue.length);
  10275. }
  10276. if (node.nodeType === 1) {
  10277. offset = Math.min(point[0], node.childNodes.length);
  10278. }
  10279. if (start) {
  10280. rng.setStart(node, offset);
  10281. } else {
  10282. rng.setEnd(node, offset);
  10283. }
  10284. }
  10285. return true;
  10286. };
  10287. var isValidTextNode = function (node) {
  10288. return isText$1(node) && node.data.length > 0;
  10289. };
  10290. var restoreEndPoint = function (dom, suffix, bookmark) {
  10291. var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev;
  10292. var keep = bookmark.keep;
  10293. var container, offset;
  10294. if (marker) {
  10295. node = marker.parentNode;
  10296. if (suffix === 'start') {
  10297. if (!keep) {
  10298. idx = dom.nodeIndex(marker);
  10299. } else {
  10300. if (marker.hasChildNodes()) {
  10301. node = marker.firstChild;
  10302. idx = 1;
  10303. } else if (isValidTextNode(marker.nextSibling)) {
  10304. node = marker.nextSibling;
  10305. idx = 0;
  10306. } else if (isValidTextNode(marker.previousSibling)) {
  10307. node = marker.previousSibling;
  10308. idx = marker.previousSibling.data.length;
  10309. } else {
  10310. node = marker.parentNode;
  10311. idx = dom.nodeIndex(marker) + 1;
  10312. }
  10313. }
  10314. container = node;
  10315. offset = idx;
  10316. } else {
  10317. if (!keep) {
  10318. idx = dom.nodeIndex(marker);
  10319. } else {
  10320. if (marker.hasChildNodes()) {
  10321. node = marker.firstChild;
  10322. idx = 1;
  10323. } else if (isValidTextNode(marker.previousSibling)) {
  10324. node = marker.previousSibling;
  10325. idx = marker.previousSibling.data.length;
  10326. } else {
  10327. node = marker.parentNode;
  10328. idx = dom.nodeIndex(marker);
  10329. }
  10330. }
  10331. container = node;
  10332. offset = idx;
  10333. }
  10334. if (!keep) {
  10335. prev = marker.previousSibling;
  10336. next = marker.nextSibling;
  10337. Tools.each(Tools.grep(marker.childNodes), function (node) {
  10338. if (isText$1(node)) {
  10339. node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
  10340. }
  10341. });
  10342. while (marker = dom.get(bookmark.id + '_' + suffix)) {
  10343. dom.remove(marker, true);
  10344. }
  10345. if (prev && next && prev.nodeType === next.nodeType && isText$1(prev) && !Env.opera) {
  10346. idx = prev.nodeValue.length;
  10347. prev.appendData(next.nodeValue);
  10348. dom.remove(next);
  10349. container = prev;
  10350. offset = idx;
  10351. }
  10352. }
  10353. return Optional.some(CaretPosition$1(container, offset));
  10354. } else {
  10355. return Optional.none();
  10356. }
  10357. };
  10358. var resolvePaths = function (dom, bookmark) {
  10359. var rng = dom.createRng();
  10360. if (setEndPoint(dom, true, bookmark, rng) && setEndPoint(dom, false, bookmark, rng)) {
  10361. return Optional.some(rng);
  10362. } else {
  10363. return Optional.none();
  10364. }
  10365. };
  10366. var resolveId = function (dom, bookmark) {
  10367. var startPos = restoreEndPoint(dom, 'start', bookmark);
  10368. var endPos = restoreEndPoint(dom, 'end', bookmark);
  10369. return lift2(startPos, endPos.or(startPos), function (spos, epos) {
  10370. var rng = dom.createRng();
  10371. rng.setStart(addBogus(dom, spos.container()), spos.offset());
  10372. rng.setEnd(addBogus(dom, epos.container()), epos.offset());
  10373. return rng;
  10374. });
  10375. };
  10376. var resolveIndex$1 = function (dom, bookmark) {
  10377. return Optional.from(dom.select(bookmark.name)[bookmark.index]).map(function (elm) {
  10378. var rng = dom.createRng();
  10379. rng.selectNode(elm);
  10380. return rng;
  10381. });
  10382. };
  10383. var resolve$2 = function (selection, bookmark) {
  10384. var dom = selection.dom;
  10385. if (bookmark) {
  10386. if (isPathBookmark(bookmark)) {
  10387. return resolvePaths(dom, bookmark);
  10388. } else if (isStringPathBookmark(bookmark)) {
  10389. return Optional.some(resolveCaretPositionBookmark(dom, bookmark));
  10390. } else if (isIdBookmark(bookmark)) {
  10391. return resolveId(dom, bookmark);
  10392. } else if (isIndexBookmark(bookmark)) {
  10393. return resolveIndex$1(dom, bookmark);
  10394. } else if (isRangeBookmark(bookmark)) {
  10395. return Optional.some(bookmark.rng);
  10396. }
  10397. }
  10398. return Optional.none();
  10399. };
  10400. var getBookmark$1 = function (selection, type, normalized) {
  10401. return getBookmark(selection, type, normalized);
  10402. };
  10403. var moveToBookmark = function (selection, bookmark) {
  10404. resolve$2(selection, bookmark).each(function (rng) {
  10405. selection.setRng(rng);
  10406. });
  10407. };
  10408. var isBookmarkNode$1 = function (node) {
  10409. return isElement$1(node) && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
  10410. };
  10411. var is$2 = function (expected) {
  10412. return function (actual) {
  10413. return expected === actual;
  10414. };
  10415. };
  10416. var isNbsp = is$2(nbsp);
  10417. var isWhiteSpace$1 = function (chr) {
  10418. return chr !== '' && ' \f\n\r\t\x0B'.indexOf(chr) !== -1;
  10419. };
  10420. var isContent$1 = function (chr) {
  10421. return !isWhiteSpace$1(chr) && !isNbsp(chr);
  10422. };
  10423. var isNode = function (node) {
  10424. return !!node.nodeType;
  10425. };
  10426. var isInlineBlock = function (node) {
  10427. return node && /^(IMG)$/.test(node.nodeName);
  10428. };
  10429. var moveStart = function (dom, selection, rng) {
  10430. var offset = rng.startOffset;
  10431. var container = rng.startContainer, walker, node, nodes;
  10432. if (rng.startContainer === rng.endContainer) {
  10433. if (isInlineBlock(rng.startContainer.childNodes[rng.startOffset])) {
  10434. return;
  10435. }
  10436. }
  10437. if (container.nodeType === 1) {
  10438. nodes = container.childNodes;
  10439. if (offset < nodes.length) {
  10440. container = nodes[offset];
  10441. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10442. } else {
  10443. container = nodes[nodes.length - 1];
  10444. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10445. walker.next(true);
  10446. }
  10447. for (node = walker.current(); node; node = walker.next()) {
  10448. if (node.nodeType === 3 && !isWhiteSpaceNode(node)) {
  10449. rng.setStart(node, 0);
  10450. selection.setRng(rng);
  10451. return;
  10452. }
  10453. }
  10454. }
  10455. };
  10456. var getNonWhiteSpaceSibling = function (node, next, inc) {
  10457. if (node) {
  10458. var nextName = next ? 'nextSibling' : 'previousSibling';
  10459. for (node = inc ? node : node[nextName]; node; node = node[nextName]) {
  10460. if (node.nodeType === 1 || !isWhiteSpaceNode(node)) {
  10461. return node;
  10462. }
  10463. }
  10464. }
  10465. };
  10466. var isTextBlock$1 = function (editor, name) {
  10467. if (isNode(name)) {
  10468. name = name.nodeName;
  10469. }
  10470. return !!editor.schema.getTextBlockElements()[name.toLowerCase()];
  10471. };
  10472. var isValid = function (ed, parent, child) {
  10473. return ed.schema.isValidChild(parent, child);
  10474. };
  10475. var isWhiteSpaceNode = function (node, allowSpaces) {
  10476. if (allowSpaces === void 0) {
  10477. allowSpaces = false;
  10478. }
  10479. if (isNonNullable(node) && isText$1(node)) {
  10480. var data = allowSpaces ? node.data.replace(/ /g, '\xA0') : node.data;
  10481. return isWhitespaceText(data);
  10482. } else {
  10483. return false;
  10484. }
  10485. };
  10486. var isEmptyTextNode = function (node) {
  10487. return isNonNullable(node) && isText$1(node) && node.length === 0;
  10488. };
  10489. var replaceVars = function (value, vars) {
  10490. if (typeof value !== 'string') {
  10491. value = value(vars);
  10492. } else if (vars) {
  10493. value = value.replace(/%(\w+)/g, function (str, name) {
  10494. return vars[name] || str;
  10495. });
  10496. }
  10497. return value;
  10498. };
  10499. var isEq = function (str1, str2) {
  10500. str1 = str1 || '';
  10501. str2 = str2 || '';
  10502. str1 = '' + (str1.nodeName || str1);
  10503. str2 = '' + (str2.nodeName || str2);
  10504. return str1.toLowerCase() === str2.toLowerCase();
  10505. };
  10506. var normalizeStyleValue = function (dom, value, name) {
  10507. if (name === 'color' || name === 'backgroundColor') {
  10508. value = dom.toHex(value);
  10509. }
  10510. if (name === 'fontWeight' && value === 700) {
  10511. value = 'bold';
  10512. }
  10513. if (name === 'fontFamily') {
  10514. value = value.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
  10515. }
  10516. return '' + value;
  10517. };
  10518. var getStyle = function (dom, node, name) {
  10519. return normalizeStyleValue(dom, dom.getStyle(node, name), name);
  10520. };
  10521. var getTextDecoration = function (dom, node) {
  10522. var decoration;
  10523. dom.getParent(node, function (n) {
  10524. decoration = dom.getStyle(n, 'text-decoration');
  10525. return decoration && decoration !== 'none';
  10526. });
  10527. return decoration;
  10528. };
  10529. var getParents$1 = function (dom, node, selector) {
  10530. return dom.getParents(node, selector, dom.getRoot());
  10531. };
  10532. var isVariableFormatName = function (editor, formatName) {
  10533. var hasVariableValues = function (format) {
  10534. var isVariableValue = function (val) {
  10535. return val.length > 1 && val.charAt(0) === '%';
  10536. };
  10537. return exists([
  10538. 'styles',
  10539. 'attributes'
  10540. ], function (key) {
  10541. return get$1(format, key).exists(function (field) {
  10542. var fieldValues = isArray(field) ? field : values(field);
  10543. return exists(fieldValues, isVariableValue);
  10544. });
  10545. });
  10546. };
  10547. return exists(editor.formatter.get(formatName), hasVariableValues);
  10548. };
  10549. var areSimilarFormats = function (editor, formatName, otherFormatName) {
  10550. var validKeys = [
  10551. 'inline',
  10552. 'block',
  10553. 'selector',
  10554. 'attributes',
  10555. 'styles',
  10556. 'classes'
  10557. ];
  10558. var filterObj = function (format) {
  10559. return filter$1(format, function (_, key) {
  10560. return exists(validKeys, function (validKey) {
  10561. return validKey === key;
  10562. });
  10563. });
  10564. };
  10565. return exists(editor.formatter.get(formatName), function (fmt1) {
  10566. var filteredFmt1 = filterObj(fmt1);
  10567. return exists(editor.formatter.get(otherFormatName), function (fmt2) {
  10568. var filteredFmt2 = filterObj(fmt2);
  10569. return equal(filteredFmt1, filteredFmt2);
  10570. });
  10571. });
  10572. };
  10573. var isBlockFormat = function (format) {
  10574. return hasNonNullableKey(format, 'block');
  10575. };
  10576. var isSelectorFormat = function (format) {
  10577. return hasNonNullableKey(format, 'selector');
  10578. };
  10579. var isInlineFormat = function (format) {
  10580. return hasNonNullableKey(format, 'inline');
  10581. };
  10582. var isBookmarkNode$2 = isBookmarkNode$1;
  10583. var getParents$2 = getParents$1;
  10584. var isWhiteSpaceNode$1 = isWhiteSpaceNode;
  10585. var isTextBlock$2 = isTextBlock$1;
  10586. var isBogusBr = function (node) {
  10587. return isBr(node) && node.getAttribute('data-mce-bogus') && !node.nextSibling;
  10588. };
  10589. var findParentContentEditable = function (dom, node) {
  10590. var parent = node;
  10591. while (parent) {
  10592. if (isElement$1(parent) && dom.getContentEditable(parent)) {
  10593. return dom.getContentEditable(parent) === 'false' ? parent : node;
  10594. }
  10595. parent = parent.parentNode;
  10596. }
  10597. return node;
  10598. };
  10599. var walkText = function (start, node, offset, predicate) {
  10600. var str = node.data;
  10601. for (var i = offset; start ? i >= 0 : i < str.length; start ? i-- : i++) {
  10602. if (predicate(str.charAt(i))) {
  10603. return start ? i + 1 : i;
  10604. }
  10605. }
  10606. return -1;
  10607. };
  10608. var findSpace = function (start, node, offset) {
  10609. return walkText(start, node, offset, function (c) {
  10610. return isNbsp(c) || isWhiteSpace$1(c);
  10611. });
  10612. };
  10613. var findContent = function (start, node, offset) {
  10614. return walkText(start, node, offset, isContent$1);
  10615. };
  10616. var findWordEndPoint = function (dom, body, container, offset, start, includeTrailingSpaces) {
  10617. var lastTextNode;
  10618. var rootNode = dom.getParent(container, dom.isBlock) || body;
  10619. var walk = function (container, offset, pred) {
  10620. var textSeeker = TextSeeker(dom);
  10621. var walker = start ? textSeeker.backwards : textSeeker.forwards;
  10622. return Optional.from(walker(container, offset, function (text, textOffset) {
  10623. if (isBookmarkNode$2(text.parentNode)) {
  10624. return -1;
  10625. } else {
  10626. lastTextNode = text;
  10627. return pred(start, text, textOffset);
  10628. }
  10629. }, rootNode));
  10630. };
  10631. var spaceResult = walk(container, offset, findSpace);
  10632. return spaceResult.bind(function (result) {
  10633. return includeTrailingSpaces ? walk(result.container, result.offset + (start ? -1 : 0), findContent) : Optional.some(result);
  10634. }).orThunk(function () {
  10635. return lastTextNode ? Optional.some({
  10636. container: lastTextNode,
  10637. offset: start ? 0 : lastTextNode.length
  10638. }) : Optional.none();
  10639. });
  10640. };
  10641. var findSelectorEndPoint = function (dom, format, rng, container, siblingName) {
  10642. if (isText$1(container) && container.nodeValue.length === 0 && container[siblingName]) {
  10643. container = container[siblingName];
  10644. }
  10645. var parents = getParents$2(dom, container);
  10646. for (var i = 0; i < parents.length; i++) {
  10647. for (var y = 0; y < format.length; y++) {
  10648. var curFormat = format[y];
  10649. if ('collapsed' in curFormat && curFormat.collapsed !== rng.collapsed) {
  10650. continue;
  10651. }
  10652. if (dom.is(parents[i], curFormat.selector)) {
  10653. return parents[i];
  10654. }
  10655. }
  10656. }
  10657. return container;
  10658. };
  10659. var findBlockEndPoint = function (editor, format, container, siblingName) {
  10660. var node;
  10661. var dom = editor.dom;
  10662. var root = dom.getRoot();
  10663. if (!format[0].wrapper) {
  10664. node = dom.getParent(container, format[0].block, root);
  10665. }
  10666. if (!node) {
  10667. var scopeRoot = dom.getParent(container, 'LI,TD,TH');
  10668. node = dom.getParent(isText$1(container) ? container.parentNode : container, function (node) {
  10669. return node !== root && isTextBlock$2(editor, node);
  10670. }, scopeRoot);
  10671. }
  10672. if (node && format[0].wrapper) {
  10673. node = getParents$2(dom, node, 'ul,ol').reverse()[0] || node;
  10674. }
  10675. if (!node) {
  10676. node = container;
  10677. while (node[siblingName] && !dom.isBlock(node[siblingName])) {
  10678. node = node[siblingName];
  10679. if (isEq(node, 'br')) {
  10680. break;
  10681. }
  10682. }
  10683. }
  10684. return node || container;
  10685. };
  10686. var isAtBlockBoundary = function (dom, root, container, siblingName) {
  10687. var parent = container.parentNode;
  10688. if (isNonNullable(container[siblingName])) {
  10689. return false;
  10690. } else if (parent === root || isNullable(parent) || dom.isBlock(parent)) {
  10691. return true;
  10692. } else {
  10693. return isAtBlockBoundary(dom, root, parent, siblingName);
  10694. }
  10695. };
  10696. var findParentContainer = function (dom, format, container, offset, start) {
  10697. var parent = container;
  10698. var sibling;
  10699. var siblingName = start ? 'previousSibling' : 'nextSibling';
  10700. var root = dom.getRoot();
  10701. if (isText$1(container) && !isWhiteSpaceNode$1(container)) {
  10702. if (start ? offset > 0 : offset < container.data.length) {
  10703. return container;
  10704. }
  10705. }
  10706. while (true) {
  10707. if (!format[0].block_expand && dom.isBlock(parent)) {
  10708. return parent;
  10709. }
  10710. for (sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
  10711. var allowSpaces = isText$1(sibling) && !isAtBlockBoundary(dom, root, sibling, siblingName);
  10712. if (!isBookmarkNode$2(sibling) && !isBogusBr(sibling) && !isWhiteSpaceNode$1(sibling, allowSpaces)) {
  10713. return parent;
  10714. }
  10715. }
  10716. if (parent === root || parent.parentNode === root) {
  10717. container = parent;
  10718. break;
  10719. }
  10720. parent = parent.parentNode;
  10721. }
  10722. return container;
  10723. };
  10724. var isSelfOrParentBookmark = function (container) {
  10725. return isBookmarkNode$2(container.parentNode) || isBookmarkNode$2(container);
  10726. };
  10727. var expandRng = function (editor, rng, format, includeTrailingSpace) {
  10728. if (includeTrailingSpace === void 0) {
  10729. includeTrailingSpace = false;
  10730. }
  10731. var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  10732. var dom = editor.dom;
  10733. if (isElement$1(startContainer) && startContainer.hasChildNodes()) {
  10734. startContainer = getNode(startContainer, startOffset);
  10735. if (isText$1(startContainer)) {
  10736. startOffset = 0;
  10737. }
  10738. }
  10739. if (isElement$1(endContainer) && endContainer.hasChildNodes()) {
  10740. endContainer = getNode(endContainer, rng.collapsed ? endOffset : endOffset - 1);
  10741. if (isText$1(endContainer)) {
  10742. endOffset = endContainer.nodeValue.length;
  10743. }
  10744. }
  10745. startContainer = findParentContentEditable(dom, startContainer);
  10746. endContainer = findParentContentEditable(dom, endContainer);
  10747. if (isSelfOrParentBookmark(startContainer)) {
  10748. startContainer = isBookmarkNode$2(startContainer) ? startContainer : startContainer.parentNode;
  10749. if (rng.collapsed) {
  10750. startContainer = startContainer.previousSibling || startContainer;
  10751. } else {
  10752. startContainer = startContainer.nextSibling || startContainer;
  10753. }
  10754. if (isText$1(startContainer)) {
  10755. startOffset = rng.collapsed ? startContainer.length : 0;
  10756. }
  10757. }
  10758. if (isSelfOrParentBookmark(endContainer)) {
  10759. endContainer = isBookmarkNode$2(endContainer) ? endContainer : endContainer.parentNode;
  10760. if (rng.collapsed) {
  10761. endContainer = endContainer.nextSibling || endContainer;
  10762. } else {
  10763. endContainer = endContainer.previousSibling || endContainer;
  10764. }
  10765. if (isText$1(endContainer)) {
  10766. endOffset = rng.collapsed ? 0 : endContainer.length;
  10767. }
  10768. }
  10769. if (rng.collapsed) {
  10770. var startPoint = findWordEndPoint(dom, editor.getBody(), startContainer, startOffset, true, includeTrailingSpace);
  10771. startPoint.each(function (_a) {
  10772. var container = _a.container, offset = _a.offset;
  10773. startContainer = container;
  10774. startOffset = offset;
  10775. });
  10776. var endPoint = findWordEndPoint(dom, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
  10777. endPoint.each(function (_a) {
  10778. var container = _a.container, offset = _a.offset;
  10779. endContainer = container;
  10780. endOffset = offset;
  10781. });
  10782. }
  10783. if (format[0].inline || format[0].block_expand) {
  10784. if (!format[0].inline || (!isText$1(startContainer) || startOffset === 0)) {
  10785. startContainer = findParentContainer(dom, format, startContainer, startOffset, true);
  10786. }
  10787. if (!format[0].inline || (!isText$1(endContainer) || endOffset === endContainer.nodeValue.length)) {
  10788. endContainer = findParentContainer(dom, format, endContainer, endOffset, false);
  10789. }
  10790. }
  10791. if (format[0].selector && format[0].expand !== false && !format[0].inline) {
  10792. startContainer = findSelectorEndPoint(dom, format, rng, startContainer, 'previousSibling');
  10793. endContainer = findSelectorEndPoint(dom, format, rng, endContainer, 'nextSibling');
  10794. }
  10795. if (format[0].block || format[0].selector) {
  10796. startContainer = findBlockEndPoint(editor, format, startContainer, 'previousSibling');
  10797. endContainer = findBlockEndPoint(editor, format, endContainer, 'nextSibling');
  10798. if (format[0].block) {
  10799. if (!dom.isBlock(startContainer)) {
  10800. startContainer = findParentContainer(dom, format, startContainer, startOffset, true);
  10801. }
  10802. if (!dom.isBlock(endContainer)) {
  10803. endContainer = findParentContainer(dom, format, endContainer, endOffset, false);
  10804. }
  10805. }
  10806. }
  10807. if (isElement$1(startContainer)) {
  10808. startOffset = dom.nodeIndex(startContainer);
  10809. startContainer = startContainer.parentNode;
  10810. }
  10811. if (isElement$1(endContainer)) {
  10812. endOffset = dom.nodeIndex(endContainer) + 1;
  10813. endContainer = endContainer.parentNode;
  10814. }
  10815. return {
  10816. startContainer: startContainer,
  10817. startOffset: startOffset,
  10818. endContainer: endContainer,
  10819. endOffset: endOffset
  10820. };
  10821. };
  10822. var clampToExistingChildren = function (container, index) {
  10823. var childNodes = container.childNodes;
  10824. if (index >= childNodes.length) {
  10825. index = childNodes.length - 1;
  10826. } else if (index < 0) {
  10827. index = 0;
  10828. }
  10829. return childNodes[index] || container;
  10830. };
  10831. var getEndChild = function (container, index) {
  10832. return clampToExistingChildren(container, index - 1);
  10833. };
  10834. var walk$1 = function (dom, rng, callback) {
  10835. var startContainer = rng.startContainer;
  10836. var startOffset = rng.startOffset;
  10837. var endContainer = rng.endContainer;
  10838. var endOffset = rng.endOffset;
  10839. var exclude = function (nodes) {
  10840. var node;
  10841. node = nodes[0];
  10842. if (node.nodeType === 3 && node === startContainer && startOffset >= node.nodeValue.length) {
  10843. nodes.splice(0, 1);
  10844. }
  10845. node = nodes[nodes.length - 1];
  10846. if (endOffset === 0 && nodes.length > 0 && node === endContainer && node.nodeType === 3) {
  10847. nodes.splice(nodes.length - 1, 1);
  10848. }
  10849. return nodes;
  10850. };
  10851. var collectSiblings = function (node, name, endNode) {
  10852. var siblings = [];
  10853. for (; node && node !== endNode; node = node[name]) {
  10854. siblings.push(node);
  10855. }
  10856. return siblings;
  10857. };
  10858. var findEndPoint = function (node, root) {
  10859. do {
  10860. if (node.parentNode === root) {
  10861. return node;
  10862. }
  10863. node = node.parentNode;
  10864. } while (node);
  10865. };
  10866. var walkBoundary = function (startNode, endNode, next) {
  10867. var siblingName = next ? 'nextSibling' : 'previousSibling';
  10868. for (var node = startNode, parent_1 = node.parentNode; node && node !== endNode; node = parent_1) {
  10869. parent_1 = node.parentNode;
  10870. var siblings_1 = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
  10871. if (siblings_1.length) {
  10872. if (!next) {
  10873. siblings_1.reverse();
  10874. }
  10875. callback(exclude(siblings_1));
  10876. }
  10877. }
  10878. };
  10879. if (startContainer.nodeType === 1 && startContainer.hasChildNodes()) {
  10880. startContainer = clampToExistingChildren(startContainer, startOffset);
  10881. }
  10882. if (endContainer.nodeType === 1 && endContainer.hasChildNodes()) {
  10883. endContainer = getEndChild(endContainer, endOffset);
  10884. }
  10885. if (startContainer === endContainer) {
  10886. return callback(exclude([startContainer]));
  10887. }
  10888. var ancestor = dom.findCommonAncestor(startContainer, endContainer);
  10889. for (var node = startContainer; node; node = node.parentNode) {
  10890. if (node === endContainer) {
  10891. return walkBoundary(startContainer, ancestor, true);
  10892. }
  10893. if (node === ancestor) {
  10894. break;
  10895. }
  10896. }
  10897. for (var node = endContainer; node; node = node.parentNode) {
  10898. if (node === startContainer) {
  10899. return walkBoundary(endContainer, ancestor);
  10900. }
  10901. if (node === ancestor) {
  10902. break;
  10903. }
  10904. }
  10905. var startPoint = findEndPoint(startContainer, ancestor) || startContainer;
  10906. var endPoint = findEndPoint(endContainer, ancestor) || endContainer;
  10907. walkBoundary(startContainer, startPoint, true);
  10908. var siblings = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint === endContainer ? endPoint.nextSibling : endPoint);
  10909. if (siblings.length) {
  10910. callback(exclude(siblings));
  10911. }
  10912. walkBoundary(endContainer, endPoint);
  10913. };
  10914. var getRanges = function (selection) {
  10915. var ranges = [];
  10916. if (selection) {
  10917. for (var i = 0; i < selection.rangeCount; i++) {
  10918. ranges.push(selection.getRangeAt(i));
  10919. }
  10920. }
  10921. return ranges;
  10922. };
  10923. var getSelectedNodes = function (ranges) {
  10924. return bind(ranges, function (range) {
  10925. var node = getSelectedNode(range);
  10926. return node ? [SugarElement.fromDom(node)] : [];
  10927. });
  10928. };
  10929. var hasMultipleRanges = function (selection) {
  10930. return getRanges(selection).length > 1;
  10931. };
  10932. var getCellsFromRanges = function (ranges) {
  10933. return filter(getSelectedNodes(ranges), isTableCell$1);
  10934. };
  10935. var getCellsFromElement = function (elm) {
  10936. return descendants$1(elm, 'td[data-mce-selected],th[data-mce-selected]');
  10937. };
  10938. var getCellsFromElementOrRanges = function (ranges, element) {
  10939. var selectedCells = getCellsFromElement(element);
  10940. return selectedCells.length > 0 ? selectedCells : getCellsFromRanges(ranges);
  10941. };
  10942. var getCellsFromEditor = function (editor) {
  10943. return getCellsFromElementOrRanges(getRanges(editor.selection.getSel()), SugarElement.fromDom(editor.getBody()));
  10944. };
  10945. var getStartNode = function (rng) {
  10946. var sc = rng.startContainer, so = rng.startOffset;
  10947. if (isText$1(sc)) {
  10948. return so === 0 ? Optional.some(SugarElement.fromDom(sc)) : Optional.none();
  10949. } else {
  10950. return Optional.from(sc.childNodes[so]).map(SugarElement.fromDom);
  10951. }
  10952. };
  10953. var getEndNode = function (rng) {
  10954. var ec = rng.endContainer, eo = rng.endOffset;
  10955. if (isText$1(ec)) {
  10956. return eo === ec.data.length ? Optional.some(SugarElement.fromDom(ec)) : Optional.none();
  10957. } else {
  10958. return Optional.from(ec.childNodes[eo - 1]).map(SugarElement.fromDom);
  10959. }
  10960. };
  10961. var getFirstChildren = function (node) {
  10962. return firstChild(node).fold(constant([node]), function (child) {
  10963. return [node].concat(getFirstChildren(child));
  10964. });
  10965. };
  10966. var getLastChildren = function (node) {
  10967. return lastChild(node).fold(constant([node]), function (child) {
  10968. if (name(child) === 'br') {
  10969. return prevSibling(child).map(function (sibling) {
  10970. return [node].concat(getLastChildren(sibling));
  10971. }).getOr([]);
  10972. } else {
  10973. return [node].concat(getLastChildren(child));
  10974. }
  10975. });
  10976. };
  10977. var hasAllContentsSelected = function (elm, rng) {
  10978. return lift2(getStartNode(rng), getEndNode(rng), function (startNode, endNode) {
  10979. var start = find(getFirstChildren(elm), curry(eq$2, startNode));
  10980. var end = find(getLastChildren(elm), curry(eq$2, endNode));
  10981. return start.isSome() && end.isSome();
  10982. }).getOr(false);
  10983. };
  10984. var moveEndPoint$1 = function (dom, rng, node, start) {
  10985. var root = node, walker = new DomTreeWalker(node, root);
  10986. var moveCaretBeforeOnEnterElementsMap = filter$1(dom.schema.getMoveCaretBeforeOnEnterElements(), function (_, name) {
  10987. return !contains([
  10988. 'td',
  10989. 'th',
  10990. 'table'
  10991. ], name.toLowerCase());
  10992. });
  10993. do {
  10994. if (isText$1(node) && Tools.trim(node.nodeValue).length !== 0) {
  10995. if (start) {
  10996. rng.setStart(node, 0);
  10997. } else {
  10998. rng.setEnd(node, node.nodeValue.length);
  10999. }
  11000. return;
  11001. }
  11002. if (moveCaretBeforeOnEnterElementsMap[node.nodeName]) {
  11003. if (start) {
  11004. rng.setStartBefore(node);
  11005. } else {
  11006. if (node.nodeName === 'BR') {
  11007. rng.setEndBefore(node);
  11008. } else {
  11009. rng.setEndAfter(node);
  11010. }
  11011. }
  11012. return;
  11013. }
  11014. } while (node = start ? walker.next() : walker.prev());
  11015. if (root.nodeName === 'BODY') {
  11016. if (start) {
  11017. rng.setStart(root, 0);
  11018. } else {
  11019. rng.setEnd(root, root.childNodes.length);
  11020. }
  11021. }
  11022. };
  11023. var hasAnyRanges = function (editor) {
  11024. var sel = editor.selection.getSel();
  11025. return sel && sel.rangeCount > 0;
  11026. };
  11027. var runOnRanges = function (editor, executor) {
  11028. var fakeSelectionNodes = getCellsFromEditor(editor);
  11029. if (fakeSelectionNodes.length > 0) {
  11030. each(fakeSelectionNodes, function (elem) {
  11031. var node = elem.dom;
  11032. var fakeNodeRng = editor.dom.createRng();
  11033. fakeNodeRng.setStartBefore(node);
  11034. fakeNodeRng.setEndAfter(node);
  11035. executor(fakeNodeRng, true);
  11036. });
  11037. } else {
  11038. executor(editor.selection.getRng(), false);
  11039. }
  11040. };
  11041. var preserve = function (selection, fillBookmark, executor) {
  11042. var bookmark = getPersistentBookmark(selection, fillBookmark);
  11043. executor(bookmark);
  11044. selection.moveToBookmark(bookmark);
  11045. };
  11046. function NodeValue (is, name) {
  11047. var get = function (element) {
  11048. if (!is(element)) {
  11049. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  11050. }
  11051. return getOption(element).getOr('');
  11052. };
  11053. var getOption = function (element) {
  11054. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  11055. };
  11056. var set = function (element, value) {
  11057. if (!is(element)) {
  11058. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  11059. }
  11060. element.dom.nodeValue = value;
  11061. };
  11062. return {
  11063. get: get,
  11064. getOption: getOption,
  11065. set: set
  11066. };
  11067. }
  11068. var api = NodeValue(isText, 'text');
  11069. var get$8 = function (element) {
  11070. return api.get(element);
  11071. };
  11072. var isZeroWidth = function (elem) {
  11073. return isText(elem) && get$8(elem) === ZWSP;
  11074. };
  11075. var context = function (editor, elem, wrapName, nodeName) {
  11076. return parent(elem).fold(function () {
  11077. return 'skipping';
  11078. }, function (parent) {
  11079. if (nodeName === 'br' || isZeroWidth(elem)) {
  11080. return 'valid';
  11081. } else if (isAnnotation(elem)) {
  11082. return 'existing';
  11083. } else if (isCaretNode(elem.dom)) {
  11084. return 'caret';
  11085. } else if (!isValid(editor, wrapName, nodeName) || !isValid(editor, name(parent), wrapName)) {
  11086. return 'invalid-child';
  11087. } else {
  11088. return 'valid';
  11089. }
  11090. });
  11091. };
  11092. var applyWordGrab = function (editor, rng) {
  11093. var r = expandRng(editor, rng, [{ inline: true }]);
  11094. rng.setStart(r.startContainer, r.startOffset);
  11095. rng.setEnd(r.endContainer, r.endOffset);
  11096. editor.selection.setRng(rng);
  11097. };
  11098. var makeAnnotation = function (eDoc, _a, annotationName, decorate) {
  11099. var _b = _a.uid, uid = _b === void 0 ? generate$1('mce-annotation') : _b, data = __rest(_a, ['uid']);
  11100. var master = SugarElement.fromTag('span', eDoc);
  11101. add$3(master, annotation());
  11102. set(master, '' + dataAnnotationId(), uid);
  11103. set(master, '' + dataAnnotation(), annotationName);
  11104. var _c = decorate(uid, data), _d = _c.attributes, attributes = _d === void 0 ? {} : _d, _e = _c.classes, classes = _e === void 0 ? [] : _e;
  11105. setAll(master, attributes);
  11106. add$4(master, classes);
  11107. return master;
  11108. };
  11109. var annotate = function (editor, rng, annotationName, decorate, data) {
  11110. var newWrappers = [];
  11111. var master = makeAnnotation(editor.getDoc(), data, annotationName, decorate);
  11112. var wrapper = Cell(Optional.none());
  11113. var finishWrapper = function () {
  11114. wrapper.set(Optional.none());
  11115. };
  11116. var getOrOpenWrapper = function () {
  11117. return wrapper.get().getOrThunk(function () {
  11118. var nu = shallow(master);
  11119. newWrappers.push(nu);
  11120. wrapper.set(Optional.some(nu));
  11121. return nu;
  11122. });
  11123. };
  11124. var processElements = function (elems) {
  11125. each(elems, processElement);
  11126. };
  11127. var processElement = function (elem) {
  11128. var ctx = context(editor, elem, 'span', name(elem));
  11129. switch (ctx) {
  11130. case 'invalid-child': {
  11131. finishWrapper();
  11132. var children$1 = children(elem);
  11133. processElements(children$1);
  11134. finishWrapper();
  11135. break;
  11136. }
  11137. case 'valid': {
  11138. var w = getOrOpenWrapper();
  11139. wrap(elem, w);
  11140. break;
  11141. }
  11142. }
  11143. };
  11144. var processNodes = function (nodes) {
  11145. var elems = map(nodes, SugarElement.fromDom);
  11146. processElements(elems);
  11147. };
  11148. walk$1(editor.dom, rng, function (nodes) {
  11149. finishWrapper();
  11150. processNodes(nodes);
  11151. });
  11152. return newWrappers;
  11153. };
  11154. var annotateWithBookmark = function (editor, name, settings, data) {
  11155. editor.undoManager.transact(function () {
  11156. var selection = editor.selection;
  11157. var initialRng = selection.getRng();
  11158. var hasFakeSelection = getCellsFromEditor(editor).length > 0;
  11159. if (initialRng.collapsed && !hasFakeSelection) {
  11160. applyWordGrab(editor, initialRng);
  11161. }
  11162. if (selection.getRng().collapsed && !hasFakeSelection) {
  11163. var wrapper = makeAnnotation(editor.getDoc(), data, name, settings.decorate);
  11164. set$1(wrapper, nbsp);
  11165. selection.getRng().insertNode(wrapper.dom);
  11166. selection.select(wrapper.dom);
  11167. } else {
  11168. preserve(selection, false, function () {
  11169. runOnRanges(editor, function (selectionRng) {
  11170. annotate(editor, selectionRng, name, settings.decorate, data);
  11171. });
  11172. });
  11173. }
  11174. });
  11175. };
  11176. var Annotator = function (editor) {
  11177. var registry = create$2();
  11178. setup$1(editor, registry);
  11179. var changes = setup(editor);
  11180. return {
  11181. register: function (name, settings) {
  11182. registry.register(name, settings);
  11183. },
  11184. annotate: function (name, data) {
  11185. registry.lookup(name).each(function (settings) {
  11186. annotateWithBookmark(editor, name, settings, data);
  11187. });
  11188. },
  11189. annotationChanged: function (name, callback) {
  11190. changes.addListener(name, callback);
  11191. },
  11192. remove: function (name) {
  11193. identify(editor, Optional.some(name)).each(function (_a) {
  11194. var elements = _a.elements;
  11195. each(elements, unwrap);
  11196. });
  11197. },
  11198. getAll: function (name) {
  11199. var directory = findAll(editor, name);
  11200. return map$1(directory, function (elems) {
  11201. return map(elems, function (elem) {
  11202. return elem.dom;
  11203. });
  11204. });
  11205. }
  11206. };
  11207. };
  11208. function BookmarkManager(selection) {
  11209. return {
  11210. getBookmark: curry(getBookmark$1, selection),
  11211. moveToBookmark: curry(moveToBookmark, selection)
  11212. };
  11213. }
  11214. (function (BookmarkManager) {
  11215. BookmarkManager.isBookmarkNode = isBookmarkNode$1;
  11216. }(BookmarkManager || (BookmarkManager = {})));
  11217. var BookmarkManager$1 = BookmarkManager;
  11218. var getContentEditableRoot = function (root, node) {
  11219. while (node && node !== root) {
  11220. if (isContentEditableTrue(node) || isContentEditableFalse(node)) {
  11221. return node;
  11222. }
  11223. node = node.parentNode;
  11224. }
  11225. return null;
  11226. };
  11227. var isXYWithinRange = function (clientX, clientY, range) {
  11228. if (range.collapsed) {
  11229. return false;
  11230. }
  11231. if (Env.browser.isIE() && range.startOffset === range.endOffset - 1 && range.startContainer === range.endContainer) {
  11232. var elm = range.startContainer.childNodes[range.startOffset];
  11233. if (isElement$1(elm)) {
  11234. return exists(elm.getClientRects(), function (rect) {
  11235. return containsXY(rect, clientX, clientY);
  11236. });
  11237. }
  11238. }
  11239. return exists(range.getClientRects(), function (rect) {
  11240. return containsXY(rect, clientX, clientY);
  11241. });
  11242. };
  11243. var firePreProcess = function (editor, args) {
  11244. return editor.fire('PreProcess', args);
  11245. };
  11246. var firePostProcess = function (editor, args) {
  11247. return editor.fire('PostProcess', args);
  11248. };
  11249. var fireRemove = function (editor) {
  11250. return editor.fire('remove');
  11251. };
  11252. var fireDetach = function (editor) {
  11253. return editor.fire('detach');
  11254. };
  11255. var fireSwitchMode = function (editor, mode) {
  11256. return editor.fire('SwitchMode', { mode: mode });
  11257. };
  11258. var fireObjectResizeStart = function (editor, target, width, height, origin) {
  11259. editor.fire('ObjectResizeStart', {
  11260. target: target,
  11261. width: width,
  11262. height: height,
  11263. origin: origin
  11264. });
  11265. };
  11266. var fireObjectResized = function (editor, target, width, height, origin) {
  11267. editor.fire('ObjectResized', {
  11268. target: target,
  11269. width: width,
  11270. height: height,
  11271. origin: origin
  11272. });
  11273. };
  11274. var firePreInit = function (editor) {
  11275. return editor.fire('PreInit');
  11276. };
  11277. var firePostRender = function (editor) {
  11278. return editor.fire('PostRender');
  11279. };
  11280. var fireInit = function (editor) {
  11281. return editor.fire('Init');
  11282. };
  11283. var firePlaceholderToggle = function (editor, state) {
  11284. return editor.fire('PlaceholderToggle', { state: state });
  11285. };
  11286. var fireError = function (editor, errorType, error) {
  11287. return editor.fire(errorType, error);
  11288. };
  11289. var VK = {
  11290. BACKSPACE: 8,
  11291. DELETE: 46,
  11292. DOWN: 40,
  11293. ENTER: 13,
  11294. LEFT: 37,
  11295. RIGHT: 39,
  11296. SPACEBAR: 32,
  11297. TAB: 9,
  11298. UP: 38,
  11299. END: 35,
  11300. HOME: 36,
  11301. modifierPressed: function (e) {
  11302. return e.shiftKey || e.ctrlKey || e.altKey || this.metaKeyPressed(e);
  11303. },
  11304. metaKeyPressed: function (e) {
  11305. return Env.mac ? e.metaKey : e.ctrlKey && !e.altKey;
  11306. }
  11307. };
  11308. var isContentEditableFalse$6 = isContentEditableFalse;
  11309. var ControlSelection = function (selection, editor) {
  11310. var dom = editor.dom, each = Tools.each;
  11311. var selectedElm, selectedElmGhost, resizeHelper, selectedHandle;
  11312. var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
  11313. var width, height;
  11314. var editableDoc = editor.getDoc(), rootDocument = document;
  11315. var abs = Math.abs, round = Math.round, rootElement = editor.getBody();
  11316. var startScrollWidth, startScrollHeight;
  11317. var resizeHandles = {
  11318. nw: [
  11319. 0,
  11320. 0,
  11321. -1,
  11322. -1
  11323. ],
  11324. ne: [
  11325. 1,
  11326. 0,
  11327. 1,
  11328. -1
  11329. ],
  11330. se: [
  11331. 1,
  11332. 1,
  11333. 1,
  11334. 1
  11335. ],
  11336. sw: [
  11337. 0,
  11338. 1,
  11339. -1,
  11340. 1
  11341. ]
  11342. };
  11343. var isImage = function (elm) {
  11344. return elm && (elm.nodeName === 'IMG' || editor.dom.is(elm, 'figure.image'));
  11345. };
  11346. var isEventOnImageOutsideRange = function (evt, range) {
  11347. if (evt.type === 'longpress' || evt.type.indexOf('touch') === 0) {
  11348. var touch = evt.touches[0];
  11349. return isImage(evt.target) && !isXYWithinRange(touch.clientX, touch.clientY, range);
  11350. } else {
  11351. return isImage(evt.target) && !isXYWithinRange(evt.clientX, evt.clientY, range);
  11352. }
  11353. };
  11354. var contextMenuSelectImage = function (evt) {
  11355. var target = evt.target;
  11356. if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) && !evt.isDefaultPrevented()) {
  11357. editor.selection.select(target);
  11358. }
  11359. };
  11360. var getResizeTarget = function (elm) {
  11361. return editor.dom.is(elm, 'figure.image') ? elm.querySelector('img') : elm;
  11362. };
  11363. var isResizable = function (elm) {
  11364. var selector = getObjectResizing(editor);
  11365. if (!selector) {
  11366. return false;
  11367. }
  11368. if (elm.getAttribute('data-mce-resize') === 'false') {
  11369. return false;
  11370. }
  11371. if (elm === editor.getBody()) {
  11372. return false;
  11373. }
  11374. return is$1(SugarElement.fromDom(elm), selector);
  11375. };
  11376. var setGhostElmSize = function (ghostElm, width, height) {
  11377. dom.setStyles(getResizeTarget(ghostElm), {
  11378. width: width,
  11379. height: height
  11380. });
  11381. };
  11382. var resizeGhostElement = function (e) {
  11383. var deltaX, deltaY, proportional;
  11384. var resizeHelperX, resizeHelperY;
  11385. deltaX = e.screenX - startX;
  11386. deltaY = e.screenY - startY;
  11387. width = deltaX * selectedHandle[2] + startW;
  11388. height = deltaY * selectedHandle[3] + startH;
  11389. width = width < 5 ? 5 : width;
  11390. height = height < 5 ? 5 : height;
  11391. if (isImage(selectedElm) && getResizeImgProportional(editor) !== false) {
  11392. proportional = !VK.modifierPressed(e);
  11393. } else {
  11394. proportional = VK.modifierPressed(e);
  11395. }
  11396. if (proportional) {
  11397. if (abs(deltaX) > abs(deltaY)) {
  11398. height = round(width * ratio);
  11399. width = round(height / ratio);
  11400. } else {
  11401. width = round(height / ratio);
  11402. height = round(width * ratio);
  11403. }
  11404. }
  11405. setGhostElmSize(selectedElmGhost, width, height);
  11406. resizeHelperX = selectedHandle.startPos.x + deltaX;
  11407. resizeHelperY = selectedHandle.startPos.y + deltaY;
  11408. resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
  11409. resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
  11410. dom.setStyles(resizeHelper, {
  11411. left: resizeHelperX,
  11412. top: resizeHelperY,
  11413. display: 'block'
  11414. });
  11415. resizeHelper.innerHTML = width + ' &times; ' + height;
  11416. if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
  11417. dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
  11418. }
  11419. if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
  11420. dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
  11421. }
  11422. deltaX = rootElement.scrollWidth - startScrollWidth;
  11423. deltaY = rootElement.scrollHeight - startScrollHeight;
  11424. if (deltaX + deltaY !== 0) {
  11425. dom.setStyles(resizeHelper, {
  11426. left: resizeHelperX - deltaX,
  11427. top: resizeHelperY - deltaY
  11428. });
  11429. }
  11430. if (!resizeStarted) {
  11431. fireObjectResizeStart(editor, selectedElm, startW, startH, 'corner-' + selectedHandle.name);
  11432. resizeStarted = true;
  11433. }
  11434. };
  11435. var endGhostResize = function () {
  11436. var wasResizeStarted = resizeStarted;
  11437. resizeStarted = false;
  11438. var setSizeProp = function (name, value) {
  11439. if (value) {
  11440. if (selectedElm.style[name] || !editor.schema.isValid(selectedElm.nodeName.toLowerCase(), name)) {
  11441. dom.setStyle(getResizeTarget(selectedElm), name, value);
  11442. } else {
  11443. dom.setAttrib(getResizeTarget(selectedElm), name, '' + value);
  11444. }
  11445. }
  11446. };
  11447. if (wasResizeStarted) {
  11448. setSizeProp('width', width);
  11449. setSizeProp('height', height);
  11450. }
  11451. dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
  11452. dom.unbind(editableDoc, 'mouseup', endGhostResize);
  11453. if (rootDocument !== editableDoc) {
  11454. dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
  11455. dom.unbind(rootDocument, 'mouseup', endGhostResize);
  11456. }
  11457. dom.remove(selectedElmGhost);
  11458. dom.remove(resizeHelper);
  11459. showResizeRect(selectedElm);
  11460. if (wasResizeStarted) {
  11461. fireObjectResized(editor, selectedElm, width, height, 'corner-' + selectedHandle.name);
  11462. dom.setAttrib(selectedElm, 'style', dom.getAttrib(selectedElm, 'style'));
  11463. }
  11464. editor.nodeChanged();
  11465. };
  11466. var showResizeRect = function (targetElm) {
  11467. hideResizeRect();
  11468. unbindResizeHandleEvents();
  11469. var position = dom.getPos(targetElm, rootElement);
  11470. var selectedElmX = position.x;
  11471. var selectedElmY = position.y;
  11472. var rect = targetElm.getBoundingClientRect();
  11473. var targetWidth = rect.width || rect.right - rect.left;
  11474. var targetHeight = rect.height || rect.bottom - rect.top;
  11475. if (selectedElm !== targetElm) {
  11476. selectedElm = targetElm;
  11477. width = height = 0;
  11478. }
  11479. var e = editor.fire('ObjectSelected', { target: targetElm });
  11480. if (isResizable(targetElm) && !e.isDefaultPrevented()) {
  11481. each(resizeHandles, function (handle, name) {
  11482. var handleElm;
  11483. var startDrag = function (e) {
  11484. startX = e.screenX;
  11485. startY = e.screenY;
  11486. startW = getResizeTarget(selectedElm).clientWidth;
  11487. startH = getResizeTarget(selectedElm).clientHeight;
  11488. ratio = startH / startW;
  11489. selectedHandle = handle;
  11490. selectedHandle.name = name;
  11491. selectedHandle.startPos = {
  11492. x: targetWidth * handle[0] + selectedElmX,
  11493. y: targetHeight * handle[1] + selectedElmY
  11494. };
  11495. startScrollWidth = rootElement.scrollWidth;
  11496. startScrollHeight = rootElement.scrollHeight;
  11497. selectedElmGhost = selectedElm.cloneNode(true);
  11498. dom.addClass(selectedElmGhost, 'mce-clonedresizable');
  11499. dom.setAttrib(selectedElmGhost, 'data-mce-bogus', 'all');
  11500. selectedElmGhost.contentEditable = false;
  11501. selectedElmGhost.unSelectabe = true;
  11502. dom.setStyles(selectedElmGhost, {
  11503. left: selectedElmX,
  11504. top: selectedElmY,
  11505. margin: 0
  11506. });
  11507. setGhostElmSize(selectedElmGhost, targetWidth, targetHeight);
  11508. selectedElmGhost.removeAttribute('data-mce-selected');
  11509. rootElement.appendChild(selectedElmGhost);
  11510. dom.bind(editableDoc, 'mousemove', resizeGhostElement);
  11511. dom.bind(editableDoc, 'mouseup', endGhostResize);
  11512. if (rootDocument !== editableDoc) {
  11513. dom.bind(rootDocument, 'mousemove', resizeGhostElement);
  11514. dom.bind(rootDocument, 'mouseup', endGhostResize);
  11515. }
  11516. resizeHelper = dom.add(rootElement, 'div', {
  11517. 'class': 'mce-resize-helper',
  11518. 'data-mce-bogus': 'all'
  11519. }, startW + ' &times; ' + startH);
  11520. };
  11521. handleElm = dom.get('mceResizeHandle' + name);
  11522. if (handleElm) {
  11523. dom.remove(handleElm);
  11524. }
  11525. handleElm = dom.add(rootElement, 'div', {
  11526. 'id': 'mceResizeHandle' + name,
  11527. 'data-mce-bogus': 'all',
  11528. 'class': 'mce-resizehandle',
  11529. 'unselectable': true,
  11530. 'style': 'cursor:' + name + '-resize; margin:0; padding:0'
  11531. });
  11532. if (Env.ie === 11) {
  11533. handleElm.contentEditable = false;
  11534. }
  11535. dom.bind(handleElm, 'mousedown', function (e) {
  11536. e.stopImmediatePropagation();
  11537. e.preventDefault();
  11538. startDrag(e);
  11539. });
  11540. handle.elm = handleElm;
  11541. dom.setStyles(handleElm, {
  11542. left: targetWidth * handle[0] + selectedElmX - handleElm.offsetWidth / 2,
  11543. top: targetHeight * handle[1] + selectedElmY - handleElm.offsetHeight / 2
  11544. });
  11545. });
  11546. } else {
  11547. hideResizeRect();
  11548. }
  11549. selectedElm.setAttribute('data-mce-selected', '1');
  11550. };
  11551. var hideResizeRect = function () {
  11552. unbindResizeHandleEvents();
  11553. if (selectedElm) {
  11554. selectedElm.removeAttribute('data-mce-selected');
  11555. }
  11556. each$1(resizeHandles, function (value, name) {
  11557. var handleElm = dom.get('mceResizeHandle' + name);
  11558. if (handleElm) {
  11559. dom.unbind(handleElm);
  11560. dom.remove(handleElm);
  11561. }
  11562. });
  11563. };
  11564. var updateResizeRect = function (e) {
  11565. var startElm, controlElm;
  11566. var isChildOrEqual = function (node, parent) {
  11567. if (node) {
  11568. do {
  11569. if (node === parent) {
  11570. return true;
  11571. }
  11572. } while (node = node.parentNode);
  11573. }
  11574. };
  11575. if (resizeStarted || editor.removed) {
  11576. return;
  11577. }
  11578. each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function (img) {
  11579. img.removeAttribute('data-mce-selected');
  11580. });
  11581. controlElm = e.type === 'mousedown' ? e.target : selection.getNode();
  11582. controlElm = dom.$(controlElm).closest('table,img,figure.image,hr')[0];
  11583. if (isChildOrEqual(controlElm, rootElement)) {
  11584. disableGeckoResize();
  11585. startElm = selection.getStart(true);
  11586. if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
  11587. showResizeRect(controlElm);
  11588. return;
  11589. }
  11590. }
  11591. hideResizeRect();
  11592. };
  11593. var isWithinContentEditableFalse = function (elm) {
  11594. return isContentEditableFalse$6(getContentEditableRoot(editor.getBody(), elm));
  11595. };
  11596. var unbindResizeHandleEvents = function () {
  11597. each$1(resizeHandles, function (handle) {
  11598. if (handle.elm) {
  11599. dom.unbind(handle.elm);
  11600. delete handle.elm;
  11601. }
  11602. });
  11603. };
  11604. var disableGeckoResize = function () {
  11605. try {
  11606. editor.getDoc().execCommand('enableObjectResizing', false, 'false');
  11607. } catch (ex) {
  11608. }
  11609. };
  11610. editor.on('init', function () {
  11611. disableGeckoResize();
  11612. if (Env.browser.isIE() || Env.browser.isEdge()) {
  11613. editor.on('mousedown click', function (e) {
  11614. var target = e.target, nodeName = target.nodeName;
  11615. if (!resizeStarted && /^(TABLE|IMG|HR)$/.test(nodeName) && !isWithinContentEditableFalse(target)) {
  11616. if (e.button !== 2) {
  11617. editor.selection.select(target, nodeName === 'TABLE');
  11618. }
  11619. if (e.type === 'mousedown') {
  11620. editor.nodeChanged();
  11621. }
  11622. }
  11623. });
  11624. var handleMSControlSelect_1 = function (e) {
  11625. var delayedSelect = function (node) {
  11626. Delay.setEditorTimeout(editor, function () {
  11627. return editor.selection.select(node);
  11628. });
  11629. };
  11630. if (isWithinContentEditableFalse(e.target) || isMedia(e.target)) {
  11631. e.preventDefault();
  11632. delayedSelect(e.target);
  11633. return;
  11634. }
  11635. if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) {
  11636. e.preventDefault();
  11637. if (e.target.tagName === 'IMG') {
  11638. delayedSelect(e.target);
  11639. }
  11640. }
  11641. };
  11642. dom.bind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11643. editor.on('remove', function () {
  11644. return dom.unbind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11645. });
  11646. }
  11647. var throttledUpdateResizeRect = Delay.throttle(function (e) {
  11648. if (!editor.composing) {
  11649. updateResizeRect(e);
  11650. }
  11651. });
  11652. editor.on('nodechange ResizeEditor ResizeWindow ResizeContent drop FullscreenStateChanged', throttledUpdateResizeRect);
  11653. editor.on('keyup compositionend', function (e) {
  11654. if (selectedElm && selectedElm.nodeName === 'TABLE') {
  11655. throttledUpdateResizeRect(e);
  11656. }
  11657. });
  11658. editor.on('hide blur', hideResizeRect);
  11659. editor.on('contextmenu longpress', contextMenuSelectImage, true);
  11660. });
  11661. editor.on('remove', unbindResizeHandleEvents);
  11662. var destroy = function () {
  11663. selectedElm = selectedElmGhost = null;
  11664. };
  11665. return {
  11666. isResizable: isResizable,
  11667. showResizeRect: showResizeRect,
  11668. hideResizeRect: hideResizeRect,
  11669. updateResizeRect: updateResizeRect,
  11670. destroy: destroy
  11671. };
  11672. };
  11673. var hasCeProperty = function (node) {
  11674. return isContentEditableTrue(node) || isContentEditableFalse(node);
  11675. };
  11676. var findParent = function (node, rootNode, predicate) {
  11677. while (node && node !== rootNode) {
  11678. if (predicate(node)) {
  11679. return node;
  11680. }
  11681. node = node.parentNode;
  11682. }
  11683. return null;
  11684. };
  11685. var findClosestIeRange = function (clientX, clientY, doc) {
  11686. var rects;
  11687. var element = doc.elementFromPoint(clientX, clientY);
  11688. var rng = doc.body.createTextRange();
  11689. if (!element || element.tagName === 'HTML') {
  11690. element = doc.body;
  11691. }
  11692. rng.moveToElementText(element);
  11693. rects = Tools.toArray(rng.getClientRects());
  11694. rects = rects.sort(function (a, b) {
  11695. a = Math.abs(Math.max(a.top - clientY, a.bottom - clientY));
  11696. b = Math.abs(Math.max(b.top - clientY, b.bottom - clientY));
  11697. return a - b;
  11698. });
  11699. if (rects.length > 0) {
  11700. clientY = (rects[0].bottom + rects[0].top) / 2;
  11701. try {
  11702. rng.moveToPoint(clientX, clientY);
  11703. rng.collapse(true);
  11704. return rng;
  11705. } catch (ex) {
  11706. }
  11707. }
  11708. return null;
  11709. };
  11710. var moveOutOfContentEditableFalse = function (rng, rootNode) {
  11711. var parentElement = rng && rng.parentElement ? rng.parentElement() : null;
  11712. return isContentEditableFalse(findParent(parentElement, rootNode, hasCeProperty)) ? null : rng;
  11713. };
  11714. var fromPoint$1 = function (clientX, clientY, doc) {
  11715. var rng, point;
  11716. var pointDoc = doc;
  11717. if (pointDoc.caretPositionFromPoint) {
  11718. point = pointDoc.caretPositionFromPoint(clientX, clientY);
  11719. if (point) {
  11720. rng = doc.createRange();
  11721. rng.setStart(point.offsetNode, point.offset);
  11722. rng.collapse(true);
  11723. }
  11724. } else if (doc.caretRangeFromPoint) {
  11725. rng = doc.caretRangeFromPoint(clientX, clientY);
  11726. } else if (pointDoc.body.createTextRange) {
  11727. rng = pointDoc.body.createTextRange();
  11728. try {
  11729. rng.moveToPoint(clientX, clientY);
  11730. rng.collapse(true);
  11731. } catch (ex) {
  11732. rng = findClosestIeRange(clientX, clientY, doc);
  11733. }
  11734. return moveOutOfContentEditableFalse(rng, doc.body);
  11735. }
  11736. return rng;
  11737. };
  11738. var isEq$1 = function (rng1, rng2) {
  11739. return rng1 && rng2 && (rng1.startContainer === rng2.startContainer && rng1.startOffset === rng2.startOffset) && (rng1.endContainer === rng2.endContainer && rng1.endOffset === rng2.endOffset);
  11740. };
  11741. var findParent$1 = function (node, rootNode, predicate) {
  11742. while (node && node !== rootNode) {
  11743. if (predicate(node)) {
  11744. return node;
  11745. }
  11746. node = node.parentNode;
  11747. }
  11748. return null;
  11749. };
  11750. var hasParent = function (node, rootNode, predicate) {
  11751. return findParent$1(node, rootNode, predicate) !== null;
  11752. };
  11753. var hasParentWithName = function (node, rootNode, name) {
  11754. return hasParent(node, rootNode, function (node) {
  11755. return node.nodeName === name;
  11756. });
  11757. };
  11758. var isTable$3 = function (node) {
  11759. return node && node.nodeName === 'TABLE';
  11760. };
  11761. var isTableCell$3 = function (node) {
  11762. return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  11763. };
  11764. var isCeFalseCaretContainer = function (node, rootNode) {
  11765. return isCaretContainer(node) && hasParent(node, rootNode, isCaretNode) === false;
  11766. };
  11767. var hasBrBeforeAfter = function (dom, node, left) {
  11768. var walker = new DomTreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || dom.getRoot());
  11769. while (node = walker[left ? 'prev' : 'next']()) {
  11770. if (isBr(node)) {
  11771. return true;
  11772. }
  11773. }
  11774. };
  11775. var isPrevNode = function (node, name) {
  11776. return node.previousSibling && node.previousSibling.nodeName === name;
  11777. };
  11778. var hasContentEditableFalseParent = function (body, node) {
  11779. while (node && node !== body) {
  11780. if (isContentEditableFalse(node)) {
  11781. return true;
  11782. }
  11783. node = node.parentNode;
  11784. }
  11785. return false;
  11786. };
  11787. var findTextNodeRelative = function (dom, isAfterNode, collapsed, left, startNode) {
  11788. var lastInlineElement;
  11789. var body = dom.getRoot();
  11790. var node;
  11791. var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11792. var parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body;
  11793. if (left && isBr(startNode) && isAfterNode && dom.isEmpty(parentBlockContainer)) {
  11794. return Optional.some(CaretPosition(startNode.parentNode, dom.nodeIndex(startNode)));
  11795. }
  11796. var walker = new DomTreeWalker(startNode, parentBlockContainer);
  11797. while (node = walker[left ? 'prev' : 'next']()) {
  11798. if (dom.getContentEditableParent(node) === 'false' || isCeFalseCaretContainer(node, body)) {
  11799. return Optional.none();
  11800. }
  11801. if (isText$1(node) && node.nodeValue.length > 0) {
  11802. if (hasParentWithName(node, body, 'A') === false) {
  11803. return Optional.some(CaretPosition(node, left ? node.nodeValue.length : 0));
  11804. }
  11805. return Optional.none();
  11806. }
  11807. if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  11808. return Optional.none();
  11809. }
  11810. lastInlineElement = node;
  11811. }
  11812. if (collapsed && lastInlineElement) {
  11813. return Optional.some(CaretPosition(lastInlineElement, 0));
  11814. }
  11815. return Optional.none();
  11816. };
  11817. var normalizeEndPoint = function (dom, collapsed, start, rng) {
  11818. var container, offset;
  11819. var body = dom.getRoot();
  11820. var node;
  11821. var directionLeft, normalized = false;
  11822. container = rng[(start ? 'start' : 'end') + 'Container'];
  11823. offset = rng[(start ? 'start' : 'end') + 'Offset'];
  11824. var isAfterNode = isElement$1(container) && offset === container.childNodes.length;
  11825. var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11826. directionLeft = start;
  11827. if (isCaretContainer(container)) {
  11828. return Optional.none();
  11829. }
  11830. if (isElement$1(container) && offset > container.childNodes.length - 1) {
  11831. directionLeft = false;
  11832. }
  11833. if (isDocument$1(container)) {
  11834. container = body;
  11835. offset = 0;
  11836. }
  11837. if (container === body) {
  11838. if (directionLeft) {
  11839. node = container.childNodes[offset > 0 ? offset - 1 : 0];
  11840. if (node) {
  11841. if (isCaretContainer(node)) {
  11842. return Optional.none();
  11843. }
  11844. if (nonEmptyElementsMap[node.nodeName] || isTable$3(node)) {
  11845. return Optional.none();
  11846. }
  11847. }
  11848. }
  11849. if (container.hasChildNodes()) {
  11850. offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
  11851. container = container.childNodes[offset];
  11852. offset = isText$1(container) && isAfterNode ? container.data.length : 0;
  11853. if (!collapsed && container === body.lastChild && isTable$3(container)) {
  11854. return Optional.none();
  11855. }
  11856. if (hasContentEditableFalseParent(body, container) || isCaretContainer(container)) {
  11857. return Optional.none();
  11858. }
  11859. if (container.hasChildNodes() && isTable$3(container) === false) {
  11860. node = container;
  11861. var walker = new DomTreeWalker(container, body);
  11862. do {
  11863. if (isContentEditableFalse(node) || isCaretContainer(node)) {
  11864. normalized = false;
  11865. break;
  11866. }
  11867. if (isText$1(node) && node.nodeValue.length > 0) {
  11868. offset = directionLeft ? 0 : node.nodeValue.length;
  11869. container = node;
  11870. normalized = true;
  11871. break;
  11872. }
  11873. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCell$3(node)) {
  11874. offset = dom.nodeIndex(node);
  11875. container = node.parentNode;
  11876. if (!directionLeft) {
  11877. offset++;
  11878. }
  11879. normalized = true;
  11880. break;
  11881. }
  11882. } while (node = directionLeft ? walker.next() : walker.prev());
  11883. }
  11884. }
  11885. }
  11886. if (collapsed) {
  11887. if (isText$1(container) && offset === 0) {
  11888. findTextNodeRelative(dom, isAfterNode, collapsed, true, container).each(function (pos) {
  11889. container = pos.container();
  11890. offset = pos.offset();
  11891. normalized = true;
  11892. });
  11893. }
  11894. if (isElement$1(container)) {
  11895. node = container.childNodes[offset];
  11896. if (!node) {
  11897. node = container.childNodes[offset - 1];
  11898. }
  11899. if (node && isBr(node) && !isPrevNode(node, 'A') && !hasBrBeforeAfter(dom, node, false) && !hasBrBeforeAfter(dom, node, true)) {
  11900. findTextNodeRelative(dom, isAfterNode, collapsed, true, node).each(function (pos) {
  11901. container = pos.container();
  11902. offset = pos.offset();
  11903. normalized = true;
  11904. });
  11905. }
  11906. }
  11907. }
  11908. if (directionLeft && !collapsed && isText$1(container) && offset === container.nodeValue.length) {
  11909. findTextNodeRelative(dom, isAfterNode, collapsed, false, container).each(function (pos) {
  11910. container = pos.container();
  11911. offset = pos.offset();
  11912. normalized = true;
  11913. });
  11914. }
  11915. return normalized ? Optional.some(CaretPosition(container, offset)) : Optional.none();
  11916. };
  11917. var normalize = function (dom, rng) {
  11918. var collapsed = rng.collapsed, normRng = rng.cloneRange();
  11919. var startPos = CaretPosition.fromRangeStart(rng);
  11920. normalizeEndPoint(dom, collapsed, true, normRng).each(function (pos) {
  11921. if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
  11922. normRng.setStart(pos.container(), pos.offset());
  11923. }
  11924. });
  11925. if (!collapsed) {
  11926. normalizeEndPoint(dom, collapsed, false, normRng).each(function (pos) {
  11927. normRng.setEnd(pos.container(), pos.offset());
  11928. });
  11929. }
  11930. if (collapsed) {
  11931. normRng.collapse(true);
  11932. }
  11933. return isEq$1(rng, normRng) ? Optional.none() : Optional.some(normRng);
  11934. };
  11935. var splitText = function (node, offset) {
  11936. return node.splitText(offset);
  11937. };
  11938. var split$1 = function (rng) {
  11939. var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  11940. if (startContainer === endContainer && isText$1(startContainer)) {
  11941. if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  11942. endContainer = splitText(startContainer, startOffset);
  11943. startContainer = endContainer.previousSibling;
  11944. if (endOffset > startOffset) {
  11945. endOffset = endOffset - startOffset;
  11946. startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
  11947. endOffset = endContainer.nodeValue.length;
  11948. startOffset = 0;
  11949. } else {
  11950. endOffset = 0;
  11951. }
  11952. }
  11953. } else {
  11954. if (isText$1(startContainer) && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  11955. startContainer = splitText(startContainer, startOffset);
  11956. startOffset = 0;
  11957. }
  11958. if (isText$1(endContainer) && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
  11959. endContainer = splitText(endContainer, endOffset).previousSibling;
  11960. endOffset = endContainer.nodeValue.length;
  11961. }
  11962. }
  11963. return {
  11964. startContainer: startContainer,
  11965. startOffset: startOffset,
  11966. endContainer: endContainer,
  11967. endOffset: endOffset
  11968. };
  11969. };
  11970. function RangeUtils(dom) {
  11971. var walk = function (rng, callback) {
  11972. return walk$1(dom, rng, callback);
  11973. };
  11974. var split = split$1;
  11975. var normalize$1 = function (rng) {
  11976. return normalize(dom, rng).fold(never, function (normalizedRng) {
  11977. rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
  11978. rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
  11979. return true;
  11980. });
  11981. };
  11982. return {
  11983. walk: walk,
  11984. split: split,
  11985. normalize: normalize$1
  11986. };
  11987. }
  11988. (function (RangeUtils) {
  11989. RangeUtils.compareRanges = isEq$1;
  11990. RangeUtils.getCaretRangeFromPoint = fromPoint$1;
  11991. RangeUtils.getSelectedNode = getSelectedNode;
  11992. RangeUtils.getNode = getNode;
  11993. }(RangeUtils || (RangeUtils = {})));
  11994. var RangeUtils$1 = RangeUtils;
  11995. function Dimension (name, getOffset) {
  11996. var set = function (element, h) {
  11997. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  11998. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  11999. }
  12000. var dom = element.dom;
  12001. if (isSupported$1(dom)) {
  12002. dom.style[name] = h + 'px';
  12003. }
  12004. };
  12005. var get = function (element) {
  12006. var r = getOffset(element);
  12007. if (r <= 0 || r === null) {
  12008. var css = get$5(element, name);
  12009. return parseFloat(css) || 0;
  12010. }
  12011. return r;
  12012. };
  12013. var getOuter = get;
  12014. var aggregate = function (element, properties) {
  12015. return foldl(properties, function (acc, property) {
  12016. var val = get$5(element, property);
  12017. var value = val === undefined ? 0 : parseInt(val, 10);
  12018. return isNaN(value) ? acc : acc + value;
  12019. }, 0);
  12020. };
  12021. var max = function (element, value, properties) {
  12022. var cumulativeInclusions = aggregate(element, properties);
  12023. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  12024. return absoluteMax;
  12025. };
  12026. return {
  12027. set: set,
  12028. get: get,
  12029. getOuter: getOuter,
  12030. aggregate: aggregate,
  12031. max: max
  12032. };
  12033. }
  12034. var api$1 = Dimension('height', function (element) {
  12035. var dom = element.dom;
  12036. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  12037. });
  12038. var get$9 = function (element) {
  12039. return api$1.get(element);
  12040. };
  12041. var walkUp = function (navigation, doc) {
  12042. var frame = navigation.view(doc);
  12043. return frame.fold(constant([]), function (f) {
  12044. var parent = navigation.owner(f);
  12045. var rest = walkUp(navigation, parent);
  12046. return [f].concat(rest);
  12047. });
  12048. };
  12049. var pathTo = function (element, navigation) {
  12050. var d = navigation.owner(element);
  12051. return walkUp(navigation, d);
  12052. };
  12053. var view = function (doc) {
  12054. var _a;
  12055. var element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  12056. return element.map(SugarElement.fromDom);
  12057. };
  12058. var owner$1 = function (element) {
  12059. return documentOrOwner(element);
  12060. };
  12061. var Navigation = /*#__PURE__*/Object.freeze({
  12062. __proto__: null,
  12063. view: view,
  12064. owner: owner$1
  12065. });
  12066. var find$2 = function (element) {
  12067. var doc = SugarElement.fromDom(document);
  12068. var scroll = get$2(doc);
  12069. var frames = pathTo(element, Navigation);
  12070. var offset = viewport(element);
  12071. var r = foldr(frames, function (b, a) {
  12072. var loc = viewport(a);
  12073. return {
  12074. left: b.left + loc.left,
  12075. top: b.top + loc.top
  12076. };
  12077. }, {
  12078. left: 0,
  12079. top: 0
  12080. });
  12081. return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  12082. };
  12083. var excludeFromDescend = function (element) {
  12084. return name(element) === 'textarea';
  12085. };
  12086. var fireScrollIntoViewEvent = function (editor, data) {
  12087. var scrollEvent = editor.fire('ScrollIntoView', data);
  12088. return scrollEvent.isDefaultPrevented();
  12089. };
  12090. var fireAfterScrollIntoViewEvent = function (editor, data) {
  12091. editor.fire('AfterScrollIntoView', data);
  12092. };
  12093. var descend = function (element, offset) {
  12094. var children$1 = children(element);
  12095. if (children$1.length === 0 || excludeFromDescend(element)) {
  12096. return {
  12097. element: element,
  12098. offset: offset
  12099. };
  12100. } else if (offset < children$1.length && !excludeFromDescend(children$1[offset])) {
  12101. return {
  12102. element: children$1[offset],
  12103. offset: 0
  12104. };
  12105. } else {
  12106. var last = children$1[children$1.length - 1];
  12107. if (excludeFromDescend(last)) {
  12108. return {
  12109. element: element,
  12110. offset: offset
  12111. };
  12112. } else {
  12113. if (name(last) === 'img') {
  12114. return {
  12115. element: last,
  12116. offset: 1
  12117. };
  12118. } else if (isText(last)) {
  12119. return {
  12120. element: last,
  12121. offset: get$8(last).length
  12122. };
  12123. } else {
  12124. return {
  12125. element: last,
  12126. offset: children(last).length
  12127. };
  12128. }
  12129. }
  12130. }
  12131. };
  12132. var markerInfo = function (element, cleanupFun) {
  12133. var pos = absolute(element);
  12134. var height = get$9(element);
  12135. return {
  12136. element: element,
  12137. bottom: pos.top + height,
  12138. height: height,
  12139. pos: pos,
  12140. cleanup: cleanupFun
  12141. };
  12142. };
  12143. var createMarker = function (element, offset) {
  12144. var startPoint = descend(element, offset);
  12145. var span = SugarElement.fromHtml('<span data-mce-bogus="all">' + ZWSP + '</span>');
  12146. before(startPoint.element, span);
  12147. return markerInfo(span, function () {
  12148. return remove(span);
  12149. });
  12150. };
  12151. var elementMarker = function (element) {
  12152. return markerInfo(SugarElement.fromDom(element), noop);
  12153. };
  12154. var withMarker = function (editor, f, rng, alignToTop) {
  12155. preserveWith(editor, function (_s, _e) {
  12156. return applyWithMarker(editor, f, rng, alignToTop);
  12157. }, rng);
  12158. };
  12159. var withScrollEvents = function (editor, doc, f, marker, alignToTop) {
  12160. var data = {
  12161. elm: marker.element.dom,
  12162. alignToTop: alignToTop
  12163. };
  12164. if (fireScrollIntoViewEvent(editor, data)) {
  12165. return;
  12166. }
  12167. var scrollTop = get$2(doc).top;
  12168. f(doc, scrollTop, marker, alignToTop);
  12169. fireAfterScrollIntoViewEvent(editor, data);
  12170. };
  12171. var applyWithMarker = function (editor, f, rng, alignToTop) {
  12172. var body = SugarElement.fromDom(editor.getBody());
  12173. var doc = SugarElement.fromDom(editor.getDoc());
  12174. reflow(body);
  12175. var marker = createMarker(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  12176. withScrollEvents(editor, doc, f, marker, alignToTop);
  12177. marker.cleanup();
  12178. };
  12179. var withElement = function (editor, element, f, alignToTop) {
  12180. var doc = SugarElement.fromDom(editor.getDoc());
  12181. withScrollEvents(editor, doc, f, elementMarker(element), alignToTop);
  12182. };
  12183. var preserveWith = function (editor, f, rng) {
  12184. var startElement = rng.startContainer;
  12185. var startOffset = rng.startOffset;
  12186. var endElement = rng.endContainer;
  12187. var endOffset = rng.endOffset;
  12188. f(SugarElement.fromDom(startElement), SugarElement.fromDom(endElement));
  12189. var newRng = editor.dom.createRng();
  12190. newRng.setStart(startElement, startOffset);
  12191. newRng.setEnd(endElement, endOffset);
  12192. editor.selection.setRng(rng);
  12193. };
  12194. var scrollToMarker = function (marker, viewHeight, alignToTop, doc) {
  12195. var pos = marker.pos;
  12196. if (alignToTop) {
  12197. to(pos.left, pos.top, doc);
  12198. } else {
  12199. var y = pos.top - viewHeight + marker.height;
  12200. to(pos.left, y, doc);
  12201. }
  12202. };
  12203. var intoWindowIfNeeded = function (doc, scrollTop, viewHeight, marker, alignToTop) {
  12204. var viewportBottom = viewHeight + scrollTop;
  12205. var markerTop = marker.pos.top;
  12206. var markerBottom = marker.bottom;
  12207. var largerThanViewport = markerBottom - markerTop >= viewHeight;
  12208. if (markerTop < scrollTop) {
  12209. scrollToMarker(marker, viewHeight, alignToTop !== false, doc);
  12210. } else if (markerTop > viewportBottom) {
  12211. var align = largerThanViewport ? alignToTop !== false : alignToTop === true;
  12212. scrollToMarker(marker, viewHeight, align, doc);
  12213. } else if (markerBottom > viewportBottom && !largerThanViewport) {
  12214. scrollToMarker(marker, viewHeight, alignToTop === true, doc);
  12215. }
  12216. };
  12217. var intoWindow = function (doc, scrollTop, marker, alignToTop) {
  12218. var viewHeight = doc.dom.defaultView.innerHeight;
  12219. intoWindowIfNeeded(doc, scrollTop, viewHeight, marker, alignToTop);
  12220. };
  12221. var intoFrame = function (doc, scrollTop, marker, alignToTop) {
  12222. var frameViewHeight = doc.dom.defaultView.innerHeight;
  12223. intoWindowIfNeeded(doc, scrollTop, frameViewHeight, marker, alignToTop);
  12224. var op = find$2(marker.element);
  12225. var viewportBounds = getBounds(window);
  12226. if (op.top < viewportBounds.y) {
  12227. intoView(marker.element, alignToTop !== false);
  12228. } else if (op.top > viewportBounds.bottom) {
  12229. intoView(marker.element, alignToTop === true);
  12230. }
  12231. };
  12232. var rangeIntoWindow = function (editor, rng, alignToTop) {
  12233. return withMarker(editor, intoWindow, rng, alignToTop);
  12234. };
  12235. var elementIntoWindow = function (editor, element, alignToTop) {
  12236. return withElement(editor, element, intoWindow, alignToTop);
  12237. };
  12238. var rangeIntoFrame = function (editor, rng, alignToTop) {
  12239. return withMarker(editor, intoFrame, rng, alignToTop);
  12240. };
  12241. var elementIntoFrame = function (editor, element, alignToTop) {
  12242. return withElement(editor, element, intoFrame, alignToTop);
  12243. };
  12244. var scrollElementIntoView = function (editor, element, alignToTop) {
  12245. var scroller = editor.inline ? elementIntoWindow : elementIntoFrame;
  12246. scroller(editor, element, alignToTop);
  12247. };
  12248. var scrollRangeIntoView = function (editor, rng, alignToTop) {
  12249. var scroller = editor.inline ? rangeIntoWindow : rangeIntoFrame;
  12250. scroller(editor, rng, alignToTop);
  12251. };
  12252. var getDocument = function () {
  12253. return SugarElement.fromDom(document);
  12254. };
  12255. var focus = function (element) {
  12256. return element.dom.focus();
  12257. };
  12258. var hasFocus = function (element) {
  12259. var root = getRootNode(element).dom;
  12260. return element.dom === root.activeElement;
  12261. };
  12262. var active = function (root) {
  12263. if (root === void 0) {
  12264. root = getDocument();
  12265. }
  12266. return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  12267. };
  12268. var search = function (element) {
  12269. return active(getRootNode(element)).filter(function (e) {
  12270. return element.dom.contains(e.dom);
  12271. });
  12272. };
  12273. var create$4 = function (start, soffset, finish, foffset) {
  12274. return {
  12275. start: start,
  12276. soffset: soffset,
  12277. finish: finish,
  12278. foffset: foffset
  12279. };
  12280. };
  12281. var SimRange = { create: create$4 };
  12282. var adt = Adt.generate([
  12283. { before: ['element'] },
  12284. {
  12285. on: [
  12286. 'element',
  12287. 'offset'
  12288. ]
  12289. },
  12290. { after: ['element'] }
  12291. ]);
  12292. var cata = function (subject, onBefore, onOn, onAfter) {
  12293. return subject.fold(onBefore, onOn, onAfter);
  12294. };
  12295. var getStart = function (situ) {
  12296. return situ.fold(identity, identity, identity);
  12297. };
  12298. var before$3 = adt.before;
  12299. var on = adt.on;
  12300. var after$2 = adt.after;
  12301. var Situ = {
  12302. before: before$3,
  12303. on: on,
  12304. after: after$2,
  12305. cata: cata,
  12306. getStart: getStart
  12307. };
  12308. var adt$1 = Adt.generate([
  12309. { domRange: ['rng'] },
  12310. {
  12311. relative: [
  12312. 'startSitu',
  12313. 'finishSitu'
  12314. ]
  12315. },
  12316. {
  12317. exact: [
  12318. 'start',
  12319. 'soffset',
  12320. 'finish',
  12321. 'foffset'
  12322. ]
  12323. }
  12324. ]);
  12325. var exactFromRange = function (simRange) {
  12326. return adt$1.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  12327. };
  12328. var getStart$1 = function (selection) {
  12329. return selection.match({
  12330. domRange: function (rng) {
  12331. return SugarElement.fromDom(rng.startContainer);
  12332. },
  12333. relative: function (startSitu, _finishSitu) {
  12334. return Situ.getStart(startSitu);
  12335. },
  12336. exact: function (start, _soffset, _finish, _foffset) {
  12337. return start;
  12338. }
  12339. });
  12340. };
  12341. var domRange = adt$1.domRange;
  12342. var relative = adt$1.relative;
  12343. var exact = adt$1.exact;
  12344. var getWin = function (selection) {
  12345. var start = getStart$1(selection);
  12346. return defaultView(start);
  12347. };
  12348. var range = SimRange.create;
  12349. var SimSelection = {
  12350. domRange: domRange,
  12351. relative: relative,
  12352. exact: exact,
  12353. exactFromRange: exactFromRange,
  12354. getWin: getWin,
  12355. range: range
  12356. };
  12357. var browser$3 = detect$3().browser;
  12358. var clamp = function (offset, element) {
  12359. var max = isText(element) ? get$8(element).length : children(element).length + 1;
  12360. if (offset > max) {
  12361. return max;
  12362. } else if (offset < 0) {
  12363. return 0;
  12364. }
  12365. return offset;
  12366. };
  12367. var normalizeRng = function (rng) {
  12368. return SimSelection.range(rng.start, clamp(rng.soffset, rng.start), rng.finish, clamp(rng.foffset, rng.finish));
  12369. };
  12370. var isOrContains = function (root, elm) {
  12371. return !isRestrictedNode(elm.dom) && (contains$2(root, elm) || eq$2(root, elm));
  12372. };
  12373. var isRngInRoot = function (root) {
  12374. return function (rng) {
  12375. return isOrContains(root, rng.start) && isOrContains(root, rng.finish);
  12376. };
  12377. };
  12378. var shouldStore = function (editor) {
  12379. return editor.inline === true || browser$3.isIE();
  12380. };
  12381. var nativeRangeToSelectionRange = function (r) {
  12382. return SimSelection.range(SugarElement.fromDom(r.startContainer), r.startOffset, SugarElement.fromDom(r.endContainer), r.endOffset);
  12383. };
  12384. var readRange = function (win) {
  12385. var selection = win.getSelection();
  12386. var rng = !selection || selection.rangeCount === 0 ? Optional.none() : Optional.from(selection.getRangeAt(0));
  12387. return rng.map(nativeRangeToSelectionRange);
  12388. };
  12389. var getBookmark$2 = function (root) {
  12390. var win = defaultView(root);
  12391. return readRange(win.dom).filter(isRngInRoot(root));
  12392. };
  12393. var validate = function (root, bookmark) {
  12394. return Optional.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
  12395. };
  12396. var bookmarkToNativeRng = function (bookmark) {
  12397. var rng = document.createRange();
  12398. try {
  12399. rng.setStart(bookmark.start.dom, bookmark.soffset);
  12400. rng.setEnd(bookmark.finish.dom, bookmark.foffset);
  12401. return Optional.some(rng);
  12402. } catch (_) {
  12403. return Optional.none();
  12404. }
  12405. };
  12406. var store = function (editor) {
  12407. var newBookmark = shouldStore(editor) ? getBookmark$2(SugarElement.fromDom(editor.getBody())) : Optional.none();
  12408. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12409. };
  12410. var storeNative = function (editor, rng) {
  12411. var root = SugarElement.fromDom(editor.getBody());
  12412. var range = shouldStore(editor) ? Optional.from(rng) : Optional.none();
  12413. var newBookmark = range.map(nativeRangeToSelectionRange).filter(isRngInRoot(root));
  12414. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12415. };
  12416. var getRng = function (editor) {
  12417. var bookmark = editor.bookmark ? editor.bookmark : Optional.none();
  12418. return bookmark.bind(function (x) {
  12419. return validate(SugarElement.fromDom(editor.getBody()), x);
  12420. }).bind(bookmarkToNativeRng);
  12421. };
  12422. var restore = function (editor) {
  12423. getRng(editor).each(function (rng) {
  12424. return editor.selection.setRng(rng);
  12425. });
  12426. };
  12427. var isEditorUIElement = function (elm) {
  12428. var className = elm.className.toString();
  12429. return className.indexOf('tox-') !== -1 || className.indexOf('mce-') !== -1;
  12430. };
  12431. var FocusManager = { isEditorUIElement: isEditorUIElement };
  12432. var isManualNodeChange = function (e) {
  12433. return e.type === 'nodechange' && e.selectionChange;
  12434. };
  12435. var registerPageMouseUp = function (editor, throttledStore) {
  12436. var mouseUpPage = function () {
  12437. throttledStore.throttle();
  12438. };
  12439. DOMUtils$1.DOM.bind(document, 'mouseup', mouseUpPage);
  12440. editor.on('remove', function () {
  12441. DOMUtils$1.DOM.unbind(document, 'mouseup', mouseUpPage);
  12442. });
  12443. };
  12444. var registerFocusOut = function (editor) {
  12445. editor.on('focusout', function () {
  12446. store(editor);
  12447. });
  12448. };
  12449. var registerMouseUp = function (editor, throttledStore) {
  12450. editor.on('mouseup touchend', function (_e) {
  12451. throttledStore.throttle();
  12452. });
  12453. };
  12454. var registerEditorEvents = function (editor, throttledStore) {
  12455. var browser = detect$3().browser;
  12456. if (browser.isIE()) {
  12457. registerFocusOut(editor);
  12458. } else {
  12459. registerMouseUp(editor, throttledStore);
  12460. }
  12461. editor.on('keyup NodeChange', function (e) {
  12462. if (!isManualNodeChange(e)) {
  12463. store(editor);
  12464. }
  12465. });
  12466. };
  12467. var register = function (editor) {
  12468. var throttledStore = first(function () {
  12469. store(editor);
  12470. }, 0);
  12471. editor.on('init', function () {
  12472. if (editor.inline) {
  12473. registerPageMouseUp(editor, throttledStore);
  12474. }
  12475. registerEditorEvents(editor, throttledStore);
  12476. });
  12477. editor.on('remove', function () {
  12478. throttledStore.cancel();
  12479. });
  12480. };
  12481. var documentFocusInHandler;
  12482. var DOM$2 = DOMUtils$1.DOM;
  12483. var isEditorUIElement$1 = function (elm) {
  12484. return FocusManager.isEditorUIElement(elm);
  12485. };
  12486. var isEditorContentAreaElement = function (elm) {
  12487. var classList = elm.classList;
  12488. if (classList !== undefined) {
  12489. return classList.contains('tox-edit-area') || classList.contains('tox-edit-area__iframe') || classList.contains('mce-content-body');
  12490. } else {
  12491. return false;
  12492. }
  12493. };
  12494. var isUIElement = function (editor, elm) {
  12495. var customSelector = getCustomUiSelector(editor);
  12496. var parent = DOM$2.getParent(elm, function (elm) {
  12497. return isEditorUIElement$1(elm) || (customSelector ? editor.dom.is(elm, customSelector) : false);
  12498. });
  12499. return parent !== null;
  12500. };
  12501. var getActiveElement = function (editor) {
  12502. try {
  12503. var root = getRootNode(SugarElement.fromDom(editor.getElement()));
  12504. return active(root).fold(function () {
  12505. return document.body;
  12506. }, function (x) {
  12507. return x.dom;
  12508. });
  12509. } catch (ex) {
  12510. return document.body;
  12511. }
  12512. };
  12513. var registerEvents = function (editorManager, e) {
  12514. var editor = e.editor;
  12515. register(editor);
  12516. editor.on('focusin', function () {
  12517. var self = this;
  12518. var focusedEditor = editorManager.focusedEditor;
  12519. if (focusedEditor !== self) {
  12520. if (focusedEditor) {
  12521. focusedEditor.fire('blur', { focusedEditor: self });
  12522. }
  12523. editorManager.setActive(self);
  12524. editorManager.focusedEditor = self;
  12525. self.fire('focus', { blurredEditor: focusedEditor });
  12526. self.focus(true);
  12527. }
  12528. });
  12529. editor.on('focusout', function () {
  12530. var self = this;
  12531. Delay.setEditorTimeout(self, function () {
  12532. var focusedEditor = editorManager.focusedEditor;
  12533. if (!isUIElement(self, getActiveElement(self)) && focusedEditor === self) {
  12534. self.fire('blur', { focusedEditor: null });
  12535. editorManager.focusedEditor = null;
  12536. }
  12537. });
  12538. });
  12539. if (!documentFocusInHandler) {
  12540. documentFocusInHandler = function (e) {
  12541. var activeEditor = editorManager.activeEditor;
  12542. if (activeEditor) {
  12543. getOriginalEventTarget(e).each(function (target) {
  12544. if (target.ownerDocument === document) {
  12545. if (target !== document.body && !isUIElement(activeEditor, target) && editorManager.focusedEditor === activeEditor) {
  12546. activeEditor.fire('blur', { focusedEditor: null });
  12547. editorManager.focusedEditor = null;
  12548. }
  12549. }
  12550. });
  12551. }
  12552. };
  12553. DOM$2.bind(document, 'focusin', documentFocusInHandler);
  12554. }
  12555. };
  12556. var unregisterDocumentEvents = function (editorManager, e) {
  12557. if (editorManager.focusedEditor === e.editor) {
  12558. editorManager.focusedEditor = null;
  12559. }
  12560. if (!editorManager.activeEditor) {
  12561. DOM$2.unbind(document, 'focusin', documentFocusInHandler);
  12562. documentFocusInHandler = null;
  12563. }
  12564. };
  12565. var setup$2 = function (editorManager) {
  12566. editorManager.on('AddEditor', curry(registerEvents, editorManager));
  12567. editorManager.on('RemoveEditor', curry(unregisterDocumentEvents, editorManager));
  12568. };
  12569. var getContentEditableHost = function (editor, node) {
  12570. return editor.dom.getParent(node, function (node) {
  12571. return editor.dom.getContentEditable(node) === 'true';
  12572. });
  12573. };
  12574. var getCollapsedNode = function (rng) {
  12575. return rng.collapsed ? Optional.from(getNode(rng.startContainer, rng.startOffset)).map(SugarElement.fromDom) : Optional.none();
  12576. };
  12577. var getFocusInElement = function (root, rng) {
  12578. return getCollapsedNode(rng).bind(function (node) {
  12579. if (isTableSection(node)) {
  12580. return Optional.some(node);
  12581. } else if (contains$2(root, node) === false) {
  12582. return Optional.some(root);
  12583. } else {
  12584. return Optional.none();
  12585. }
  12586. });
  12587. };
  12588. var normalizeSelection = function (editor, rng) {
  12589. getFocusInElement(SugarElement.fromDom(editor.getBody()), rng).bind(function (elm) {
  12590. return firstPositionIn(elm.dom);
  12591. }).fold(function () {
  12592. editor.selection.normalize();
  12593. return;
  12594. }, function (caretPos) {
  12595. return editor.selection.setRng(caretPos.toRange());
  12596. });
  12597. };
  12598. var focusBody = function (body) {
  12599. if (body.setActive) {
  12600. try {
  12601. body.setActive();
  12602. } catch (ex) {
  12603. body.focus();
  12604. }
  12605. } else {
  12606. body.focus();
  12607. }
  12608. };
  12609. var hasElementFocus = function (elm) {
  12610. return hasFocus(elm) || search(elm).isSome();
  12611. };
  12612. var hasIframeFocus = function (editor) {
  12613. return editor.iframeElement && hasFocus(SugarElement.fromDom(editor.iframeElement));
  12614. };
  12615. var hasInlineFocus = function (editor) {
  12616. var rawBody = editor.getBody();
  12617. return rawBody && hasElementFocus(SugarElement.fromDom(rawBody));
  12618. };
  12619. var hasUiFocus = function (editor) {
  12620. return active().filter(function (elem) {
  12621. return !isEditorContentAreaElement(elem.dom) && isUIElement(editor, elem.dom);
  12622. }).isSome();
  12623. };
  12624. var hasFocus$1 = function (editor) {
  12625. return editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
  12626. };
  12627. var hasEditorOrUiFocus = function (editor) {
  12628. return hasFocus$1(editor) || hasUiFocus(editor);
  12629. };
  12630. var focusEditor = function (editor) {
  12631. var selection = editor.selection;
  12632. var body = editor.getBody();
  12633. var rng = selection.getRng();
  12634. editor.quirks.refreshContentEditable();
  12635. if (editor.bookmark !== undefined && hasFocus$1(editor) === false) {
  12636. getRng(editor).each(function (bookmarkRng) {
  12637. editor.selection.setRng(bookmarkRng);
  12638. rng = bookmarkRng;
  12639. });
  12640. }
  12641. var contentEditableHost = getContentEditableHost(editor, selection.getNode());
  12642. if (editor.$.contains(body, contentEditableHost)) {
  12643. focusBody(contentEditableHost);
  12644. normalizeSelection(editor, rng);
  12645. activateEditor(editor);
  12646. return;
  12647. }
  12648. if (!editor.inline) {
  12649. if (!Env.opera) {
  12650. focusBody(body);
  12651. }
  12652. editor.getWin().focus();
  12653. }
  12654. if (Env.gecko || editor.inline) {
  12655. focusBody(body);
  12656. normalizeSelection(editor, rng);
  12657. }
  12658. activateEditor(editor);
  12659. };
  12660. var activateEditor = function (editor) {
  12661. return editor.editorManager.setActive(editor);
  12662. };
  12663. var focus$1 = function (editor, skipFocus) {
  12664. if (editor.removed) {
  12665. return;
  12666. }
  12667. skipFocus ? activateEditor(editor) : focusEditor(editor);
  12668. };
  12669. var getEndpointElement = function (root, rng, start, real, resolve) {
  12670. var container = start ? rng.startContainer : rng.endContainer;
  12671. var offset = start ? rng.startOffset : rng.endOffset;
  12672. return Optional.from(container).map(SugarElement.fromDom).map(function (elm) {
  12673. return !real || !rng.collapsed ? child(elm, resolve(elm, offset)).getOr(elm) : elm;
  12674. }).bind(function (elm) {
  12675. return isElement(elm) ? Optional.some(elm) : parent(elm).filter(isElement);
  12676. }).map(function (elm) {
  12677. return elm.dom;
  12678. }).getOr(root);
  12679. };
  12680. var getStart$2 = function (root, rng, real) {
  12681. return getEndpointElement(root, rng, true, real, function (elm, offset) {
  12682. return Math.min(childNodesCount(elm), offset);
  12683. });
  12684. };
  12685. var getEnd = function (root, rng, real) {
  12686. return getEndpointElement(root, rng, false, real, function (elm, offset) {
  12687. return offset > 0 ? offset - 1 : offset;
  12688. });
  12689. };
  12690. var skipEmptyTextNodes = function (node, forwards) {
  12691. var orig = node;
  12692. while (node && isText$1(node) && node.length === 0) {
  12693. node = forwards ? node.nextSibling : node.previousSibling;
  12694. }
  12695. return node || orig;
  12696. };
  12697. var getNode$1 = function (root, rng) {
  12698. var elm, startContainer, endContainer;
  12699. if (!rng) {
  12700. return root;
  12701. }
  12702. startContainer = rng.startContainer;
  12703. endContainer = rng.endContainer;
  12704. var startOffset = rng.startOffset;
  12705. var endOffset = rng.endOffset;
  12706. elm = rng.commonAncestorContainer;
  12707. if (!rng.collapsed) {
  12708. if (startContainer === endContainer) {
  12709. if (endOffset - startOffset < 2) {
  12710. if (startContainer.hasChildNodes()) {
  12711. elm = startContainer.childNodes[startOffset];
  12712. }
  12713. }
  12714. }
  12715. if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
  12716. if (startContainer.length === startOffset) {
  12717. startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
  12718. } else {
  12719. startContainer = startContainer.parentNode;
  12720. }
  12721. if (endOffset === 0) {
  12722. endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
  12723. } else {
  12724. endContainer = endContainer.parentNode;
  12725. }
  12726. if (startContainer && startContainer === endContainer) {
  12727. return startContainer;
  12728. }
  12729. }
  12730. }
  12731. if (elm && elm.nodeType === 3) {
  12732. return elm.parentNode;
  12733. }
  12734. return elm;
  12735. };
  12736. var getSelectedBlocks = function (dom, rng, startElm, endElm) {
  12737. var node;
  12738. var selectedBlocks = [];
  12739. var root = dom.getRoot();
  12740. startElm = dom.getParent(startElm || getStart$2(root, rng, rng.collapsed), dom.isBlock);
  12741. endElm = dom.getParent(endElm || getEnd(root, rng, rng.collapsed), dom.isBlock);
  12742. if (startElm && startElm !== root) {
  12743. selectedBlocks.push(startElm);
  12744. }
  12745. if (startElm && endElm && startElm !== endElm) {
  12746. node = startElm;
  12747. var walker = new DomTreeWalker(startElm, root);
  12748. while ((node = walker.next()) && node !== endElm) {
  12749. if (dom.isBlock(node)) {
  12750. selectedBlocks.push(node);
  12751. }
  12752. }
  12753. }
  12754. if (endElm && startElm !== endElm && endElm !== root) {
  12755. selectedBlocks.push(endElm);
  12756. }
  12757. return selectedBlocks;
  12758. };
  12759. var select$1 = function (dom, node, content) {
  12760. return Optional.from(node).map(function (node) {
  12761. var idx = dom.nodeIndex(node);
  12762. var rng = dom.createRng();
  12763. rng.setStart(node.parentNode, idx);
  12764. rng.setEnd(node.parentNode, idx + 1);
  12765. if (content) {
  12766. moveEndPoint$1(dom, rng, node, true);
  12767. moveEndPoint$1(dom, rng, node, false);
  12768. }
  12769. return rng;
  12770. });
  12771. };
  12772. var processRanges = function (editor, ranges) {
  12773. return map(ranges, function (range) {
  12774. var evt = editor.fire('GetSelectionRange', { range: range });
  12775. return evt.range !== range ? evt.range : range;
  12776. });
  12777. };
  12778. var ensureIsRoot = function (isRoot) {
  12779. return isFunction(isRoot) ? isRoot : never;
  12780. };
  12781. var ancestor$3 = function (scope, transform, isRoot) {
  12782. var element = scope.dom;
  12783. var stop = ensureIsRoot(isRoot);
  12784. while (element.parentNode) {
  12785. element = element.parentNode;
  12786. var el = SugarElement.fromDom(element);
  12787. var transformed = transform(el);
  12788. if (transformed.isSome()) {
  12789. return transformed;
  12790. } else if (stop(el)) {
  12791. break;
  12792. }
  12793. }
  12794. return Optional.none();
  12795. };
  12796. var closest$2 = function (scope, transform, isRoot) {
  12797. var current = transform(scope);
  12798. var stop = ensureIsRoot(isRoot);
  12799. return current.orThunk(function () {
  12800. return stop(scope) ? Optional.none() : ancestor$3(scope, transform, stop);
  12801. });
  12802. };
  12803. var isEq$2 = isEq;
  12804. var matchesUnInheritedFormatSelector = function (ed, node, name) {
  12805. var formatList = ed.formatter.get(name);
  12806. if (formatList) {
  12807. for (var i = 0; i < formatList.length; i++) {
  12808. if (formatList[i].inherit === false && ed.dom.is(node, formatList[i].selector)) {
  12809. return true;
  12810. }
  12811. }
  12812. }
  12813. return false;
  12814. };
  12815. var matchParents = function (editor, node, name, vars) {
  12816. var root = editor.dom.getRoot();
  12817. if (node === root) {
  12818. return false;
  12819. }
  12820. node = editor.dom.getParent(node, function (node) {
  12821. if (matchesUnInheritedFormatSelector(editor, node, name)) {
  12822. return true;
  12823. }
  12824. return node.parentNode === root || !!matchNode(editor, node, name, vars, true);
  12825. });
  12826. return matchNode(editor, node, name, vars);
  12827. };
  12828. var matchName = function (dom, node, format) {
  12829. if (isEq$2(node, format.inline)) {
  12830. return true;
  12831. }
  12832. if (isEq$2(node, format.block)) {
  12833. return true;
  12834. }
  12835. if (format.selector) {
  12836. return node.nodeType === 1 && dom.is(node, format.selector);
  12837. }
  12838. };
  12839. var matchItems = function (dom, node, format, itemName, similar, vars) {
  12840. var key, value;
  12841. var items = format[itemName];
  12842. var i;
  12843. if (format.onmatch) {
  12844. return format.onmatch(node, format, itemName);
  12845. }
  12846. if (items) {
  12847. if (typeof items.length === 'undefined') {
  12848. for (key in items) {
  12849. if (items.hasOwnProperty(key)) {
  12850. if (itemName === 'attributes') {
  12851. value = dom.getAttrib(node, key);
  12852. } else {
  12853. value = getStyle(dom, node, key);
  12854. }
  12855. if (similar && !value && !format.exact) {
  12856. return;
  12857. }
  12858. if ((!similar || format.exact) && !isEq$2(value, normalizeStyleValue(dom, replaceVars(items[key], vars), key))) {
  12859. return;
  12860. }
  12861. }
  12862. }
  12863. } else {
  12864. for (i = 0; i < items.length; i++) {
  12865. if (itemName === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(dom, node, items[i])) {
  12866. return format;
  12867. }
  12868. }
  12869. }
  12870. }
  12871. return format;
  12872. };
  12873. var matchNode = function (ed, node, name, vars, similar) {
  12874. var formatList = ed.formatter.get(name);
  12875. var format, i, x, classes;
  12876. var dom = ed.dom;
  12877. if (formatList && node) {
  12878. for (i = 0; i < formatList.length; i++) {
  12879. format = formatList[i];
  12880. if (matchName(ed.dom, node, format) && matchItems(dom, node, format, 'attributes', similar, vars) && matchItems(dom, node, format, 'styles', similar, vars)) {
  12881. if (classes = format.classes) {
  12882. for (x = 0; x < classes.length; x++) {
  12883. if (!ed.dom.hasClass(node, classes[x])) {
  12884. return;
  12885. }
  12886. }
  12887. }
  12888. return format;
  12889. }
  12890. }
  12891. }
  12892. };
  12893. var match = function (editor, name, vars, node) {
  12894. if (node) {
  12895. return matchParents(editor, node, name, vars);
  12896. }
  12897. node = editor.selection.getNode();
  12898. if (matchParents(editor, node, name, vars)) {
  12899. return true;
  12900. }
  12901. var startNode = editor.selection.getStart();
  12902. if (startNode !== node) {
  12903. if (matchParents(editor, startNode, name, vars)) {
  12904. return true;
  12905. }
  12906. }
  12907. return false;
  12908. };
  12909. var matchAll = function (editor, names, vars) {
  12910. var matchedFormatNames = [];
  12911. var checkedMap = {};
  12912. var startElement = editor.selection.getStart();
  12913. editor.dom.getParent(startElement, function (node) {
  12914. for (var i = 0; i < names.length; i++) {
  12915. var name_1 = names[i];
  12916. if (!checkedMap[name_1] && matchNode(editor, node, name_1, vars)) {
  12917. checkedMap[name_1] = true;
  12918. matchedFormatNames.push(name_1);
  12919. }
  12920. }
  12921. }, editor.dom.getRoot());
  12922. return matchedFormatNames;
  12923. };
  12924. var closest$3 = function (editor, names) {
  12925. var isRoot = function (elm) {
  12926. return eq$2(elm, SugarElement.fromDom(editor.getBody()));
  12927. };
  12928. var match = function (elm, name) {
  12929. return matchNode(editor, elm.dom, name) ? Optional.some(name) : Optional.none();
  12930. };
  12931. return Optional.from(editor.selection.getStart(true)).bind(function (rawElm) {
  12932. return closest$2(SugarElement.fromDom(rawElm), function (elm) {
  12933. return findMap(names, function (name) {
  12934. return match(elm, name);
  12935. });
  12936. }, isRoot);
  12937. }).getOrNull();
  12938. };
  12939. var canApply = function (editor, name) {
  12940. var formatList = editor.formatter.get(name);
  12941. var startNode, parents, i, x, selector;
  12942. var dom = editor.dom;
  12943. if (formatList) {
  12944. startNode = editor.selection.getStart();
  12945. parents = getParents$1(dom, startNode);
  12946. for (x = formatList.length - 1; x >= 0; x--) {
  12947. selector = formatList[x].selector;
  12948. if (!selector || formatList[x].defaultBlock) {
  12949. return true;
  12950. }
  12951. for (i = parents.length - 1; i >= 0; i--) {
  12952. if (dom.is(parents[i], selector)) {
  12953. return true;
  12954. }
  12955. }
  12956. }
  12957. }
  12958. return false;
  12959. };
  12960. var matchAllOnNode = function (editor, node, formatNames) {
  12961. return foldl(formatNames, function (acc, name) {
  12962. var matchSimilar = isVariableFormatName(editor, name);
  12963. if (editor.formatter.matchNode(node, name, {}, matchSimilar)) {
  12964. return acc.concat([name]);
  12965. } else {
  12966. return acc;
  12967. }
  12968. }, []);
  12969. };
  12970. var typeLookup = {
  12971. '#text': 3,
  12972. '#comment': 8,
  12973. '#cdata': 4,
  12974. '#pi': 7,
  12975. '#doctype': 10,
  12976. '#document-fragment': 11
  12977. };
  12978. var walk$2 = function (node, root, prev) {
  12979. var startName = prev ? 'lastChild' : 'firstChild';
  12980. var siblingName = prev ? 'prev' : 'next';
  12981. if (node[startName]) {
  12982. return node[startName];
  12983. }
  12984. if (node !== root) {
  12985. var sibling = node[siblingName];
  12986. if (sibling) {
  12987. return sibling;
  12988. }
  12989. for (var parent_1 = node.parent; parent_1 && parent_1 !== root; parent_1 = parent_1.parent) {
  12990. sibling = parent_1[siblingName];
  12991. if (sibling) {
  12992. return sibling;
  12993. }
  12994. }
  12995. }
  12996. };
  12997. var isEmptyTextNode$1 = function (node) {
  12998. if (!isWhitespaceText(node.value)) {
  12999. return false;
  13000. }
  13001. var parentNode = node.parent;
  13002. if (parentNode && (parentNode.name !== 'span' || parentNode.attr('style')) && /^[ ]+$/.test(node.value)) {
  13003. return false;
  13004. }
  13005. return true;
  13006. };
  13007. var isNonEmptyElement = function (node) {
  13008. var isNamedAnchor = node.name === 'a' && !node.attr('href') && node.attr('id');
  13009. return node.attr('name') || node.attr('id') && !node.firstChild || node.attr('data-mce-bookmark') || isNamedAnchor;
  13010. };
  13011. var AstNode = function () {
  13012. function AstNode(name, type) {
  13013. this.name = name;
  13014. this.type = type;
  13015. if (type === 1) {
  13016. this.attributes = [];
  13017. this.attributes.map = {};
  13018. }
  13019. }
  13020. AstNode.create = function (name, attrs) {
  13021. var node = new AstNode(name, typeLookup[name] || 1);
  13022. if (attrs) {
  13023. each$1(attrs, function (value, attrName) {
  13024. node.attr(attrName, value);
  13025. });
  13026. }
  13027. return node;
  13028. };
  13029. AstNode.prototype.replace = function (node) {
  13030. var self = this;
  13031. if (node.parent) {
  13032. node.remove();
  13033. }
  13034. self.insert(node, self);
  13035. self.remove();
  13036. return self;
  13037. };
  13038. AstNode.prototype.attr = function (name, value) {
  13039. var self = this;
  13040. var attrs;
  13041. if (typeof name !== 'string') {
  13042. if (name !== undefined && name !== null) {
  13043. each$1(name, function (value, key) {
  13044. self.attr(key, value);
  13045. });
  13046. }
  13047. return self;
  13048. }
  13049. if (attrs = self.attributes) {
  13050. if (value !== undefined) {
  13051. if (value === null) {
  13052. if (name in attrs.map) {
  13053. delete attrs.map[name];
  13054. var i = attrs.length;
  13055. while (i--) {
  13056. if (attrs[i].name === name) {
  13057. attrs.splice(i, 1);
  13058. return self;
  13059. }
  13060. }
  13061. }
  13062. return self;
  13063. }
  13064. if (name in attrs.map) {
  13065. var i = attrs.length;
  13066. while (i--) {
  13067. if (attrs[i].name === name) {
  13068. attrs[i].value = value;
  13069. break;
  13070. }
  13071. }
  13072. } else {
  13073. attrs.push({
  13074. name: name,
  13075. value: value
  13076. });
  13077. }
  13078. attrs.map[name] = value;
  13079. return self;
  13080. }
  13081. return attrs.map[name];
  13082. }
  13083. };
  13084. AstNode.prototype.clone = function () {
  13085. var self = this;
  13086. var clone = new AstNode(self.name, self.type);
  13087. var selfAttrs;
  13088. if (selfAttrs = self.attributes) {
  13089. var cloneAttrs = [];
  13090. cloneAttrs.map = {};
  13091. for (var i = 0, l = selfAttrs.length; i < l; i++) {
  13092. var selfAttr = selfAttrs[i];
  13093. if (selfAttr.name !== 'id') {
  13094. cloneAttrs[cloneAttrs.length] = {
  13095. name: selfAttr.name,
  13096. value: selfAttr.value
  13097. };
  13098. cloneAttrs.map[selfAttr.name] = selfAttr.value;
  13099. }
  13100. }
  13101. clone.attributes = cloneAttrs;
  13102. }
  13103. clone.value = self.value;
  13104. clone.shortEnded = self.shortEnded;
  13105. return clone;
  13106. };
  13107. AstNode.prototype.wrap = function (wrapper) {
  13108. var self = this;
  13109. self.parent.insert(wrapper, self);
  13110. wrapper.append(self);
  13111. return self;
  13112. };
  13113. AstNode.prototype.unwrap = function () {
  13114. var self = this;
  13115. for (var node = self.firstChild; node;) {
  13116. var next = node.next;
  13117. self.insert(node, self, true);
  13118. node = next;
  13119. }
  13120. self.remove();
  13121. };
  13122. AstNode.prototype.remove = function () {
  13123. var self = this, parent = self.parent, next = self.next, prev = self.prev;
  13124. if (parent) {
  13125. if (parent.firstChild === self) {
  13126. parent.firstChild = next;
  13127. if (next) {
  13128. next.prev = null;
  13129. }
  13130. } else {
  13131. prev.next = next;
  13132. }
  13133. if (parent.lastChild === self) {
  13134. parent.lastChild = prev;
  13135. if (prev) {
  13136. prev.next = null;
  13137. }
  13138. } else {
  13139. next.prev = prev;
  13140. }
  13141. self.parent = self.next = self.prev = null;
  13142. }
  13143. return self;
  13144. };
  13145. AstNode.prototype.append = function (node) {
  13146. var self = this;
  13147. if (node.parent) {
  13148. node.remove();
  13149. }
  13150. var last = self.lastChild;
  13151. if (last) {
  13152. last.next = node;
  13153. node.prev = last;
  13154. self.lastChild = node;
  13155. } else {
  13156. self.lastChild = self.firstChild = node;
  13157. }
  13158. node.parent = self;
  13159. return node;
  13160. };
  13161. AstNode.prototype.insert = function (node, refNode, before) {
  13162. if (node.parent) {
  13163. node.remove();
  13164. }
  13165. var parent = refNode.parent || this;
  13166. if (before) {
  13167. if (refNode === parent.firstChild) {
  13168. parent.firstChild = node;
  13169. } else {
  13170. refNode.prev.next = node;
  13171. }
  13172. node.prev = refNode.prev;
  13173. node.next = refNode;
  13174. refNode.prev = node;
  13175. } else {
  13176. if (refNode === parent.lastChild) {
  13177. parent.lastChild = node;
  13178. } else {
  13179. refNode.next.prev = node;
  13180. }
  13181. node.next = refNode.next;
  13182. node.prev = refNode;
  13183. refNode.next = node;
  13184. }
  13185. node.parent = parent;
  13186. return node;
  13187. };
  13188. AstNode.prototype.getAll = function (name) {
  13189. var self = this;
  13190. var collection = [];
  13191. for (var node = self.firstChild; node; node = walk$2(node, self)) {
  13192. if (node.name === name) {
  13193. collection.push(node);
  13194. }
  13195. }
  13196. return collection;
  13197. };
  13198. AstNode.prototype.empty = function () {
  13199. var self = this;
  13200. if (self.firstChild) {
  13201. var nodes = [];
  13202. for (var node = self.firstChild; node; node = walk$2(node, self)) {
  13203. nodes.push(node);
  13204. }
  13205. var i = nodes.length;
  13206. while (i--) {
  13207. var node = nodes[i];
  13208. node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
  13209. }
  13210. }
  13211. self.firstChild = self.lastChild = null;
  13212. return self;
  13213. };
  13214. AstNode.prototype.isEmpty = function (elements, whitespace, predicate) {
  13215. if (whitespace === void 0) {
  13216. whitespace = {};
  13217. }
  13218. var self = this;
  13219. var node = self.firstChild;
  13220. if (isNonEmptyElement(self)) {
  13221. return false;
  13222. }
  13223. if (node) {
  13224. do {
  13225. if (node.type === 1) {
  13226. if (node.attr('data-mce-bogus')) {
  13227. continue;
  13228. }
  13229. if (elements[node.name]) {
  13230. return false;
  13231. }
  13232. if (isNonEmptyElement(node)) {
  13233. return false;
  13234. }
  13235. }
  13236. if (node.type === 8) {
  13237. return false;
  13238. }
  13239. if (node.type === 3 && !isEmptyTextNode$1(node)) {
  13240. return false;
  13241. }
  13242. if (node.type === 3 && node.parent && whitespace[node.parent.name] && isWhitespaceText(node.value)) {
  13243. return false;
  13244. }
  13245. if (predicate && predicate(node)) {
  13246. return false;
  13247. }
  13248. } while (node = walk$2(node, self));
  13249. }
  13250. return true;
  13251. };
  13252. AstNode.prototype.walk = function (prev) {
  13253. return walk$2(this, null, prev);
  13254. };
  13255. return AstNode;
  13256. }();
  13257. var makeMap$3 = Tools.makeMap;
  13258. var Writer = function (settings) {
  13259. var html = [];
  13260. settings = settings || {};
  13261. var indent = settings.indent;
  13262. var indentBefore = makeMap$3(settings.indent_before || '');
  13263. var indentAfter = makeMap$3(settings.indent_after || '');
  13264. var encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
  13265. var htmlOutput = settings.element_format === 'html';
  13266. return {
  13267. start: function (name, attrs, empty) {
  13268. var i, l, attr, value;
  13269. if (indent && indentBefore[name] && html.length > 0) {
  13270. value = html[html.length - 1];
  13271. if (value.length > 0 && value !== '\n') {
  13272. html.push('\n');
  13273. }
  13274. }
  13275. html.push('<', name);
  13276. if (attrs) {
  13277. for (i = 0, l = attrs.length; i < l; i++) {
  13278. attr = attrs[i];
  13279. html.push(' ', attr.name, '="', encode(attr.value, true), '"');
  13280. }
  13281. }
  13282. if (!empty || htmlOutput) {
  13283. html[html.length] = '>';
  13284. } else {
  13285. html[html.length] = ' />';
  13286. }
  13287. if (empty && indent && indentAfter[name] && html.length > 0) {
  13288. value = html[html.length - 1];
  13289. if (value.length > 0 && value !== '\n') {
  13290. html.push('\n');
  13291. }
  13292. }
  13293. },
  13294. end: function (name) {
  13295. var value;
  13296. html.push('</', name, '>');
  13297. if (indent && indentAfter[name] && html.length > 0) {
  13298. value = html[html.length - 1];
  13299. if (value.length > 0 && value !== '\n') {
  13300. html.push('\n');
  13301. }
  13302. }
  13303. },
  13304. text: function (text, raw) {
  13305. if (text.length > 0) {
  13306. html[html.length] = raw ? text : encode(text);
  13307. }
  13308. },
  13309. cdata: function (text) {
  13310. html.push('<![CDATA[', text, ']]>');
  13311. },
  13312. comment: function (text) {
  13313. html.push('<!--', text, '-->');
  13314. },
  13315. pi: function (name, text) {
  13316. if (text) {
  13317. html.push('<?', name, ' ', encode(text), '?>');
  13318. } else {
  13319. html.push('<?', name, '?>');
  13320. }
  13321. if (indent) {
  13322. html.push('\n');
  13323. }
  13324. },
  13325. doctype: function (text) {
  13326. html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
  13327. },
  13328. reset: function () {
  13329. html.length = 0;
  13330. },
  13331. getContent: function () {
  13332. return html.join('').replace(/\n$/, '');
  13333. }
  13334. };
  13335. };
  13336. var HtmlSerializer = function (settings, schema) {
  13337. if (schema === void 0) {
  13338. schema = Schema();
  13339. }
  13340. var writer = Writer(settings);
  13341. settings = settings || {};
  13342. settings.validate = 'validate' in settings ? settings.validate : true;
  13343. var serialize = function (node) {
  13344. var validate = settings.validate;
  13345. var handlers = {
  13346. 3: function (node) {
  13347. writer.text(node.value, node.raw);
  13348. },
  13349. 8: function (node) {
  13350. writer.comment(node.value);
  13351. },
  13352. 7: function (node) {
  13353. writer.pi(node.name, node.value);
  13354. },
  13355. 10: function (node) {
  13356. writer.doctype(node.value);
  13357. },
  13358. 4: function (node) {
  13359. writer.cdata(node.value);
  13360. },
  13361. 11: function (node) {
  13362. if (node = node.firstChild) {
  13363. do {
  13364. walk(node);
  13365. } while (node = node.next);
  13366. }
  13367. }
  13368. };
  13369. writer.reset();
  13370. var walk = function (node) {
  13371. var handler = handlers[node.type];
  13372. var name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule;
  13373. if (!handler) {
  13374. name = node.name;
  13375. isEmpty = node.shortEnded;
  13376. attrs = node.attributes;
  13377. if (validate && attrs && attrs.length > 1) {
  13378. sortedAttrs = [];
  13379. sortedAttrs.map = {};
  13380. elementRule = schema.getElementRule(node.name);
  13381. if (elementRule) {
  13382. for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
  13383. attrName = elementRule.attributesOrder[i];
  13384. if (attrName in attrs.map) {
  13385. attrValue = attrs.map[attrName];
  13386. sortedAttrs.map[attrName] = attrValue;
  13387. sortedAttrs.push({
  13388. name: attrName,
  13389. value: attrValue
  13390. });
  13391. }
  13392. }
  13393. for (i = 0, l = attrs.length; i < l; i++) {
  13394. attrName = attrs[i].name;
  13395. if (!(attrName in sortedAttrs.map)) {
  13396. attrValue = attrs.map[attrName];
  13397. sortedAttrs.map[attrName] = attrValue;
  13398. sortedAttrs.push({
  13399. name: attrName,
  13400. value: attrValue
  13401. });
  13402. }
  13403. }
  13404. attrs = sortedAttrs;
  13405. }
  13406. }
  13407. writer.start(node.name, attrs, isEmpty);
  13408. if (!isEmpty) {
  13409. if (node = node.firstChild) {
  13410. do {
  13411. walk(node);
  13412. } while (node = node.next);
  13413. }
  13414. writer.end(name);
  13415. }
  13416. } else {
  13417. handler(node);
  13418. }
  13419. };
  13420. if (node.type === 1 && !settings.inner) {
  13421. walk(node);
  13422. } else {
  13423. handlers[11](node);
  13424. }
  13425. return writer.getContent();
  13426. };
  13427. return { serialize: serialize };
  13428. };
  13429. var extractBase64DataUris = function (html) {
  13430. var dataImageUri = /data:[^;]+;base64,([a-z0-9\+\/=]+)/gi;
  13431. var chunks = [];
  13432. var uris = {};
  13433. var prefix = generate$1('img');
  13434. var matches;
  13435. var index = 0;
  13436. var count = 0;
  13437. while (matches = dataImageUri.exec(html)) {
  13438. var uri = matches[0];
  13439. var imageId = prefix + '_' + count++;
  13440. uris[imageId] = uri;
  13441. if (index < matches.index) {
  13442. chunks.push(html.substr(index, matches.index - index));
  13443. }
  13444. chunks.push(imageId);
  13445. index = matches.index + uri.length;
  13446. }
  13447. if (index === 0) {
  13448. return {
  13449. prefix: prefix,
  13450. uris: uris,
  13451. html: html
  13452. };
  13453. } else {
  13454. if (index < html.length) {
  13455. chunks.push(html.substr(index));
  13456. }
  13457. return {
  13458. prefix: prefix,
  13459. uris: uris,
  13460. html: chunks.join('')
  13461. };
  13462. }
  13463. };
  13464. var restoreDataUris = function (html, result) {
  13465. return html.replace(new RegExp(result.prefix + '_[0-9]+', 'g'), function (imageId) {
  13466. return get$1(result.uris, imageId).getOr(imageId);
  13467. });
  13468. };
  13469. var parseDataUri = function (uri) {
  13470. var matches = /data:([^;]+);base64,([a-z0-9\+\/=]+)/i.exec(uri);
  13471. if (matches) {
  13472. return Optional.some({
  13473. type: matches[1],
  13474. data: decodeURIComponent(matches[2])
  13475. });
  13476. } else {
  13477. return Optional.none();
  13478. }
  13479. };
  13480. var safeSvgDataUrlElements = [
  13481. 'img',
  13482. 'video'
  13483. ];
  13484. var isValidPrefixAttrName = function (name) {
  13485. return name.indexOf('data-') === 0 || name.indexOf('aria-') === 0;
  13486. };
  13487. var blockSvgDataUris = function (allowSvgDataUrls, tagName) {
  13488. var allowed = isNullable(allowSvgDataUrls) ? contains(safeSvgDataUrlElements, tagName) : allowSvgDataUrls;
  13489. return !allowed;
  13490. };
  13491. var isInvalidUri = function (settings, uri, tagName) {
  13492. if (settings.allow_html_data_urls) {
  13493. return false;
  13494. } else if (/^data:image\//i.test(uri)) {
  13495. return blockSvgDataUris(settings.allow_svg_data_urls, tagName) && /^data:image\/svg\+xml/i.test(uri);
  13496. } else {
  13497. return /^data:/i.test(uri);
  13498. }
  13499. };
  13500. var findEndTagIndex = function (schema, html, startIndex) {
  13501. var count = 1, index, matches;
  13502. var shortEndedElements = schema.getShortEndedElements();
  13503. var tokenRegExp = /<([!?\/])?([A-Za-z0-9\-_\:\.]+)((?:\s+[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*|\/|\s+)>/g;
  13504. tokenRegExp.lastIndex = index = startIndex;
  13505. while (matches = tokenRegExp.exec(html)) {
  13506. index = tokenRegExp.lastIndex;
  13507. if (matches[1] === '/') {
  13508. count--;
  13509. } else if (!matches[1]) {
  13510. if (matches[2] in shortEndedElements) {
  13511. continue;
  13512. }
  13513. count++;
  13514. }
  13515. if (count === 0) {
  13516. break;
  13517. }
  13518. }
  13519. return index;
  13520. };
  13521. var isConditionalComment = function (html, startIndex) {
  13522. return /^\s*\[if [\w\W]+\]>.*<!\[endif\](--!?)?>/.test(html.substr(startIndex));
  13523. };
  13524. var findCommentEndIndex = function (html, isBogus, startIndex) {
  13525. if (startIndex === void 0) {
  13526. startIndex = 0;
  13527. }
  13528. var lcHtml = html.toLowerCase();
  13529. if (lcHtml.indexOf('[if ', startIndex) !== -1 && isConditionalComment(lcHtml, startIndex)) {
  13530. var endIfIndex = lcHtml.indexOf('[endif]', startIndex);
  13531. return lcHtml.indexOf('>', endIfIndex);
  13532. } else {
  13533. if (isBogus) {
  13534. var endIndex = lcHtml.indexOf('>', startIndex);
  13535. return endIndex !== -1 ? endIndex : lcHtml.length;
  13536. } else {
  13537. var endCommentRegexp = /--!?>/;
  13538. endCommentRegexp.lastIndex = startIndex;
  13539. var match = endCommentRegexp.exec(html);
  13540. return match ? match.index + match[0].length : lcHtml.length;
  13541. }
  13542. }
  13543. };
  13544. var checkBogusAttribute = function (regExp, attrString) {
  13545. var matches = regExp.exec(attrString);
  13546. if (matches) {
  13547. var name_1 = matches[1];
  13548. var value = matches[2];
  13549. return typeof name_1 === 'string' && name_1.toLowerCase() === 'data-mce-bogus' ? value : null;
  13550. } else {
  13551. return null;
  13552. }
  13553. };
  13554. function SaxParser(settings, schema) {
  13555. if (schema === void 0) {
  13556. schema = Schema();
  13557. }
  13558. var noop = function () {
  13559. };
  13560. settings = settings || {};
  13561. if (settings.fix_self_closing !== false) {
  13562. settings.fix_self_closing = true;
  13563. }
  13564. var comment = settings.comment ? settings.comment : noop;
  13565. var cdata = settings.cdata ? settings.cdata : noop;
  13566. var text = settings.text ? settings.text : noop;
  13567. var start = settings.start ? settings.start : noop;
  13568. var end = settings.end ? settings.end : noop;
  13569. var pi = settings.pi ? settings.pi : noop;
  13570. var doctype = settings.doctype ? settings.doctype : noop;
  13571. var parseInternal = function (base64Extract, format) {
  13572. if (format === void 0) {
  13573. format = 'html';
  13574. }
  13575. var html = base64Extract.html;
  13576. var matches, index = 0, value, endRegExp;
  13577. var stack = [];
  13578. var attrList, i, textData, name;
  13579. var isInternalElement, isShortEnded;
  13580. var elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns;
  13581. var attributesRequired, attributesDefault, attributesForced;
  13582. var anyAttributesRequired, attrValue, idCount = 0;
  13583. var decode = Entities.decode;
  13584. var filteredUrlAttrs = Tools.makeMap('src,href,data,background,formaction,poster,xlink:href');
  13585. var scriptUriRegExp = /((java|vb)script|mhtml):/i;
  13586. var parsingMode = format === 'html' ? 0 : 1;
  13587. var processEndTag = function (name) {
  13588. var pos, i;
  13589. pos = stack.length;
  13590. while (pos--) {
  13591. if (stack[pos].name === name) {
  13592. break;
  13593. }
  13594. }
  13595. if (pos >= 0) {
  13596. for (i = stack.length - 1; i >= pos; i--) {
  13597. name = stack[i];
  13598. if (name.valid) {
  13599. end(name.name);
  13600. }
  13601. }
  13602. stack.length = pos;
  13603. }
  13604. };
  13605. var processText = function (value, raw) {
  13606. return text(restoreDataUris(value, base64Extract), raw);
  13607. };
  13608. var processComment = function (value) {
  13609. if (value === '') {
  13610. return;
  13611. }
  13612. if (value.charAt(0) === '>') {
  13613. value = ' ' + value;
  13614. }
  13615. if (!settings.allow_conditional_comments && value.substr(0, 3).toLowerCase() === '[if') {
  13616. value = ' ' + value;
  13617. }
  13618. comment(restoreDataUris(value, base64Extract));
  13619. };
  13620. var processAttr = function (value) {
  13621. return get$1(base64Extract.uris, value).getOr(value);
  13622. };
  13623. var processMalformedComment = function (value, startIndex) {
  13624. var startTag = value || '';
  13625. var isBogus = !startsWith(startTag, '--');
  13626. var endIndex = findCommentEndIndex(html, isBogus, startIndex);
  13627. value = html.substr(startIndex, endIndex - startIndex);
  13628. processComment(isBogus ? startTag + value : value);
  13629. return endIndex + 1;
  13630. };
  13631. var parseAttribute = function (tagName, name, value, val2, val3) {
  13632. var attrRule, i;
  13633. var trimRegExp = /[\s\u0000-\u001F]+/g;
  13634. name = name.toLowerCase();
  13635. value = processAttr(name in fillAttrsMap ? name : decode(value || val2 || val3 || ''));
  13636. if (validate && !isInternalElement && isValidPrefixAttrName(name) === false) {
  13637. attrRule = validAttributesMap[name];
  13638. if (!attrRule && validAttributePatterns) {
  13639. i = validAttributePatterns.length;
  13640. while (i--) {
  13641. attrRule = validAttributePatterns[i];
  13642. if (attrRule.pattern.test(name)) {
  13643. break;
  13644. }
  13645. }
  13646. if (i === -1) {
  13647. attrRule = null;
  13648. }
  13649. }
  13650. if (!attrRule) {
  13651. return;
  13652. }
  13653. if (attrRule.validValues && !(value in attrRule.validValues)) {
  13654. return;
  13655. }
  13656. }
  13657. if (filteredUrlAttrs[name] && !settings.allow_script_urls) {
  13658. var uri = value.replace(trimRegExp, '');
  13659. try {
  13660. uri = decodeURIComponent(uri);
  13661. } catch (ex) {
  13662. uri = unescape(uri);
  13663. }
  13664. if (scriptUriRegExp.test(uri)) {
  13665. return;
  13666. }
  13667. if (isInvalidUri(settings, uri, tagName)) {
  13668. return;
  13669. }
  13670. }
  13671. if (isInternalElement && (name in filteredUrlAttrs || name.indexOf('on') === 0)) {
  13672. return;
  13673. }
  13674. attrList.map[name] = value;
  13675. attrList.push({
  13676. name: name,
  13677. value: value
  13678. });
  13679. };
  13680. 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');
  13681. var attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g;
  13682. var shortEndedElements = schema.getShortEndedElements();
  13683. var selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
  13684. var fillAttrsMap = schema.getBoolAttrs();
  13685. var validate = settings.validate;
  13686. var removeInternalElements = settings.remove_internals;
  13687. var fixSelfClosing = settings.fix_self_closing;
  13688. var specialElements = schema.getSpecialElements();
  13689. var processHtml = html + '>';
  13690. while (matches = tokenRegExp.exec(processHtml)) {
  13691. var matchText = matches[0];
  13692. if (index < matches.index) {
  13693. processText(decode(html.substr(index, matches.index - index)));
  13694. }
  13695. if (value = matches[7]) {
  13696. value = value.toLowerCase();
  13697. if (value.charAt(0) === ':') {
  13698. value = value.substr(1);
  13699. }
  13700. processEndTag(value);
  13701. } else if (value = matches[8]) {
  13702. if (matches.index + matchText.length > html.length) {
  13703. processText(decode(html.substr(matches.index)));
  13704. index = matches.index + matchText.length;
  13705. continue;
  13706. }
  13707. value = value.toLowerCase();
  13708. if (value.charAt(0) === ':') {
  13709. value = value.substr(1);
  13710. }
  13711. isShortEnded = value in shortEndedElements;
  13712. if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value) {
  13713. processEndTag(value);
  13714. }
  13715. var bogusValue = checkBogusAttribute(attrRegExp, matches[9]);
  13716. if (bogusValue !== null) {
  13717. if (bogusValue === 'all') {
  13718. index = findEndTagIndex(schema, html, tokenRegExp.lastIndex);
  13719. tokenRegExp.lastIndex = index;
  13720. continue;
  13721. }
  13722. isValidElement = false;
  13723. }
  13724. if (!validate || (elementRule = schema.getElementRule(value))) {
  13725. isValidElement = true;
  13726. if (validate) {
  13727. validAttributesMap = elementRule.attributes;
  13728. validAttributePatterns = elementRule.attributePatterns;
  13729. }
  13730. if (attribsValue = matches[9]) {
  13731. isInternalElement = attribsValue.indexOf('data-mce-type') !== -1;
  13732. if (isInternalElement && removeInternalElements) {
  13733. isValidElement = false;
  13734. }
  13735. attrList = [];
  13736. attrList.map = {};
  13737. attribsValue.replace(attrRegExp, function (match, name, val, val2, val3) {
  13738. parseAttribute(value, name, val, val2, val3);
  13739. return '';
  13740. });
  13741. } else {
  13742. attrList = [];
  13743. attrList.map = {};
  13744. }
  13745. if (validate && !isInternalElement) {
  13746. attributesRequired = elementRule.attributesRequired;
  13747. attributesDefault = elementRule.attributesDefault;
  13748. attributesForced = elementRule.attributesForced;
  13749. anyAttributesRequired = elementRule.removeEmptyAttrs;
  13750. if (anyAttributesRequired && !attrList.length) {
  13751. isValidElement = false;
  13752. }
  13753. if (attributesForced) {
  13754. i = attributesForced.length;
  13755. while (i--) {
  13756. attr = attributesForced[i];
  13757. name = attr.name;
  13758. attrValue = attr.value;
  13759. if (attrValue === '{$uid}') {
  13760. attrValue = 'mce_' + idCount++;
  13761. }
  13762. attrList.map[name] = attrValue;
  13763. attrList.push({
  13764. name: name,
  13765. value: attrValue
  13766. });
  13767. }
  13768. }
  13769. if (attributesDefault) {
  13770. i = attributesDefault.length;
  13771. while (i--) {
  13772. attr = attributesDefault[i];
  13773. name = attr.name;
  13774. if (!(name in attrList.map)) {
  13775. attrValue = attr.value;
  13776. if (attrValue === '{$uid}') {
  13777. attrValue = 'mce_' + idCount++;
  13778. }
  13779. attrList.map[name] = attrValue;
  13780. attrList.push({
  13781. name: name,
  13782. value: attrValue
  13783. });
  13784. }
  13785. }
  13786. }
  13787. if (attributesRequired) {
  13788. i = attributesRequired.length;
  13789. while (i--) {
  13790. if (attributesRequired[i] in attrList.map) {
  13791. break;
  13792. }
  13793. }
  13794. if (i === -1) {
  13795. isValidElement = false;
  13796. }
  13797. }
  13798. if (attr = attrList.map['data-mce-bogus']) {
  13799. if (attr === 'all') {
  13800. index = findEndTagIndex(schema, html, tokenRegExp.lastIndex);
  13801. tokenRegExp.lastIndex = index;
  13802. continue;
  13803. }
  13804. isValidElement = false;
  13805. }
  13806. }
  13807. if (isValidElement) {
  13808. start(value, attrList, isShortEnded);
  13809. }
  13810. } else {
  13811. isValidElement = false;
  13812. }
  13813. if (endRegExp = specialElements[value]) {
  13814. endRegExp.lastIndex = index = matches.index + matchText.length;
  13815. if (matches = endRegExp.exec(html)) {
  13816. if (isValidElement) {
  13817. textData = html.substr(index, matches.index - index);
  13818. }
  13819. index = matches.index + matches[0].length;
  13820. } else {
  13821. textData = html.substr(index);
  13822. index = html.length;
  13823. }
  13824. if (isValidElement) {
  13825. if (textData.length > 0) {
  13826. processText(textData, true);
  13827. }
  13828. end(value);
  13829. }
  13830. tokenRegExp.lastIndex = index;
  13831. continue;
  13832. }
  13833. if (!isShortEnded) {
  13834. if (!attribsValue || attribsValue.indexOf('/') !== attribsValue.length - 1) {
  13835. stack.push({
  13836. name: value,
  13837. valid: isValidElement
  13838. });
  13839. } else if (isValidElement) {
  13840. end(value);
  13841. }
  13842. }
  13843. } else if (value = matches[1]) {
  13844. processComment(value);
  13845. } else if (value = matches[2]) {
  13846. var isValidCdataSection = parsingMode === 1 || settings.preserve_cdata || stack.length > 0 && schema.isValidChild(stack[stack.length - 1].name, '#cdata');
  13847. if (isValidCdataSection) {
  13848. cdata(value);
  13849. } else {
  13850. index = processMalformedComment('', matches.index + 2);
  13851. tokenRegExp.lastIndex = index;
  13852. continue;
  13853. }
  13854. } else if (value = matches[3]) {
  13855. doctype(value);
  13856. } else if ((value = matches[4]) || matchText === '<!') {
  13857. index = processMalformedComment(value, matches.index + matchText.length);
  13858. tokenRegExp.lastIndex = index;
  13859. continue;
  13860. } else if (value = matches[5]) {
  13861. if (parsingMode === 1) {
  13862. pi(value, matches[6]);
  13863. } else {
  13864. index = processMalformedComment('?', matches.index + 2);
  13865. tokenRegExp.lastIndex = index;
  13866. continue;
  13867. }
  13868. }
  13869. index = matches.index + matchText.length;
  13870. }
  13871. if (index < html.length) {
  13872. processText(decode(html.substr(index)));
  13873. }
  13874. for (i = stack.length - 1; i >= 0; i--) {
  13875. value = stack[i];
  13876. if (value.valid) {
  13877. end(value.name);
  13878. }
  13879. }
  13880. };
  13881. var parse = function (html, format) {
  13882. if (format === void 0) {
  13883. format = 'html';
  13884. }
  13885. parseInternal(extractBase64DataUris(html), format);
  13886. };
  13887. return { parse: parse };
  13888. }
  13889. (function (SaxParser) {
  13890. SaxParser.findEndTag = findEndTagIndex;
  13891. }(SaxParser || (SaxParser = {})));
  13892. var SaxParser$1 = SaxParser;
  13893. var trimHtml = function (tempAttrs, html) {
  13894. var trimContentRegExp = new RegExp(['\\s?(' + tempAttrs.join('|') + ')="[^"]+"'].join('|'), 'gi');
  13895. return html.replace(trimContentRegExp, '');
  13896. };
  13897. var trimInternal = function (serializer, html) {
  13898. var content = html;
  13899. var bogusAllRegExp = /<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g;
  13900. var endTagIndex, index, matchLength, matches;
  13901. var schema = serializer.schema;
  13902. content = trimHtml(serializer.getTempAttrs(), content);
  13903. var shortEndedElements = schema.getShortEndedElements();
  13904. while (matches = bogusAllRegExp.exec(content)) {
  13905. index = bogusAllRegExp.lastIndex;
  13906. matchLength = matches[0].length;
  13907. if (shortEndedElements[matches[1]]) {
  13908. endTagIndex = index;
  13909. } else {
  13910. endTagIndex = SaxParser$1.findEndTag(schema, content, index);
  13911. }
  13912. content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
  13913. bogusAllRegExp.lastIndex = index - matchLength;
  13914. }
  13915. return trim$2(content);
  13916. };
  13917. var trimExternal = trimInternal;
  13918. var trimEmptyContents = function (editor, html) {
  13919. var blockName = getForcedRootBlock(editor);
  13920. var emptyRegExp = new RegExp('^(<' + blockName + '[^>]*>(&nbsp;|&#160;|\\s|\xA0|<br \\/>|)<\\/' + blockName + '>[\r\n]*|<br \\/>[\r\n]*)$');
  13921. return html.replace(emptyRegExp, '');
  13922. };
  13923. var getContentFromBody = function (editor, args, format, body) {
  13924. var content;
  13925. args.format = format;
  13926. args.get = true;
  13927. args.getInner = true;
  13928. if (!args.no_events) {
  13929. editor.fire('BeforeGetContent', args);
  13930. }
  13931. if (args.format === 'raw') {
  13932. content = Tools.trim(trimExternal(editor.serializer, body.innerHTML));
  13933. } else if (args.format === 'text') {
  13934. content = editor.dom.isEmpty(body) ? '' : trim$2(body.innerText || body.textContent);
  13935. } else if (args.format === 'tree') {
  13936. content = editor.serializer.serialize(body, args);
  13937. } else {
  13938. content = trimEmptyContents(editor, editor.serializer.serialize(body, args));
  13939. }
  13940. if (!contains([
  13941. 'text',
  13942. 'tree'
  13943. ], args.format) && !isWsPreserveElement(SugarElement.fromDom(body))) {
  13944. args.content = Tools.trim(content);
  13945. } else {
  13946. args.content = content;
  13947. }
  13948. if (!args.no_events) {
  13949. editor.fire('GetContent', args);
  13950. }
  13951. return args.content;
  13952. };
  13953. var getContentInternal = function (editor, args, format) {
  13954. return Optional.from(editor.getBody()).fold(constant(args.format === 'tree' ? new AstNode('body', 11) : ''), function (body) {
  13955. return getContentFromBody(editor, args, format, body);
  13956. });
  13957. };
  13958. var each$7 = Tools.each;
  13959. var ElementUtils = function (dom) {
  13960. this.compare = function (node1, node2) {
  13961. if (node1.nodeName !== node2.nodeName) {
  13962. return false;
  13963. }
  13964. var getAttribs = function (node) {
  13965. var attribs = {};
  13966. each$7(dom.getAttribs(node), function (attr) {
  13967. var name = attr.nodeName.toLowerCase();
  13968. if (name.indexOf('_') !== 0 && name !== 'style' && name.indexOf('data-') !== 0) {
  13969. attribs[name] = dom.getAttrib(node, name);
  13970. }
  13971. });
  13972. return attribs;
  13973. };
  13974. var compareObjects = function (obj1, obj2) {
  13975. var value, name;
  13976. for (name in obj1) {
  13977. if (obj1.hasOwnProperty(name)) {
  13978. value = obj2[name];
  13979. if (typeof value === 'undefined') {
  13980. return false;
  13981. }
  13982. if (obj1[name] !== value) {
  13983. return false;
  13984. }
  13985. delete obj2[name];
  13986. }
  13987. }
  13988. for (name in obj2) {
  13989. if (obj2.hasOwnProperty(name)) {
  13990. return false;
  13991. }
  13992. }
  13993. return true;
  13994. };
  13995. if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
  13996. return false;
  13997. }
  13998. if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
  13999. return false;
  14000. }
  14001. return !isBookmarkNode$1(node1) && !isBookmarkNode$1(node2);
  14002. };
  14003. };
  14004. var isChar = function (forward, predicate, pos) {
  14005. return Optional.from(pos.container()).filter(isText$1).exists(function (text) {
  14006. var delta = forward ? 0 : -1;
  14007. return predicate(text.data.charAt(pos.offset() + delta));
  14008. });
  14009. };
  14010. var isBeforeSpace = curry(isChar, true, isWhiteSpace$1);
  14011. var isAfterSpace = curry(isChar, false, isWhiteSpace$1);
  14012. var isEmptyText = function (pos) {
  14013. var container = pos.container();
  14014. return isText$1(container) && (container.data.length === 0 || isZwsp$1(container.data) && BookmarkManager$1.isBookmarkNode(container.parentNode));
  14015. };
  14016. var matchesElementPosition = function (before, predicate) {
  14017. return function (pos) {
  14018. return Optional.from(getChildNodeAtRelativeOffset(before ? 0 : -1, pos)).filter(predicate).isSome();
  14019. };
  14020. };
  14021. var isImageBlock = function (node) {
  14022. return isImg(node) && get$5(SugarElement.fromDom(node), 'display') === 'block';
  14023. };
  14024. var isCefNode = function (node) {
  14025. return isContentEditableFalse(node) && !isBogusAll(node);
  14026. };
  14027. var isBeforeImageBlock = matchesElementPosition(true, isImageBlock);
  14028. var isAfterImageBlock = matchesElementPosition(false, isImageBlock);
  14029. var isBeforeMedia = matchesElementPosition(true, isMedia);
  14030. var isAfterMedia = matchesElementPosition(false, isMedia);
  14031. var isBeforeTable = matchesElementPosition(true, isTable);
  14032. var isAfterTable = matchesElementPosition(false, isTable);
  14033. var isBeforeContentEditableFalse = matchesElementPosition(true, isCefNode);
  14034. var isAfterContentEditableFalse = matchesElementPosition(false, isCefNode);
  14035. var getLastChildren$1 = function (elm) {
  14036. var children = [];
  14037. var rawNode = elm.dom;
  14038. while (rawNode) {
  14039. children.push(SugarElement.fromDom(rawNode));
  14040. rawNode = rawNode.lastChild;
  14041. }
  14042. return children;
  14043. };
  14044. var removeTrailingBr = function (elm) {
  14045. var allBrs = descendants$1(elm, 'br');
  14046. var brs = filter(getLastChildren$1(elm).slice(-1), isBr$1);
  14047. if (allBrs.length === brs.length) {
  14048. each(brs, remove);
  14049. }
  14050. };
  14051. var fillWithPaddingBr = function (elm) {
  14052. empty(elm);
  14053. append(elm, SugarElement.fromHtml('<br data-mce-bogus="1">'));
  14054. };
  14055. var trimBlockTrailingBr = function (elm) {
  14056. lastChild(elm).each(function (lastChild) {
  14057. prevSibling(lastChild).each(function (lastChildPrevSibling) {
  14058. if (isBlock(elm) && isBr$1(lastChild) && isBlock(lastChildPrevSibling)) {
  14059. remove(lastChild);
  14060. }
  14061. });
  14062. });
  14063. };
  14064. var dropLast = function (xs) {
  14065. return xs.slice(0, -1);
  14066. };
  14067. var parentsUntil$1 = function (start, root, predicate) {
  14068. if (contains$2(root, start)) {
  14069. return dropLast(parents(start, function (elm) {
  14070. return predicate(elm) || eq$2(elm, root);
  14071. }));
  14072. } else {
  14073. return [];
  14074. }
  14075. };
  14076. var parents$1 = function (start, root) {
  14077. return parentsUntil$1(start, root, never);
  14078. };
  14079. var parentsAndSelf = function (start, root) {
  14080. return [start].concat(parents$1(start, root));
  14081. };
  14082. var navigateIgnoreEmptyTextNodes = function (forward, root, from) {
  14083. return navigateIgnore(forward, root, from, isEmptyText);
  14084. };
  14085. var getClosestBlock = function (root, pos) {
  14086. return find(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock);
  14087. };
  14088. var isAtBeforeAfterBlockBoundary = function (forward, root, pos) {
  14089. return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  14090. return getClosestBlock(root, pos).fold(function () {
  14091. return isInSameBlock(newPos, pos, root.dom) === false;
  14092. }, function (fromBlock) {
  14093. return isInSameBlock(newPos, pos, root.dom) === false && contains$2(fromBlock, SugarElement.fromDom(newPos.container()));
  14094. });
  14095. });
  14096. };
  14097. var isAtBlockBoundary$1 = function (forward, root, pos) {
  14098. return getClosestBlock(root, pos).fold(function () {
  14099. return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  14100. return isInSameBlock(newPos, pos, root.dom) === false;
  14101. });
  14102. }, function (parent) {
  14103. return navigateIgnoreEmptyTextNodes(forward, parent.dom, pos).isNone();
  14104. });
  14105. };
  14106. var isAtStartOfBlock = curry(isAtBlockBoundary$1, false);
  14107. var isAtEndOfBlock = curry(isAtBlockBoundary$1, true);
  14108. var isBeforeBlock = curry(isAtBeforeAfterBlockBoundary, false);
  14109. var isAfterBlock = curry(isAtBeforeAfterBlockBoundary, true);
  14110. var isBr$5 = function (pos) {
  14111. return getElementFromPosition(pos).exists(isBr$1);
  14112. };
  14113. var findBr = function (forward, root, pos) {
  14114. var parentBlocks = filter(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock);
  14115. var scope = head(parentBlocks).getOr(root);
  14116. return fromPosition(forward, scope.dom, pos).filter(isBr$5);
  14117. };
  14118. var isBeforeBr = function (root, pos) {
  14119. return getElementFromPosition(pos).exists(isBr$1) || findBr(true, root, pos).isSome();
  14120. };
  14121. var isAfterBr = function (root, pos) {
  14122. return getElementFromPrevPosition(pos).exists(isBr$1) || findBr(false, root, pos).isSome();
  14123. };
  14124. var findPreviousBr = curry(findBr, false);
  14125. var findNextBr = curry(findBr, true);
  14126. var isInMiddleOfText = function (pos) {
  14127. return CaretPosition.isTextPosition(pos) && !pos.isAtStart() && !pos.isAtEnd();
  14128. };
  14129. var getClosestBlock$1 = function (root, pos) {
  14130. var parentBlocks = filter(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock);
  14131. return head(parentBlocks).getOr(root);
  14132. };
  14133. var hasSpaceBefore = function (root, pos) {
  14134. if (isInMiddleOfText(pos)) {
  14135. return isAfterSpace(pos);
  14136. } else {
  14137. return isAfterSpace(pos) || prevPosition(getClosestBlock$1(root, pos).dom, pos).exists(isAfterSpace);
  14138. }
  14139. };
  14140. var hasSpaceAfter = function (root, pos) {
  14141. if (isInMiddleOfText(pos)) {
  14142. return isBeforeSpace(pos);
  14143. } else {
  14144. return isBeforeSpace(pos) || nextPosition(getClosestBlock$1(root, pos).dom, pos).exists(isBeforeSpace);
  14145. }
  14146. };
  14147. var isPreValue = function (value) {
  14148. return contains([
  14149. 'pre',
  14150. 'pre-wrap'
  14151. ], value);
  14152. };
  14153. var isInPre = function (pos) {
  14154. return getElementFromPosition(pos).bind(function (elm) {
  14155. return closest(elm, isElement);
  14156. }).exists(function (elm) {
  14157. return isPreValue(get$5(elm, 'white-space'));
  14158. });
  14159. };
  14160. var isAtBeginningOfBody = function (root, pos) {
  14161. return prevPosition(root.dom, pos).isNone();
  14162. };
  14163. var isAtEndOfBody = function (root, pos) {
  14164. return nextPosition(root.dom, pos).isNone();
  14165. };
  14166. var isAtLineBoundary = function (root, pos) {
  14167. return isAtBeginningOfBody(root, pos) || isAtEndOfBody(root, pos) || isAtStartOfBlock(root, pos) || isAtEndOfBlock(root, pos) || isAfterBr(root, pos) || isBeforeBr(root, pos);
  14168. };
  14169. var needsToHaveNbsp = function (root, pos) {
  14170. if (isInPre(pos)) {
  14171. return false;
  14172. } else {
  14173. return isAtLineBoundary(root, pos) || hasSpaceBefore(root, pos) || hasSpaceAfter(root, pos);
  14174. }
  14175. };
  14176. var needsToBeNbspLeft = function (root, pos) {
  14177. if (isInPre(pos)) {
  14178. return false;
  14179. } else {
  14180. return isAtStartOfBlock(root, pos) || isBeforeBlock(root, pos) || isAfterBr(root, pos) || hasSpaceBefore(root, pos);
  14181. }
  14182. };
  14183. var leanRight = function (pos) {
  14184. var container = pos.container();
  14185. var offset = pos.offset();
  14186. if (isText$1(container) && offset < container.data.length) {
  14187. return CaretPosition(container, offset + 1);
  14188. } else {
  14189. return pos;
  14190. }
  14191. };
  14192. var needsToBeNbspRight = function (root, pos) {
  14193. if (isInPre(pos)) {
  14194. return false;
  14195. } else {
  14196. return isAtEndOfBlock(root, pos) || isAfterBlock(root, pos) || isBeforeBr(root, pos) || hasSpaceAfter(root, pos);
  14197. }
  14198. };
  14199. var needsToBeNbsp = function (root, pos) {
  14200. return needsToBeNbspLeft(root, pos) || needsToBeNbspRight(root, leanRight(pos));
  14201. };
  14202. var isNbspAt = function (text, offset) {
  14203. return isNbsp(text.charAt(offset));
  14204. };
  14205. var hasNbsp = function (pos) {
  14206. var container = pos.container();
  14207. return isText$1(container) && contains$1(container.data, nbsp);
  14208. };
  14209. var normalizeNbspMiddle = function (text) {
  14210. var chars = text.split('');
  14211. return map(chars, function (chr, i) {
  14212. if (isNbsp(chr) && i > 0 && i < chars.length - 1 && isContent$1(chars[i - 1]) && isContent$1(chars[i + 1])) {
  14213. return ' ';
  14214. } else {
  14215. return chr;
  14216. }
  14217. }).join('');
  14218. };
  14219. var normalizeNbspAtStart = function (root, node) {
  14220. var text = node.data;
  14221. var firstPos = CaretPosition(node, 0);
  14222. if (isNbspAt(text, 0) && !needsToBeNbsp(root, firstPos)) {
  14223. node.data = ' ' + text.slice(1);
  14224. return true;
  14225. } else {
  14226. return false;
  14227. }
  14228. };
  14229. var normalizeNbspInMiddleOfTextNode = function (node) {
  14230. var text = node.data;
  14231. var newText = normalizeNbspMiddle(text);
  14232. if (newText !== text) {
  14233. node.data = newText;
  14234. return true;
  14235. } else {
  14236. return false;
  14237. }
  14238. };
  14239. var normalizeNbspAtEnd = function (root, node) {
  14240. var text = node.data;
  14241. var lastPos = CaretPosition(node, text.length - 1);
  14242. if (isNbspAt(text, text.length - 1) && !needsToBeNbsp(root, lastPos)) {
  14243. node.data = text.slice(0, -1) + ' ';
  14244. return true;
  14245. } else {
  14246. return false;
  14247. }
  14248. };
  14249. var normalizeNbsps = function (root, pos) {
  14250. return Optional.some(pos).filter(hasNbsp).bind(function (pos) {
  14251. var container = pos.container();
  14252. var normalized = normalizeNbspAtStart(root, container) || normalizeNbspInMiddleOfTextNode(container) || normalizeNbspAtEnd(root, container);
  14253. return normalized ? Optional.some(pos) : Optional.none();
  14254. });
  14255. };
  14256. var normalizeNbspsInEditor = function (editor) {
  14257. var root = SugarElement.fromDom(editor.getBody());
  14258. if (editor.selection.isCollapsed()) {
  14259. normalizeNbsps(root, CaretPosition.fromRangeStart(editor.selection.getRng())).each(function (pos) {
  14260. editor.selection.setRng(pos.toRange());
  14261. });
  14262. }
  14263. };
  14264. var normalizeContent = function (content, isStartOfContent, isEndOfContent) {
  14265. var result = foldl(content, function (acc, c) {
  14266. if (isWhiteSpace$1(c) || isNbsp(c)) {
  14267. if (acc.previousCharIsSpace || acc.str === '' && isStartOfContent || acc.str.length === content.length - 1 && isEndOfContent) {
  14268. return {
  14269. previousCharIsSpace: false,
  14270. str: acc.str + nbsp
  14271. };
  14272. } else {
  14273. return {
  14274. previousCharIsSpace: true,
  14275. str: acc.str + ' '
  14276. };
  14277. }
  14278. } else {
  14279. return {
  14280. previousCharIsSpace: false,
  14281. str: acc.str + c
  14282. };
  14283. }
  14284. }, {
  14285. previousCharIsSpace: false,
  14286. str: ''
  14287. });
  14288. return result.str;
  14289. };
  14290. var normalize$1 = function (node, offset, count) {
  14291. if (count === 0) {
  14292. return;
  14293. }
  14294. var elm = SugarElement.fromDom(node);
  14295. var root = ancestor(elm, isBlock).getOr(elm);
  14296. var whitespace = node.data.slice(offset, offset + count);
  14297. var isEndOfContent = offset + count >= node.data.length && needsToBeNbspRight(root, CaretPosition$1(node, node.data.length));
  14298. var isStartOfContent = offset === 0 && needsToBeNbspLeft(root, CaretPosition$1(node, 0));
  14299. node.replaceData(offset, count, normalizeContent(whitespace, isStartOfContent, isEndOfContent));
  14300. };
  14301. var normalizeWhitespaceAfter = function (node, offset) {
  14302. var content = node.data.slice(offset);
  14303. var whitespaceCount = content.length - lTrim(content).length;
  14304. return normalize$1(node, offset, whitespaceCount);
  14305. };
  14306. var normalizeWhitespaceBefore = function (node, offset) {
  14307. var content = node.data.slice(0, offset);
  14308. var whitespaceCount = content.length - rTrim(content).length;
  14309. return normalize$1(node, offset - whitespaceCount, whitespaceCount);
  14310. };
  14311. var mergeTextNodes = function (prevNode, nextNode, normalizeWhitespace, mergeToPrev) {
  14312. if (mergeToPrev === void 0) {
  14313. mergeToPrev = true;
  14314. }
  14315. var whitespaceOffset = rTrim(prevNode.data).length;
  14316. var newNode = mergeToPrev ? prevNode : nextNode;
  14317. var removeNode = mergeToPrev ? nextNode : prevNode;
  14318. if (mergeToPrev) {
  14319. newNode.appendData(removeNode.data);
  14320. } else {
  14321. newNode.insertData(0, removeNode.data);
  14322. }
  14323. remove(SugarElement.fromDom(removeNode));
  14324. if (normalizeWhitespace) {
  14325. normalizeWhitespaceAfter(newNode, whitespaceOffset);
  14326. }
  14327. return newNode;
  14328. };
  14329. var needsReposition = function (pos, elm) {
  14330. var container = pos.container();
  14331. var offset = pos.offset();
  14332. return CaretPosition$1.isTextPosition(pos) === false && container === elm.parentNode && offset > CaretPosition$1.before(elm).offset();
  14333. };
  14334. var reposition = function (elm, pos) {
  14335. return needsReposition(pos, elm) ? CaretPosition$1(pos.container(), pos.offset() - 1) : pos;
  14336. };
  14337. var beforeOrStartOf = function (node) {
  14338. return isText$1(node) ? CaretPosition$1(node, 0) : CaretPosition$1.before(node);
  14339. };
  14340. var afterOrEndOf = function (node) {
  14341. return isText$1(node) ? CaretPosition$1(node, node.data.length) : CaretPosition$1.after(node);
  14342. };
  14343. var getPreviousSiblingCaretPosition = function (elm) {
  14344. if (isCaretCandidate(elm.previousSibling)) {
  14345. return Optional.some(afterOrEndOf(elm.previousSibling));
  14346. } else {
  14347. return elm.previousSibling ? lastPositionIn(elm.previousSibling) : Optional.none();
  14348. }
  14349. };
  14350. var getNextSiblingCaretPosition = function (elm) {
  14351. if (isCaretCandidate(elm.nextSibling)) {
  14352. return Optional.some(beforeOrStartOf(elm.nextSibling));
  14353. } else {
  14354. return elm.nextSibling ? firstPositionIn(elm.nextSibling) : Optional.none();
  14355. }
  14356. };
  14357. var findCaretPositionBackwardsFromElm = function (rootElement, elm) {
  14358. var startPosition = CaretPosition$1.before(elm.previousSibling ? elm.previousSibling : elm.parentNode);
  14359. return prevPosition(rootElement, startPosition).fold(function () {
  14360. return nextPosition(rootElement, CaretPosition$1.after(elm));
  14361. }, Optional.some);
  14362. };
  14363. var findCaretPositionForwardsFromElm = function (rootElement, elm) {
  14364. return nextPosition(rootElement, CaretPosition$1.after(elm)).fold(function () {
  14365. return prevPosition(rootElement, CaretPosition$1.before(elm));
  14366. }, Optional.some);
  14367. };
  14368. var findCaretPositionBackwards = function (rootElement, elm) {
  14369. return getPreviousSiblingCaretPosition(elm).orThunk(function () {
  14370. return getNextSiblingCaretPosition(elm);
  14371. }).orThunk(function () {
  14372. return findCaretPositionBackwardsFromElm(rootElement, elm);
  14373. });
  14374. };
  14375. var findCaretPositionForward = function (rootElement, elm) {
  14376. return getNextSiblingCaretPosition(elm).orThunk(function () {
  14377. return getPreviousSiblingCaretPosition(elm);
  14378. }).orThunk(function () {
  14379. return findCaretPositionForwardsFromElm(rootElement, elm);
  14380. });
  14381. };
  14382. var findCaretPosition$1 = function (forward, rootElement, elm) {
  14383. return forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
  14384. };
  14385. var findCaretPosOutsideElmAfterDelete = function (forward, rootElement, elm) {
  14386. return findCaretPosition$1(forward, rootElement, elm).map(curry(reposition, elm));
  14387. };
  14388. var setSelection = function (editor, forward, pos) {
  14389. pos.fold(function () {
  14390. editor.focus();
  14391. }, function (pos) {
  14392. editor.selection.setRng(pos.toRange(), forward);
  14393. });
  14394. };
  14395. var eqRawNode = function (rawNode) {
  14396. return function (elm) {
  14397. return elm.dom === rawNode;
  14398. };
  14399. };
  14400. var isBlock$2 = function (editor, elm) {
  14401. return elm && has(editor.schema.getBlockElements(), name(elm));
  14402. };
  14403. var paddEmptyBlock = function (elm) {
  14404. if (isEmpty(elm)) {
  14405. var br = SugarElement.fromHtml('<br data-mce-bogus="1">');
  14406. empty(elm);
  14407. append(elm, br);
  14408. return Optional.some(CaretPosition$1.before(br.dom));
  14409. } else {
  14410. return Optional.none();
  14411. }
  14412. };
  14413. var deleteNormalized = function (elm, afterDeletePosOpt, normalizeWhitespace) {
  14414. var prevTextOpt = prevSibling(elm).filter(isText);
  14415. var nextTextOpt = nextSibling(elm).filter(isText);
  14416. remove(elm);
  14417. return lift3(prevTextOpt, nextTextOpt, afterDeletePosOpt, function (prev, next, pos) {
  14418. var prevNode = prev.dom, nextNode = next.dom;
  14419. var offset = prevNode.data.length;
  14420. mergeTextNodes(prevNode, nextNode, normalizeWhitespace);
  14421. return pos.container() === nextNode ? CaretPosition$1(prevNode, offset) : pos;
  14422. }).orThunk(function () {
  14423. if (normalizeWhitespace) {
  14424. prevTextOpt.each(function (elm) {
  14425. return normalizeWhitespaceBefore(elm.dom, elm.dom.length);
  14426. });
  14427. nextTextOpt.each(function (elm) {
  14428. return normalizeWhitespaceAfter(elm.dom, 0);
  14429. });
  14430. }
  14431. return afterDeletePosOpt;
  14432. });
  14433. };
  14434. var isInlineElement = function (editor, element) {
  14435. return has(editor.schema.getTextInlineElements(), name(element));
  14436. };
  14437. var deleteElement = function (editor, forward, elm, moveCaret) {
  14438. if (moveCaret === void 0) {
  14439. moveCaret = true;
  14440. }
  14441. var afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom);
  14442. var parentBlock = ancestor(elm, curry(isBlock$2, editor), eqRawNode(editor.getBody()));
  14443. var normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos, isInlineElement(editor, elm));
  14444. if (editor.dom.isEmpty(editor.getBody())) {
  14445. editor.setContent('');
  14446. editor.selection.setCursorLocation();
  14447. } else {
  14448. parentBlock.bind(paddEmptyBlock).fold(function () {
  14449. if (moveCaret) {
  14450. setSelection(editor, forward, normalizedAfterDeletePos);
  14451. }
  14452. }, function (paddPos) {
  14453. if (moveCaret) {
  14454. setSelection(editor, forward, Optional.some(paddPos));
  14455. }
  14456. });
  14457. }
  14458. };
  14459. var tableCellRng = function (start, end) {
  14460. return {
  14461. start: start,
  14462. end: end
  14463. };
  14464. };
  14465. var tableSelection = function (rng, table, cells) {
  14466. return {
  14467. rng: rng,
  14468. table: table,
  14469. cells: cells
  14470. };
  14471. };
  14472. var deleteAction = Adt.generate([
  14473. { removeTable: ['element'] },
  14474. { emptyCells: ['cells'] },
  14475. {
  14476. deleteCellSelection: [
  14477. 'rng',
  14478. 'cell'
  14479. ]
  14480. }
  14481. ]);
  14482. var isRootFromElement = function (root) {
  14483. return function (cur) {
  14484. return eq$2(root, cur);
  14485. };
  14486. };
  14487. var getClosestCell = function (container, isRoot) {
  14488. return closest$1(SugarElement.fromDom(container), 'td,th', isRoot);
  14489. };
  14490. var getClosestTable = function (cell, isRoot) {
  14491. return ancestor$1(cell, 'table', isRoot);
  14492. };
  14493. var isExpandedCellRng = function (cellRng) {
  14494. return !eq$2(cellRng.start, cellRng.end);
  14495. };
  14496. var getTableFromCellRng = function (cellRng, isRoot) {
  14497. return getClosestTable(cellRng.start, isRoot).bind(function (startParentTable) {
  14498. return getClosestTable(cellRng.end, isRoot).bind(function (endParentTable) {
  14499. return someIf(eq$2(startParentTable, endParentTable), startParentTable);
  14500. });
  14501. });
  14502. };
  14503. var isSingleCellTable = function (cellRng, isRoot) {
  14504. return !isExpandedCellRng(cellRng) && getTableFromCellRng(cellRng, isRoot).exists(function (table) {
  14505. var rows = table.dom.rows;
  14506. return rows.length === 1 && rows[0].cells.length === 1;
  14507. });
  14508. };
  14509. var getTableCells = function (table) {
  14510. return descendants$1(table, 'td,th');
  14511. };
  14512. var getCellRng = function (rng, isRoot) {
  14513. var startCell = getClosestCell(rng.startContainer, isRoot);
  14514. var endCell = getClosestCell(rng.endContainer, isRoot);
  14515. return lift2(startCell, endCell, tableCellRng);
  14516. };
  14517. var getCellRangeFromStartTable = function (cellRng, isRoot) {
  14518. return getClosestTable(cellRng.start, isRoot).bind(function (table) {
  14519. return last(getTableCells(table)).map(function (endCell) {
  14520. return tableCellRng(cellRng.start, endCell);
  14521. });
  14522. });
  14523. };
  14524. var partialSelection = function (isRoot, rng) {
  14525. var startCell = getClosestCell(rng.startContainer, isRoot);
  14526. var endCell = getClosestCell(rng.endContainer, isRoot);
  14527. return rng.collapsed ? Optional.none() : lift2(startCell, endCell, tableCellRng).fold(function () {
  14528. return startCell.fold(function () {
  14529. return endCell.bind(function (endCell) {
  14530. return getClosestTable(endCell, isRoot).bind(function (table) {
  14531. return head(getTableCells(table)).map(function (startCell) {
  14532. return tableCellRng(startCell, endCell);
  14533. });
  14534. });
  14535. });
  14536. }, function (startCell) {
  14537. return getClosestTable(startCell, isRoot).bind(function (table) {
  14538. return last(getTableCells(table)).map(function (endCell) {
  14539. return tableCellRng(startCell, endCell);
  14540. });
  14541. });
  14542. });
  14543. }, function (cellRng) {
  14544. return isWithinSameTable(isRoot, cellRng) ? Optional.none() : getCellRangeFromStartTable(cellRng, isRoot);
  14545. });
  14546. };
  14547. var isWithinSameTable = function (isRoot, cellRng) {
  14548. return getTableFromCellRng(cellRng, isRoot).isSome();
  14549. };
  14550. var getTableSelectionFromCellRng = function (cellRng, isRoot) {
  14551. return getTableFromCellRng(cellRng, isRoot).map(function (table) {
  14552. return tableSelection(cellRng, table, getTableCells(table));
  14553. });
  14554. };
  14555. var getTableSelection = function (optCellRng, rng, isRoot) {
  14556. return optCellRng.filter(function (cellRng) {
  14557. return isExpandedCellRng(cellRng) && isWithinSameTable(isRoot, cellRng);
  14558. }).orThunk(function () {
  14559. return partialSelection(isRoot, rng);
  14560. }).bind(function (cRng) {
  14561. return getTableSelectionFromCellRng(cRng, isRoot);
  14562. });
  14563. };
  14564. var getCellIndex = function (cells, cell) {
  14565. return findIndex(cells, function (x) {
  14566. return eq$2(x, cell);
  14567. });
  14568. };
  14569. var getSelectedCells = function (tableSelection) {
  14570. return lift2(getCellIndex(tableSelection.cells, tableSelection.rng.start), getCellIndex(tableSelection.cells, tableSelection.rng.end), function (startIndex, endIndex) {
  14571. return tableSelection.cells.slice(startIndex, endIndex + 1);
  14572. });
  14573. };
  14574. var isSingleCellTableContentSelected = function (optCellRng, rng, isRoot) {
  14575. return optCellRng.filter(function (cellRng) {
  14576. return isSingleCellTable(cellRng, isRoot) && hasAllContentsSelected(cellRng.start, rng);
  14577. }).map(function (cellRng) {
  14578. return cellRng.start;
  14579. });
  14580. };
  14581. var getAction = function (tableSelection) {
  14582. return getSelectedCells(tableSelection).map(function (selected) {
  14583. var cells = tableSelection.cells;
  14584. return selected.length === cells.length ? deleteAction.removeTable(tableSelection.table) : deleteAction.emptyCells(selected);
  14585. });
  14586. };
  14587. var getActionFromRange = function (root, rng) {
  14588. var isRoot = isRootFromElement(root);
  14589. var optCellRng = getCellRng(rng, isRoot);
  14590. return isSingleCellTableContentSelected(optCellRng, rng, isRoot).map(function (cell) {
  14591. return deleteAction.deleteCellSelection(rng, cell);
  14592. }).orThunk(function () {
  14593. return getTableSelection(optCellRng, rng, isRoot).bind(getAction);
  14594. });
  14595. };
  14596. var freefallRtl = function (root) {
  14597. var child = isComment(root) ? prevSibling(root) : lastChild(root);
  14598. return child.bind(freefallRtl).orThunk(function () {
  14599. return Optional.some(root);
  14600. });
  14601. };
  14602. var emptyCells = function (editor, cells) {
  14603. each(cells, fillWithPaddingBr);
  14604. editor.selection.setCursorLocation(cells[0].dom, 0);
  14605. return true;
  14606. };
  14607. var deleteCellContents = function (editor, rng, cell) {
  14608. rng.deleteContents();
  14609. var lastNode = freefallRtl(cell).getOr(cell);
  14610. var lastBlock = SugarElement.fromDom(editor.dom.getParent(lastNode.dom, editor.dom.isBlock));
  14611. if (isEmpty(lastBlock)) {
  14612. fillWithPaddingBr(lastBlock);
  14613. editor.selection.setCursorLocation(lastBlock.dom, 0);
  14614. }
  14615. if (!eq$2(cell, lastBlock)) {
  14616. var additionalCleanupNodes = parent(lastBlock).is(cell) ? [] : siblings(lastBlock);
  14617. each(additionalCleanupNodes.concat(children(cell)), function (node) {
  14618. if (!eq$2(node, lastBlock) && !contains$2(node, lastBlock)) {
  14619. remove(node);
  14620. }
  14621. });
  14622. }
  14623. return true;
  14624. };
  14625. var deleteTableElement = function (editor, table) {
  14626. deleteElement(editor, false, table);
  14627. return true;
  14628. };
  14629. var deleteCellRange = function (editor, rootElm, rng) {
  14630. return getActionFromRange(rootElm, rng).map(function (action) {
  14631. return action.fold(curry(deleteTableElement, editor), curry(emptyCells, editor), curry(deleteCellContents, editor));
  14632. });
  14633. };
  14634. var deleteCaptionRange = function (editor, caption) {
  14635. return emptyElement(editor, caption);
  14636. };
  14637. var deleteTableRange = function (editor, rootElm, rng, startElm) {
  14638. return getParentCaption(rootElm, startElm).fold(function () {
  14639. return deleteCellRange(editor, rootElm, rng);
  14640. }, function (caption) {
  14641. return deleteCaptionRange(editor, caption);
  14642. }).getOr(false);
  14643. };
  14644. var deleteRange = function (editor, startElm) {
  14645. var rootNode = SugarElement.fromDom(editor.getBody());
  14646. var rng = editor.selection.getRng();
  14647. var selectedCells = getCellsFromEditor(editor);
  14648. return selectedCells.length !== 0 ? emptyCells(editor, selectedCells) : deleteTableRange(editor, rootNode, rng, startElm);
  14649. };
  14650. var getParentCell = function (rootElm, elm) {
  14651. return find(parentsAndSelf(elm, rootElm), isTableCell$1);
  14652. };
  14653. var getParentCaption = function (rootElm, elm) {
  14654. return find(parentsAndSelf(elm, rootElm), function (elm) {
  14655. return name(elm) === 'caption';
  14656. });
  14657. };
  14658. var deleteBetweenCells = function (editor, rootElm, forward, fromCell, from) {
  14659. return navigate(forward, editor.getBody(), from).bind(function (to) {
  14660. return getParentCell(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCell) {
  14661. return eq$2(toCell, fromCell) === false;
  14662. });
  14663. });
  14664. };
  14665. var emptyElement = function (editor, elm) {
  14666. fillWithPaddingBr(elm);
  14667. editor.selection.setCursorLocation(elm.dom, 0);
  14668. return Optional.some(true);
  14669. };
  14670. var isDeleteOfLastCharPos = function (fromCaption, forward, from, to) {
  14671. return firstPositionIn(fromCaption.dom).bind(function (first) {
  14672. return lastPositionIn(fromCaption.dom).map(function (last) {
  14673. return forward ? from.isEqual(first) && to.isEqual(last) : from.isEqual(last) && to.isEqual(first);
  14674. });
  14675. }).getOr(true);
  14676. };
  14677. var emptyCaretCaption = function (editor, elm) {
  14678. return emptyElement(editor, elm);
  14679. };
  14680. var validateCaretCaption = function (rootElm, fromCaption, to) {
  14681. return getParentCaption(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCaption) {
  14682. return eq$2(toCaption, fromCaption) === false;
  14683. });
  14684. };
  14685. var deleteCaretInsideCaption = function (editor, rootElm, forward, fromCaption, from) {
  14686. return navigate(forward, editor.getBody(), from).bind(function (to) {
  14687. return isDeleteOfLastCharPos(fromCaption, forward, from, to) ? emptyCaretCaption(editor, fromCaption) : validateCaretCaption(rootElm, fromCaption, to);
  14688. }).or(Optional.some(true));
  14689. };
  14690. var deleteCaretCells = function (editor, forward, rootElm, startElm) {
  14691. var from = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  14692. return getParentCell(rootElm, startElm).bind(function (fromCell) {
  14693. return isEmpty(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from);
  14694. }).getOr(false);
  14695. };
  14696. var deleteCaretCaption = function (editor, forward, rootElm, fromCaption) {
  14697. var from = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  14698. return isEmpty(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from);
  14699. };
  14700. var isNearTable = function (forward, pos) {
  14701. return forward ? isBeforeTable(pos) : isAfterTable(pos);
  14702. };
  14703. var isBeforeOrAfterTable = function (editor, forward) {
  14704. var fromPos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  14705. return isNearTable(forward, fromPos) || fromPosition(forward, editor.getBody(), fromPos).exists(function (pos) {
  14706. return isNearTable(forward, pos);
  14707. });
  14708. };
  14709. var deleteCaret = function (editor, forward, startElm) {
  14710. var rootElm = SugarElement.fromDom(editor.getBody());
  14711. return getParentCaption(rootElm, startElm).fold(function () {
  14712. return deleteCaretCells(editor, forward, rootElm, startElm) || isBeforeOrAfterTable(editor, forward);
  14713. }, function (fromCaption) {
  14714. return deleteCaretCaption(editor, forward, rootElm, fromCaption).getOr(false);
  14715. });
  14716. };
  14717. var backspaceDelete = function (editor, forward) {
  14718. var startElm = SugarElement.fromDom(editor.selection.getStart(true));
  14719. var cells = getCellsFromEditor(editor);
  14720. return editor.selection.isCollapsed() && cells.length === 0 ? deleteCaret(editor, forward, startElm) : deleteRange(editor, startElm);
  14721. };
  14722. var createRange$1 = function (sc, so, ec, eo) {
  14723. var rng = document.createRange();
  14724. rng.setStart(sc, so);
  14725. rng.setEnd(ec, eo);
  14726. return rng;
  14727. };
  14728. var normalizeBlockSelectionRange = function (rng) {
  14729. var startPos = CaretPosition$1.fromRangeStart(rng);
  14730. var endPos = CaretPosition$1.fromRangeEnd(rng);
  14731. var rootNode = rng.commonAncestorContainer;
  14732. return fromPosition(false, rootNode, endPos).map(function (newEndPos) {
  14733. if (!isInSameBlock(startPos, endPos, rootNode) && isInSameBlock(startPos, newEndPos, rootNode)) {
  14734. return createRange$1(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
  14735. } else {
  14736. return rng;
  14737. }
  14738. }).getOr(rng);
  14739. };
  14740. var normalize$2 = function (rng) {
  14741. return rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
  14742. };
  14743. var hasOnlyOneChild = function (node) {
  14744. return node.firstChild && node.firstChild === node.lastChild;
  14745. };
  14746. var isPaddingNode = function (node) {
  14747. return node.name === 'br' || node.value === nbsp;
  14748. };
  14749. var isPaddedEmptyBlock = function (schema, node) {
  14750. var blockElements = schema.getBlockElements();
  14751. return blockElements[node.name] && hasOnlyOneChild(node) && isPaddingNode(node.firstChild);
  14752. };
  14753. var isEmptyFragmentElement = function (schema, node) {
  14754. var nonEmptyElements = schema.getNonEmptyElements();
  14755. return node && (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
  14756. };
  14757. var isListFragment = function (schema, fragment) {
  14758. var firstChild = fragment.firstChild;
  14759. var lastChild = fragment.lastChild;
  14760. if (firstChild && firstChild.name === 'meta') {
  14761. firstChild = firstChild.next;
  14762. }
  14763. if (lastChild && lastChild.attr('id') === 'mce_marker') {
  14764. lastChild = lastChild.prev;
  14765. }
  14766. if (isEmptyFragmentElement(schema, lastChild)) {
  14767. lastChild = lastChild.prev;
  14768. }
  14769. if (!firstChild || firstChild !== lastChild) {
  14770. return false;
  14771. }
  14772. return firstChild.name === 'ul' || firstChild.name === 'ol';
  14773. };
  14774. var cleanupDomFragment = function (domFragment) {
  14775. var firstChild = domFragment.firstChild;
  14776. var lastChild = domFragment.lastChild;
  14777. if (firstChild && firstChild.nodeName === 'META') {
  14778. firstChild.parentNode.removeChild(firstChild);
  14779. }
  14780. if (lastChild && lastChild.id === 'mce_marker') {
  14781. lastChild.parentNode.removeChild(lastChild);
  14782. }
  14783. return domFragment;
  14784. };
  14785. var toDomFragment = function (dom, serializer, fragment) {
  14786. var html = serializer.serialize(fragment);
  14787. var domFragment = dom.createFragment(html);
  14788. return cleanupDomFragment(domFragment);
  14789. };
  14790. var listItems$1 = function (elm) {
  14791. return Tools.grep(elm.childNodes, function (child) {
  14792. return child.nodeName === 'LI';
  14793. });
  14794. };
  14795. var isPadding = function (node) {
  14796. return node.data === nbsp || isBr(node);
  14797. };
  14798. var isListItemPadded = function (node) {
  14799. return node && node.firstChild && node.firstChild === node.lastChild && isPadding(node.firstChild);
  14800. };
  14801. var isEmptyOrPadded = function (elm) {
  14802. return !elm.firstChild || isListItemPadded(elm);
  14803. };
  14804. var trimListItems = function (elms) {
  14805. return elms.length > 0 && isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
  14806. };
  14807. var getParentLi = function (dom, node) {
  14808. var parentBlock = dom.getParent(node, dom.isBlock);
  14809. return parentBlock && parentBlock.nodeName === 'LI' ? parentBlock : null;
  14810. };
  14811. var isParentBlockLi = function (dom, node) {
  14812. return !!getParentLi(dom, node);
  14813. };
  14814. var getSplit = function (parentNode, rng) {
  14815. var beforeRng = rng.cloneRange();
  14816. var afterRng = rng.cloneRange();
  14817. beforeRng.setStartBefore(parentNode);
  14818. afterRng.setEndAfter(parentNode);
  14819. return [
  14820. beforeRng.cloneContents(),
  14821. afterRng.cloneContents()
  14822. ];
  14823. };
  14824. var findFirstIn = function (node, rootNode) {
  14825. var caretPos = CaretPosition$1.before(node);
  14826. var caretWalker = CaretWalker(rootNode);
  14827. var newCaretPos = caretWalker.next(caretPos);
  14828. return newCaretPos ? newCaretPos.toRange() : null;
  14829. };
  14830. var findLastOf = function (node, rootNode) {
  14831. var caretPos = CaretPosition$1.after(node);
  14832. var caretWalker = CaretWalker(rootNode);
  14833. var newCaretPos = caretWalker.prev(caretPos);
  14834. return newCaretPos ? newCaretPos.toRange() : null;
  14835. };
  14836. var insertMiddle = function (target, elms, rootNode, rng) {
  14837. var parts = getSplit(target, rng);
  14838. var parentElm = target.parentNode;
  14839. parentElm.insertBefore(parts[0], target);
  14840. Tools.each(elms, function (li) {
  14841. parentElm.insertBefore(li, target);
  14842. });
  14843. parentElm.insertBefore(parts[1], target);
  14844. parentElm.removeChild(target);
  14845. return findLastOf(elms[elms.length - 1], rootNode);
  14846. };
  14847. var insertBefore = function (target, elms, rootNode) {
  14848. var parentElm = target.parentNode;
  14849. Tools.each(elms, function (elm) {
  14850. parentElm.insertBefore(elm, target);
  14851. });
  14852. return findFirstIn(target, rootNode);
  14853. };
  14854. var insertAfter = function (target, elms, rootNode, dom) {
  14855. dom.insertAfter(elms.reverse(), target);
  14856. return findLastOf(elms[0], rootNode);
  14857. };
  14858. var insertAtCaret = function (serializer, dom, rng, fragment) {
  14859. var domFragment = toDomFragment(dom, serializer, fragment);
  14860. var liTarget = getParentLi(dom, rng.startContainer);
  14861. var liElms = trimListItems(listItems$1(domFragment.firstChild));
  14862. var BEGINNING = 1, END = 2;
  14863. var rootNode = dom.getRoot();
  14864. var isAt = function (location) {
  14865. var caretPos = CaretPosition$1.fromRangeStart(rng);
  14866. var caretWalker = CaretWalker(dom.getRoot());
  14867. var newPos = location === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
  14868. return newPos ? getParentLi(dom, newPos.getNode()) !== liTarget : true;
  14869. };
  14870. if (isAt(BEGINNING)) {
  14871. return insertBefore(liTarget, liElms, rootNode);
  14872. } else if (isAt(END)) {
  14873. return insertAfter(liTarget, liElms, rootNode, dom);
  14874. }
  14875. return insertMiddle(liTarget, liElms, rootNode, rng);
  14876. };
  14877. var trimOrPadLeftRight = function (dom, rng, html) {
  14878. var root = SugarElement.fromDom(dom.getRoot());
  14879. if (needsToBeNbspLeft(root, CaretPosition$1.fromRangeStart(rng))) {
  14880. html = html.replace(/^ /, '&nbsp;');
  14881. } else {
  14882. html = html.replace(/^&nbsp;/, ' ');
  14883. }
  14884. if (needsToBeNbspRight(root, CaretPosition$1.fromRangeEnd(rng))) {
  14885. html = html.replace(/(&nbsp;| )(<br( \/)>)?$/, '&nbsp;');
  14886. } else {
  14887. html = html.replace(/&nbsp;(<br( \/)?>)?$/, ' ');
  14888. }
  14889. return html;
  14890. };
  14891. var isTableCell$4 = isTableCell;
  14892. var isTableCellContentSelected = function (dom, rng, cell) {
  14893. if (cell !== null) {
  14894. var endCell = dom.getParent(rng.endContainer, isTableCell$4);
  14895. return cell === endCell && hasAllContentsSelected(SugarElement.fromDom(cell), rng);
  14896. } else {
  14897. return false;
  14898. }
  14899. };
  14900. var validInsertion = function (editor, value, parentNode) {
  14901. if (parentNode.getAttribute('data-mce-bogus') === 'all') {
  14902. parentNode.parentNode.insertBefore(editor.dom.createFragment(value), parentNode);
  14903. } else {
  14904. var node = parentNode.firstChild;
  14905. var node2 = parentNode.lastChild;
  14906. if (!node || node === node2 && node.nodeName === 'BR') {
  14907. editor.dom.setHTML(parentNode, value);
  14908. } else {
  14909. editor.selection.setContent(value);
  14910. }
  14911. }
  14912. };
  14913. var trimBrsFromTableCell = function (dom, elm) {
  14914. Optional.from(dom.getParent(elm, 'td,th')).map(SugarElement.fromDom).each(trimBlockTrailingBr);
  14915. };
  14916. var reduceInlineTextElements = function (editor, merge) {
  14917. var textInlineElements = editor.schema.getTextInlineElements();
  14918. var dom = editor.dom;
  14919. if (merge) {
  14920. var root_1 = editor.getBody(), elementUtils_1 = new ElementUtils(dom);
  14921. Tools.each(dom.select('*[data-mce-fragment]'), function (node) {
  14922. for (var testNode = node.parentNode; testNode && testNode !== root_1; testNode = testNode.parentNode) {
  14923. if (textInlineElements[node.nodeName.toLowerCase()] && elementUtils_1.compare(testNode, node)) {
  14924. dom.remove(node, true);
  14925. }
  14926. }
  14927. });
  14928. }
  14929. };
  14930. var markFragmentElements = function (fragment) {
  14931. var node = fragment;
  14932. while (node = node.walk()) {
  14933. if (node.type === 1) {
  14934. node.attr('data-mce-fragment', '1');
  14935. }
  14936. }
  14937. };
  14938. var unmarkFragmentElements = function (elm) {
  14939. Tools.each(elm.getElementsByTagName('*'), function (elm) {
  14940. elm.removeAttribute('data-mce-fragment');
  14941. });
  14942. };
  14943. var isPartOfFragment = function (node) {
  14944. return !!node.getAttribute('data-mce-fragment');
  14945. };
  14946. var canHaveChildren = function (editor, node) {
  14947. return node && !editor.schema.getShortEndedElements()[node.nodeName];
  14948. };
  14949. var moveSelectionToMarker = function (editor, marker) {
  14950. var nextRng;
  14951. var dom = editor.dom, selection = editor.selection;
  14952. var node2;
  14953. var getContentEditableFalseParent = function (node) {
  14954. var root = editor.getBody();
  14955. for (; node && node !== root; node = node.parentNode) {
  14956. if (dom.getContentEditable(node) === 'false') {
  14957. return node;
  14958. }
  14959. }
  14960. return null;
  14961. };
  14962. if (!marker) {
  14963. return;
  14964. }
  14965. selection.scrollIntoView(marker);
  14966. var parentEditableFalseElm = getContentEditableFalseParent(marker);
  14967. if (parentEditableFalseElm) {
  14968. dom.remove(marker);
  14969. selection.select(parentEditableFalseElm);
  14970. return;
  14971. }
  14972. var rng = dom.createRng();
  14973. var node = marker.previousSibling;
  14974. if (node && node.nodeType === 3) {
  14975. rng.setStart(node, node.nodeValue.length);
  14976. if (!Env.ie) {
  14977. node2 = marker.nextSibling;
  14978. if (node2 && node2.nodeType === 3) {
  14979. node.appendData(node2.data);
  14980. node2.parentNode.removeChild(node2);
  14981. }
  14982. }
  14983. } else {
  14984. rng.setStartBefore(marker);
  14985. rng.setEndBefore(marker);
  14986. }
  14987. var findNextCaretRng = function (rng) {
  14988. var caretPos = CaretPosition$1.fromRangeStart(rng);
  14989. var caretWalker = CaretWalker(editor.getBody());
  14990. caretPos = caretWalker.next(caretPos);
  14991. if (caretPos) {
  14992. return caretPos.toRange();
  14993. }
  14994. };
  14995. var parentBlock = dom.getParent(marker, dom.isBlock);
  14996. dom.remove(marker);
  14997. if (parentBlock && dom.isEmpty(parentBlock)) {
  14998. editor.$(parentBlock).empty();
  14999. rng.setStart(parentBlock, 0);
  15000. rng.setEnd(parentBlock, 0);
  15001. if (!isTableCell$4(parentBlock) && !isPartOfFragment(parentBlock) && (nextRng = findNextCaretRng(rng))) {
  15002. rng = nextRng;
  15003. dom.remove(parentBlock);
  15004. } else {
  15005. dom.add(parentBlock, dom.create('br', { 'data-mce-bogus': '1' }));
  15006. }
  15007. }
  15008. selection.setRng(rng);
  15009. };
  15010. var deleteSelectedContent = function (editor) {
  15011. var dom = editor.dom;
  15012. var rng = normalize$2(editor.selection.getRng());
  15013. editor.selection.setRng(rng);
  15014. var startCell = dom.getParent(rng.startContainer, isTableCell$4);
  15015. if (isTableCellContentSelected(dom, rng, startCell)) {
  15016. deleteCellContents(editor, rng, SugarElement.fromDom(startCell));
  15017. } else {
  15018. editor.getDoc().execCommand('Delete', false, null);
  15019. }
  15020. };
  15021. var insertHtmlAtCaret = function (editor, value, details) {
  15022. var parentNode, rootNode, args;
  15023. var marker, rng, node;
  15024. var selection = editor.selection, dom = editor.dom;
  15025. if (/^ | $/.test(value)) {
  15026. value = trimOrPadLeftRight(dom, selection.getRng(), value);
  15027. }
  15028. var parser = editor.parser;
  15029. var merge = details.merge;
  15030. var serializer = HtmlSerializer({ validate: shouldValidate(editor) }, editor.schema);
  15031. var bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>';
  15032. args = {
  15033. content: value,
  15034. format: 'html',
  15035. selection: true,
  15036. paste: details.paste
  15037. };
  15038. args = editor.fire('BeforeSetContent', args);
  15039. if (args.isDefaultPrevented()) {
  15040. editor.fire('SetContent', {
  15041. content: args.content,
  15042. format: 'html',
  15043. selection: true,
  15044. paste: details.paste
  15045. });
  15046. return;
  15047. }
  15048. value = args.content;
  15049. if (value.indexOf('{$caret}') === -1) {
  15050. value += '{$caret}';
  15051. }
  15052. value = value.replace(/\{\$caret\}/, bookmarkHtml);
  15053. rng = selection.getRng();
  15054. var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
  15055. var body = editor.getBody();
  15056. if (caretElement === body && selection.isCollapsed()) {
  15057. if (dom.isBlock(body.firstChild) && canHaveChildren(editor, body.firstChild) && dom.isEmpty(body.firstChild)) {
  15058. rng = dom.createRng();
  15059. rng.setStart(body.firstChild, 0);
  15060. rng.setEnd(body.firstChild, 0);
  15061. selection.setRng(rng);
  15062. }
  15063. }
  15064. if (!selection.isCollapsed()) {
  15065. deleteSelectedContent(editor);
  15066. }
  15067. parentNode = selection.getNode();
  15068. var parserArgs = {
  15069. context: parentNode.nodeName.toLowerCase(),
  15070. data: details.data,
  15071. insert: true
  15072. };
  15073. var fragment = parser.parse(value, parserArgs);
  15074. if (details.paste === true && isListFragment(editor.schema, fragment) && isParentBlockLi(dom, parentNode)) {
  15075. rng = insertAtCaret(serializer, dom, selection.getRng(), fragment);
  15076. selection.setRng(rng);
  15077. editor.fire('SetContent', args);
  15078. return;
  15079. }
  15080. markFragmentElements(fragment);
  15081. node = fragment.lastChild;
  15082. if (node.attr('id') === 'mce_marker') {
  15083. marker = node;
  15084. for (node = node.prev; node; node = node.walk(true)) {
  15085. if (node.type === 3 || !dom.isBlock(node.name)) {
  15086. if (editor.schema.isValidChild(node.parent.name, 'span')) {
  15087. node.parent.insert(marker, node, node.name === 'br');
  15088. }
  15089. break;
  15090. }
  15091. }
  15092. }
  15093. editor._selectionOverrides.showBlockCaretContainer(parentNode);
  15094. if (!parserArgs.invalid) {
  15095. value = serializer.serialize(fragment);
  15096. validInsertion(editor, value, parentNode);
  15097. } else {
  15098. editor.selection.setContent(bookmarkHtml);
  15099. parentNode = selection.getNode();
  15100. rootNode = editor.getBody();
  15101. if (parentNode.nodeType === 9) {
  15102. parentNode = node = rootNode;
  15103. } else {
  15104. node = parentNode;
  15105. }
  15106. while (node !== rootNode) {
  15107. parentNode = node;
  15108. node = node.parentNode;
  15109. }
  15110. value = parentNode === rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
  15111. value = serializer.serialize(parser.parse(value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function () {
  15112. return serializer.serialize(fragment);
  15113. })));
  15114. if (parentNode === rootNode) {
  15115. dom.setHTML(rootNode, value);
  15116. } else {
  15117. dom.setOuterHTML(parentNode, value);
  15118. }
  15119. }
  15120. reduceInlineTextElements(editor, merge);
  15121. moveSelectionToMarker(editor, dom.get('mce_marker'));
  15122. unmarkFragmentElements(editor.getBody());
  15123. trimBrsFromTableCell(dom, selection.getStart());
  15124. editor.fire('SetContent', args);
  15125. editor.addVisual();
  15126. };
  15127. var traverse = function (node, fn) {
  15128. fn(node);
  15129. if (node.firstChild) {
  15130. traverse(node.firstChild, fn);
  15131. }
  15132. if (node.next) {
  15133. traverse(node.next, fn);
  15134. }
  15135. };
  15136. var findMatchingNodes = function (nodeFilters, attributeFilters, node) {
  15137. var nodeMatches = {};
  15138. var attrMatches = {};
  15139. var matches = [];
  15140. if (node.firstChild) {
  15141. traverse(node.firstChild, function (node) {
  15142. each(nodeFilters, function (filter) {
  15143. if (filter.name === node.name) {
  15144. if (nodeMatches[filter.name]) {
  15145. nodeMatches[filter.name].nodes.push(node);
  15146. } else {
  15147. nodeMatches[filter.name] = {
  15148. filter: filter,
  15149. nodes: [node]
  15150. };
  15151. }
  15152. }
  15153. });
  15154. each(attributeFilters, function (filter) {
  15155. if (typeof node.attr(filter.name) === 'string') {
  15156. if (attrMatches[filter.name]) {
  15157. attrMatches[filter.name].nodes.push(node);
  15158. } else {
  15159. attrMatches[filter.name] = {
  15160. filter: filter,
  15161. nodes: [node]
  15162. };
  15163. }
  15164. }
  15165. });
  15166. });
  15167. }
  15168. for (var name_1 in nodeMatches) {
  15169. if (nodeMatches.hasOwnProperty(name_1)) {
  15170. matches.push(nodeMatches[name_1]);
  15171. }
  15172. }
  15173. for (var name_2 in attrMatches) {
  15174. if (attrMatches.hasOwnProperty(name_2)) {
  15175. matches.push(attrMatches[name_2]);
  15176. }
  15177. }
  15178. return matches;
  15179. };
  15180. var filter$3 = function (nodeFilters, attributeFilters, node) {
  15181. var matches = findMatchingNodes(nodeFilters, attributeFilters, node);
  15182. each(matches, function (match) {
  15183. each(match.filter.callbacks, function (callback) {
  15184. callback(match.nodes, match.filter.name, {});
  15185. });
  15186. });
  15187. };
  15188. var defaultFormat = 'html';
  15189. var isTreeNode = function (content) {
  15190. return content instanceof AstNode;
  15191. };
  15192. var moveSelection = function (editor) {
  15193. if (hasFocus$1(editor)) {
  15194. firstPositionIn(editor.getBody()).each(function (pos) {
  15195. var node = pos.getNode();
  15196. var caretPos = isTable(node) ? firstPositionIn(node).getOr(pos) : pos;
  15197. editor.selection.setRng(caretPos.toRange());
  15198. });
  15199. }
  15200. };
  15201. var setEditorHtml = function (editor, html) {
  15202. editor.dom.setHTML(editor.getBody(), html);
  15203. moveSelection(editor);
  15204. };
  15205. var setContentString = function (editor, body, content, args) {
  15206. var forcedRootBlockName, padd;
  15207. if (content.length === 0 || /^\s+$/.test(content)) {
  15208. padd = '<br data-mce-bogus="1">';
  15209. if (body.nodeName === 'TABLE') {
  15210. content = '<tr><td>' + padd + '</td></tr>';
  15211. } else if (/^(UL|OL)$/.test(body.nodeName)) {
  15212. content = '<li>' + padd + '</li>';
  15213. }
  15214. forcedRootBlockName = getForcedRootBlock(editor);
  15215. if (forcedRootBlockName && editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
  15216. content = padd;
  15217. content = editor.dom.createHTML(forcedRootBlockName, getForcedRootBlockAttrs(editor), content);
  15218. } else if (!content) {
  15219. content = '<br data-mce-bogus="1">';
  15220. }
  15221. setEditorHtml(editor, content);
  15222. editor.fire('SetContent', args);
  15223. } else {
  15224. if (args.format !== 'raw') {
  15225. content = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(editor.parser.parse(content, {
  15226. isRootContent: true,
  15227. insert: true
  15228. }));
  15229. }
  15230. args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? content : Tools.trim(content);
  15231. setEditorHtml(editor, args.content);
  15232. if (!args.no_events) {
  15233. editor.fire('SetContent', args);
  15234. }
  15235. }
  15236. return args.content;
  15237. };
  15238. var setContentTree = function (editor, body, content, args) {
  15239. filter$3(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
  15240. var html = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(content);
  15241. args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? html : Tools.trim(html);
  15242. setEditorHtml(editor, args.content);
  15243. if (!args.no_events) {
  15244. editor.fire('SetContent', args);
  15245. }
  15246. return content;
  15247. };
  15248. var setContentInternal = function (editor, content, args) {
  15249. args.format = args.format ? args.format : defaultFormat;
  15250. args.set = true;
  15251. args.content = isTreeNode(content) ? '' : content;
  15252. if (!args.no_events) {
  15253. editor.fire('BeforeSetContent', args);
  15254. }
  15255. if (!isTreeNode(content)) {
  15256. content = args.content;
  15257. }
  15258. return Optional.from(editor.getBody()).fold(constant(content), function (body) {
  15259. return isTreeNode(content) ? setContentTree(editor, body, content, args) : setContentString(editor, body, content, args);
  15260. });
  15261. };
  15262. var addVisualInternal = function (editor, elm) {
  15263. var dom = editor.dom;
  15264. var scope = isNonNullable(elm) ? elm : editor.getBody();
  15265. if (isUndefined(editor.hasVisual)) {
  15266. editor.hasVisual = isVisualAidsEnabled(editor);
  15267. }
  15268. each(dom.select('table,a', scope), function (matchedElm) {
  15269. switch (matchedElm.nodeName) {
  15270. case 'TABLE':
  15271. var cls = getVisualAidsTableClass(editor);
  15272. var value = dom.getAttrib(matchedElm, 'border');
  15273. if ((!value || value === '0') && editor.hasVisual) {
  15274. dom.addClass(matchedElm, cls);
  15275. } else {
  15276. dom.removeClass(matchedElm, cls);
  15277. }
  15278. break;
  15279. case 'A':
  15280. if (!dom.getAttrib(matchedElm, 'href')) {
  15281. var value_1 = dom.getAttrib(matchedElm, 'name') || matchedElm.id;
  15282. var cls_1 = getVisualAidsAnchorClass(editor);
  15283. if (value_1 && editor.hasVisual) {
  15284. dom.addClass(matchedElm, cls_1);
  15285. } else {
  15286. dom.removeClass(matchedElm, cls_1);
  15287. }
  15288. }
  15289. break;
  15290. }
  15291. });
  15292. editor.fire('VisualAid', {
  15293. element: elm,
  15294. hasVisual: editor.hasVisual
  15295. });
  15296. };
  15297. var sibling$2 = function (scope, predicate) {
  15298. return sibling(scope, predicate).isSome();
  15299. };
  15300. var ZWSP$1 = ZWSP, CARET_ID$1 = '_mce_caret';
  15301. var importNode = function (ownerDocument, node) {
  15302. return ownerDocument.importNode(node, true);
  15303. };
  15304. var getEmptyCaretContainers = function (node) {
  15305. var nodes = [];
  15306. while (node) {
  15307. if (node.nodeType === 3 && node.nodeValue !== ZWSP$1 || node.childNodes.length > 1) {
  15308. return [];
  15309. }
  15310. if (node.nodeType === 1) {
  15311. nodes.push(node);
  15312. }
  15313. node = node.firstChild;
  15314. }
  15315. return nodes;
  15316. };
  15317. var isCaretContainerEmpty = function (node) {
  15318. return getEmptyCaretContainers(node).length > 0;
  15319. };
  15320. var findFirstTextNode = function (node) {
  15321. if (node) {
  15322. var walker = new DomTreeWalker(node, node);
  15323. for (node = walker.current(); node; node = walker.next()) {
  15324. if (isText$1(node)) {
  15325. return node;
  15326. }
  15327. }
  15328. }
  15329. return null;
  15330. };
  15331. var createCaretContainer = function (fill) {
  15332. var caretContainer = SugarElement.fromTag('span');
  15333. setAll(caretContainer, {
  15334. 'id': CARET_ID$1,
  15335. 'data-mce-bogus': '1',
  15336. 'data-mce-type': 'format-caret'
  15337. });
  15338. if (fill) {
  15339. append(caretContainer, SugarElement.fromText(ZWSP$1));
  15340. }
  15341. return caretContainer;
  15342. };
  15343. var trimZwspFromCaretContainer = function (caretContainerNode) {
  15344. var textNode = findFirstTextNode(caretContainerNode);
  15345. if (textNode && textNode.nodeValue.charAt(0) === ZWSP$1) {
  15346. textNode.deleteData(0, 1);
  15347. }
  15348. return textNode;
  15349. };
  15350. var removeCaretContainerNode = function (editor, node, moveCaret) {
  15351. if (moveCaret === void 0) {
  15352. moveCaret = true;
  15353. }
  15354. var dom = editor.dom, selection = editor.selection;
  15355. if (isCaretContainerEmpty(node)) {
  15356. deleteElement(editor, false, SugarElement.fromDom(node), moveCaret);
  15357. } else {
  15358. var rng = selection.getRng();
  15359. var block = dom.getParent(node, dom.isBlock);
  15360. var startContainer = rng.startContainer;
  15361. var startOffset = rng.startOffset;
  15362. var endContainer = rng.endContainer;
  15363. var endOffset = rng.endOffset;
  15364. var textNode = trimZwspFromCaretContainer(node);
  15365. dom.remove(node, true);
  15366. if (startContainer === textNode && startOffset > 0) {
  15367. rng.setStart(textNode, startOffset - 1);
  15368. }
  15369. if (endContainer === textNode && endOffset > 0) {
  15370. rng.setEnd(textNode, endOffset - 1);
  15371. }
  15372. if (block && dom.isEmpty(block)) {
  15373. fillWithPaddingBr(SugarElement.fromDom(block));
  15374. }
  15375. selection.setRng(rng);
  15376. }
  15377. };
  15378. var removeCaretContainer = function (editor, node, moveCaret) {
  15379. if (moveCaret === void 0) {
  15380. moveCaret = true;
  15381. }
  15382. var dom = editor.dom, selection = editor.selection;
  15383. if (!node) {
  15384. node = getParentCaretContainer(editor.getBody(), selection.getStart());
  15385. if (!node) {
  15386. while (node = dom.get(CARET_ID$1)) {
  15387. removeCaretContainerNode(editor, node, false);
  15388. }
  15389. }
  15390. } else {
  15391. removeCaretContainerNode(editor, node, moveCaret);
  15392. }
  15393. };
  15394. var insertCaretContainerNode = function (editor, caretContainer, formatNode) {
  15395. var dom = editor.dom, block = dom.getParent(formatNode, curry(isTextBlock$1, editor));
  15396. if (block && dom.isEmpty(block)) {
  15397. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15398. } else {
  15399. removeTrailingBr(SugarElement.fromDom(formatNode));
  15400. if (dom.isEmpty(formatNode)) {
  15401. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15402. } else {
  15403. dom.insertAfter(caretContainer, formatNode);
  15404. }
  15405. }
  15406. };
  15407. var appendNode = function (parentNode, node) {
  15408. parentNode.appendChild(node);
  15409. return node;
  15410. };
  15411. var insertFormatNodesIntoCaretContainer = function (formatNodes, caretContainer) {
  15412. var innerMostFormatNode = foldr(formatNodes, function (parentNode, formatNode) {
  15413. return appendNode(parentNode, formatNode.cloneNode(false));
  15414. }, caretContainer);
  15415. return appendNode(innerMostFormatNode, innerMostFormatNode.ownerDocument.createTextNode(ZWSP$1));
  15416. };
  15417. var cleanFormatNode = function (editor, caretContainer, formatNode, name, vars, similar) {
  15418. var formatter = editor.formatter;
  15419. var dom = editor.dom;
  15420. var validFormats = filter(keys(formatter.get()), function (formatName) {
  15421. return formatName !== name && !contains$1(formatName, 'removeformat');
  15422. });
  15423. var matchedFormats = matchAllOnNode(editor, formatNode, validFormats);
  15424. var uniqueFormats = filter(matchedFormats, function (fmtName) {
  15425. return !areSimilarFormats(editor, fmtName, name);
  15426. });
  15427. if (uniqueFormats.length > 0) {
  15428. var clonedFormatNode = formatNode.cloneNode(false);
  15429. dom.add(caretContainer, clonedFormatNode);
  15430. formatter.remove(name, vars, clonedFormatNode, similar);
  15431. dom.remove(clonedFormatNode);
  15432. return Optional.some(clonedFormatNode);
  15433. } else {
  15434. return Optional.none();
  15435. }
  15436. };
  15437. var applyCaretFormat = function (editor, name, vars) {
  15438. var caretContainer, textNode;
  15439. var selection = editor.selection;
  15440. var selectionRng = selection.getRng();
  15441. var offset = selectionRng.startOffset;
  15442. var container = selectionRng.startContainer;
  15443. var text = container.nodeValue;
  15444. caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
  15445. if (caretContainer) {
  15446. textNode = findFirstTextNode(caretContainer);
  15447. }
  15448. var wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
  15449. if (text && offset > 0 && offset < text.length && wordcharRegex.test(text.charAt(offset)) && wordcharRegex.test(text.charAt(offset - 1))) {
  15450. var bookmark = selection.getBookmark();
  15451. selectionRng.collapse(true);
  15452. var rng = expandRng(editor, selectionRng, editor.formatter.get(name));
  15453. rng = split$1(rng);
  15454. editor.formatter.apply(name, vars, rng);
  15455. selection.moveToBookmark(bookmark);
  15456. } else {
  15457. if (!caretContainer || textNode.nodeValue !== ZWSP$1) {
  15458. caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom);
  15459. textNode = caretContainer.firstChild;
  15460. selectionRng.insertNode(caretContainer);
  15461. offset = 1;
  15462. editor.formatter.apply(name, vars, caretContainer);
  15463. } else {
  15464. editor.formatter.apply(name, vars, caretContainer);
  15465. }
  15466. selection.setCursorLocation(textNode, offset);
  15467. }
  15468. };
  15469. var removeCaretFormat = function (editor, name, vars, similar) {
  15470. var dom = editor.dom;
  15471. var selection = editor.selection;
  15472. var hasContentAfter, node, formatNode;
  15473. var parents = [];
  15474. var rng = selection.getRng();
  15475. var container = rng.startContainer;
  15476. var offset = rng.startOffset;
  15477. node = container;
  15478. if (container.nodeType === 3) {
  15479. if (offset !== container.nodeValue.length) {
  15480. hasContentAfter = true;
  15481. }
  15482. node = node.parentNode;
  15483. }
  15484. while (node) {
  15485. if (matchNode(editor, node, name, vars, similar)) {
  15486. formatNode = node;
  15487. break;
  15488. }
  15489. if (node.nextSibling) {
  15490. hasContentAfter = true;
  15491. }
  15492. parents.push(node);
  15493. node = node.parentNode;
  15494. }
  15495. if (!formatNode) {
  15496. return;
  15497. }
  15498. if (hasContentAfter) {
  15499. var bookmark = selection.getBookmark();
  15500. rng.collapse(true);
  15501. var expandedRng = expandRng(editor, rng, editor.formatter.get(name), true);
  15502. expandedRng = split$1(expandedRng);
  15503. editor.formatter.remove(name, vars, expandedRng, similar);
  15504. selection.moveToBookmark(bookmark);
  15505. } else {
  15506. var caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
  15507. var newCaretContainer = createCaretContainer(false).dom;
  15508. insertCaretContainerNode(editor, newCaretContainer, caretContainer !== null ? caretContainer : formatNode);
  15509. var cleanedFormatNode = cleanFormatNode(editor, newCaretContainer, formatNode, name, vars, similar);
  15510. var caretTextNode = insertFormatNodesIntoCaretContainer(parents.concat(cleanedFormatNode.toArray()), newCaretContainer);
  15511. removeCaretContainerNode(editor, caretContainer, false);
  15512. selection.setCursorLocation(caretTextNode, 1);
  15513. if (dom.isEmpty(formatNode)) {
  15514. dom.remove(formatNode);
  15515. }
  15516. }
  15517. };
  15518. var disableCaretContainer = function (editor, keyCode) {
  15519. var selection = editor.selection, body = editor.getBody();
  15520. removeCaretContainer(editor, null, false);
  15521. if ((keyCode === 8 || keyCode === 46) && selection.isCollapsed() && selection.getStart().innerHTML === ZWSP$1) {
  15522. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15523. }
  15524. if (keyCode === 37 || keyCode === 39) {
  15525. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15526. }
  15527. };
  15528. var setup$3 = function (editor) {
  15529. editor.on('mouseup keydown', function (e) {
  15530. disableCaretContainer(editor, e.keyCode);
  15531. });
  15532. };
  15533. var replaceWithCaretFormat = function (targetNode, formatNodes) {
  15534. var caretContainer = createCaretContainer(false);
  15535. var innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom);
  15536. before(SugarElement.fromDom(targetNode), caretContainer);
  15537. remove(SugarElement.fromDom(targetNode));
  15538. return CaretPosition$1(innerMost, 0);
  15539. };
  15540. var isFormatElement = function (editor, element) {
  15541. var inlineElements = editor.schema.getTextInlineElements();
  15542. return inlineElements.hasOwnProperty(name(element)) && !isCaretNode(element.dom) && !isBogus(element.dom);
  15543. };
  15544. var isEmptyCaretFormatElement = function (element) {
  15545. return isCaretNode(element.dom) && isCaretContainerEmpty(element.dom);
  15546. };
  15547. var postProcessHooks = {};
  15548. var filter$4 = filter$2;
  15549. var each$8 = each$2;
  15550. var addPostProcessHook = function (name, hook) {
  15551. var hooks = postProcessHooks[name];
  15552. if (!hooks) {
  15553. postProcessHooks[name] = [];
  15554. }
  15555. postProcessHooks[name].push(hook);
  15556. };
  15557. var postProcess = function (name, editor) {
  15558. each$8(postProcessHooks[name], function (hook) {
  15559. hook(editor);
  15560. });
  15561. };
  15562. addPostProcessHook('pre', function (editor) {
  15563. var rng = editor.selection.getRng();
  15564. var blocks;
  15565. var hasPreSibling = function (pre) {
  15566. return isPre(pre.previousSibling) && indexOf$1(blocks, pre.previousSibling) !== -1;
  15567. };
  15568. var joinPre = function (pre1, pre2) {
  15569. DomQuery(pre2).remove();
  15570. DomQuery(pre1).append('<br><br>').append(pre2.childNodes);
  15571. };
  15572. var isPre = matchNodeNames(['pre']);
  15573. if (!rng.collapsed) {
  15574. blocks = editor.selection.getSelectedBlocks();
  15575. each$8(filter$4(filter$4(blocks, isPre), hasPreSibling), function (pre) {
  15576. joinPre(pre.previousSibling, pre);
  15577. });
  15578. }
  15579. });
  15580. var each$9 = Tools.each;
  15581. var isElementNode = function (node) {
  15582. return isElement$1(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus(node);
  15583. };
  15584. var findElementSibling = function (node, siblingName) {
  15585. var sibling;
  15586. for (sibling = node; sibling; sibling = sibling[siblingName]) {
  15587. if (isText$1(sibling) && sibling.nodeValue.length !== 0) {
  15588. return node;
  15589. }
  15590. if (isElement$1(sibling) && !isBookmarkNode$1(sibling)) {
  15591. return sibling;
  15592. }
  15593. }
  15594. return node;
  15595. };
  15596. var mergeSiblingsNodes = function (dom, prev, next) {
  15597. var sibling, tmpSibling;
  15598. var elementUtils = new ElementUtils(dom);
  15599. if (prev && next) {
  15600. prev = findElementSibling(prev, 'previousSibling');
  15601. next = findElementSibling(next, 'nextSibling');
  15602. if (elementUtils.compare(prev, next)) {
  15603. for (sibling = prev.nextSibling; sibling && sibling !== next;) {
  15604. tmpSibling = sibling;
  15605. sibling = sibling.nextSibling;
  15606. prev.appendChild(tmpSibling);
  15607. }
  15608. dom.remove(next);
  15609. Tools.each(Tools.grep(next.childNodes), function (node) {
  15610. prev.appendChild(node);
  15611. });
  15612. return prev;
  15613. }
  15614. }
  15615. return next;
  15616. };
  15617. var mergeSiblings = function (dom, format, vars, node) {
  15618. if (node && format.merge_siblings !== false) {
  15619. var newNode = mergeSiblingsNodes(dom, getNonWhiteSpaceSibling(node), node);
  15620. mergeSiblingsNodes(dom, newNode, getNonWhiteSpaceSibling(newNode, true));
  15621. }
  15622. };
  15623. var clearChildStyles = function (dom, format, node) {
  15624. if (format.clear_child_styles) {
  15625. var selector = format.links ? '*:not(a)' : '*';
  15626. each$9(dom.select(selector, node), function (node) {
  15627. if (isElementNode(node)) {
  15628. each$9(format.styles, function (value, name) {
  15629. dom.setStyle(node, name, '');
  15630. });
  15631. }
  15632. });
  15633. }
  15634. };
  15635. var processChildElements = function (node, filter, process) {
  15636. each$9(node.childNodes, function (node) {
  15637. if (isElementNode(node)) {
  15638. if (filter(node)) {
  15639. process(node);
  15640. }
  15641. if (node.hasChildNodes()) {
  15642. processChildElements(node, filter, process);
  15643. }
  15644. }
  15645. });
  15646. };
  15647. var unwrapEmptySpan = function (dom, node) {
  15648. if (node.nodeName === 'SPAN' && dom.getAttribs(node).length === 0) {
  15649. dom.remove(node, true);
  15650. }
  15651. };
  15652. var hasStyle = function (dom, name) {
  15653. return function (node) {
  15654. return !!(node && getStyle(dom, node, name));
  15655. };
  15656. };
  15657. var applyStyle = function (dom, name, value) {
  15658. return function (node) {
  15659. dom.setStyle(node, name, value);
  15660. if (node.getAttribute('style') === '') {
  15661. node.removeAttribute('style');
  15662. }
  15663. unwrapEmptySpan(dom, node);
  15664. };
  15665. };
  15666. var removeResult = Adt.generate([
  15667. { keep: [] },
  15668. { rename: ['name'] },
  15669. { removed: [] }
  15670. ]);
  15671. var MCE_ATTR_RE = /^(src|href|style)$/;
  15672. var each$a = Tools.each;
  15673. var isEq$3 = isEq;
  15674. var isTableCellOrRow = function (node) {
  15675. return /^(TR|TH|TD)$/.test(node.nodeName);
  15676. };
  15677. var isChildOfInlineParent = function (dom, node, parent) {
  15678. return dom.isChildOf(node, parent) && node !== parent && !dom.isBlock(parent);
  15679. };
  15680. var getContainer = function (ed, rng, start) {
  15681. var container, offset;
  15682. container = rng[start ? 'startContainer' : 'endContainer'];
  15683. offset = rng[start ? 'startOffset' : 'endOffset'];
  15684. if (isElement$1(container)) {
  15685. var lastIdx = container.childNodes.length - 1;
  15686. if (!start && offset) {
  15687. offset--;
  15688. }
  15689. container = container.childNodes[offset > lastIdx ? lastIdx : offset];
  15690. }
  15691. if (isText$1(container) && start && offset >= container.nodeValue.length) {
  15692. container = new DomTreeWalker(container, ed.getBody()).next() || container;
  15693. }
  15694. if (isText$1(container) && !start && offset === 0) {
  15695. container = new DomTreeWalker(container, ed.getBody()).prev() || container;
  15696. }
  15697. return container;
  15698. };
  15699. var normalizeTableSelection = function (node, start) {
  15700. var prop = start ? 'firstChild' : 'lastChild';
  15701. if (isTableCellOrRow(node) && node[prop]) {
  15702. var childNode = node[prop];
  15703. if (node.nodeName === 'TR') {
  15704. return childNode[prop] || childNode;
  15705. } else {
  15706. return childNode;
  15707. }
  15708. }
  15709. return node;
  15710. };
  15711. var wrap$2 = function (dom, node, name, attrs) {
  15712. var wrapper = dom.create(name, attrs);
  15713. node.parentNode.insertBefore(wrapper, node);
  15714. wrapper.appendChild(node);
  15715. return wrapper;
  15716. };
  15717. var wrapWithSiblings = function (dom, node, next, name, attrs) {
  15718. var start = SugarElement.fromDom(node);
  15719. var wrapper = SugarElement.fromDom(dom.create(name, attrs));
  15720. var siblings = next ? nextSiblings(start) : prevSiblings(start);
  15721. append$1(wrapper, siblings);
  15722. if (next) {
  15723. before(start, wrapper);
  15724. prepend(wrapper, start);
  15725. } else {
  15726. after(start, wrapper);
  15727. append(wrapper, start);
  15728. }
  15729. return wrapper.dom;
  15730. };
  15731. var matchName$1 = function (dom, node, format) {
  15732. if (isEq$3(node, format.inline)) {
  15733. return true;
  15734. }
  15735. if (isEq$3(node, format.block)) {
  15736. return true;
  15737. }
  15738. if (format.selector) {
  15739. return isElement$1(node) && dom.is(node, format.selector);
  15740. }
  15741. };
  15742. var isColorFormatAndAnchor = function (node, format) {
  15743. return format.links && node.nodeName === 'A';
  15744. };
  15745. var find$3 = function (dom, node, next, inc) {
  15746. node = getNonWhiteSpaceSibling(node, next, inc);
  15747. return !node || (node.nodeName === 'BR' || dom.isBlock(node));
  15748. };
  15749. var removeNode$1 = function (ed, node, format) {
  15750. var parentNode = node.parentNode;
  15751. var rootBlockElm;
  15752. var dom = ed.dom, forcedRootBlock = getForcedRootBlock(ed);
  15753. if (format.block) {
  15754. if (!forcedRootBlock) {
  15755. if (dom.isBlock(node) && !dom.isBlock(parentNode)) {
  15756. if (!find$3(dom, node, false) && !find$3(dom, node.firstChild, true, true)) {
  15757. node.insertBefore(dom.create('br'), node.firstChild);
  15758. }
  15759. if (!find$3(dom, node, true) && !find$3(dom, node.lastChild, false, true)) {
  15760. node.appendChild(dom.create('br'));
  15761. }
  15762. }
  15763. } else {
  15764. if (parentNode === dom.getRoot()) {
  15765. if (!format.list_block || !isEq$3(node, format.list_block)) {
  15766. each(from$1(node.childNodes), function (node) {
  15767. if (isValid(ed, forcedRootBlock, node.nodeName.toLowerCase())) {
  15768. if (!rootBlockElm) {
  15769. rootBlockElm = wrap$2(dom, node, forcedRootBlock);
  15770. dom.setAttribs(rootBlockElm, ed.settings.forced_root_block_attrs);
  15771. } else {
  15772. rootBlockElm.appendChild(node);
  15773. }
  15774. } else {
  15775. rootBlockElm = 0;
  15776. }
  15777. });
  15778. }
  15779. }
  15780. }
  15781. }
  15782. if (format.selector && format.inline && !isEq$3(format.inline, node)) {
  15783. return;
  15784. }
  15785. dom.remove(node, true);
  15786. };
  15787. var removeFormatInternal = function (ed, format, vars, node, compareNode) {
  15788. var stylesModified;
  15789. var dom = ed.dom;
  15790. if (!matchName$1(dom, node, format) && !isColorFormatAndAnchor(node, format)) {
  15791. return removeResult.keep();
  15792. }
  15793. var elm = node;
  15794. if (format.inline && format.remove === 'all' && isArray(format.preserve_attributes)) {
  15795. var attrsToPreserve = filter(dom.getAttribs(elm), function (attr) {
  15796. return contains(format.preserve_attributes, attr.name.toLowerCase());
  15797. });
  15798. dom.removeAllAttribs(elm);
  15799. each(attrsToPreserve, function (attr) {
  15800. return dom.setAttrib(elm, attr.name, attr.value);
  15801. });
  15802. if (attrsToPreserve.length > 0) {
  15803. return removeResult.rename('span');
  15804. }
  15805. }
  15806. if (format.remove !== 'all') {
  15807. each$a(format.styles, function (value, name) {
  15808. value = normalizeStyleValue(dom, replaceVars(value, vars), name + '');
  15809. if (isNumber(name)) {
  15810. name = value;
  15811. compareNode = null;
  15812. }
  15813. if (format.remove_similar || (!compareNode || isEq$3(getStyle(dom, compareNode, name), value))) {
  15814. dom.setStyle(elm, name, '');
  15815. }
  15816. stylesModified = true;
  15817. });
  15818. if (stylesModified && dom.getAttrib(elm, 'style') === '') {
  15819. elm.removeAttribute('style');
  15820. elm.removeAttribute('data-mce-style');
  15821. }
  15822. each$a(format.attributes, function (value, name) {
  15823. var valueOut;
  15824. value = replaceVars(value, vars);
  15825. if (isNumber(name)) {
  15826. name = value;
  15827. compareNode = null;
  15828. }
  15829. if (format.remove_similar || (!compareNode || isEq$3(dom.getAttrib(compareNode, name), value))) {
  15830. if (name === 'class') {
  15831. value = dom.getAttrib(elm, name);
  15832. if (value) {
  15833. valueOut = '';
  15834. each(value.split(/\s+/), function (cls) {
  15835. if (/mce\-\w+/.test(cls)) {
  15836. valueOut += (valueOut ? ' ' : '') + cls;
  15837. }
  15838. });
  15839. if (valueOut) {
  15840. dom.setAttrib(elm, name, valueOut);
  15841. return;
  15842. }
  15843. }
  15844. }
  15845. if (name === 'class') {
  15846. elm.removeAttribute('className');
  15847. }
  15848. if (MCE_ATTR_RE.test(name)) {
  15849. elm.removeAttribute('data-mce-' + name);
  15850. }
  15851. elm.removeAttribute(name);
  15852. }
  15853. });
  15854. each$a(format.classes, function (value) {
  15855. value = replaceVars(value, vars);
  15856. if (!compareNode || dom.hasClass(compareNode, value)) {
  15857. dom.removeClass(elm, value);
  15858. }
  15859. });
  15860. var attrs = dom.getAttribs(elm);
  15861. for (var i = 0; i < attrs.length; i++) {
  15862. var attrName = attrs[i].nodeName;
  15863. if (attrName.indexOf('_') !== 0 && attrName.indexOf('data-') !== 0) {
  15864. return removeResult.keep();
  15865. }
  15866. }
  15867. }
  15868. if (format.remove !== 'none') {
  15869. removeNode$1(ed, elm, format);
  15870. return removeResult.removed();
  15871. }
  15872. return removeResult.keep();
  15873. };
  15874. var removeFormat = function (ed, format, vars, node, compareNode) {
  15875. return removeFormatInternal(ed, format, vars, node, compareNode).fold(never, function (newName) {
  15876. ed.dom.rename(node, newName);
  15877. return true;
  15878. }, always);
  15879. };
  15880. var findFormatRoot = function (editor, container, name, vars, similar) {
  15881. var formatRoot;
  15882. each(getParents$1(editor.dom, container.parentNode).reverse(), function (parent) {
  15883. if (!formatRoot && parent.id !== '_start' && parent.id !== '_end') {
  15884. var format = matchNode(editor, parent, name, vars, similar);
  15885. if (format && format.split !== false) {
  15886. formatRoot = parent;
  15887. }
  15888. }
  15889. });
  15890. return formatRoot;
  15891. };
  15892. var removeFormatFromClone = function (editor, format, vars, clone) {
  15893. return removeFormatInternal(editor, format, vars, clone, clone).fold(constant(clone), function (newName) {
  15894. var fragment = editor.dom.createFragment();
  15895. fragment.appendChild(clone);
  15896. return editor.dom.rename(clone, newName);
  15897. }, constant(null));
  15898. };
  15899. var wrapAndSplit = function (editor, formatList, formatRoot, container, target, split, format, vars) {
  15900. var clone, lastClone, firstClone;
  15901. var dom = editor.dom;
  15902. if (formatRoot) {
  15903. var formatRootParent = formatRoot.parentNode;
  15904. for (var parent_1 = container.parentNode; parent_1 && parent_1 !== formatRootParent; parent_1 = parent_1.parentNode) {
  15905. clone = dom.clone(parent_1, false);
  15906. for (var i = 0; i < formatList.length; i++) {
  15907. clone = removeFormatFromClone(editor, formatList[i], vars, clone);
  15908. if (clone === null) {
  15909. break;
  15910. }
  15911. }
  15912. if (clone) {
  15913. if (lastClone) {
  15914. clone.appendChild(lastClone);
  15915. }
  15916. if (!firstClone) {
  15917. firstClone = clone;
  15918. }
  15919. lastClone = clone;
  15920. }
  15921. }
  15922. if (split && (!format.mixed || !dom.isBlock(formatRoot))) {
  15923. container = dom.split(formatRoot, container);
  15924. }
  15925. if (lastClone) {
  15926. target.parentNode.insertBefore(lastClone, target);
  15927. firstClone.appendChild(target);
  15928. if (format.inline) {
  15929. mergeSiblings(dom, format, vars, lastClone);
  15930. }
  15931. }
  15932. }
  15933. return container;
  15934. };
  15935. var remove$6 = function (ed, name, vars, node, similar) {
  15936. var formatList = ed.formatter.get(name);
  15937. var format = formatList[0];
  15938. var contentEditable = true;
  15939. var dom = ed.dom;
  15940. var selection = ed.selection;
  15941. var splitToFormatRoot = function (container) {
  15942. var formatRoot = findFormatRoot(ed, container, name, vars, similar);
  15943. return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format, vars);
  15944. };
  15945. var isRemoveBookmarkNode = function (node) {
  15946. return isBookmarkNode$1(node) && isElement$1(node) && (node.id === '_start' || node.id === '_end');
  15947. };
  15948. var process = function (node) {
  15949. var lastContentEditable, hasContentEditableState;
  15950. if (isElement$1(node) && dom.getContentEditable(node)) {
  15951. lastContentEditable = contentEditable;
  15952. contentEditable = dom.getContentEditable(node) === 'true';
  15953. hasContentEditableState = true;
  15954. }
  15955. var children = from$1(node.childNodes);
  15956. if (contentEditable && !hasContentEditableState) {
  15957. for (var i = 0; i < formatList.length; i++) {
  15958. if (removeFormat(ed, formatList[i], vars, node, node)) {
  15959. break;
  15960. }
  15961. }
  15962. }
  15963. if (format.deep) {
  15964. if (children.length) {
  15965. for (var i = 0; i < children.length; i++) {
  15966. process(children[i]);
  15967. }
  15968. if (hasContentEditableState) {
  15969. contentEditable = lastContentEditable;
  15970. }
  15971. }
  15972. }
  15973. };
  15974. var unwrap = function (start) {
  15975. var node = dom.get(start ? '_start' : '_end');
  15976. var out = node[start ? 'firstChild' : 'lastChild'];
  15977. if (isRemoveBookmarkNode(out)) {
  15978. out = out[start ? 'firstChild' : 'lastChild'];
  15979. }
  15980. if (isText$1(out) && out.data.length === 0) {
  15981. out = start ? node.previousSibling || node.nextSibling : node.nextSibling || node.previousSibling;
  15982. }
  15983. dom.remove(node, true);
  15984. return out;
  15985. };
  15986. var removeRngStyle = function (rng) {
  15987. var startContainer, endContainer;
  15988. var expandedRng = expandRng(ed, rng, formatList, rng.collapsed);
  15989. if (format.split) {
  15990. expandedRng = split$1(expandedRng);
  15991. startContainer = getContainer(ed, expandedRng, true);
  15992. endContainer = getContainer(ed, expandedRng);
  15993. if (startContainer !== endContainer) {
  15994. startContainer = normalizeTableSelection(startContainer, true);
  15995. endContainer = normalizeTableSelection(endContainer, false);
  15996. if (isChildOfInlineParent(dom, startContainer, endContainer)) {
  15997. var marker = Optional.from(startContainer.firstChild).getOr(startContainer);
  15998. splitToFormatRoot(wrapWithSiblings(dom, marker, true, 'span', {
  15999. 'id': '_start',
  16000. 'data-mce-type': 'bookmark'
  16001. }));
  16002. unwrap(true);
  16003. return;
  16004. }
  16005. if (isChildOfInlineParent(dom, endContainer, startContainer)) {
  16006. var marker = Optional.from(endContainer.lastChild).getOr(endContainer);
  16007. splitToFormatRoot(wrapWithSiblings(dom, marker, false, 'span', {
  16008. 'id': '_end',
  16009. 'data-mce-type': 'bookmark'
  16010. }));
  16011. unwrap(false);
  16012. return;
  16013. }
  16014. startContainer = wrap$2(dom, startContainer, 'span', {
  16015. 'id': '_start',
  16016. 'data-mce-type': 'bookmark'
  16017. });
  16018. endContainer = wrap$2(dom, endContainer, 'span', {
  16019. 'id': '_end',
  16020. 'data-mce-type': 'bookmark'
  16021. });
  16022. var newRng = dom.createRng();
  16023. newRng.setStartAfter(startContainer);
  16024. newRng.setEndBefore(endContainer);
  16025. walk$1(dom, newRng, function (nodes) {
  16026. each(nodes, function (n) {
  16027. if (!isBookmarkNode$1(n) && !isBookmarkNode$1(n.parentNode)) {
  16028. splitToFormatRoot(n);
  16029. }
  16030. });
  16031. });
  16032. splitToFormatRoot(startContainer);
  16033. splitToFormatRoot(endContainer);
  16034. startContainer = unwrap(true);
  16035. endContainer = unwrap();
  16036. } else {
  16037. startContainer = endContainer = splitToFormatRoot(startContainer);
  16038. }
  16039. expandedRng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
  16040. expandedRng.startOffset = dom.nodeIndex(startContainer);
  16041. expandedRng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
  16042. expandedRng.endOffset = dom.nodeIndex(endContainer) + 1;
  16043. }
  16044. walk$1(dom, expandedRng, function (nodes) {
  16045. each(nodes, function (node) {
  16046. process(node);
  16047. var textDecorations = [
  16048. 'underline',
  16049. 'line-through',
  16050. 'overline'
  16051. ];
  16052. each(textDecorations, function (decoration) {
  16053. if (isElement$1(node) && ed.dom.getStyle(node, 'text-decoration') === decoration && node.parentNode && getTextDecoration(dom, node.parentNode) === decoration) {
  16054. removeFormat(ed, {
  16055. deep: false,
  16056. exact: true,
  16057. inline: 'span',
  16058. styles: { textDecoration: decoration }
  16059. }, null, node);
  16060. }
  16061. });
  16062. });
  16063. });
  16064. };
  16065. if (node) {
  16066. if (isNode(node)) {
  16067. var rng = dom.createRng();
  16068. rng.setStartBefore(node);
  16069. rng.setEndAfter(node);
  16070. removeRngStyle(rng);
  16071. } else {
  16072. removeRngStyle(node);
  16073. }
  16074. return;
  16075. }
  16076. if (dom.getContentEditable(selection.getNode()) === 'false') {
  16077. node = selection.getNode();
  16078. for (var i = 0; i < formatList.length; i++) {
  16079. if (formatList[i].ceFalseOverride) {
  16080. if (removeFormat(ed, formatList[i], vars, node, node)) {
  16081. break;
  16082. }
  16083. }
  16084. }
  16085. return;
  16086. }
  16087. if (!selection.isCollapsed() || !format.inline || getCellsFromEditor(ed).length) {
  16088. preserve(selection, true, function () {
  16089. runOnRanges(ed, removeRngStyle);
  16090. });
  16091. if (format.inline && match(ed, name, vars, selection.getStart())) {
  16092. moveStart(dom, selection, selection.getRng());
  16093. }
  16094. ed.nodeChanged();
  16095. } else {
  16096. removeCaretFormat(ed, name, vars, similar);
  16097. }
  16098. };
  16099. var each$b = Tools.each;
  16100. var mergeTextDecorationsAndColor = function (dom, format, vars, node) {
  16101. var processTextDecorationsAndColor = function (n) {
  16102. if (n.nodeType === 1 && n.parentNode && n.parentNode.nodeType === 1) {
  16103. var textDecoration = getTextDecoration(dom, n.parentNode);
  16104. if (dom.getStyle(n, 'color') && textDecoration) {
  16105. dom.setStyle(n, 'text-decoration', textDecoration);
  16106. } else if (dom.getStyle(n, 'text-decoration') === textDecoration) {
  16107. dom.setStyle(n, 'text-decoration', null);
  16108. }
  16109. }
  16110. };
  16111. if (format.styles && (format.styles.color || format.styles.textDecoration)) {
  16112. Tools.walk(node, processTextDecorationsAndColor, 'childNodes');
  16113. processTextDecorationsAndColor(node);
  16114. }
  16115. };
  16116. var mergeBackgroundColorAndFontSize = function (dom, format, vars, node) {
  16117. if (format.styles && format.styles.backgroundColor) {
  16118. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'backgroundColor', replaceVars(format.styles.backgroundColor, vars)));
  16119. }
  16120. };
  16121. var mergeSubSup = function (dom, format, vars, node) {
  16122. if (format.inline === 'sub' || format.inline === 'sup') {
  16123. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'fontSize', ''));
  16124. dom.remove(dom.select(format.inline === 'sup' ? 'sub' : 'sup', node), true);
  16125. }
  16126. };
  16127. var mergeWithChildren = function (editor, formatList, vars, node) {
  16128. each$b(formatList, function (format) {
  16129. each$b(editor.dom.select(format.inline, node), function (child) {
  16130. if (!isElementNode(child)) {
  16131. return;
  16132. }
  16133. removeFormat(editor, format, vars, child, format.exact ? child : null);
  16134. });
  16135. clearChildStyles(editor.dom, format, node);
  16136. });
  16137. };
  16138. var mergeWithParents = function (editor, format, name, vars, node) {
  16139. if (matchNode(editor, node.parentNode, name, vars)) {
  16140. if (removeFormat(editor, format, vars, node)) {
  16141. return;
  16142. }
  16143. }
  16144. if (format.merge_with_parents) {
  16145. editor.dom.getParent(node.parentNode, function (parent) {
  16146. if (matchNode(editor, parent, name, vars)) {
  16147. removeFormat(editor, format, vars, node);
  16148. return true;
  16149. }
  16150. });
  16151. }
  16152. };
  16153. var each$c = Tools.each;
  16154. var hasFormatProperty = function (format, prop) {
  16155. return hasNonNullableKey(format, prop);
  16156. };
  16157. var isElementNode$1 = function (node) {
  16158. return node && node.nodeType === 1 && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus(node);
  16159. };
  16160. var canFormatBR = function (editor, format, node, parentName) {
  16161. if (canFormatEmptyLines(editor) && isInlineFormat(format)) {
  16162. var validBRParentElements = __assign(__assign({}, editor.schema.getTextBlockElements()), {
  16163. td: {},
  16164. th: {},
  16165. li: {},
  16166. dt: {},
  16167. dd: {},
  16168. figcaption: {},
  16169. caption: {},
  16170. details: {},
  16171. summary: {}
  16172. });
  16173. var hasCaretNodeSibling = sibling$2(SugarElement.fromDom(node), function (sibling) {
  16174. return isCaretNode(sibling.dom);
  16175. });
  16176. return hasNonNullableKey(validBRParentElements, parentName) && isEmpty(SugarElement.fromDom(node.parentNode), false) && !hasCaretNodeSibling;
  16177. } else {
  16178. return false;
  16179. }
  16180. };
  16181. var applyFormat = function (ed, name, vars, node) {
  16182. var formatList = ed.formatter.get(name);
  16183. var format = formatList[0];
  16184. var isCollapsed = !node && ed.selection.isCollapsed();
  16185. var dom = ed.dom;
  16186. var selection = ed.selection;
  16187. var setElementFormat = function (elm, fmt) {
  16188. fmt = fmt || format;
  16189. if (elm) {
  16190. if (fmt.onformat) {
  16191. fmt.onformat(elm, fmt, vars, node);
  16192. }
  16193. each$c(fmt.styles, function (value, name) {
  16194. dom.setStyle(elm, name, replaceVars(value, vars));
  16195. });
  16196. if (fmt.styles) {
  16197. var styleVal = dom.getAttrib(elm, 'style');
  16198. if (styleVal) {
  16199. dom.setAttrib(elm, 'data-mce-style', styleVal);
  16200. }
  16201. }
  16202. each$c(fmt.attributes, function (value, name) {
  16203. dom.setAttrib(elm, name, replaceVars(value, vars));
  16204. });
  16205. each$c(fmt.classes, function (value) {
  16206. value = replaceVars(value, vars);
  16207. if (!dom.hasClass(elm, value)) {
  16208. dom.addClass(elm, value);
  16209. }
  16210. });
  16211. }
  16212. };
  16213. var applyNodeStyle = function (formatList, node) {
  16214. var found = false;
  16215. if (!isSelectorFormat(format)) {
  16216. return false;
  16217. }
  16218. each$c(formatList, function (format) {
  16219. if ('collapsed' in format && format.collapsed !== isCollapsed) {
  16220. return;
  16221. }
  16222. if (dom.is(node, format.selector) && !isCaretNode(node)) {
  16223. setElementFormat(node, format);
  16224. found = true;
  16225. return false;
  16226. }
  16227. });
  16228. return found;
  16229. };
  16230. var applyRngStyle = function (dom, rng, bookmark, nodeSpecific) {
  16231. var newWrappers = [];
  16232. var contentEditable = true;
  16233. var wrapName = format.inline || format.block;
  16234. var wrapElm = dom.create(wrapName);
  16235. setElementFormat(wrapElm);
  16236. walk$1(dom, rng, function (nodes) {
  16237. var currentWrapElm;
  16238. var process = function (node) {
  16239. var hasContentEditableState = false;
  16240. var lastContentEditable = contentEditable;
  16241. var nodeName = node.nodeName.toLowerCase();
  16242. var parentName = node.parentNode.nodeName.toLowerCase();
  16243. if (isElement$1(node) && dom.getContentEditable(node)) {
  16244. lastContentEditable = contentEditable;
  16245. contentEditable = dom.getContentEditable(node) === 'true';
  16246. hasContentEditableState = true;
  16247. }
  16248. if (isBr(node) && !canFormatBR(ed, format, node, parentName)) {
  16249. currentWrapElm = null;
  16250. if (isBlockFormat(format)) {
  16251. dom.remove(node);
  16252. }
  16253. return;
  16254. }
  16255. if (format.wrapper && matchNode(ed, node, name, vars)) {
  16256. currentWrapElm = null;
  16257. return;
  16258. }
  16259. if (contentEditable && !hasContentEditableState && isBlockFormat(format) && !format.wrapper && isTextBlock$1(ed, nodeName) && isValid(ed, parentName, wrapName)) {
  16260. var elm = dom.rename(node, wrapName);
  16261. setElementFormat(elm);
  16262. newWrappers.push(elm);
  16263. currentWrapElm = null;
  16264. return;
  16265. }
  16266. if (isSelectorFormat(format)) {
  16267. var found = applyNodeStyle(formatList, node);
  16268. if (!hasFormatProperty(format, 'inline') || found) {
  16269. currentWrapElm = null;
  16270. return;
  16271. }
  16272. }
  16273. 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) && (!hasFormatProperty(format, 'inline') || !dom.isBlock(node))) {
  16274. if (!currentWrapElm) {
  16275. currentWrapElm = dom.clone(wrapElm, false);
  16276. node.parentNode.insertBefore(currentWrapElm, node);
  16277. newWrappers.push(currentWrapElm);
  16278. }
  16279. currentWrapElm.appendChild(node);
  16280. } else {
  16281. currentWrapElm = null;
  16282. each$c(Tools.grep(node.childNodes), process);
  16283. if (hasContentEditableState) {
  16284. contentEditable = lastContentEditable;
  16285. }
  16286. currentWrapElm = null;
  16287. }
  16288. };
  16289. each$c(nodes, process);
  16290. });
  16291. if (format.links === true) {
  16292. each$c(newWrappers, function (node) {
  16293. var process = function (node) {
  16294. if (node.nodeName === 'A') {
  16295. setElementFormat(node, format);
  16296. }
  16297. each$c(Tools.grep(node.childNodes), process);
  16298. };
  16299. process(node);
  16300. });
  16301. }
  16302. each$c(newWrappers, function (node) {
  16303. var getChildCount = function (node) {
  16304. var count = 0;
  16305. each$c(node.childNodes, function (node) {
  16306. if (!isEmptyTextNode(node) && !isBookmarkNode$1(node)) {
  16307. count++;
  16308. }
  16309. });
  16310. return count;
  16311. };
  16312. var getChildElementNode = function (root) {
  16313. var child = false;
  16314. each$c(root.childNodes, function (node) {
  16315. if (isElementNode$1(node)) {
  16316. child = node;
  16317. return false;
  16318. }
  16319. });
  16320. return child;
  16321. };
  16322. var mergeStyles = function (node) {
  16323. var clone;
  16324. var child = getChildElementNode(node);
  16325. if (child && !isBookmarkNode$1(child) && matchName(dom, child, format)) {
  16326. clone = dom.clone(child, false);
  16327. setElementFormat(clone);
  16328. dom.replace(clone, node, true);
  16329. dom.remove(child, true);
  16330. }
  16331. return clone || node;
  16332. };
  16333. var childCount = getChildCount(node);
  16334. if ((newWrappers.length > 1 || !dom.isBlock(node)) && childCount === 0) {
  16335. dom.remove(node, true);
  16336. return;
  16337. }
  16338. if (isInlineFormat(format) || format.wrapper) {
  16339. if (!format.exact && childCount === 1) {
  16340. node = mergeStyles(node);
  16341. }
  16342. mergeWithChildren(ed, formatList, vars, node);
  16343. mergeWithParents(ed, format, name, vars, node);
  16344. mergeBackgroundColorAndFontSize(dom, format, vars, node);
  16345. mergeTextDecorationsAndColor(dom, format, vars, node);
  16346. mergeSubSup(dom, format, vars, node);
  16347. mergeSiblings(dom, format, vars, node);
  16348. }
  16349. });
  16350. };
  16351. if (dom.getContentEditable(selection.getNode()) === 'false') {
  16352. node = selection.getNode();
  16353. for (var i = 0, l = formatList.length; i < l; i++) {
  16354. var formatItem = formatList[i];
  16355. if (formatItem.ceFalseOverride && isSelectorFormat(formatItem) && dom.is(node, formatItem.selector)) {
  16356. setElementFormat(node, formatItem);
  16357. return;
  16358. }
  16359. }
  16360. return;
  16361. }
  16362. if (format) {
  16363. if (node) {
  16364. if (isNode(node)) {
  16365. if (!applyNodeStyle(formatList, node)) {
  16366. var rng = dom.createRng();
  16367. rng.setStartBefore(node);
  16368. rng.setEndAfter(node);
  16369. applyRngStyle(dom, expandRng(ed, rng, formatList), null, true);
  16370. }
  16371. } else {
  16372. applyRngStyle(dom, node, null, true);
  16373. }
  16374. } else {
  16375. if (!isCollapsed || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  16376. var curSelNode = selection.getNode();
  16377. var firstFormat = formatList[0];
  16378. if (!ed.settings.forced_root_block && firstFormat.defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) {
  16379. applyFormat(ed, firstFormat.defaultBlock);
  16380. }
  16381. selection.setRng(normalize$2(selection.getRng()));
  16382. preserve(selection, true, function (bookmark) {
  16383. runOnRanges(ed, function (selectionRng, fake) {
  16384. var expandedRng = fake ? selectionRng : expandRng(ed, selectionRng, formatList);
  16385. applyRngStyle(dom, expandedRng);
  16386. });
  16387. });
  16388. moveStart(dom, selection, selection.getRng());
  16389. ed.nodeChanged();
  16390. } else {
  16391. applyCaretFormat(ed, name, vars);
  16392. }
  16393. }
  16394. postProcess(name, ed);
  16395. }
  16396. };
  16397. var setup$4 = function (registeredFormatListeners, editor) {
  16398. var currentFormats = Cell({});
  16399. registeredFormatListeners.set({});
  16400. editor.on('NodeChange', function (e) {
  16401. updateAndFireChangeCallbacks(editor, e.element, currentFormats, registeredFormatListeners.get());
  16402. });
  16403. };
  16404. var updateAndFireChangeCallbacks = function (editor, elm, currentFormats, formatChangeData) {
  16405. var formatsList = keys(currentFormats.get());
  16406. var newFormats = {};
  16407. var matchedFormats = {};
  16408. var parents = filter(getParents$1(editor.dom, elm), function (node) {
  16409. return node.nodeType === 1 && !node.getAttribute('data-mce-bogus');
  16410. });
  16411. each$1(formatChangeData, function (data, format) {
  16412. Tools.each(parents, function (node) {
  16413. if (editor.formatter.matchNode(node, format, {}, data.similar)) {
  16414. if (formatsList.indexOf(format) === -1) {
  16415. each(data.callbacks, function (callback) {
  16416. callback(true, {
  16417. node: node,
  16418. format: format,
  16419. parents: parents
  16420. });
  16421. });
  16422. newFormats[format] = data.callbacks;
  16423. }
  16424. matchedFormats[format] = data.callbacks;
  16425. return false;
  16426. }
  16427. if (matchesUnInheritedFormatSelector(editor, node, format)) {
  16428. return false;
  16429. }
  16430. });
  16431. });
  16432. var remainingFormats = filterRemainingFormats(currentFormats.get(), matchedFormats, elm, parents);
  16433. currentFormats.set(__assign(__assign({}, newFormats), remainingFormats));
  16434. };
  16435. var filterRemainingFormats = function (currentFormats, matchedFormats, elm, parents) {
  16436. return bifilter(currentFormats, function (callbacks, format) {
  16437. if (!has(matchedFormats, format)) {
  16438. each(callbacks, function (callback) {
  16439. callback(false, {
  16440. node: elm,
  16441. format: format,
  16442. parents: parents
  16443. });
  16444. });
  16445. return false;
  16446. } else {
  16447. return true;
  16448. }
  16449. }).t;
  16450. };
  16451. var addListeners = function (registeredFormatListeners, formats, callback, similar) {
  16452. var formatChangeItems = registeredFormatListeners.get();
  16453. each(formats.split(','), function (format) {
  16454. if (!formatChangeItems[format]) {
  16455. formatChangeItems[format] = {
  16456. similar: similar,
  16457. callbacks: []
  16458. };
  16459. }
  16460. formatChangeItems[format].callbacks.push(callback);
  16461. });
  16462. registeredFormatListeners.set(formatChangeItems);
  16463. };
  16464. var removeListeners = function (registeredFormatListeners, formats, callback) {
  16465. var formatChangeItems = registeredFormatListeners.get();
  16466. each(formats.split(','), function (format) {
  16467. formatChangeItems[format].callbacks = filter(formatChangeItems[format].callbacks, function (c) {
  16468. return c !== callback;
  16469. });
  16470. if (formatChangeItems[format].callbacks.length === 0) {
  16471. delete formatChangeItems[format];
  16472. }
  16473. });
  16474. registeredFormatListeners.set(formatChangeItems);
  16475. };
  16476. var formatChangedInternal = function (editor, registeredFormatListeners, formats, callback, similar) {
  16477. if (registeredFormatListeners.get() === null) {
  16478. setup$4(registeredFormatListeners, editor);
  16479. }
  16480. addListeners(registeredFormatListeners, formats, callback, similar);
  16481. return {
  16482. unbind: function () {
  16483. return removeListeners(registeredFormatListeners, formats, callback);
  16484. }
  16485. };
  16486. };
  16487. var toggle = function (editor, name, vars, node) {
  16488. var fmt = editor.formatter.get(name);
  16489. if (match(editor, name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) {
  16490. remove$6(editor, name, vars, node);
  16491. } else {
  16492. applyFormat(editor, name, vars, node);
  16493. }
  16494. };
  16495. var fromElements = function (elements, scope) {
  16496. var doc = scope || document;
  16497. var fragment = doc.createDocumentFragment();
  16498. each(elements, function (element) {
  16499. fragment.appendChild(element.dom);
  16500. });
  16501. return SugarElement.fromDom(fragment);
  16502. };
  16503. var tableModel = function (element, width, rows) {
  16504. return {
  16505. element: element,
  16506. width: width,
  16507. rows: rows
  16508. };
  16509. };
  16510. var tableRow = function (element, cells) {
  16511. return {
  16512. element: element,
  16513. cells: cells
  16514. };
  16515. };
  16516. var cellPosition = function (x, y) {
  16517. return {
  16518. x: x,
  16519. y: y
  16520. };
  16521. };
  16522. var getSpan = function (td, key) {
  16523. var value = parseInt(get$4(td, key), 10);
  16524. return isNaN(value) ? 1 : value;
  16525. };
  16526. var fillout = function (table, x, y, tr, td) {
  16527. var rowspan = getSpan(td, 'rowspan');
  16528. var colspan = getSpan(td, 'colspan');
  16529. var rows = table.rows;
  16530. for (var y2 = y; y2 < y + rowspan; y2++) {
  16531. if (!rows[y2]) {
  16532. rows[y2] = tableRow(deep(tr), []);
  16533. }
  16534. for (var x2 = x; x2 < x + colspan; x2++) {
  16535. var cells = rows[y2].cells;
  16536. cells[x2] = y2 === y && x2 === x ? td : shallow(td);
  16537. }
  16538. }
  16539. };
  16540. var cellExists = function (table, x, y) {
  16541. var rows = table.rows;
  16542. var cells = rows[y] ? rows[y].cells : [];
  16543. return !!cells[x];
  16544. };
  16545. var skipCellsX = function (table, x, y) {
  16546. while (cellExists(table, x, y)) {
  16547. x++;
  16548. }
  16549. return x;
  16550. };
  16551. var getWidth = function (rows) {
  16552. return foldl(rows, function (acc, row) {
  16553. return row.cells.length > acc ? row.cells.length : acc;
  16554. }, 0);
  16555. };
  16556. var findElementPos = function (table, element) {
  16557. var rows = table.rows;
  16558. for (var y = 0; y < rows.length; y++) {
  16559. var cells = rows[y].cells;
  16560. for (var x = 0; x < cells.length; x++) {
  16561. if (eq$2(cells[x], element)) {
  16562. return Optional.some(cellPosition(x, y));
  16563. }
  16564. }
  16565. }
  16566. return Optional.none();
  16567. };
  16568. var extractRows = function (table, sx, sy, ex, ey) {
  16569. var newRows = [];
  16570. var rows = table.rows;
  16571. for (var y = sy; y <= ey; y++) {
  16572. var cells = rows[y].cells;
  16573. var slice = sx < ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
  16574. newRows.push(tableRow(rows[y].element, slice));
  16575. }
  16576. return newRows;
  16577. };
  16578. var subTable = function (table, startPos, endPos) {
  16579. var sx = startPos.x, sy = startPos.y;
  16580. var ex = endPos.x, ey = endPos.y;
  16581. var newRows = sy < ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
  16582. return tableModel(table.element, getWidth(newRows), newRows);
  16583. };
  16584. var createDomTable = function (table, rows) {
  16585. var tableElement = shallow(table.element);
  16586. var tableBody = SugarElement.fromTag('tbody');
  16587. append$1(tableBody, rows);
  16588. append(tableElement, tableBody);
  16589. return tableElement;
  16590. };
  16591. var modelRowsToDomRows = function (table) {
  16592. return map(table.rows, function (row) {
  16593. var cells = map(row.cells, function (cell) {
  16594. var td = deep(cell);
  16595. remove$1(td, 'colspan');
  16596. remove$1(td, 'rowspan');
  16597. return td;
  16598. });
  16599. var tr = shallow(row.element);
  16600. append$1(tr, cells);
  16601. return tr;
  16602. });
  16603. };
  16604. var fromDom$1 = function (tableElm) {
  16605. var table = tableModel(shallow(tableElm), 0, []);
  16606. each(descendants$1(tableElm, 'tr'), function (tr, y) {
  16607. each(descendants$1(tr, 'td,th'), function (td, x) {
  16608. fillout(table, skipCellsX(table, x, y), y, tr, td);
  16609. });
  16610. });
  16611. return tableModel(table.element, getWidth(table.rows), table.rows);
  16612. };
  16613. var toDom = function (table) {
  16614. return createDomTable(table, modelRowsToDomRows(table));
  16615. };
  16616. var subsection = function (table, startElement, endElement) {
  16617. return findElementPos(table, startElement).bind(function (startPos) {
  16618. return findElementPos(table, endElement).map(function (endPos) {
  16619. return subTable(table, startPos, endPos);
  16620. });
  16621. });
  16622. };
  16623. var findParentListContainer = function (parents) {
  16624. return find(parents, function (elm) {
  16625. return name(elm) === 'ul' || name(elm) === 'ol';
  16626. });
  16627. };
  16628. var getFullySelectedListWrappers = function (parents, rng) {
  16629. return find(parents, function (elm) {
  16630. return name(elm) === 'li' && hasAllContentsSelected(elm, rng);
  16631. }).fold(constant([]), function (_li) {
  16632. return findParentListContainer(parents).map(function (listCont) {
  16633. var listElm = SugarElement.fromTag(name(listCont));
  16634. var listStyles = filter$1(getAllRaw(listCont), function (_style, name) {
  16635. return startsWith(name, 'list-style');
  16636. });
  16637. setAll$1(listElm, listStyles);
  16638. return [
  16639. SugarElement.fromTag('li'),
  16640. listElm
  16641. ];
  16642. }).getOr([]);
  16643. });
  16644. };
  16645. var wrap$3 = function (innerElm, elms) {
  16646. var wrapped = foldl(elms, function (acc, elm) {
  16647. append(elm, acc);
  16648. return elm;
  16649. }, innerElm);
  16650. return elms.length > 0 ? fromElements([wrapped]) : wrapped;
  16651. };
  16652. var directListWrappers = function (commonAnchorContainer) {
  16653. if (isListItem(commonAnchorContainer)) {
  16654. return parent(commonAnchorContainer).filter(isList).fold(constant([]), function (listElm) {
  16655. return [
  16656. commonAnchorContainer,
  16657. listElm
  16658. ];
  16659. });
  16660. } else {
  16661. return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
  16662. }
  16663. };
  16664. var getWrapElements = function (rootNode, rng) {
  16665. var commonAnchorContainer = SugarElement.fromDom(rng.commonAncestorContainer);
  16666. var parents = parentsAndSelf(commonAnchorContainer, rootNode);
  16667. var wrapElements = filter(parents, function (elm) {
  16668. return isInline(elm) || isHeading(elm);
  16669. });
  16670. var listWrappers = getFullySelectedListWrappers(parents, rng);
  16671. var allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
  16672. return map(allWrappers, shallow);
  16673. };
  16674. var emptyFragment = function () {
  16675. return fromElements([]);
  16676. };
  16677. var getFragmentFromRange = function (rootNode, rng) {
  16678. return wrap$3(SugarElement.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
  16679. };
  16680. var getParentTable = function (rootElm, cell) {
  16681. return ancestor$1(cell, 'table', curry(eq$2, rootElm));
  16682. };
  16683. var getTableFragment = function (rootNode, selectedTableCells) {
  16684. return getParentTable(rootNode, selectedTableCells[0]).bind(function (tableElm) {
  16685. var firstCell = selectedTableCells[0];
  16686. var lastCell = selectedTableCells[selectedTableCells.length - 1];
  16687. var fullTableModel = fromDom$1(tableElm);
  16688. return subsection(fullTableModel, firstCell, lastCell).map(function (sectionedTableModel) {
  16689. return fromElements([toDom(sectionedTableModel)]);
  16690. });
  16691. }).getOrThunk(emptyFragment);
  16692. };
  16693. var getSelectionFragment = function (rootNode, ranges) {
  16694. return ranges.length > 0 && ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
  16695. };
  16696. var read$1 = function (rootNode, ranges) {
  16697. var selectedCells = getCellsFromElementOrRanges(ranges, rootNode);
  16698. return selectedCells.length > 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
  16699. };
  16700. var trimLeadingCollapsibleText = function (text) {
  16701. return text.replace(/^[ \f\n\r\t\v]+/, '');
  16702. };
  16703. var isCollapsibleWhitespace = function (text, index) {
  16704. return index >= 0 && index < text.length && isWhiteSpace$1(text.charAt(index));
  16705. };
  16706. var getInnerText = function (bin, shouldTrim) {
  16707. var text = trim$2(bin.innerText);
  16708. return shouldTrim ? trimLeadingCollapsibleText(text) : text;
  16709. };
  16710. var getContextNodeName = function (parentBlockOpt) {
  16711. return parentBlockOpt.map(function (block) {
  16712. return block.nodeName;
  16713. }).getOr('div').toLowerCase();
  16714. };
  16715. var getTextContent = function (editor) {
  16716. return Optional.from(editor.selection.getRng()).map(function (rng) {
  16717. var parentBlockOpt = Optional.from(editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock));
  16718. var body = editor.getBody();
  16719. var contextNodeName = getContextNodeName(parentBlockOpt);
  16720. var shouldTrimSpaces = Env.browser.isIE() && contextNodeName !== 'pre';
  16721. var bin = editor.dom.add(body, contextNodeName, {
  16722. 'data-mce-bogus': 'all',
  16723. 'style': 'overflow: hidden; opacity: 0;'
  16724. }, rng.cloneContents());
  16725. var text = getInnerText(bin, shouldTrimSpaces);
  16726. var nonRenderedText = trim$2(bin.textContent);
  16727. editor.dom.remove(bin);
  16728. if (isCollapsibleWhitespace(nonRenderedText, 0) || isCollapsibleWhitespace(nonRenderedText, nonRenderedText.length - 1)) {
  16729. var parentBlock = parentBlockOpt.getOr(body);
  16730. var parentBlockText = getInnerText(parentBlock, shouldTrimSpaces);
  16731. var textIndex = parentBlockText.indexOf(text);
  16732. if (textIndex === -1) {
  16733. return text;
  16734. } else {
  16735. var hasProceedingSpace = isCollapsibleWhitespace(parentBlockText, textIndex - 1);
  16736. var hasTrailingSpace = isCollapsibleWhitespace(parentBlockText, textIndex + text.length);
  16737. return (hasProceedingSpace ? ' ' : '') + text + (hasTrailingSpace ? ' ' : '');
  16738. }
  16739. } else {
  16740. return text;
  16741. }
  16742. }).getOr('');
  16743. };
  16744. var getSerializedContent = function (editor, args) {
  16745. var rng = editor.selection.getRng(), tmpElm = editor.dom.create('body');
  16746. var sel = editor.selection.getSel();
  16747. var ranges = processRanges(editor, getRanges(sel));
  16748. var fragment = args.contextual ? read$1(SugarElement.fromDom(editor.getBody()), ranges).dom : rng.cloneContents();
  16749. if (fragment) {
  16750. tmpElm.appendChild(fragment);
  16751. }
  16752. return editor.selection.serializer.serialize(tmpElm, args);
  16753. };
  16754. var getSelectedContentInternal = function (editor, format, args) {
  16755. if (args === void 0) {
  16756. args = {};
  16757. }
  16758. args.get = true;
  16759. args.format = format;
  16760. args.selection = true;
  16761. args = editor.fire('BeforeGetContent', args);
  16762. if (args.isDefaultPrevented()) {
  16763. editor.fire('GetContent', args);
  16764. return args.content;
  16765. }
  16766. if (args.format === 'text') {
  16767. return getTextContent(editor);
  16768. } else {
  16769. args.getInner = true;
  16770. var content = getSerializedContent(editor, args);
  16771. if (args.format === 'tree') {
  16772. return content;
  16773. } else {
  16774. args.content = editor.selection.isCollapsed() ? '' : content;
  16775. editor.fire('GetContent', args);
  16776. return args.content;
  16777. }
  16778. }
  16779. };
  16780. var KEEP = 0, INSERT = 1, DELETE = 2;
  16781. var diff = function (left, right) {
  16782. var size = left.length + right.length + 2;
  16783. var vDown = new Array(size);
  16784. var vUp = new Array(size);
  16785. var snake = function (start, end, diag) {
  16786. return {
  16787. start: start,
  16788. end: end,
  16789. diag: diag
  16790. };
  16791. };
  16792. var buildScript = function (start1, end1, start2, end2, script) {
  16793. var middle = getMiddleSnake(start1, end1, start2, end2);
  16794. if (middle === null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) {
  16795. var i = start1;
  16796. var j = start2;
  16797. while (i < end1 || j < end2) {
  16798. if (i < end1 && j < end2 && left[i] === right[j]) {
  16799. script.push([
  16800. KEEP,
  16801. left[i]
  16802. ]);
  16803. ++i;
  16804. ++j;
  16805. } else {
  16806. if (end1 - start1 > end2 - start2) {
  16807. script.push([
  16808. DELETE,
  16809. left[i]
  16810. ]);
  16811. ++i;
  16812. } else {
  16813. script.push([
  16814. INSERT,
  16815. right[j]
  16816. ]);
  16817. ++j;
  16818. }
  16819. }
  16820. }
  16821. } else {
  16822. buildScript(start1, middle.start, start2, middle.start - middle.diag, script);
  16823. for (var i2 = middle.start; i2 < middle.end; ++i2) {
  16824. script.push([
  16825. KEEP,
  16826. left[i2]
  16827. ]);
  16828. }
  16829. buildScript(middle.end, end1, middle.end - middle.diag, end2, script);
  16830. }
  16831. };
  16832. var buildSnake = function (start, diag, end1, end2) {
  16833. var end = start;
  16834. while (end - diag < end2 && end < end1 && left[end] === right[end - diag]) {
  16835. ++end;
  16836. }
  16837. return snake(start, end, diag);
  16838. };
  16839. var getMiddleSnake = function (start1, end1, start2, end2) {
  16840. var m = end1 - start1;
  16841. var n = end2 - start2;
  16842. if (m === 0 || n === 0) {
  16843. return null;
  16844. }
  16845. var delta = m - n;
  16846. var sum = n + m;
  16847. var offset = (sum % 2 === 0 ? sum : sum + 1) / 2;
  16848. vDown[1 + offset] = start1;
  16849. vUp[1 + offset] = end1 + 1;
  16850. var d, k, i, x, y;
  16851. for (d = 0; d <= offset; ++d) {
  16852. for (k = -d; k <= d; k += 2) {
  16853. i = k + offset;
  16854. if (k === -d || k !== d && vDown[i - 1] < vDown[i + 1]) {
  16855. vDown[i] = vDown[i + 1];
  16856. } else {
  16857. vDown[i] = vDown[i - 1] + 1;
  16858. }
  16859. x = vDown[i];
  16860. y = x - start1 + start2 - k;
  16861. while (x < end1 && y < end2 && left[x] === right[y]) {
  16862. vDown[i] = ++x;
  16863. ++y;
  16864. }
  16865. if (delta % 2 !== 0 && delta - d <= k && k <= delta + d) {
  16866. if (vUp[i - delta] <= vDown[i]) {
  16867. return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2);
  16868. }
  16869. }
  16870. }
  16871. for (k = delta - d; k <= delta + d; k += 2) {
  16872. i = k + offset - delta;
  16873. if (k === delta - d || k !== delta + d && vUp[i + 1] <= vUp[i - 1]) {
  16874. vUp[i] = vUp[i + 1] - 1;
  16875. } else {
  16876. vUp[i] = vUp[i - 1];
  16877. }
  16878. x = vUp[i] - 1;
  16879. y = x - start1 + start2 - k;
  16880. while (x >= start1 && y >= start2 && left[x] === right[y]) {
  16881. vUp[i] = x--;
  16882. y--;
  16883. }
  16884. if (delta % 2 === 0 && -d <= k && k <= d) {
  16885. if (vUp[i] <= vDown[i + delta]) {
  16886. return buildSnake(vUp[i], k + start1 - start2, end1, end2);
  16887. }
  16888. }
  16889. }
  16890. }
  16891. };
  16892. var script = [];
  16893. buildScript(0, left.length, 0, right.length, script);
  16894. return script;
  16895. };
  16896. var getOuterHtml = function (elm) {
  16897. if (isElement$1(elm)) {
  16898. return elm.outerHTML;
  16899. } else if (isText$1(elm)) {
  16900. return Entities.encodeRaw(elm.data, false);
  16901. } else if (isComment$1(elm)) {
  16902. return '<!--' + elm.data + '-->';
  16903. }
  16904. return '';
  16905. };
  16906. var createFragment$1 = function (html) {
  16907. var node;
  16908. var container = document.createElement('div');
  16909. var frag = document.createDocumentFragment();
  16910. if (html) {
  16911. container.innerHTML = html;
  16912. }
  16913. while (node = container.firstChild) {
  16914. frag.appendChild(node);
  16915. }
  16916. return frag;
  16917. };
  16918. var insertAt = function (elm, html, index) {
  16919. var fragment = createFragment$1(html);
  16920. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  16921. var target = elm.childNodes[index];
  16922. target.parentNode.insertBefore(fragment, target);
  16923. } else {
  16924. elm.appendChild(fragment);
  16925. }
  16926. };
  16927. var removeAt = function (elm, index) {
  16928. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  16929. var target = elm.childNodes[index];
  16930. target.parentNode.removeChild(target);
  16931. }
  16932. };
  16933. var applyDiff = function (diff, elm) {
  16934. var index = 0;
  16935. each(diff, function (action) {
  16936. if (action[0] === KEEP) {
  16937. index++;
  16938. } else if (action[0] === INSERT) {
  16939. insertAt(elm, action[1], index);
  16940. index++;
  16941. } else if (action[0] === DELETE) {
  16942. removeAt(elm, index);
  16943. }
  16944. });
  16945. };
  16946. var read$2 = function (elm) {
  16947. return filter(map(from$1(elm.childNodes), getOuterHtml), function (item) {
  16948. return item.length > 0;
  16949. });
  16950. };
  16951. var write = function (fragments, elm) {
  16952. var currentFragments = map(from$1(elm.childNodes), getOuterHtml);
  16953. applyDiff(diff(currentFragments, fragments), elm);
  16954. return elm;
  16955. };
  16956. var undoLevelDocument = Cell(Optional.none());
  16957. var lazyTempDocument = function () {
  16958. return undoLevelDocument.get().getOrThunk(function () {
  16959. var doc = document.implementation.createHTMLDocument('undo');
  16960. undoLevelDocument.set(Optional.some(doc));
  16961. return doc;
  16962. });
  16963. };
  16964. var hasIframes = function (html) {
  16965. return html.indexOf('</iframe>') !== -1;
  16966. };
  16967. var createFragmentedLevel = function (fragments) {
  16968. return {
  16969. type: 'fragmented',
  16970. fragments: fragments,
  16971. content: '',
  16972. bookmark: null,
  16973. beforeBookmark: null
  16974. };
  16975. };
  16976. var createCompleteLevel = function (content) {
  16977. return {
  16978. type: 'complete',
  16979. fragments: null,
  16980. content: content,
  16981. bookmark: null,
  16982. beforeBookmark: null
  16983. };
  16984. };
  16985. var createFromEditor = function (editor) {
  16986. var fragments = read$2(editor.getBody());
  16987. var trimmedFragments = bind(fragments, function (html) {
  16988. var trimmed = trimInternal(editor.serializer, html);
  16989. return trimmed.length > 0 ? [trimmed] : [];
  16990. });
  16991. var content = trimmedFragments.join('');
  16992. return hasIframes(content) ? createFragmentedLevel(trimmedFragments) : createCompleteLevel(content);
  16993. };
  16994. var applyToEditor = function (editor, level, before) {
  16995. if (level.type === 'fragmented') {
  16996. write(level.fragments, editor.getBody());
  16997. } else {
  16998. editor.setContent(level.content, { format: 'raw' });
  16999. }
  17000. editor.selection.moveToBookmark(before ? level.beforeBookmark : level.bookmark);
  17001. };
  17002. var getLevelContent = function (level) {
  17003. return level.type === 'fragmented' ? level.fragments.join('') : level.content;
  17004. };
  17005. var getCleanLevelContent = function (level) {
  17006. var elm = SugarElement.fromTag('body', lazyTempDocument());
  17007. set$1(elm, getLevelContent(level));
  17008. each(descendants$1(elm, '*[data-mce-bogus]'), unwrap);
  17009. return get$7(elm);
  17010. };
  17011. var hasEqualContent = function (level1, level2) {
  17012. return getLevelContent(level1) === getLevelContent(level2);
  17013. };
  17014. var hasEqualCleanedContent = function (level1, level2) {
  17015. return getCleanLevelContent(level1) === getCleanLevelContent(level2);
  17016. };
  17017. var isEq$4 = function (level1, level2) {
  17018. if (!level1 || !level2) {
  17019. return false;
  17020. } else if (hasEqualContent(level1, level2)) {
  17021. return true;
  17022. } else {
  17023. return hasEqualCleanedContent(level1, level2);
  17024. }
  17025. };
  17026. var isUnlocked = function (locks) {
  17027. return locks.get() === 0;
  17028. };
  17029. var setTyping = function (undoManager, typing, locks) {
  17030. if (isUnlocked(locks)) {
  17031. undoManager.typing = typing;
  17032. }
  17033. };
  17034. var endTyping = function (undoManager, locks) {
  17035. if (undoManager.typing) {
  17036. setTyping(undoManager, false, locks);
  17037. undoManager.add();
  17038. }
  17039. };
  17040. var endTypingLevelIgnoreLocks = function (undoManager) {
  17041. if (undoManager.typing) {
  17042. undoManager.typing = false;
  17043. undoManager.add();
  17044. }
  17045. };
  17046. var beforeChange = function (editor, locks, beforeBookmark) {
  17047. if (isUnlocked(locks)) {
  17048. beforeBookmark.set(Optional.some(getUndoBookmark(editor.selection)));
  17049. }
  17050. };
  17051. var addUndoLevel = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  17052. var currentLevel = createFromEditor(editor);
  17053. level = level || {};
  17054. level = Tools.extend(level, currentLevel);
  17055. if (isUnlocked(locks) === false || editor.removed) {
  17056. return null;
  17057. }
  17058. var lastLevel = undoManager.data[index.get()];
  17059. if (editor.fire('BeforeAddUndo', {
  17060. level: level,
  17061. lastLevel: lastLevel,
  17062. originalEvent: event
  17063. }).isDefaultPrevented()) {
  17064. return null;
  17065. }
  17066. if (lastLevel && isEq$4(lastLevel, level)) {
  17067. return null;
  17068. }
  17069. if (undoManager.data[index.get()]) {
  17070. beforeBookmark.get().each(function (bm) {
  17071. undoManager.data[index.get()].beforeBookmark = bm;
  17072. });
  17073. }
  17074. var customUndoRedoLevels = getCustomUndoRedoLevels(editor);
  17075. if (customUndoRedoLevels) {
  17076. if (undoManager.data.length > customUndoRedoLevels) {
  17077. for (var i = 0; i < undoManager.data.length - 1; i++) {
  17078. undoManager.data[i] = undoManager.data[i + 1];
  17079. }
  17080. undoManager.data.length--;
  17081. index.set(undoManager.data.length);
  17082. }
  17083. }
  17084. level.bookmark = getUndoBookmark(editor.selection);
  17085. if (index.get() < undoManager.data.length - 1) {
  17086. undoManager.data.length = index.get() + 1;
  17087. }
  17088. undoManager.data.push(level);
  17089. index.set(undoManager.data.length - 1);
  17090. var args = {
  17091. level: level,
  17092. lastLevel: lastLevel,
  17093. originalEvent: event
  17094. };
  17095. if (index.get() > 0) {
  17096. editor.setDirty(true);
  17097. editor.fire('AddUndo', args);
  17098. editor.fire('change', args);
  17099. } else {
  17100. editor.fire('AddUndo', args);
  17101. }
  17102. return level;
  17103. };
  17104. var clear = function (editor, undoManager, index) {
  17105. undoManager.data = [];
  17106. index.set(0);
  17107. undoManager.typing = false;
  17108. editor.fire('ClearUndos');
  17109. };
  17110. var extra = function (editor, undoManager, index, callback1, callback2) {
  17111. if (undoManager.transact(callback1)) {
  17112. var bookmark = undoManager.data[index.get()].bookmark;
  17113. var lastLevel = undoManager.data[index.get() - 1];
  17114. applyToEditor(editor, lastLevel, true);
  17115. if (undoManager.transact(callback2)) {
  17116. undoManager.data[index.get() - 1].beforeBookmark = bookmark;
  17117. }
  17118. }
  17119. };
  17120. var redo = function (editor, index, data) {
  17121. var level;
  17122. if (index.get() < data.length - 1) {
  17123. index.set(index.get() + 1);
  17124. level = data[index.get()];
  17125. applyToEditor(editor, level, false);
  17126. editor.setDirty(true);
  17127. editor.fire('Redo', { level: level });
  17128. }
  17129. return level;
  17130. };
  17131. var undo = function (editor, undoManager, locks, index) {
  17132. var level;
  17133. if (undoManager.typing) {
  17134. undoManager.add();
  17135. undoManager.typing = false;
  17136. setTyping(undoManager, false, locks);
  17137. }
  17138. if (index.get() > 0) {
  17139. index.set(index.get() - 1);
  17140. level = undoManager.data[index.get()];
  17141. applyToEditor(editor, level, true);
  17142. editor.setDirty(true);
  17143. editor.fire('Undo', { level: level });
  17144. }
  17145. return level;
  17146. };
  17147. var reset = function (undoManager) {
  17148. undoManager.clear();
  17149. undoManager.add();
  17150. };
  17151. var hasUndo = function (editor, undoManager, index) {
  17152. return index.get() > 0 || undoManager.typing && undoManager.data[0] && !isEq$4(createFromEditor(editor), undoManager.data[0]);
  17153. };
  17154. var hasRedo = function (undoManager, index) {
  17155. return index.get() < undoManager.data.length - 1 && !undoManager.typing;
  17156. };
  17157. var transact = function (undoManager, locks, callback) {
  17158. endTyping(undoManager, locks);
  17159. undoManager.beforeChange();
  17160. undoManager.ignore(callback);
  17161. return undoManager.add();
  17162. };
  17163. var ignore = function (locks, callback) {
  17164. try {
  17165. locks.set(locks.get() + 1);
  17166. callback();
  17167. } finally {
  17168. locks.set(locks.get() - 1);
  17169. }
  17170. };
  17171. var isTreeNode$1 = function (content) {
  17172. return content instanceof AstNode;
  17173. };
  17174. var runSerializerFiltersOnFragment = function (editor, fragment) {
  17175. filter$3(editor.serializer.getNodeFilters(), editor.serializer.getAttributeFilters(), fragment);
  17176. };
  17177. var getInsertContext = function (editor) {
  17178. return Optional.from(editor.selection.getStart(true)).map(function (elm) {
  17179. return elm.nodeName.toLowerCase();
  17180. });
  17181. };
  17182. var createDummyUndoLevel = function () {
  17183. return {
  17184. type: 'complete',
  17185. fragments: [],
  17186. content: '',
  17187. bookmark: null,
  17188. beforeBookmark: null
  17189. };
  17190. };
  17191. var makePlainAdaptor = function (editor) {
  17192. return {
  17193. undoManager: {
  17194. beforeChange: function (locks, beforeBookmark) {
  17195. return beforeChange(editor, locks, beforeBookmark);
  17196. },
  17197. addUndoLevel: function (undoManager, index, locks, beforeBookmark, level, event) {
  17198. return addUndoLevel(editor, undoManager, index, locks, beforeBookmark, level, event);
  17199. },
  17200. undo: function (undoManager, locks, index) {
  17201. return undo(editor, undoManager, locks, index);
  17202. },
  17203. redo: function (index, data) {
  17204. return redo(editor, index, data);
  17205. },
  17206. clear: function (undoManager, index) {
  17207. return clear(editor, undoManager, index);
  17208. },
  17209. reset: function (undoManager) {
  17210. return reset(undoManager);
  17211. },
  17212. hasUndo: function (undoManager, index) {
  17213. return hasUndo(editor, undoManager, index);
  17214. },
  17215. hasRedo: function (undoManager, index) {
  17216. return hasRedo(undoManager, index);
  17217. },
  17218. transact: function (undoManager, locks, callback) {
  17219. return transact(undoManager, locks, callback);
  17220. },
  17221. ignore: function (locks, callback) {
  17222. return ignore(locks, callback);
  17223. },
  17224. extra: function (undoManager, index, callback1, callback2) {
  17225. return extra(editor, undoManager, index, callback1, callback2);
  17226. }
  17227. },
  17228. formatter: {
  17229. match: function (name, vars, node) {
  17230. return match(editor, name, vars, node);
  17231. },
  17232. matchAll: function (names, vars) {
  17233. return matchAll(editor, names, vars);
  17234. },
  17235. matchNode: function (node, name, vars, similar) {
  17236. return matchNode(editor, node, name, vars, similar);
  17237. },
  17238. canApply: function (name) {
  17239. return canApply(editor, name);
  17240. },
  17241. closest: function (names) {
  17242. return closest$3(editor, names);
  17243. },
  17244. apply: function (name, vars, node) {
  17245. return applyFormat(editor, name, vars, node);
  17246. },
  17247. remove: function (name, vars, node, similar) {
  17248. return remove$6(editor, name, vars, node, similar);
  17249. },
  17250. toggle: function (name, vars, node) {
  17251. return toggle(editor, name, vars, node);
  17252. },
  17253. formatChanged: function (registeredFormatListeners, formats, callback, similar) {
  17254. return formatChangedInternal(editor, registeredFormatListeners, formats, callback, similar);
  17255. }
  17256. },
  17257. editor: {
  17258. getContent: function (args, format) {
  17259. return getContentInternal(editor, args, format);
  17260. },
  17261. setContent: function (content, args) {
  17262. return setContentInternal(editor, content, args);
  17263. },
  17264. insertContent: function (value, details) {
  17265. return insertHtmlAtCaret(editor, value, details);
  17266. },
  17267. addVisual: function (elm) {
  17268. return addVisualInternal(editor, elm);
  17269. }
  17270. },
  17271. selection: {
  17272. getContent: function (format, args) {
  17273. return getSelectedContentInternal(editor, format, args);
  17274. }
  17275. },
  17276. raw: {
  17277. getModel: function () {
  17278. return Optional.none();
  17279. }
  17280. }
  17281. };
  17282. };
  17283. var makeRtcAdaptor = function (tinymceEditor, rtcEditor) {
  17284. var defaultVars = function (vars) {
  17285. return isObject(vars) ? vars : {};
  17286. };
  17287. var unsupported = die('Unimplemented feature for rtc');
  17288. var ignore = noop;
  17289. return {
  17290. undoManager: {
  17291. beforeChange: ignore,
  17292. addUndoLevel: unsupported,
  17293. undo: function () {
  17294. rtcEditor.undo();
  17295. return createDummyUndoLevel();
  17296. },
  17297. redo: function () {
  17298. rtcEditor.redo();
  17299. return createDummyUndoLevel();
  17300. },
  17301. clear: unsupported,
  17302. reset: unsupported,
  17303. hasUndo: function () {
  17304. return rtcEditor.hasUndo();
  17305. },
  17306. hasRedo: function () {
  17307. return rtcEditor.hasRedo();
  17308. },
  17309. transact: function (_undoManager, _locks, fn) {
  17310. rtcEditor.transact(fn);
  17311. return createDummyUndoLevel();
  17312. },
  17313. ignore: unsupported,
  17314. extra: unsupported
  17315. },
  17316. formatter: {
  17317. match: function (name, vars, _node) {
  17318. return rtcEditor.matchFormat(name, defaultVars(vars));
  17319. },
  17320. matchAll: unsupported,
  17321. matchNode: unsupported,
  17322. canApply: function (name) {
  17323. return rtcEditor.canApplyFormat(name);
  17324. },
  17325. closest: function (names) {
  17326. return rtcEditor.closestFormat(names);
  17327. },
  17328. apply: function (name, vars, _node) {
  17329. return rtcEditor.applyFormat(name, defaultVars(vars));
  17330. },
  17331. remove: function (name, vars, _node, _similar) {
  17332. return rtcEditor.removeFormat(name, defaultVars(vars));
  17333. },
  17334. toggle: function (name, vars, _node) {
  17335. return rtcEditor.toggleFormat(name, defaultVars(vars));
  17336. },
  17337. formatChanged: function (_rfl, formats, callback, similar) {
  17338. return rtcEditor.formatChanged(formats, callback, similar);
  17339. }
  17340. },
  17341. editor: {
  17342. getContent: function (args, format) {
  17343. if (format === 'html' || format === 'tree') {
  17344. var fragment = rtcEditor.getContent();
  17345. var serializer = HtmlSerializer({ inner: true });
  17346. runSerializerFiltersOnFragment(tinymceEditor, fragment);
  17347. return format === 'tree' ? fragment : serializer.serialize(fragment);
  17348. } else {
  17349. return makePlainAdaptor(tinymceEditor).editor.getContent(args, format);
  17350. }
  17351. },
  17352. setContent: function (content, _args) {
  17353. var fragment = isTreeNode$1(content) ? content : tinymceEditor.parser.parse(content, {
  17354. isRootContent: true,
  17355. insert: true
  17356. });
  17357. rtcEditor.setContent(fragment);
  17358. return content;
  17359. },
  17360. insertContent: function (value, _details) {
  17361. var contextArgs = getInsertContext(tinymceEditor).fold(function () {
  17362. return {};
  17363. }, function (context) {
  17364. return { context: context };
  17365. });
  17366. var fragment = isTreeNode$1(value) ? value : tinymceEditor.parser.parse(value, __assign(__assign({}, contextArgs), { insert: true }));
  17367. rtcEditor.insertContent(fragment);
  17368. },
  17369. addVisual: function (_elm) {
  17370. }
  17371. },
  17372. selection: {
  17373. getContent: function (format, args) {
  17374. if (format === 'html' || format === 'tree') {
  17375. var fragment = rtcEditor.getSelectedContent();
  17376. var serializer = HtmlSerializer({});
  17377. runSerializerFiltersOnFragment(tinymceEditor, fragment);
  17378. return format === 'tree' ? fragment : serializer.serialize(fragment);
  17379. } else {
  17380. return makePlainAdaptor(tinymceEditor).selection.getContent(format, args);
  17381. }
  17382. }
  17383. },
  17384. raw: {
  17385. getModel: function () {
  17386. return Optional.some(rtcEditor.getRawModel());
  17387. }
  17388. }
  17389. };
  17390. };
  17391. var isRtc = function (editor) {
  17392. return has(editor.plugins, 'rtc');
  17393. };
  17394. var setup$5 = function (editor) {
  17395. var editorCast = editor;
  17396. return get$1(editor.plugins, 'rtc').fold(function () {
  17397. editorCast.rtcInstance = makePlainAdaptor(editor);
  17398. return Optional.none();
  17399. }, function (rtc) {
  17400. return Optional.some(rtc.setup().then(function (rtcEditor) {
  17401. editorCast.rtcInstance = makeRtcAdaptor(editor, rtcEditor);
  17402. return rtcEditor.isRemote;
  17403. }));
  17404. });
  17405. };
  17406. var getRtcInstanceWithFallback = function (editor) {
  17407. return editor.rtcInstance ? editor.rtcInstance : makePlainAdaptor(editor);
  17408. };
  17409. var getRtcInstanceWithError = function (editor) {
  17410. var rtcInstance = editor.rtcInstance;
  17411. if (!rtcInstance) {
  17412. throw new Error('Failed to get RTC instance not yet initialized.');
  17413. } else {
  17414. return rtcInstance;
  17415. }
  17416. };
  17417. var beforeChange$1 = function (editor, locks, beforeBookmark) {
  17418. getRtcInstanceWithError(editor).undoManager.beforeChange(locks, beforeBookmark);
  17419. };
  17420. var addUndoLevel$1 = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  17421. return getRtcInstanceWithError(editor).undoManager.addUndoLevel(undoManager, index, locks, beforeBookmark, level, event);
  17422. };
  17423. var undo$1 = function (editor, undoManager, locks, index) {
  17424. return getRtcInstanceWithError(editor).undoManager.undo(undoManager, locks, index);
  17425. };
  17426. var redo$1 = function (editor, index, data) {
  17427. return getRtcInstanceWithError(editor).undoManager.redo(index, data);
  17428. };
  17429. var clear$1 = function (editor, undoManager, index) {
  17430. getRtcInstanceWithError(editor).undoManager.clear(undoManager, index);
  17431. };
  17432. var reset$1 = function (editor, undoManager) {
  17433. getRtcInstanceWithError(editor).undoManager.reset(undoManager);
  17434. };
  17435. var hasUndo$1 = function (editor, undoManager, index) {
  17436. return getRtcInstanceWithError(editor).undoManager.hasUndo(undoManager, index);
  17437. };
  17438. var hasRedo$1 = function (editor, undoManager, index) {
  17439. return getRtcInstanceWithError(editor).undoManager.hasRedo(undoManager, index);
  17440. };
  17441. var transact$1 = function (editor, undoManager, locks, callback) {
  17442. return getRtcInstanceWithError(editor).undoManager.transact(undoManager, locks, callback);
  17443. };
  17444. var ignore$1 = function (editor, locks, callback) {
  17445. getRtcInstanceWithError(editor).undoManager.ignore(locks, callback);
  17446. };
  17447. var extra$1 = function (editor, undoManager, index, callback1, callback2) {
  17448. getRtcInstanceWithError(editor).undoManager.extra(undoManager, index, callback1, callback2);
  17449. };
  17450. var matchFormat = function (editor, name, vars, node) {
  17451. return getRtcInstanceWithError(editor).formatter.match(name, vars, node);
  17452. };
  17453. var matchAllFormats = function (editor, names, vars) {
  17454. return getRtcInstanceWithError(editor).formatter.matchAll(names, vars);
  17455. };
  17456. var matchNodeFormat = function (editor, node, name, vars, similar) {
  17457. return getRtcInstanceWithError(editor).formatter.matchNode(node, name, vars, similar);
  17458. };
  17459. var canApplyFormat = function (editor, name) {
  17460. return getRtcInstanceWithError(editor).formatter.canApply(name);
  17461. };
  17462. var closestFormat = function (editor, names) {
  17463. return getRtcInstanceWithError(editor).formatter.closest(names);
  17464. };
  17465. var applyFormat$1 = function (editor, name, vars, node) {
  17466. getRtcInstanceWithError(editor).formatter.apply(name, vars, node);
  17467. };
  17468. var removeFormat$1 = function (editor, name, vars, node, similar) {
  17469. getRtcInstanceWithError(editor).formatter.remove(name, vars, node, similar);
  17470. };
  17471. var toggleFormat = function (editor, name, vars, node) {
  17472. getRtcInstanceWithError(editor).formatter.toggle(name, vars, node);
  17473. };
  17474. var formatChanged = function (editor, registeredFormatListeners, formats, callback, similar) {
  17475. if (similar === void 0) {
  17476. similar = false;
  17477. }
  17478. return getRtcInstanceWithError(editor).formatter.formatChanged(registeredFormatListeners, formats, callback, similar);
  17479. };
  17480. var getContent = function (editor, args, format) {
  17481. return getRtcInstanceWithFallback(editor).editor.getContent(args, format);
  17482. };
  17483. var setContent = function (editor, content, args) {
  17484. return getRtcInstanceWithFallback(editor).editor.setContent(content, args);
  17485. };
  17486. var insertContent = function (editor, value, details) {
  17487. return getRtcInstanceWithFallback(editor).editor.insertContent(value, details);
  17488. };
  17489. var getSelectedContent = function (editor, format, args) {
  17490. return getRtcInstanceWithError(editor).selection.getContent(format, args);
  17491. };
  17492. var addVisual = function (editor, elm) {
  17493. return getRtcInstanceWithError(editor).editor.addVisual(elm);
  17494. };
  17495. var getContent$1 = function (editor, args) {
  17496. if (args === void 0) {
  17497. args = {};
  17498. }
  17499. var format = args.format ? args.format : 'html';
  17500. return getSelectedContent(editor, format, args);
  17501. };
  17502. var removeEmpty = function (text) {
  17503. if (text.dom.length === 0) {
  17504. remove(text);
  17505. return Optional.none();
  17506. } else {
  17507. return Optional.some(text);
  17508. }
  17509. };
  17510. var walkPastBookmark = function (node, start) {
  17511. return node.filter(function (elm) {
  17512. return BookmarkManager$1.isBookmarkNode(elm.dom);
  17513. }).bind(start ? nextSibling : prevSibling);
  17514. };
  17515. var merge = function (outer, inner, rng, start) {
  17516. var outerElm = outer.dom;
  17517. var innerElm = inner.dom;
  17518. var oldLength = start ? outerElm.length : innerElm.length;
  17519. if (start) {
  17520. mergeTextNodes(outerElm, innerElm, false, !start);
  17521. rng.setStart(innerElm, oldLength);
  17522. } else {
  17523. mergeTextNodes(innerElm, outerElm, false, !start);
  17524. rng.setEnd(innerElm, oldLength);
  17525. }
  17526. };
  17527. var normalizeTextIfRequired = function (inner, start) {
  17528. parent(inner).each(function (root) {
  17529. var text = inner.dom;
  17530. if (start && needsToBeNbspLeft(root, CaretPosition$1(text, 0))) {
  17531. normalizeWhitespaceAfter(text, 0);
  17532. } else if (!start && needsToBeNbspRight(root, CaretPosition$1(text, text.length))) {
  17533. normalizeWhitespaceBefore(text, text.length);
  17534. }
  17535. });
  17536. };
  17537. var mergeAndNormalizeText = function (outerNode, innerNode, rng, start) {
  17538. outerNode.bind(function (outer) {
  17539. var normalizer = start ? normalizeWhitespaceBefore : normalizeWhitespaceAfter;
  17540. normalizer(outer.dom, start ? outer.dom.length : 0);
  17541. return innerNode.filter(isText).map(function (inner) {
  17542. return merge(outer, inner, rng, start);
  17543. });
  17544. }).orThunk(function () {
  17545. var innerTextNode = walkPastBookmark(innerNode, start).or(innerNode).filter(isText);
  17546. return innerTextNode.map(function (inner) {
  17547. return normalizeTextIfRequired(inner, start);
  17548. });
  17549. });
  17550. };
  17551. var rngSetContent = function (rng, fragment) {
  17552. var firstChild = Optional.from(fragment.firstChild).map(SugarElement.fromDom);
  17553. var lastChild = Optional.from(fragment.lastChild).map(SugarElement.fromDom);
  17554. rng.deleteContents();
  17555. rng.insertNode(fragment);
  17556. var prevText = firstChild.bind(prevSibling).filter(isText).bind(removeEmpty);
  17557. var nextText = lastChild.bind(nextSibling).filter(isText).bind(removeEmpty);
  17558. mergeAndNormalizeText(prevText, firstChild, rng, true);
  17559. mergeAndNormalizeText(nextText, lastChild, rng, false);
  17560. rng.collapse(false);
  17561. };
  17562. var setupArgs = function (args, content) {
  17563. return __assign(__assign({ format: 'html' }, args), {
  17564. set: true,
  17565. selection: true,
  17566. content: content
  17567. });
  17568. };
  17569. var cleanContent = function (editor, args) {
  17570. if (args.format !== 'raw') {
  17571. var rng = editor.selection.getRng();
  17572. var contextBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
  17573. var contextArgs = contextBlock ? { context: contextBlock.nodeName.toLowerCase() } : {};
  17574. var node = editor.parser.parse(args.content, __assign(__assign({
  17575. isRootContent: true,
  17576. forced_root_block: false
  17577. }, contextArgs), args));
  17578. return HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(node);
  17579. } else {
  17580. return args.content;
  17581. }
  17582. };
  17583. var setContent$1 = function (editor, content, args) {
  17584. if (args === void 0) {
  17585. args = {};
  17586. }
  17587. var contentArgs = setupArgs(args, content);
  17588. if (!contentArgs.no_events) {
  17589. contentArgs = editor.fire('BeforeSetContent', contentArgs);
  17590. if (contentArgs.isDefaultPrevented()) {
  17591. editor.fire('SetContent', contentArgs);
  17592. return;
  17593. }
  17594. }
  17595. args.content = cleanContent(editor, contentArgs);
  17596. var rng = editor.selection.getRng();
  17597. rngSetContent(rng, rng.createContextualFragment(args.content));
  17598. editor.selection.setRng(rng);
  17599. scrollRangeIntoView(editor, rng);
  17600. if (!contentArgs.no_events) {
  17601. editor.fire('SetContent', contentArgs);
  17602. }
  17603. };
  17604. var deleteFromCallbackMap = function (callbackMap, selector, callback) {
  17605. if (callbackMap && callbackMap.hasOwnProperty(selector)) {
  17606. var newCallbacks = filter(callbackMap[selector], function (cb) {
  17607. return cb !== callback;
  17608. });
  17609. if (newCallbacks.length === 0) {
  17610. delete callbackMap[selector];
  17611. } else {
  17612. callbackMap[selector] = newCallbacks;
  17613. }
  17614. }
  17615. };
  17616. function SelectorChanged (dom, editor) {
  17617. var selectorChangedData;
  17618. var currentSelectors;
  17619. return {
  17620. selectorChangedWithUnbind: function (selector, callback) {
  17621. if (!selectorChangedData) {
  17622. selectorChangedData = {};
  17623. currentSelectors = {};
  17624. editor.on('NodeChange', function (e) {
  17625. var node = e.element, parents = dom.getParents(node, null, dom.getRoot()), matchedSelectors = {};
  17626. Tools.each(selectorChangedData, function (callbacks, selector) {
  17627. Tools.each(parents, function (node) {
  17628. if (dom.is(node, selector)) {
  17629. if (!currentSelectors[selector]) {
  17630. Tools.each(callbacks, function (callback) {
  17631. callback(true, {
  17632. node: node,
  17633. selector: selector,
  17634. parents: parents
  17635. });
  17636. });
  17637. currentSelectors[selector] = callbacks;
  17638. }
  17639. matchedSelectors[selector] = callbacks;
  17640. return false;
  17641. }
  17642. });
  17643. });
  17644. Tools.each(currentSelectors, function (callbacks, selector) {
  17645. if (!matchedSelectors[selector]) {
  17646. delete currentSelectors[selector];
  17647. Tools.each(callbacks, function (callback) {
  17648. callback(false, {
  17649. node: node,
  17650. selector: selector,
  17651. parents: parents
  17652. });
  17653. });
  17654. }
  17655. });
  17656. });
  17657. }
  17658. if (!selectorChangedData[selector]) {
  17659. selectorChangedData[selector] = [];
  17660. }
  17661. selectorChangedData[selector].push(callback);
  17662. return {
  17663. unbind: function () {
  17664. deleteFromCallbackMap(selectorChangedData, selector, callback);
  17665. deleteFromCallbackMap(currentSelectors, selector, callback);
  17666. }
  17667. };
  17668. }
  17669. };
  17670. }
  17671. var isNativeIeSelection = function (rng) {
  17672. return !!rng.select;
  17673. };
  17674. var isAttachedToDom = function (node) {
  17675. return !!(node && node.ownerDocument) && contains$2(SugarElement.fromDom(node.ownerDocument), SugarElement.fromDom(node));
  17676. };
  17677. var isValidRange = function (rng) {
  17678. if (!rng) {
  17679. return false;
  17680. } else if (isNativeIeSelection(rng)) {
  17681. return true;
  17682. } else {
  17683. return isAttachedToDom(rng.startContainer) && isAttachedToDom(rng.endContainer);
  17684. }
  17685. };
  17686. var EditorSelection = function (dom, win, serializer, editor) {
  17687. var selectedRange;
  17688. var explicitRange;
  17689. var selectorChangedWithUnbind = SelectorChanged(dom, editor).selectorChangedWithUnbind;
  17690. var setCursorLocation = function (node, offset) {
  17691. var rng = dom.createRng();
  17692. if (!node) {
  17693. moveEndPoint$1(dom, rng, editor.getBody(), true);
  17694. setRng(rng);
  17695. } else {
  17696. rng.setStart(node, offset);
  17697. rng.setEnd(node, offset);
  17698. setRng(rng);
  17699. collapse(false);
  17700. }
  17701. };
  17702. var getContent = function (args) {
  17703. return getContent$1(editor, args);
  17704. };
  17705. var setContent = function (content, args) {
  17706. return setContent$1(editor, content, args);
  17707. };
  17708. var getStart = function (real) {
  17709. return getStart$2(editor.getBody(), getRng$1(), real);
  17710. };
  17711. var getEnd$1 = function (real) {
  17712. return getEnd(editor.getBody(), getRng$1(), real);
  17713. };
  17714. var getBookmark = function (type, normalized) {
  17715. return bookmarkManager.getBookmark(type, normalized);
  17716. };
  17717. var moveToBookmark = function (bookmark) {
  17718. return bookmarkManager.moveToBookmark(bookmark);
  17719. };
  17720. var select = function (node, content) {
  17721. select$1(dom, node, content).each(setRng);
  17722. return node;
  17723. };
  17724. var isCollapsed = function () {
  17725. var rng = getRng$1(), sel = getSel();
  17726. if (!rng || rng.item) {
  17727. return false;
  17728. }
  17729. if (rng.compareEndPoints) {
  17730. return rng.compareEndPoints('StartToEnd', rng) === 0;
  17731. }
  17732. return !sel || rng.collapsed;
  17733. };
  17734. var collapse = function (toStart) {
  17735. var rng = getRng$1();
  17736. rng.collapse(!!toStart);
  17737. setRng(rng);
  17738. };
  17739. var getSel = function () {
  17740. return win.getSelection ? win.getSelection() : win.document.selection;
  17741. };
  17742. var getRng$1 = function () {
  17743. var selection, rng, elm;
  17744. var tryCompareBoundaryPoints = function (how, sourceRange, destinationRange) {
  17745. try {
  17746. return sourceRange.compareBoundaryPoints(how, destinationRange);
  17747. } catch (ex) {
  17748. return -1;
  17749. }
  17750. };
  17751. if (!win) {
  17752. return null;
  17753. }
  17754. var doc = win.document;
  17755. if (typeof doc === 'undefined' || doc === null) {
  17756. return null;
  17757. }
  17758. if (editor.bookmark !== undefined && hasFocus$1(editor) === false) {
  17759. var bookmark = getRng(editor);
  17760. if (bookmark.isSome()) {
  17761. return bookmark.map(function (r) {
  17762. return processRanges(editor, [r])[0];
  17763. }).getOr(doc.createRange());
  17764. }
  17765. }
  17766. try {
  17767. if ((selection = getSel()) && !isRestrictedNode(selection.anchorNode)) {
  17768. if (selection.rangeCount > 0) {
  17769. rng = selection.getRangeAt(0);
  17770. } else {
  17771. rng = selection.createRange ? selection.createRange() : doc.createRange();
  17772. }
  17773. rng = processRanges(editor, [rng])[0];
  17774. }
  17775. } catch (ex) {
  17776. }
  17777. if (!rng) {
  17778. rng = doc.createRange ? doc.createRange() : doc.body.createTextRange();
  17779. }
  17780. if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
  17781. elm = dom.getRoot();
  17782. rng.setStart(elm, 0);
  17783. rng.setEnd(elm, 0);
  17784. }
  17785. if (selectedRange && explicitRange) {
  17786. if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 && tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
  17787. rng = explicitRange;
  17788. } else {
  17789. selectedRange = null;
  17790. explicitRange = null;
  17791. }
  17792. }
  17793. return rng;
  17794. };
  17795. var setRng = function (rng, forward) {
  17796. var node;
  17797. if (!isValidRange(rng)) {
  17798. return;
  17799. }
  17800. var ieRange = isNativeIeSelection(rng) ? rng : null;
  17801. if (ieRange) {
  17802. explicitRange = null;
  17803. try {
  17804. ieRange.select();
  17805. } catch (ex) {
  17806. }
  17807. return;
  17808. }
  17809. var sel = getSel();
  17810. var evt = editor.fire('SetSelectionRange', {
  17811. range: rng,
  17812. forward: forward
  17813. });
  17814. rng = evt.range;
  17815. if (sel) {
  17816. explicitRange = rng;
  17817. try {
  17818. sel.removeAllRanges();
  17819. sel.addRange(rng);
  17820. } catch (ex) {
  17821. }
  17822. if (forward === false && sel.extend) {
  17823. sel.collapse(rng.endContainer, rng.endOffset);
  17824. sel.extend(rng.startContainer, rng.startOffset);
  17825. }
  17826. selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
  17827. }
  17828. if (!rng.collapsed && rng.startContainer === rng.endContainer && sel.setBaseAndExtent && !Env.ie) {
  17829. if (rng.endOffset - rng.startOffset < 2) {
  17830. if (rng.startContainer.hasChildNodes()) {
  17831. node = rng.startContainer.childNodes[rng.startOffset];
  17832. if (node && node.tagName === 'IMG') {
  17833. sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
  17834. if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
  17835. sel.setBaseAndExtent(node, 0, node, 1);
  17836. }
  17837. }
  17838. }
  17839. }
  17840. }
  17841. editor.fire('AfterSetSelectionRange', {
  17842. range: rng,
  17843. forward: forward
  17844. });
  17845. };
  17846. var setNode = function (elm) {
  17847. setContent(dom.getOuterHTML(elm));
  17848. return elm;
  17849. };
  17850. var getNode = function () {
  17851. return getNode$1(editor.getBody(), getRng$1());
  17852. };
  17853. var getSelectedBlocks$1 = function (startElm, endElm) {
  17854. return getSelectedBlocks(dom, getRng$1(), startElm, endElm);
  17855. };
  17856. var isForward = function () {
  17857. var sel = getSel();
  17858. var anchorNode = sel === null || sel === void 0 ? void 0 : sel.anchorNode;
  17859. var focusNode = sel === null || sel === void 0 ? void 0 : sel.focusNode;
  17860. if (!sel || !anchorNode || !focusNode || isRestrictedNode(anchorNode) || isRestrictedNode(focusNode)) {
  17861. return true;
  17862. }
  17863. var anchorRange = dom.createRng();
  17864. anchorRange.setStart(anchorNode, sel.anchorOffset);
  17865. anchorRange.collapse(true);
  17866. var focusRange = dom.createRng();
  17867. focusRange.setStart(focusNode, sel.focusOffset);
  17868. focusRange.collapse(true);
  17869. return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
  17870. };
  17871. var normalize$1 = function () {
  17872. var rng = getRng$1();
  17873. var sel = getSel();
  17874. if (!hasMultipleRanges(sel) && hasAnyRanges(editor)) {
  17875. var normRng = normalize(dom, rng);
  17876. normRng.each(function (normRng) {
  17877. setRng(normRng, isForward());
  17878. });
  17879. return normRng.getOr(rng);
  17880. }
  17881. return rng;
  17882. };
  17883. var selectorChanged = function (selector, callback) {
  17884. selectorChangedWithUnbind(selector, callback);
  17885. return exports;
  17886. };
  17887. var getScrollContainer = function () {
  17888. var scrollContainer;
  17889. var node = dom.getRoot();
  17890. while (node && node.nodeName !== 'BODY') {
  17891. if (node.scrollHeight > node.clientHeight) {
  17892. scrollContainer = node;
  17893. break;
  17894. }
  17895. node = node.parentNode;
  17896. }
  17897. return scrollContainer;
  17898. };
  17899. var scrollIntoView = function (elm, alignToTop) {
  17900. return scrollElementIntoView(editor, elm, alignToTop);
  17901. };
  17902. var placeCaretAt = function (clientX, clientY) {
  17903. return setRng(fromPoint$1(clientX, clientY, editor.getDoc()));
  17904. };
  17905. var getBoundingClientRect = function () {
  17906. var rng = getRng$1();
  17907. return rng.collapsed ? CaretPosition$1.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
  17908. };
  17909. var destroy = function () {
  17910. win = selectedRange = explicitRange = null;
  17911. controlSelection.destroy();
  17912. };
  17913. var exports = {
  17914. bookmarkManager: null,
  17915. controlSelection: null,
  17916. dom: dom,
  17917. win: win,
  17918. serializer: serializer,
  17919. editor: editor,
  17920. collapse: collapse,
  17921. setCursorLocation: setCursorLocation,
  17922. getContent: getContent,
  17923. setContent: setContent,
  17924. getBookmark: getBookmark,
  17925. moveToBookmark: moveToBookmark,
  17926. select: select,
  17927. isCollapsed: isCollapsed,
  17928. isForward: isForward,
  17929. setNode: setNode,
  17930. getNode: getNode,
  17931. getSel: getSel,
  17932. setRng: setRng,
  17933. getRng: getRng$1,
  17934. getStart: getStart,
  17935. getEnd: getEnd$1,
  17936. getSelectedBlocks: getSelectedBlocks$1,
  17937. normalize: normalize$1,
  17938. selectorChanged: selectorChanged,
  17939. selectorChangedWithUnbind: selectorChangedWithUnbind,
  17940. getScrollContainer: getScrollContainer,
  17941. scrollIntoView: scrollIntoView,
  17942. placeCaretAt: placeCaretAt,
  17943. getBoundingClientRect: getBoundingClientRect,
  17944. destroy: destroy
  17945. };
  17946. var bookmarkManager = BookmarkManager$1(exports);
  17947. var controlSelection = ControlSelection(exports, editor);
  17948. exports.bookmarkManager = bookmarkManager;
  17949. exports.controlSelection = controlSelection;
  17950. return exports;
  17951. };
  17952. var removeAttrs = function (node, names) {
  17953. each(names, function (name) {
  17954. node.attr(name, null);
  17955. });
  17956. };
  17957. var addFontToSpansFilter = function (domParser, styles, fontSizes) {
  17958. domParser.addNodeFilter('font', function (nodes) {
  17959. each(nodes, function (node) {
  17960. var props = styles.parse(node.attr('style'));
  17961. var color = node.attr('color');
  17962. var face = node.attr('face');
  17963. var size = node.attr('size');
  17964. if (color) {
  17965. props.color = color;
  17966. }
  17967. if (face) {
  17968. props['font-family'] = face;
  17969. }
  17970. if (size) {
  17971. props['font-size'] = fontSizes[parseInt(node.attr('size'), 10) - 1];
  17972. }
  17973. node.name = 'span';
  17974. node.attr('style', styles.serialize(props));
  17975. removeAttrs(node, [
  17976. 'color',
  17977. 'face',
  17978. 'size'
  17979. ]);
  17980. });
  17981. });
  17982. };
  17983. var addStrikeToSpanFilter = function (domParser, styles) {
  17984. domParser.addNodeFilter('strike', function (nodes) {
  17985. each(nodes, function (node) {
  17986. var props = styles.parse(node.attr('style'));
  17987. props['text-decoration'] = 'line-through';
  17988. node.name = 'span';
  17989. node.attr('style', styles.serialize(props));
  17990. });
  17991. });
  17992. };
  17993. var addFilters = function (domParser, settings) {
  17994. var styles = Styles();
  17995. if (settings.convert_fonts_to_spans) {
  17996. addFontToSpansFilter(domParser, styles, Tools.explode(settings.font_size_legacy_values));
  17997. }
  17998. addStrikeToSpanFilter(domParser, styles);
  17999. };
  18000. var register$1 = function (domParser, settings) {
  18001. if (settings.inline_styles) {
  18002. addFilters(domParser, settings);
  18003. }
  18004. };
  18005. var blobUriToBlob = function (url) {
  18006. return new promiseObj(function (resolve, reject) {
  18007. var rejectWithError = function () {
  18008. reject('Cannot convert ' + url + ' to Blob. Resource might not exist or is inaccessible.');
  18009. };
  18010. try {
  18011. var xhr = new XMLHttpRequest();
  18012. xhr.open('GET', url, true);
  18013. xhr.responseType = 'blob';
  18014. xhr.onload = function () {
  18015. if (this.status === 200) {
  18016. resolve(this.response);
  18017. } else {
  18018. rejectWithError();
  18019. }
  18020. };
  18021. xhr.onerror = rejectWithError;
  18022. xhr.send();
  18023. } catch (ex) {
  18024. rejectWithError();
  18025. }
  18026. });
  18027. };
  18028. var parseDataUri$1 = function (uri) {
  18029. var type;
  18030. var uriParts = decodeURIComponent(uri).split(',');
  18031. var matches = /data:([^;]+)/.exec(uriParts[0]);
  18032. if (matches) {
  18033. type = matches[1];
  18034. }
  18035. return {
  18036. type: type,
  18037. data: uriParts[1]
  18038. };
  18039. };
  18040. var buildBlob = function (type, data) {
  18041. var str;
  18042. try {
  18043. str = atob(data);
  18044. } catch (e) {
  18045. return Optional.none();
  18046. }
  18047. var arr = new Uint8Array(str.length);
  18048. for (var i = 0; i < arr.length; i++) {
  18049. arr[i] = str.charCodeAt(i);
  18050. }
  18051. return Optional.some(new Blob([arr], { type: type }));
  18052. };
  18053. var dataUriToBlob = function (uri) {
  18054. return new promiseObj(function (resolve) {
  18055. var _a = parseDataUri$1(uri), type = _a.type, data = _a.data;
  18056. buildBlob(type, data).fold(function () {
  18057. return resolve(new Blob([]));
  18058. }, resolve);
  18059. });
  18060. };
  18061. var uriToBlob = function (url) {
  18062. if (url.indexOf('blob:') === 0) {
  18063. return blobUriToBlob(url);
  18064. }
  18065. if (url.indexOf('data:') === 0) {
  18066. return dataUriToBlob(url);
  18067. }
  18068. return null;
  18069. };
  18070. var blobToDataUri = function (blob) {
  18071. return new promiseObj(function (resolve) {
  18072. var reader = new FileReader();
  18073. reader.onloadend = function () {
  18074. resolve(reader.result);
  18075. };
  18076. reader.readAsDataURL(blob);
  18077. });
  18078. };
  18079. var count = 0;
  18080. var uniqueId = function (prefix) {
  18081. return (prefix || 'blobid') + count++;
  18082. };
  18083. var imageToBlobInfo = function (blobCache, img, resolve, reject) {
  18084. var base64, blobInfo;
  18085. if (img.src.indexOf('blob:') === 0) {
  18086. blobInfo = blobCache.getByUri(img.src);
  18087. if (blobInfo) {
  18088. resolve({
  18089. image: img,
  18090. blobInfo: blobInfo
  18091. });
  18092. } else {
  18093. uriToBlob(img.src).then(function (blob) {
  18094. blobToDataUri(blob).then(function (dataUri) {
  18095. base64 = parseDataUri$1(dataUri).data;
  18096. blobInfo = blobCache.create(uniqueId(), blob, base64);
  18097. blobCache.add(blobInfo);
  18098. resolve({
  18099. image: img,
  18100. blobInfo: blobInfo
  18101. });
  18102. });
  18103. }, function (err) {
  18104. reject(err);
  18105. });
  18106. }
  18107. return;
  18108. }
  18109. var _a = parseDataUri$1(img.src), data = _a.data, type = _a.type;
  18110. base64 = data;
  18111. blobInfo = blobCache.getByData(base64, type);
  18112. if (blobInfo) {
  18113. resolve({
  18114. image: img,
  18115. blobInfo: blobInfo
  18116. });
  18117. } else {
  18118. uriToBlob(img.src).then(function (blob) {
  18119. blobInfo = blobCache.create(uniqueId(), blob, base64);
  18120. blobCache.add(blobInfo);
  18121. resolve({
  18122. image: img,
  18123. blobInfo: blobInfo
  18124. });
  18125. }, function (err) {
  18126. reject(err);
  18127. });
  18128. }
  18129. };
  18130. var getAllImages = function (elm) {
  18131. return elm ? from$1(elm.getElementsByTagName('img')) : [];
  18132. };
  18133. function ImageScanner(uploadStatus, blobCache) {
  18134. var cachedPromises = {};
  18135. var findAll = function (elm, predicate) {
  18136. if (!predicate) {
  18137. predicate = always;
  18138. }
  18139. var images = filter(getAllImages(elm), function (img) {
  18140. var src = img.src;
  18141. if (!Env.fileApi) {
  18142. return false;
  18143. }
  18144. if (img.hasAttribute('data-mce-bogus')) {
  18145. return false;
  18146. }
  18147. if (img.hasAttribute('data-mce-placeholder')) {
  18148. return false;
  18149. }
  18150. if (!src || src === Env.transparentSrc) {
  18151. return false;
  18152. }
  18153. if (src.indexOf('blob:') === 0) {
  18154. return !uploadStatus.isUploaded(src) && predicate(img);
  18155. }
  18156. if (src.indexOf('data:') === 0) {
  18157. return predicate(img);
  18158. }
  18159. return false;
  18160. });
  18161. var promises = map(images, function (img) {
  18162. if (cachedPromises[img.src] !== undefined) {
  18163. return new promiseObj(function (resolve) {
  18164. cachedPromises[img.src].then(function (imageInfo) {
  18165. if (typeof imageInfo === 'string') {
  18166. return imageInfo;
  18167. }
  18168. resolve({
  18169. image: img,
  18170. blobInfo: imageInfo.blobInfo
  18171. });
  18172. });
  18173. });
  18174. }
  18175. var newPromise = new promiseObj(function (resolve, reject) {
  18176. imageToBlobInfo(blobCache, img, resolve, reject);
  18177. }).then(function (result) {
  18178. delete cachedPromises[result.image.src];
  18179. return result;
  18180. }).catch(function (error) {
  18181. delete cachedPromises[img.src];
  18182. return error;
  18183. });
  18184. cachedPromises[img.src] = newPromise;
  18185. return newPromise;
  18186. });
  18187. return promiseObj.all(promises);
  18188. };
  18189. return { findAll: findAll };
  18190. }
  18191. var paddEmptyNode = function (settings, args, blockElements, node) {
  18192. var brPreferred = settings.padd_empty_with_br || args.insert;
  18193. if (brPreferred && blockElements[node.name]) {
  18194. node.empty().append(new AstNode('br', 1)).shortEnded = true;
  18195. } else {
  18196. node.empty().append(new AstNode('#text', 3)).value = nbsp;
  18197. }
  18198. };
  18199. var isPaddedWithNbsp = function (node) {
  18200. return hasOnlyChild(node, '#text') && node.firstChild.value === nbsp;
  18201. };
  18202. var hasOnlyChild = function (node, name) {
  18203. return node && node.firstChild && node.firstChild === node.lastChild && node.firstChild.name === name;
  18204. };
  18205. var isPadded = function (schema, node) {
  18206. var rule = schema.getElementRule(node.name);
  18207. return rule && rule.paddEmpty;
  18208. };
  18209. var isEmpty$2 = function (schema, nonEmptyElements, whitespaceElements, node) {
  18210. return node.isEmpty(nonEmptyElements, whitespaceElements, function (node) {
  18211. return isPadded(schema, node);
  18212. });
  18213. };
  18214. var isLineBreakNode = function (node, blockElements) {
  18215. return node && (blockElements[node.name] || node.name === 'br');
  18216. };
  18217. var isBogusImage = function (img) {
  18218. return img.attr('data-mce-bogus');
  18219. };
  18220. var isInternalImageSource = function (img) {
  18221. return img.attr('src') === Env.transparentSrc || img.attr('data-mce-placeholder');
  18222. };
  18223. var isValidDataImg = function (img, settings) {
  18224. if (settings.images_dataimg_filter) {
  18225. var imgElem_1 = new Image();
  18226. imgElem_1.src = img.attr('src');
  18227. each$1(img.attributes.map, function (value, key) {
  18228. imgElem_1.setAttribute(key, value);
  18229. });
  18230. return settings.images_dataimg_filter(imgElem_1);
  18231. } else {
  18232. return true;
  18233. }
  18234. };
  18235. var registerBase64ImageFilter = function (parser, settings) {
  18236. var blobCache = settings.blob_cache;
  18237. var processImage = function (img) {
  18238. var inputSrc = img.attr('src');
  18239. if (isInternalImageSource(img) || isBogusImage(img)) {
  18240. return;
  18241. }
  18242. parseDataUri(inputSrc).filter(function () {
  18243. return isValidDataImg(img, settings);
  18244. }).bind(function (_a) {
  18245. var type = _a.type, data = _a.data;
  18246. return Optional.from(blobCache.getByData(data, type)).orThunk(function () {
  18247. return buildBlob(type, data).map(function (blob) {
  18248. var blobInfo = blobCache.create(uniqueId(), blob, data);
  18249. blobCache.add(blobInfo);
  18250. return blobInfo;
  18251. });
  18252. });
  18253. }).each(function (blobInfo) {
  18254. img.attr('src', blobInfo.blobUri());
  18255. });
  18256. };
  18257. if (blobCache) {
  18258. parser.addAttributeFilter('src', function (nodes) {
  18259. return each(nodes, processImage);
  18260. });
  18261. }
  18262. };
  18263. var register$2 = function (parser, settings) {
  18264. var schema = parser.schema;
  18265. if (settings.remove_trailing_brs) {
  18266. parser.addNodeFilter('br', function (nodes, _, args) {
  18267. var i;
  18268. var l = nodes.length;
  18269. var node;
  18270. var blockElements = Tools.extend({}, schema.getBlockElements());
  18271. var nonEmptyElements = schema.getNonEmptyElements();
  18272. var parent, lastParent, prev, prevName;
  18273. var whiteSpaceElements = schema.getWhiteSpaceElements();
  18274. var elementRule, textNode;
  18275. blockElements.body = 1;
  18276. for (i = 0; i < l; i++) {
  18277. node = nodes[i];
  18278. parent = node.parent;
  18279. if (blockElements[node.parent.name] && node === parent.lastChild) {
  18280. prev = node.prev;
  18281. while (prev) {
  18282. prevName = prev.name;
  18283. if (prevName !== 'span' || prev.attr('data-mce-type') !== 'bookmark') {
  18284. if (prevName === 'br') {
  18285. node = null;
  18286. }
  18287. break;
  18288. }
  18289. prev = prev.prev;
  18290. }
  18291. if (node) {
  18292. node.remove();
  18293. if (isEmpty$2(schema, nonEmptyElements, whiteSpaceElements, parent)) {
  18294. elementRule = schema.getElementRule(parent.name);
  18295. if (elementRule) {
  18296. if (elementRule.removeEmpty) {
  18297. parent.remove();
  18298. } else if (elementRule.paddEmpty) {
  18299. paddEmptyNode(settings, args, blockElements, parent);
  18300. }
  18301. }
  18302. }
  18303. }
  18304. } else {
  18305. lastParent = node;
  18306. while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) {
  18307. lastParent = parent;
  18308. if (blockElements[parent.name]) {
  18309. break;
  18310. }
  18311. parent = parent.parent;
  18312. }
  18313. if (lastParent === parent && settings.padd_empty_with_br !== true) {
  18314. textNode = new AstNode('#text', 3);
  18315. textNode.value = nbsp;
  18316. node.replace(textNode);
  18317. }
  18318. }
  18319. }
  18320. });
  18321. }
  18322. parser.addAttributeFilter('href', function (nodes) {
  18323. var i = nodes.length;
  18324. var appendRel = function (rel) {
  18325. var parts = rel.split(' ').filter(function (p) {
  18326. return p.length > 0;
  18327. });
  18328. return parts.concat(['noopener']).sort().join(' ');
  18329. };
  18330. var addNoOpener = function (rel) {
  18331. var newRel = rel ? Tools.trim(rel) : '';
  18332. if (!/\b(noopener)\b/g.test(newRel)) {
  18333. return appendRel(newRel);
  18334. } else {
  18335. return newRel;
  18336. }
  18337. };
  18338. if (!settings.allow_unsafe_link_target) {
  18339. while (i--) {
  18340. var node = nodes[i];
  18341. if (node.name === 'a' && node.attr('target') === '_blank') {
  18342. node.attr('rel', addNoOpener(node.attr('rel')));
  18343. }
  18344. }
  18345. }
  18346. });
  18347. if (!settings.allow_html_in_named_anchor) {
  18348. parser.addAttributeFilter('id,name', function (nodes) {
  18349. var i = nodes.length, sibling, prevSibling, parent, node;
  18350. while (i--) {
  18351. node = nodes[i];
  18352. if (node.name === 'a' && node.firstChild && !node.attr('href')) {
  18353. parent = node.parent;
  18354. sibling = node.lastChild;
  18355. do {
  18356. prevSibling = sibling.prev;
  18357. parent.insert(sibling, node);
  18358. sibling = prevSibling;
  18359. } while (sibling);
  18360. }
  18361. }
  18362. });
  18363. }
  18364. if (settings.fix_list_elements) {
  18365. parser.addNodeFilter('ul,ol', function (nodes) {
  18366. var i = nodes.length, node, parentNode;
  18367. while (i--) {
  18368. node = nodes[i];
  18369. parentNode = node.parent;
  18370. if (parentNode.name === 'ul' || parentNode.name === 'ol') {
  18371. if (node.prev && node.prev.name === 'li') {
  18372. node.prev.append(node);
  18373. } else {
  18374. var li = new AstNode('li', 1);
  18375. li.attr('style', 'list-style-type: none');
  18376. node.wrap(li);
  18377. }
  18378. }
  18379. }
  18380. });
  18381. }
  18382. if (settings.validate && schema.getValidClasses()) {
  18383. parser.addAttributeFilter('class', function (nodes) {
  18384. var i = nodes.length, node, classList, ci, className, classValue;
  18385. var validClasses = schema.getValidClasses();
  18386. var validClassesMap, valid;
  18387. while (i--) {
  18388. node = nodes[i];
  18389. classList = node.attr('class').split(' ');
  18390. classValue = '';
  18391. for (ci = 0; ci < classList.length; ci++) {
  18392. className = classList[ci];
  18393. valid = false;
  18394. validClassesMap = validClasses['*'];
  18395. if (validClassesMap && validClassesMap[className]) {
  18396. valid = true;
  18397. }
  18398. validClassesMap = validClasses[node.name];
  18399. if (!valid && validClassesMap && validClassesMap[className]) {
  18400. valid = true;
  18401. }
  18402. if (valid) {
  18403. if (classValue) {
  18404. classValue += ' ';
  18405. }
  18406. classValue += className;
  18407. }
  18408. }
  18409. if (!classValue.length) {
  18410. classValue = null;
  18411. }
  18412. node.attr('class', classValue);
  18413. }
  18414. });
  18415. }
  18416. registerBase64ImageFilter(parser, settings);
  18417. };
  18418. var makeMap$4 = Tools.makeMap, each$d = Tools.each, explode$2 = Tools.explode, extend$2 = Tools.extend;
  18419. var DomParser = function (settings, schema) {
  18420. if (schema === void 0) {
  18421. schema = Schema();
  18422. }
  18423. var nodeFilters = {};
  18424. var attributeFilters = [];
  18425. var matchedNodes = {};
  18426. var matchedAttributes = {};
  18427. settings = settings || {};
  18428. settings.validate = 'validate' in settings ? settings.validate : true;
  18429. settings.root_name = settings.root_name || 'body';
  18430. var fixInvalidChildren = function (nodes) {
  18431. var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i;
  18432. var sibling, nextNode;
  18433. var nonSplitableElements = makeMap$4('tr,td,th,tbody,thead,tfoot,table');
  18434. var nonEmptyElements = schema.getNonEmptyElements();
  18435. var whitespaceElements = schema.getWhiteSpaceElements();
  18436. var textBlockElements = schema.getTextBlockElements();
  18437. var specialElements = schema.getSpecialElements();
  18438. for (ni = 0; ni < nodes.length; ni++) {
  18439. node = nodes[ni];
  18440. if (!node.parent || node.fixed) {
  18441. continue;
  18442. }
  18443. if (textBlockElements[node.name] && node.parent.name === 'li') {
  18444. sibling = node.next;
  18445. while (sibling) {
  18446. if (textBlockElements[sibling.name]) {
  18447. sibling.name = 'li';
  18448. sibling.fixed = true;
  18449. node.parent.insert(sibling, node.parent);
  18450. } else {
  18451. break;
  18452. }
  18453. sibling = sibling.next;
  18454. }
  18455. node.unwrap(node);
  18456. continue;
  18457. }
  18458. parents = [node];
  18459. for (parent = node.parent; parent && !schema.isValidChild(parent.name, node.name) && !nonSplitableElements[parent.name]; parent = parent.parent) {
  18460. parents.push(parent);
  18461. }
  18462. if (parent && parents.length > 1) {
  18463. parents.reverse();
  18464. newParent = currentNode = filterNode(parents[0].clone());
  18465. for (i = 0; i < parents.length - 1; i++) {
  18466. if (schema.isValidChild(currentNode.name, parents[i].name)) {
  18467. tempNode = filterNode(parents[i].clone());
  18468. currentNode.append(tempNode);
  18469. } else {
  18470. tempNode = currentNode;
  18471. }
  18472. for (childNode = parents[i].firstChild; childNode && childNode !== parents[i + 1];) {
  18473. nextNode = childNode.next;
  18474. tempNode.append(childNode);
  18475. childNode = nextNode;
  18476. }
  18477. currentNode = tempNode;
  18478. }
  18479. if (!isEmpty$2(schema, nonEmptyElements, whitespaceElements, newParent)) {
  18480. parent.insert(newParent, parents[0], true);
  18481. parent.insert(node, newParent);
  18482. } else {
  18483. parent.insert(node, parents[0], true);
  18484. }
  18485. parent = parents[0];
  18486. if (isEmpty$2(schema, nonEmptyElements, whitespaceElements, parent) || hasOnlyChild(parent, 'br')) {
  18487. parent.empty().remove();
  18488. }
  18489. } else if (node.parent) {
  18490. if (node.name === 'li') {
  18491. sibling = node.prev;
  18492. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  18493. sibling.append(node);
  18494. continue;
  18495. }
  18496. sibling = node.next;
  18497. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  18498. sibling.insert(node, sibling.firstChild, true);
  18499. continue;
  18500. }
  18501. node.wrap(filterNode(new AstNode('ul', 1)));
  18502. continue;
  18503. }
  18504. if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
  18505. node.wrap(filterNode(new AstNode('div', 1)));
  18506. } else {
  18507. if (specialElements[node.name]) {
  18508. node.empty().remove();
  18509. } else {
  18510. node.unwrap();
  18511. }
  18512. }
  18513. }
  18514. }
  18515. };
  18516. var filterNode = function (node) {
  18517. var i, name, list;
  18518. name = node.name;
  18519. if (name in nodeFilters) {
  18520. list = matchedNodes[name];
  18521. if (list) {
  18522. list.push(node);
  18523. } else {
  18524. matchedNodes[name] = [node];
  18525. }
  18526. }
  18527. i = attributeFilters.length;
  18528. while (i--) {
  18529. name = attributeFilters[i].name;
  18530. if (name in node.attributes.map) {
  18531. list = matchedAttributes[name];
  18532. if (list) {
  18533. list.push(node);
  18534. } else {
  18535. matchedAttributes[name] = [node];
  18536. }
  18537. }
  18538. }
  18539. return node;
  18540. };
  18541. var addNodeFilter = function (name, callback) {
  18542. each$d(explode$2(name), function (name) {
  18543. var list = nodeFilters[name];
  18544. if (!list) {
  18545. nodeFilters[name] = list = [];
  18546. }
  18547. list.push(callback);
  18548. });
  18549. };
  18550. var getNodeFilters = function () {
  18551. var out = [];
  18552. for (var name_1 in nodeFilters) {
  18553. if (nodeFilters.hasOwnProperty(name_1)) {
  18554. out.push({
  18555. name: name_1,
  18556. callbacks: nodeFilters[name_1]
  18557. });
  18558. }
  18559. }
  18560. return out;
  18561. };
  18562. var addAttributeFilter = function (name, callback) {
  18563. each$d(explode$2(name), function (name) {
  18564. var i;
  18565. for (i = 0; i < attributeFilters.length; i++) {
  18566. if (attributeFilters[i].name === name) {
  18567. attributeFilters[i].callbacks.push(callback);
  18568. return;
  18569. }
  18570. }
  18571. attributeFilters.push({
  18572. name: name,
  18573. callbacks: [callback]
  18574. });
  18575. });
  18576. };
  18577. var getAttributeFilters = function () {
  18578. return [].concat(attributeFilters);
  18579. };
  18580. var parse = function (html, args) {
  18581. var nodes, i, l, fi, fl, list, name;
  18582. var invalidChildren = [];
  18583. var isInWhiteSpacePreservedElement;
  18584. var node;
  18585. var getRootBlockName = function (name) {
  18586. if (name === false) {
  18587. return '';
  18588. } else if (name === true) {
  18589. return 'p';
  18590. } else {
  18591. return name;
  18592. }
  18593. };
  18594. args = args || {};
  18595. matchedNodes = {};
  18596. matchedAttributes = {};
  18597. var blockElements = extend$2(makeMap$4('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  18598. var nonEmptyElements = schema.getNonEmptyElements();
  18599. var children = schema.children;
  18600. var validate = settings.validate;
  18601. var forcedRootBlockName = 'forced_root_block' in args ? args.forced_root_block : settings.forced_root_block;
  18602. var rootBlockName = getRootBlockName(forcedRootBlockName);
  18603. var whiteSpaceElements = schema.getWhiteSpaceElements();
  18604. var startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  18605. var endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  18606. var allWhiteSpaceRegExp = /[ \t\r\n]+/g;
  18607. var isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/;
  18608. isInWhiteSpacePreservedElement = whiteSpaceElements.hasOwnProperty(args.context) || whiteSpaceElements.hasOwnProperty(settings.root_name);
  18609. var addRootBlocks = function () {
  18610. var node = rootNode.firstChild, next, rootBlockNode;
  18611. var trim = function (rootBlockNode) {
  18612. if (rootBlockNode) {
  18613. node = rootBlockNode.firstChild;
  18614. if (node && node.type === 3) {
  18615. node.value = node.value.replace(startWhiteSpaceRegExp, '');
  18616. }
  18617. node = rootBlockNode.lastChild;
  18618. if (node && node.type === 3) {
  18619. node.value = node.value.replace(endWhiteSpaceRegExp, '');
  18620. }
  18621. }
  18622. };
  18623. if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
  18624. return;
  18625. }
  18626. while (node) {
  18627. next = node.next;
  18628. if (node.type === 3 || node.type === 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type')) {
  18629. if (!rootBlockNode) {
  18630. rootBlockNode = createNode(rootBlockName, 1);
  18631. rootBlockNode.attr(settings.forced_root_block_attrs);
  18632. rootNode.insert(rootBlockNode, node);
  18633. rootBlockNode.append(node);
  18634. } else {
  18635. rootBlockNode.append(node);
  18636. }
  18637. } else {
  18638. trim(rootBlockNode);
  18639. rootBlockNode = null;
  18640. }
  18641. node = next;
  18642. }
  18643. trim(rootBlockNode);
  18644. };
  18645. var createNode = function (name, type) {
  18646. var node = new AstNode(name, type);
  18647. var list;
  18648. if (name in nodeFilters) {
  18649. list = matchedNodes[name];
  18650. if (list) {
  18651. list.push(node);
  18652. } else {
  18653. matchedNodes[name] = [node];
  18654. }
  18655. }
  18656. return node;
  18657. };
  18658. var removeWhitespaceBefore = function (node) {
  18659. var textNode, textNodeNext, textVal, sibling;
  18660. var blockElements = schema.getBlockElements();
  18661. for (textNode = node.prev; textNode && textNode.type === 3;) {
  18662. textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
  18663. if (textVal.length > 0) {
  18664. textNode.value = textVal;
  18665. return;
  18666. }
  18667. textNodeNext = textNode.next;
  18668. if (textNodeNext) {
  18669. if (textNodeNext.type === 3 && textNodeNext.value.length) {
  18670. textNode = textNode.prev;
  18671. continue;
  18672. }
  18673. if (!blockElements[textNodeNext.name] && textNodeNext.name !== 'script' && textNodeNext.name !== 'style') {
  18674. textNode = textNode.prev;
  18675. continue;
  18676. }
  18677. }
  18678. sibling = textNode.prev;
  18679. textNode.remove();
  18680. textNode = sibling;
  18681. }
  18682. };
  18683. var cloneAndExcludeBlocks = function (input) {
  18684. var name;
  18685. var output = {};
  18686. for (name in input) {
  18687. if (name !== 'li' && name !== 'p') {
  18688. output[name] = input[name];
  18689. }
  18690. }
  18691. return output;
  18692. };
  18693. var parser = SaxParser$1({
  18694. validate: validate,
  18695. allow_html_data_urls: settings.allow_html_data_urls,
  18696. allow_svg_data_urls: settings.allow_svg_data_urls,
  18697. allow_script_urls: settings.allow_script_urls,
  18698. allow_conditional_comments: settings.allow_conditional_comments,
  18699. preserve_cdata: settings.preserve_cdata,
  18700. self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()),
  18701. cdata: function (text) {
  18702. node.append(createNode('#cdata', 4)).value = text;
  18703. },
  18704. text: function (text, raw) {
  18705. var textNode;
  18706. if (!isInWhiteSpacePreservedElement) {
  18707. text = text.replace(allWhiteSpaceRegExp, ' ');
  18708. if (isLineBreakNode(node.lastChild, blockElements)) {
  18709. text = text.replace(startWhiteSpaceRegExp, '');
  18710. }
  18711. }
  18712. if (text.length !== 0) {
  18713. textNode = createNode('#text', 3);
  18714. textNode.raw = !!raw;
  18715. node.append(textNode).value = text;
  18716. }
  18717. },
  18718. comment: function (text) {
  18719. node.append(createNode('#comment', 8)).value = text;
  18720. },
  18721. pi: function (name, text) {
  18722. node.append(createNode(name, 7)).value = text;
  18723. removeWhitespaceBefore(node);
  18724. },
  18725. doctype: function (text) {
  18726. var newNode = node.append(createNode('#doctype', 10));
  18727. newNode.value = text;
  18728. removeWhitespaceBefore(node);
  18729. },
  18730. start: function (name, attrs, empty) {
  18731. var newNode, attrFiltersLen, attrName, parent;
  18732. var elementRule = validate ? schema.getElementRule(name) : {};
  18733. if (elementRule) {
  18734. newNode = createNode(elementRule.outputName || name, 1);
  18735. newNode.attributes = attrs;
  18736. newNode.shortEnded = empty;
  18737. node.append(newNode);
  18738. parent = children[node.name];
  18739. if (parent && children[newNode.name] && !parent[newNode.name]) {
  18740. invalidChildren.push(newNode);
  18741. }
  18742. attrFiltersLen = attributeFilters.length;
  18743. while (attrFiltersLen--) {
  18744. attrName = attributeFilters[attrFiltersLen].name;
  18745. if (attrName in attrs.map) {
  18746. list = matchedAttributes[attrName];
  18747. if (list) {
  18748. list.push(newNode);
  18749. } else {
  18750. matchedAttributes[attrName] = [newNode];
  18751. }
  18752. }
  18753. }
  18754. if (blockElements[name]) {
  18755. removeWhitespaceBefore(newNode);
  18756. }
  18757. if (!empty) {
  18758. node = newNode;
  18759. }
  18760. if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  18761. isInWhiteSpacePreservedElement = true;
  18762. }
  18763. }
  18764. },
  18765. end: function (name) {
  18766. var textNode, text, sibling, tempNode;
  18767. var elementRule = validate ? schema.getElementRule(name) : {};
  18768. if (elementRule) {
  18769. if (blockElements[name]) {
  18770. if (!isInWhiteSpacePreservedElement) {
  18771. textNode = node.firstChild;
  18772. if (textNode && textNode.type === 3) {
  18773. text = textNode.value.replace(startWhiteSpaceRegExp, '');
  18774. if (text.length > 0) {
  18775. textNode.value = text;
  18776. textNode = textNode.next;
  18777. } else {
  18778. sibling = textNode.next;
  18779. textNode.remove();
  18780. textNode = sibling;
  18781. while (textNode && textNode.type === 3) {
  18782. text = textNode.value;
  18783. sibling = textNode.next;
  18784. if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  18785. textNode.remove();
  18786. textNode = sibling;
  18787. }
  18788. textNode = sibling;
  18789. }
  18790. }
  18791. }
  18792. textNode = node.lastChild;
  18793. if (textNode && textNode.type === 3) {
  18794. text = textNode.value.replace(endWhiteSpaceRegExp, '');
  18795. if (text.length > 0) {
  18796. textNode.value = text;
  18797. textNode = textNode.prev;
  18798. } else {
  18799. sibling = textNode.prev;
  18800. textNode.remove();
  18801. textNode = sibling;
  18802. while (textNode && textNode.type === 3) {
  18803. text = textNode.value;
  18804. sibling = textNode.prev;
  18805. if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  18806. textNode.remove();
  18807. textNode = sibling;
  18808. }
  18809. textNode = sibling;
  18810. }
  18811. }
  18812. }
  18813. }
  18814. }
  18815. if (isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  18816. isInWhiteSpacePreservedElement = false;
  18817. }
  18818. if (elementRule.removeEmpty && isEmpty$2(schema, nonEmptyElements, whiteSpaceElements, node)) {
  18819. tempNode = node.parent;
  18820. if (blockElements[node.name]) {
  18821. node.empty().remove();
  18822. } else {
  18823. node.unwrap();
  18824. }
  18825. node = tempNode;
  18826. return;
  18827. }
  18828. if (elementRule.paddEmpty && (isPaddedWithNbsp(node) || isEmpty$2(schema, nonEmptyElements, whiteSpaceElements, node))) {
  18829. paddEmptyNode(settings, args, blockElements, node);
  18830. }
  18831. node = node.parent;
  18832. }
  18833. }
  18834. }, schema);
  18835. var rootNode = node = new AstNode(args.context || settings.root_name, 11);
  18836. parser.parse(html, args.format);
  18837. if (validate && invalidChildren.length) {
  18838. if (!args.context) {
  18839. fixInvalidChildren(invalidChildren);
  18840. } else {
  18841. args.invalid = true;
  18842. }
  18843. }
  18844. if (rootBlockName && (rootNode.name === 'body' || args.isRootContent)) {
  18845. addRootBlocks();
  18846. }
  18847. if (!args.invalid) {
  18848. for (name in matchedNodes) {
  18849. if (!matchedNodes.hasOwnProperty(name)) {
  18850. continue;
  18851. }
  18852. list = nodeFilters[name];
  18853. nodes = matchedNodes[name];
  18854. fi = nodes.length;
  18855. while (fi--) {
  18856. if (!nodes[fi].parent) {
  18857. nodes.splice(fi, 1);
  18858. }
  18859. }
  18860. for (i = 0, l = list.length; i < l; i++) {
  18861. list[i](nodes, name, args);
  18862. }
  18863. }
  18864. for (i = 0, l = attributeFilters.length; i < l; i++) {
  18865. list = attributeFilters[i];
  18866. if (list.name in matchedAttributes) {
  18867. nodes = matchedAttributes[list.name];
  18868. fi = nodes.length;
  18869. while (fi--) {
  18870. if (!nodes[fi].parent) {
  18871. nodes.splice(fi, 1);
  18872. }
  18873. }
  18874. for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) {
  18875. list.callbacks[fi](nodes, list.name, args);
  18876. }
  18877. }
  18878. }
  18879. }
  18880. return rootNode;
  18881. };
  18882. var exports = {
  18883. schema: schema,
  18884. addAttributeFilter: addAttributeFilter,
  18885. getAttributeFilters: getAttributeFilters,
  18886. addNodeFilter: addNodeFilter,
  18887. getNodeFilters: getNodeFilters,
  18888. filterNode: filterNode,
  18889. parse: parse
  18890. };
  18891. register$2(exports, settings);
  18892. register$1(exports, settings);
  18893. return exports;
  18894. };
  18895. var register$3 = function (htmlParser, settings, dom) {
  18896. htmlParser.addAttributeFilter('data-mce-tabindex', function (nodes, name) {
  18897. var i = nodes.length, node;
  18898. while (i--) {
  18899. node = nodes[i];
  18900. node.attr('tabindex', node.attr('data-mce-tabindex'));
  18901. node.attr(name, null);
  18902. }
  18903. });
  18904. htmlParser.addAttributeFilter('src,href,style', function (nodes, name) {
  18905. var i = nodes.length, node, value;
  18906. var internalName = 'data-mce-' + name;
  18907. var urlConverter = settings.url_converter;
  18908. var urlConverterScope = settings.url_converter_scope;
  18909. while (i--) {
  18910. node = nodes[i];
  18911. value = node.attr(internalName);
  18912. if (value !== undefined) {
  18913. node.attr(name, value.length > 0 ? value : null);
  18914. node.attr(internalName, null);
  18915. } else {
  18916. value = node.attr(name);
  18917. if (name === 'style') {
  18918. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  18919. } else if (urlConverter) {
  18920. value = urlConverter.call(urlConverterScope, value, name, node.name);
  18921. }
  18922. node.attr(name, value.length > 0 ? value : null);
  18923. }
  18924. }
  18925. });
  18926. htmlParser.addAttributeFilter('class', function (nodes) {
  18927. var i = nodes.length, node, value;
  18928. while (i--) {
  18929. node = nodes[i];
  18930. value = node.attr('class');
  18931. if (value) {
  18932. value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
  18933. node.attr('class', value.length > 0 ? value : null);
  18934. }
  18935. }
  18936. });
  18937. htmlParser.addAttributeFilter('data-mce-type', function (nodes, name, args) {
  18938. var i = nodes.length, node;
  18939. while (i--) {
  18940. node = nodes[i];
  18941. if (node.attr('data-mce-type') === 'bookmark' && !args.cleanup) {
  18942. var hasChildren = Optional.from(node.firstChild).exists(function (firstChild) {
  18943. return !isZwsp$1(firstChild.value);
  18944. });
  18945. if (hasChildren) {
  18946. node.unwrap();
  18947. } else {
  18948. node.remove();
  18949. }
  18950. }
  18951. }
  18952. });
  18953. htmlParser.addNodeFilter('noscript', function (nodes) {
  18954. var i = nodes.length, node;
  18955. while (i--) {
  18956. node = nodes[i].firstChild;
  18957. if (node) {
  18958. node.value = Entities.decode(node.value);
  18959. }
  18960. }
  18961. });
  18962. htmlParser.addNodeFilter('script,style', function (nodes, name) {
  18963. var i = nodes.length, node, value, type;
  18964. var trim = function (value) {
  18965. 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, '');
  18966. };
  18967. while (i--) {
  18968. node = nodes[i];
  18969. value = node.firstChild ? node.firstChild.value : '';
  18970. if (name === 'script') {
  18971. type = node.attr('type');
  18972. if (type) {
  18973. node.attr('type', type === 'mce-no/type' ? null : type.replace(/^mce\-/, ''));
  18974. }
  18975. if (settings.element_format === 'xhtml' && value.length > 0) {
  18976. node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
  18977. }
  18978. } else {
  18979. if (settings.element_format === 'xhtml' && value.length > 0) {
  18980. node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
  18981. }
  18982. }
  18983. }
  18984. });
  18985. htmlParser.addNodeFilter('#comment', function (nodes) {
  18986. var i = nodes.length, node;
  18987. while (i--) {
  18988. node = nodes[i];
  18989. if (settings.preserve_cdata && node.value.indexOf('[CDATA[') === 0) {
  18990. node.name = '#cdata';
  18991. node.type = 4;
  18992. node.value = dom.decode(node.value.replace(/^\[CDATA\[|\]\]$/g, ''));
  18993. } else if (node.value.indexOf('mce:protected ') === 0) {
  18994. node.name = '#text';
  18995. node.type = 3;
  18996. node.raw = true;
  18997. node.value = unescape(node.value).substr(14);
  18998. }
  18999. }
  19000. });
  19001. htmlParser.addNodeFilter('xml:namespace,input', function (nodes, name) {
  19002. var i = nodes.length, node;
  19003. while (i--) {
  19004. node = nodes[i];
  19005. if (node.type === 7) {
  19006. node.remove();
  19007. } else if (node.type === 1) {
  19008. if (name === 'input' && !node.attr('type')) {
  19009. node.attr('type', 'text');
  19010. }
  19011. }
  19012. }
  19013. });
  19014. htmlParser.addAttributeFilter('data-mce-type', function (nodes) {
  19015. each(nodes, function (node) {
  19016. if (node.attr('data-mce-type') === 'format-caret') {
  19017. if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
  19018. node.remove();
  19019. } else {
  19020. node.unwrap();
  19021. }
  19022. }
  19023. });
  19024. });
  19025. 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) {
  19026. var i = nodes.length;
  19027. while (i--) {
  19028. nodes[i].attr(name, null);
  19029. }
  19030. });
  19031. };
  19032. var trimTrailingBr = function (rootNode) {
  19033. var isBr = function (node) {
  19034. return node && node.name === 'br';
  19035. };
  19036. var brNode1 = rootNode.lastChild;
  19037. if (isBr(brNode1)) {
  19038. var brNode2 = brNode1.prev;
  19039. if (isBr(brNode2)) {
  19040. brNode1.remove();
  19041. brNode2.remove();
  19042. }
  19043. }
  19044. };
  19045. var preProcess = function (editor, node, args) {
  19046. var doc, oldDoc;
  19047. var dom = editor.dom;
  19048. node = node.cloneNode(true);
  19049. var impl = document.implementation;
  19050. if (impl.createHTMLDocument) {
  19051. doc = impl.createHTMLDocument('');
  19052. Tools.each(node.nodeName === 'BODY' ? node.childNodes : [node], function (node) {
  19053. doc.body.appendChild(doc.importNode(node, true));
  19054. });
  19055. if (node.nodeName !== 'BODY') {
  19056. node = doc.body.firstChild;
  19057. } else {
  19058. node = doc.body;
  19059. }
  19060. oldDoc = dom.doc;
  19061. dom.doc = doc;
  19062. }
  19063. firePreProcess(editor, __assign(__assign({}, args), { node: node }));
  19064. if (oldDoc) {
  19065. dom.doc = oldDoc;
  19066. }
  19067. return node;
  19068. };
  19069. var shouldFireEvent = function (editor, args) {
  19070. return editor && editor.hasEventListeners('PreProcess') && !args.no_events;
  19071. };
  19072. var process = function (editor, node, args) {
  19073. return shouldFireEvent(editor, args) ? preProcess(editor, node, args) : node;
  19074. };
  19075. var addTempAttr = function (htmlParser, tempAttrs, name) {
  19076. if (Tools.inArray(tempAttrs, name) === -1) {
  19077. htmlParser.addAttributeFilter(name, function (nodes, name) {
  19078. var i = nodes.length;
  19079. while (i--) {
  19080. nodes[i].attr(name, null);
  19081. }
  19082. });
  19083. tempAttrs.push(name);
  19084. }
  19085. };
  19086. var postProcess$1 = function (editor, args, content) {
  19087. if (!args.no_events && editor) {
  19088. var outArgs = firePostProcess(editor, __assign(__assign({}, args), { content: content }));
  19089. return outArgs.content;
  19090. } else {
  19091. return content;
  19092. }
  19093. };
  19094. var getHtmlFromNode = function (dom, node, args) {
  19095. var html = trim$2(args.getInner ? node.innerHTML : dom.getOuterHTML(node));
  19096. return args.selection || isWsPreserveElement(SugarElement.fromDom(node)) ? html : Tools.trim(html);
  19097. };
  19098. var parseHtml = function (htmlParser, html, args) {
  19099. var parserArgs = args.selection ? __assign({ forced_root_block: false }, args) : args;
  19100. var rootNode = htmlParser.parse(html, parserArgs);
  19101. trimTrailingBr(rootNode);
  19102. return rootNode;
  19103. };
  19104. var serializeNode = function (settings, schema, node) {
  19105. var htmlSerializer = HtmlSerializer(settings, schema);
  19106. return htmlSerializer.serialize(node);
  19107. };
  19108. var toHtml = function (editor, settings, schema, rootNode, args) {
  19109. var content = serializeNode(settings, schema, rootNode);
  19110. return postProcess$1(editor, args, content);
  19111. };
  19112. var DomSerializerImpl = function (settings, editor) {
  19113. var tempAttrs = ['data-mce-selected'];
  19114. var dom = editor && editor.dom ? editor.dom : DOMUtils$1.DOM;
  19115. var schema = editor && editor.schema ? editor.schema : Schema(settings);
  19116. settings.entity_encoding = settings.entity_encoding || 'named';
  19117. settings.remove_trailing_brs = 'remove_trailing_brs' in settings ? settings.remove_trailing_brs : true;
  19118. var htmlParser = DomParser(settings, schema);
  19119. register$3(htmlParser, settings, dom);
  19120. var serialize = function (node, parserArgs) {
  19121. if (parserArgs === void 0) {
  19122. parserArgs = {};
  19123. }
  19124. var args = __assign({ format: 'html' }, parserArgs);
  19125. var targetNode = process(editor, node, args);
  19126. var html = getHtmlFromNode(dom, targetNode, args);
  19127. var rootNode = parseHtml(htmlParser, html, args);
  19128. return args.format === 'tree' ? rootNode : toHtml(editor, settings, schema, rootNode, args);
  19129. };
  19130. return {
  19131. schema: schema,
  19132. addNodeFilter: htmlParser.addNodeFilter,
  19133. addAttributeFilter: htmlParser.addAttributeFilter,
  19134. serialize: serialize,
  19135. addRules: function (rules) {
  19136. schema.addValidElements(rules);
  19137. },
  19138. setRules: function (rules) {
  19139. schema.setValidElements(rules);
  19140. },
  19141. addTempAttr: curry(addTempAttr, htmlParser, tempAttrs),
  19142. getTempAttrs: function () {
  19143. return tempAttrs;
  19144. },
  19145. getNodeFilters: htmlParser.getNodeFilters,
  19146. getAttributeFilters: htmlParser.getAttributeFilters
  19147. };
  19148. };
  19149. var DomSerializer = function (settings, editor) {
  19150. var domSerializer = DomSerializerImpl(settings, editor);
  19151. return {
  19152. schema: domSerializer.schema,
  19153. addNodeFilter: domSerializer.addNodeFilter,
  19154. addAttributeFilter: domSerializer.addAttributeFilter,
  19155. serialize: domSerializer.serialize,
  19156. addRules: domSerializer.addRules,
  19157. setRules: domSerializer.setRules,
  19158. addTempAttr: domSerializer.addTempAttr,
  19159. getTempAttrs: domSerializer.getTempAttrs,
  19160. getNodeFilters: domSerializer.getNodeFilters,
  19161. getAttributeFilters: domSerializer.getAttributeFilters
  19162. };
  19163. };
  19164. var defaultFormat$1 = 'html';
  19165. var getContent$2 = function (editor, args) {
  19166. if (args === void 0) {
  19167. args = {};
  19168. }
  19169. var format = args.format ? args.format : defaultFormat$1;
  19170. return getContent(editor, args, format);
  19171. };
  19172. var setContent$2 = function (editor, content, args) {
  19173. if (args === void 0) {
  19174. args = {};
  19175. }
  19176. return setContent(editor, content, args);
  19177. };
  19178. var DOM$3 = DOMUtils$1.DOM;
  19179. var restoreOriginalStyles = function (editor) {
  19180. DOM$3.setStyle(editor.id, 'display', editor.orgDisplay);
  19181. };
  19182. var safeDestroy = function (x) {
  19183. return Optional.from(x).each(function (x) {
  19184. return x.destroy();
  19185. });
  19186. };
  19187. var clearDomReferences = function (editor) {
  19188. editor.contentAreaContainer = editor.formElement = editor.container = editor.editorContainer = null;
  19189. editor.bodyElement = editor.contentDocument = editor.contentWindow = null;
  19190. editor.iframeElement = editor.targetElm = null;
  19191. if (editor.selection) {
  19192. editor.selection = editor.selection.win = editor.selection.dom = editor.selection.dom.doc = null;
  19193. }
  19194. };
  19195. var restoreForm = function (editor) {
  19196. var form = editor.formElement;
  19197. if (form) {
  19198. if (form._mceOldSubmit) {
  19199. form.submit = form._mceOldSubmit;
  19200. form._mceOldSubmit = null;
  19201. }
  19202. DOM$3.unbind(form, 'submit reset', editor.formEventDelegate);
  19203. }
  19204. };
  19205. var remove$7 = function (editor) {
  19206. if (!editor.removed) {
  19207. var _selectionOverrides = editor._selectionOverrides, editorUpload = editor.editorUpload;
  19208. var body = editor.getBody();
  19209. var element = editor.getElement();
  19210. if (body) {
  19211. editor.save({ is_removing: true });
  19212. }
  19213. editor.removed = true;
  19214. editor.unbindAllNativeEvents();
  19215. if (editor.hasHiddenInput && element) {
  19216. DOM$3.remove(element.nextSibling);
  19217. }
  19218. fireRemove(editor);
  19219. editor.editorManager.remove(editor);
  19220. if (!editor.inline && body) {
  19221. restoreOriginalStyles(editor);
  19222. }
  19223. fireDetach(editor);
  19224. DOM$3.remove(editor.getContainer());
  19225. safeDestroy(_selectionOverrides);
  19226. safeDestroy(editorUpload);
  19227. editor.destroy();
  19228. }
  19229. };
  19230. var destroy = function (editor, automatic) {
  19231. var selection = editor.selection, dom = editor.dom;
  19232. if (editor.destroyed) {
  19233. return;
  19234. }
  19235. if (!automatic && !editor.removed) {
  19236. editor.remove();
  19237. return;
  19238. }
  19239. if (!automatic) {
  19240. editor.editorManager.off('beforeunload', editor._beforeUnload);
  19241. if (editor.theme && editor.theme.destroy) {
  19242. editor.theme.destroy();
  19243. }
  19244. safeDestroy(selection);
  19245. safeDestroy(dom);
  19246. }
  19247. restoreForm(editor);
  19248. clearDomReferences(editor);
  19249. editor.destroyed = true;
  19250. };
  19251. var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
  19252. var deep$1 = function (old, nu) {
  19253. var bothObjects = isObject(old) && isObject(nu);
  19254. return bothObjects ? deepMerge(old, nu) : nu;
  19255. };
  19256. var baseMerge = function (merger) {
  19257. return function () {
  19258. var objects = new Array(arguments.length);
  19259. for (var i = 0; i < objects.length; i++) {
  19260. objects[i] = arguments[i];
  19261. }
  19262. if (objects.length === 0) {
  19263. throw new Error('Can\'t merge zero objects');
  19264. }
  19265. var ret = {};
  19266. for (var j = 0; j < objects.length; j++) {
  19267. var curObject = objects[j];
  19268. for (var key in curObject) {
  19269. if (hasOwnProperty$2.call(curObject, key)) {
  19270. ret[key] = merger(ret[key], curObject[key]);
  19271. }
  19272. }
  19273. }
  19274. return ret;
  19275. };
  19276. };
  19277. var deepMerge = baseMerge(deep$1);
  19278. var sectionResult = function (sections, settings) {
  19279. return {
  19280. sections: constant(sections),
  19281. settings: constant(settings)
  19282. };
  19283. };
  19284. var deviceDetection = detect$3().deviceType;
  19285. var isTouch = deviceDetection.isTouch();
  19286. var isPhone = deviceDetection.isPhone();
  19287. var isTablet = deviceDetection.isTablet();
  19288. var legacyMobilePlugins = [
  19289. 'lists',
  19290. 'autolink',
  19291. 'autosave'
  19292. ];
  19293. var defaultTouchSettings = {
  19294. table_grid: false,
  19295. object_resizing: false,
  19296. resize: false
  19297. };
  19298. var normalizePlugins = function (plugins) {
  19299. var pluginNames = isArray(plugins) ? plugins.join(' ') : plugins;
  19300. var trimmedPlugins = map(isString(pluginNames) ? pluginNames.split(' ') : [], trim);
  19301. return filter(trimmedPlugins, function (item) {
  19302. return item.length > 0;
  19303. });
  19304. };
  19305. var filterLegacyMobilePlugins = function (plugins) {
  19306. return filter(plugins, curry(contains, legacyMobilePlugins));
  19307. };
  19308. var extractSections = function (keys, settings) {
  19309. var result = bifilter(settings, function (value, key) {
  19310. return contains(keys, key);
  19311. });
  19312. return sectionResult(result.t, result.f);
  19313. };
  19314. var getSection = function (sectionResult, name, defaults) {
  19315. if (defaults === void 0) {
  19316. defaults = {};
  19317. }
  19318. var sections = sectionResult.sections();
  19319. var sectionSettings = sections.hasOwnProperty(name) ? sections[name] : {};
  19320. return Tools.extend({}, defaults, sectionSettings);
  19321. };
  19322. var hasSection = function (sectionResult, name) {
  19323. return sectionResult.sections().hasOwnProperty(name);
  19324. };
  19325. var isSectionTheme = function (sectionResult, name, theme) {
  19326. var section = sectionResult.sections();
  19327. return hasSection(sectionResult, name) && section[name].theme === theme;
  19328. };
  19329. var getSectionConfig = function (sectionResult, name) {
  19330. return hasSection(sectionResult, name) ? sectionResult.sections()[name] : {};
  19331. };
  19332. var getToolbarMode = function (settings, defaultVal) {
  19333. return get$1(settings, 'toolbar_mode').orThunk(function () {
  19334. return get$1(settings, 'toolbar_drawer').map(function (val) {
  19335. return val === false ? 'wrap' : val;
  19336. });
  19337. }).getOr(defaultVal);
  19338. };
  19339. var getDefaultSettings = function (settings, id, documentBaseUrl, isTouch, editor) {
  19340. var baseDefaults = {
  19341. id: id,
  19342. theme: 'silver',
  19343. toolbar_mode: getToolbarMode(settings, 'floating'),
  19344. plugins: '',
  19345. document_base_url: documentBaseUrl,
  19346. add_form_submit_trigger: true,
  19347. submit_patch: true,
  19348. add_unload_trigger: true,
  19349. convert_urls: true,
  19350. relative_urls: true,
  19351. remove_script_host: true,
  19352. object_resizing: true,
  19353. doctype: '<!DOCTYPE html>',
  19354. visual: true,
  19355. font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%',
  19356. forced_root_block: 'p',
  19357. hidden_input: true,
  19358. inline_styles: true,
  19359. convert_fonts_to_spans: true,
  19360. indent: true,
  19361. 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',
  19362. 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',
  19363. entity_encoding: 'named',
  19364. url_converter: editor.convertURL,
  19365. url_converter_scope: editor
  19366. };
  19367. return __assign(__assign({}, baseDefaults), isTouch ? defaultTouchSettings : {});
  19368. };
  19369. var getDefaultMobileSettings = function (mobileSettings, isPhone) {
  19370. var defaultMobileSettings = {
  19371. resize: false,
  19372. toolbar_mode: getToolbarMode(mobileSettings, 'scrolling'),
  19373. toolbar_sticky: false
  19374. };
  19375. var defaultPhoneSettings = { menubar: false };
  19376. return __assign(__assign(__assign({}, defaultTouchSettings), defaultMobileSettings), isPhone ? defaultPhoneSettings : {});
  19377. };
  19378. var getExternalPlugins$1 = function (overrideSettings, settings) {
  19379. var userDefinedExternalPlugins = settings.external_plugins ? settings.external_plugins : {};
  19380. if (overrideSettings && overrideSettings.external_plugins) {
  19381. return Tools.extend({}, overrideSettings.external_plugins, userDefinedExternalPlugins);
  19382. } else {
  19383. return userDefinedExternalPlugins;
  19384. }
  19385. };
  19386. var combinePlugins = function (forcedPlugins, plugins) {
  19387. return [].concat(normalizePlugins(forcedPlugins)).concat(normalizePlugins(plugins));
  19388. };
  19389. var getPlatformPlugins = function (isMobileDevice, sectionResult, desktopPlugins, mobilePlugins) {
  19390. if (isMobileDevice && isSectionTheme(sectionResult, 'mobile', 'mobile')) {
  19391. return filterLegacyMobilePlugins(mobilePlugins);
  19392. } else if (isMobileDevice && hasSection(sectionResult, 'mobile')) {
  19393. return mobilePlugins;
  19394. } else {
  19395. return desktopPlugins;
  19396. }
  19397. };
  19398. var processPlugins = function (isMobileDevice, sectionResult, defaultOverrideSettings, settings) {
  19399. var forcedPlugins = normalizePlugins(defaultOverrideSettings.forced_plugins);
  19400. var desktopPlugins = normalizePlugins(settings.plugins);
  19401. var mobileConfig = getSectionConfig(sectionResult, 'mobile');
  19402. var mobilePlugins = mobileConfig.plugins ? normalizePlugins(mobileConfig.plugins) : desktopPlugins;
  19403. var platformPlugins = getPlatformPlugins(isMobileDevice, sectionResult, desktopPlugins, mobilePlugins);
  19404. var combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
  19405. if (Env.browser.isIE() && contains(combinedPlugins, 'rtc')) {
  19406. throw new Error('RTC plugin is not supported on IE 11.');
  19407. }
  19408. return Tools.extend(settings, { plugins: combinedPlugins.join(' ') });
  19409. };
  19410. var isOnMobile = function (isMobileDevice, sectionResult) {
  19411. return isMobileDevice && hasSection(sectionResult, 'mobile');
  19412. };
  19413. var combineSettings = function (isMobileDevice, isPhone, defaultSettings, defaultOverrideSettings, settings) {
  19414. var defaultDeviceSettings = isMobileDevice ? { mobile: getDefaultMobileSettings(settings.mobile || {}, isPhone) } : {};
  19415. var sectionResult = extractSections(['mobile'], deepMerge(defaultDeviceSettings, settings));
  19416. var extendedSettings = Tools.extend(defaultSettings, defaultOverrideSettings, sectionResult.settings(), isOnMobile(isMobileDevice, sectionResult) ? getSection(sectionResult, 'mobile') : {}, {
  19417. validate: true,
  19418. external_plugins: getExternalPlugins$1(defaultOverrideSettings, sectionResult.settings())
  19419. });
  19420. return processPlugins(isMobileDevice, sectionResult, defaultOverrideSettings, extendedSettings);
  19421. };
  19422. var getEditorSettings = function (editor, id, documentBaseUrl, defaultOverrideSettings, settings) {
  19423. var defaultSettings = getDefaultSettings(settings, id, documentBaseUrl, isTouch, editor);
  19424. return combineSettings(isPhone || isTablet, isPhone, defaultSettings, defaultOverrideSettings, settings);
  19425. };
  19426. var getFiltered = function (predicate, editor, name) {
  19427. return Optional.from(editor.settings[name]).filter(predicate);
  19428. };
  19429. var getParamObject = function (value) {
  19430. var output = {};
  19431. if (typeof value === 'string') {
  19432. each(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function (val) {
  19433. var arr = val.split('=');
  19434. if (arr.length > 1) {
  19435. output[Tools.trim(arr[0])] = Tools.trim(arr[1]);
  19436. } else {
  19437. output[Tools.trim(arr[0])] = Tools.trim(arr[0]);
  19438. }
  19439. });
  19440. } else {
  19441. output = value;
  19442. }
  19443. return output;
  19444. };
  19445. var isArrayOf = function (p) {
  19446. return function (a) {
  19447. return isArray(a) && forall(a, p);
  19448. };
  19449. };
  19450. var getParam = function (editor, name, defaultVal, type) {
  19451. var value = name in editor.settings ? editor.settings[name] : defaultVal;
  19452. if (type === 'hash') {
  19453. return getParamObject(value);
  19454. } else if (type === 'string') {
  19455. return getFiltered(isString, editor, name).getOr(defaultVal);
  19456. } else if (type === 'number') {
  19457. return getFiltered(isNumber, editor, name).getOr(defaultVal);
  19458. } else if (type === 'boolean') {
  19459. return getFiltered(isBoolean, editor, name).getOr(defaultVal);
  19460. } else if (type === 'object') {
  19461. return getFiltered(isObject, editor, name).getOr(defaultVal);
  19462. } else if (type === 'array') {
  19463. return getFiltered(isArray, editor, name).getOr(defaultVal);
  19464. } else if (type === 'string[]') {
  19465. return getFiltered(isArrayOf(isString), editor, name).getOr(defaultVal);
  19466. } else if (type === 'function') {
  19467. return getFiltered(isFunction, editor, name).getOr(defaultVal);
  19468. } else {
  19469. return value;
  19470. }
  19471. };
  19472. var CreateIconManager = function () {
  19473. var lookup = {};
  19474. var add = function (id, iconPack) {
  19475. lookup[id] = iconPack;
  19476. };
  19477. var get = function (id) {
  19478. if (lookup[id]) {
  19479. return lookup[id];
  19480. }
  19481. return { icons: {} };
  19482. };
  19483. var has$1 = function (id) {
  19484. return has(lookup, id);
  19485. };
  19486. return {
  19487. add: add,
  19488. get: get,
  19489. has: has$1
  19490. };
  19491. };
  19492. var IconManager = CreateIconManager();
  19493. var getProp = function (propName, elm) {
  19494. var rawElm = elm.dom;
  19495. return rawElm[propName];
  19496. };
  19497. var getComputedSizeProp = function (propName, elm) {
  19498. return parseInt(get$5(elm, propName), 10);
  19499. };
  19500. var getClientWidth = curry(getProp, 'clientWidth');
  19501. var getClientHeight = curry(getProp, 'clientHeight');
  19502. var getMarginTop = curry(getComputedSizeProp, 'margin-top');
  19503. var getMarginLeft = curry(getComputedSizeProp, 'margin-left');
  19504. var getBoundingClientRect$1 = function (elm) {
  19505. return elm.dom.getBoundingClientRect();
  19506. };
  19507. var isInsideElementContentArea = function (bodyElm, clientX, clientY) {
  19508. var clientWidth = getClientWidth(bodyElm);
  19509. var clientHeight = getClientHeight(bodyElm);
  19510. return clientX >= 0 && clientY >= 0 && clientX <= clientWidth && clientY <= clientHeight;
  19511. };
  19512. var transpose = function (inline, elm, clientX, clientY) {
  19513. var clientRect = getBoundingClientRect$1(elm);
  19514. var deltaX = inline ? clientRect.left + elm.dom.clientLeft + getMarginLeft(elm) : 0;
  19515. var deltaY = inline ? clientRect.top + elm.dom.clientTop + getMarginTop(elm) : 0;
  19516. var x = clientX - deltaX;
  19517. var y = clientY - deltaY;
  19518. return {
  19519. x: x,
  19520. y: y
  19521. };
  19522. };
  19523. var isXYInContentArea = function (editor, clientX, clientY) {
  19524. var bodyElm = SugarElement.fromDom(editor.getBody());
  19525. var targetElm = editor.inline ? bodyElm : documentElement(bodyElm);
  19526. var transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
  19527. return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
  19528. };
  19529. var fromDomSafe = function (node) {
  19530. return Optional.from(node).map(SugarElement.fromDom);
  19531. };
  19532. var isEditorAttachedToDom = function (editor) {
  19533. var rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
  19534. return fromDomSafe(rawContainer).map(inBody).getOr(false);
  19535. };
  19536. function NotificationManagerImpl() {
  19537. var unimplemented = function () {
  19538. throw new Error('Theme did not provide a NotificationManager implementation.');
  19539. };
  19540. return {
  19541. open: unimplemented,
  19542. close: unimplemented,
  19543. reposition: unimplemented,
  19544. getArgs: unimplemented
  19545. };
  19546. }
  19547. function NotificationManager(editor) {
  19548. var notifications = [];
  19549. var getImplementation = function () {
  19550. var theme = editor.theme;
  19551. return theme && theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
  19552. };
  19553. var getTopNotification = function () {
  19554. return Optional.from(notifications[0]);
  19555. };
  19556. var isEqual = function (a, b) {
  19557. return a.type === b.type && a.text === b.text && !a.progressBar && !a.timeout && !b.progressBar && !b.timeout;
  19558. };
  19559. var reposition = function () {
  19560. if (notifications.length > 0) {
  19561. getImplementation().reposition(notifications);
  19562. }
  19563. };
  19564. var addNotification = function (notification) {
  19565. notifications.push(notification);
  19566. };
  19567. var closeNotification = function (notification) {
  19568. findIndex(notifications, function (otherNotification) {
  19569. return otherNotification === notification;
  19570. }).each(function (index) {
  19571. notifications.splice(index, 1);
  19572. });
  19573. };
  19574. var open = function (spec, fireEvent) {
  19575. if (fireEvent === void 0) {
  19576. fireEvent = true;
  19577. }
  19578. if (editor.removed || !isEditorAttachedToDom(editor)) {
  19579. return;
  19580. }
  19581. if (fireEvent) {
  19582. editor.fire('BeforeOpenNotification', { notification: spec });
  19583. }
  19584. return find(notifications, function (notification) {
  19585. return isEqual(getImplementation().getArgs(notification), spec);
  19586. }).getOrThunk(function () {
  19587. editor.editorManager.setActive(editor);
  19588. var notification = getImplementation().open(spec, function () {
  19589. closeNotification(notification);
  19590. reposition();
  19591. getTopNotification().fold(function () {
  19592. return editor.focus();
  19593. }, function (top) {
  19594. return focus(SugarElement.fromDom(top.getEl()));
  19595. });
  19596. });
  19597. addNotification(notification);
  19598. reposition();
  19599. editor.fire('OpenNotification', __assign({}, notification));
  19600. return notification;
  19601. });
  19602. };
  19603. var close = function () {
  19604. getTopNotification().each(function (notification) {
  19605. getImplementation().close(notification);
  19606. closeNotification(notification);
  19607. reposition();
  19608. });
  19609. };
  19610. var getNotifications = function () {
  19611. return notifications;
  19612. };
  19613. var registerEvents = function (editor) {
  19614. editor.on('SkinLoaded', function () {
  19615. var serviceMessage = getServiceMessage(editor);
  19616. if (serviceMessage) {
  19617. open({
  19618. text: serviceMessage,
  19619. type: 'warning',
  19620. timeout: 0
  19621. }, false);
  19622. }
  19623. });
  19624. editor.on('ResizeEditor ResizeWindow NodeChange', function () {
  19625. Delay.requestAnimationFrame(reposition);
  19626. });
  19627. editor.on('remove', function () {
  19628. each(notifications.slice(), function (notification) {
  19629. getImplementation().close(notification);
  19630. });
  19631. });
  19632. };
  19633. registerEvents(editor);
  19634. return {
  19635. open: open,
  19636. close: close,
  19637. getNotifications: getNotifications
  19638. };
  19639. }
  19640. var PluginManager = AddOnManager$1.PluginManager;
  19641. var ThemeManager = AddOnManager$1.ThemeManager;
  19642. function WindowManagerImpl () {
  19643. var unimplemented = function () {
  19644. throw new Error('Theme did not provide a WindowManager implementation.');
  19645. };
  19646. return {
  19647. open: unimplemented,
  19648. openUrl: unimplemented,
  19649. alert: unimplemented,
  19650. confirm: unimplemented,
  19651. close: unimplemented,
  19652. getParams: unimplemented,
  19653. setParams: unimplemented
  19654. };
  19655. }
  19656. var WindowManager = function (editor) {
  19657. var dialogs = [];
  19658. var getImplementation = function () {
  19659. var theme = editor.theme;
  19660. return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
  19661. };
  19662. var funcBind = function (scope, f) {
  19663. return function () {
  19664. return f ? f.apply(scope, arguments) : undefined;
  19665. };
  19666. };
  19667. var fireOpenEvent = function (dialog) {
  19668. editor.fire('OpenWindow', { dialog: dialog });
  19669. };
  19670. var fireCloseEvent = function (dialog) {
  19671. editor.fire('CloseWindow', { dialog: dialog });
  19672. };
  19673. var addDialog = function (dialog) {
  19674. dialogs.push(dialog);
  19675. fireOpenEvent(dialog);
  19676. };
  19677. var closeDialog = function (dialog) {
  19678. fireCloseEvent(dialog);
  19679. dialogs = filter(dialogs, function (otherDialog) {
  19680. return otherDialog !== dialog;
  19681. });
  19682. if (dialogs.length === 0) {
  19683. editor.focus();
  19684. }
  19685. };
  19686. var getTopDialog = function () {
  19687. return Optional.from(dialogs[dialogs.length - 1]);
  19688. };
  19689. var storeSelectionAndOpenDialog = function (openDialog) {
  19690. editor.editorManager.setActive(editor);
  19691. store(editor);
  19692. var dialog = openDialog();
  19693. addDialog(dialog);
  19694. return dialog;
  19695. };
  19696. var open = function (args, params) {
  19697. return storeSelectionAndOpenDialog(function () {
  19698. return getImplementation().open(args, params, closeDialog);
  19699. });
  19700. };
  19701. var openUrl = function (args) {
  19702. return storeSelectionAndOpenDialog(function () {
  19703. return getImplementation().openUrl(args, closeDialog);
  19704. });
  19705. };
  19706. var alert = function (message, callback, scope) {
  19707. getImplementation().alert(message, funcBind(scope ? scope : this, callback));
  19708. };
  19709. var confirm = function (message, callback, scope) {
  19710. getImplementation().confirm(message, funcBind(scope ? scope : this, callback));
  19711. };
  19712. var close = function () {
  19713. getTopDialog().each(function (dialog) {
  19714. getImplementation().close(dialog);
  19715. closeDialog(dialog);
  19716. });
  19717. };
  19718. editor.on('remove', function () {
  19719. each(dialogs, function (dialog) {
  19720. getImplementation().close(dialog);
  19721. });
  19722. });
  19723. return {
  19724. open: open,
  19725. openUrl: openUrl,
  19726. alert: alert,
  19727. confirm: confirm,
  19728. close: close
  19729. };
  19730. };
  19731. var displayNotification = function (editor, message) {
  19732. editor.notificationManager.open({
  19733. type: 'error',
  19734. text: message
  19735. });
  19736. };
  19737. var displayError = function (editor, message) {
  19738. if (editor._skinLoaded) {
  19739. displayNotification(editor, message);
  19740. } else {
  19741. editor.on('SkinLoaded', function () {
  19742. displayNotification(editor, message);
  19743. });
  19744. }
  19745. };
  19746. var uploadError = function (editor, message) {
  19747. displayError(editor, I18n.translate([
  19748. 'Failed to upload image: {0}',
  19749. message
  19750. ]));
  19751. };
  19752. var logError = function (editor, errorType, msg) {
  19753. fireError(editor, errorType, { message: msg });
  19754. console.error(msg);
  19755. };
  19756. var createLoadError = function (type, url, name) {
  19757. return name ? 'Failed to load ' + type + ': ' + name + ' from url ' + url : 'Failed to load ' + type + ' url: ' + url;
  19758. };
  19759. var pluginLoadError = function (editor, url, name) {
  19760. logError(editor, 'PluginLoadError', createLoadError('plugin', url, name));
  19761. };
  19762. var iconsLoadError = function (editor, url, name) {
  19763. logError(editor, 'IconsLoadError', createLoadError('icons', url, name));
  19764. };
  19765. var languageLoadError = function (editor, url, name) {
  19766. logError(editor, 'LanguageLoadError', createLoadError('language', url, name));
  19767. };
  19768. var pluginInitError = function (editor, name, err) {
  19769. var message = I18n.translate([
  19770. 'Failed to initialize plugin: {0}',
  19771. name
  19772. ]);
  19773. initError(message, err);
  19774. displayError(editor, message);
  19775. };
  19776. var initError = function (message) {
  19777. var x = [];
  19778. for (var _i = 1; _i < arguments.length; _i++) {
  19779. x[_i - 1] = arguments[_i];
  19780. }
  19781. var console = window.console;
  19782. if (console) {
  19783. if (console.error) {
  19784. console.error.apply(console, __spreadArrays([message], x));
  19785. } else {
  19786. console.log.apply(console, __spreadArrays([message], x));
  19787. }
  19788. }
  19789. };
  19790. var isContentCssSkinName = function (url) {
  19791. return /^[a-z0-9\-]+$/i.test(url);
  19792. };
  19793. var getContentCssUrls = function (editor) {
  19794. var contentCss = getContentCss(editor);
  19795. var skinUrl = editor.editorManager.baseURL + '/skins/content';
  19796. var suffix = editor.editorManager.suffix;
  19797. var contentCssFile = 'content' + suffix + '.css';
  19798. var inline = editor.inline === true;
  19799. return map(contentCss, function (url) {
  19800. if (isContentCssSkinName(url) && !inline) {
  19801. return skinUrl + '/' + url + '/' + contentCssFile;
  19802. } else {
  19803. return editor.documentBaseURI.toAbsolute(url);
  19804. }
  19805. });
  19806. };
  19807. var appendContentCssFromSettings = function (editor) {
  19808. editor.contentCSS = editor.contentCSS.concat(getContentCssUrls(editor));
  19809. };
  19810. function Uploader(uploadStatus, settings) {
  19811. var pendingPromises = {};
  19812. var pathJoin = function (path1, path2) {
  19813. if (path1) {
  19814. return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
  19815. }
  19816. return path2;
  19817. };
  19818. var defaultHandler = function (blobInfo, success, failure, progress) {
  19819. var xhr = new XMLHttpRequest();
  19820. xhr.open('POST', settings.url);
  19821. xhr.withCredentials = settings.credentials;
  19822. xhr.upload.onprogress = function (e) {
  19823. progress(e.loaded / e.total * 100);
  19824. };
  19825. xhr.onerror = function () {
  19826. failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  19827. };
  19828. xhr.onload = function () {
  19829. if (xhr.status < 200 || xhr.status >= 300) {
  19830. failure('HTTP Error: ' + xhr.status);
  19831. return;
  19832. }
  19833. var json = JSON.parse(xhr.responseText);
  19834. if (!json || typeof json.location !== 'string') {
  19835. failure('Invalid JSON: ' + xhr.responseText);
  19836. return;
  19837. }
  19838. success(pathJoin(settings.basePath, json.location));
  19839. };
  19840. var formData = new FormData();
  19841. formData.append('file', blobInfo.blob(), blobInfo.filename());
  19842. xhr.send(formData);
  19843. };
  19844. var noUpload = function () {
  19845. return new promiseObj(function (resolve) {
  19846. resolve([]);
  19847. });
  19848. };
  19849. var handlerSuccess = function (blobInfo, url) {
  19850. return {
  19851. url: url,
  19852. blobInfo: blobInfo,
  19853. status: true
  19854. };
  19855. };
  19856. var handlerFailure = function (blobInfo, message, options) {
  19857. return {
  19858. url: '',
  19859. blobInfo: blobInfo,
  19860. status: false,
  19861. error: {
  19862. message: message,
  19863. options: options
  19864. }
  19865. };
  19866. };
  19867. var resolvePending = function (blobUri, result) {
  19868. Tools.each(pendingPromises[blobUri], function (resolve) {
  19869. resolve(result);
  19870. });
  19871. delete pendingPromises[blobUri];
  19872. };
  19873. var uploadBlobInfo = function (blobInfo, handler, openNotification) {
  19874. uploadStatus.markPending(blobInfo.blobUri());
  19875. return new promiseObj(function (resolve) {
  19876. var notification, progress;
  19877. var noop = function () {
  19878. };
  19879. try {
  19880. var closeNotification_1 = function () {
  19881. if (notification) {
  19882. notification.close();
  19883. progress = noop;
  19884. }
  19885. };
  19886. var success = function (url) {
  19887. closeNotification_1();
  19888. uploadStatus.markUploaded(blobInfo.blobUri(), url);
  19889. resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
  19890. resolve(handlerSuccess(blobInfo, url));
  19891. };
  19892. var failure = function (error, options) {
  19893. var failureOptions = options ? options : {};
  19894. closeNotification_1();
  19895. uploadStatus.removeFailed(blobInfo.blobUri());
  19896. resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error, failureOptions));
  19897. resolve(handlerFailure(blobInfo, error, failureOptions));
  19898. };
  19899. progress = function (percent) {
  19900. if (percent < 0 || percent > 100) {
  19901. return;
  19902. }
  19903. if (!notification) {
  19904. notification = openNotification();
  19905. }
  19906. notification.progressBar.value(percent);
  19907. };
  19908. handler(blobInfo, success, failure, progress);
  19909. } catch (ex) {
  19910. resolve(handlerFailure(blobInfo, ex.message, {}));
  19911. }
  19912. });
  19913. };
  19914. var isDefaultHandler = function (handler) {
  19915. return handler === defaultHandler;
  19916. };
  19917. var pendingUploadBlobInfo = function (blobInfo) {
  19918. var blobUri = blobInfo.blobUri();
  19919. return new promiseObj(function (resolve) {
  19920. pendingPromises[blobUri] = pendingPromises[blobUri] || [];
  19921. pendingPromises[blobUri].push(resolve);
  19922. });
  19923. };
  19924. var uploadBlobs = function (blobInfos, openNotification) {
  19925. blobInfos = Tools.grep(blobInfos, function (blobInfo) {
  19926. return !uploadStatus.isUploaded(blobInfo.blobUri());
  19927. });
  19928. return promiseObj.all(Tools.map(blobInfos, function (blobInfo) {
  19929. return uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification);
  19930. }));
  19931. };
  19932. var upload = function (blobInfos, openNotification) {
  19933. return !settings.url && isDefaultHandler(settings.handler) ? noUpload() : uploadBlobs(blobInfos, openNotification);
  19934. };
  19935. if (isFunction(settings.handler) === false) {
  19936. settings.handler = defaultHandler;
  19937. }
  19938. return { upload: upload };
  19939. }
  19940. function UploadStatus () {
  19941. var PENDING = 1, UPLOADED = 2;
  19942. var blobUriStatuses = {};
  19943. var createStatus = function (status, resultUri) {
  19944. return {
  19945. status: status,
  19946. resultUri: resultUri
  19947. };
  19948. };
  19949. var hasBlobUri = function (blobUri) {
  19950. return blobUri in blobUriStatuses;
  19951. };
  19952. var getResultUri = function (blobUri) {
  19953. var result = blobUriStatuses[blobUri];
  19954. return result ? result.resultUri : null;
  19955. };
  19956. var isPending = function (blobUri) {
  19957. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
  19958. };
  19959. var isUploaded = function (blobUri) {
  19960. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
  19961. };
  19962. var markPending = function (blobUri) {
  19963. blobUriStatuses[blobUri] = createStatus(PENDING, null);
  19964. };
  19965. var markUploaded = function (blobUri, resultUri) {
  19966. blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
  19967. };
  19968. var removeFailed = function (blobUri) {
  19969. delete blobUriStatuses[blobUri];
  19970. };
  19971. var destroy = function () {
  19972. blobUriStatuses = {};
  19973. };
  19974. return {
  19975. hasBlobUri: hasBlobUri,
  19976. getResultUri: getResultUri,
  19977. isPending: isPending,
  19978. isUploaded: isUploaded,
  19979. markPending: markPending,
  19980. markUploaded: markUploaded,
  19981. removeFailed: removeFailed,
  19982. destroy: destroy
  19983. };
  19984. }
  19985. var count$1 = 0;
  19986. var seed = function () {
  19987. var rnd = function () {
  19988. return Math.round(Math.random() * 4294967295).toString(36);
  19989. };
  19990. var now = new Date().getTime();
  19991. return 's' + now.toString(36) + rnd() + rnd() + rnd();
  19992. };
  19993. var uuid = function (prefix) {
  19994. return prefix + count$1++ + seed();
  19995. };
  19996. var BlobCache = function () {
  19997. var cache = [];
  19998. var mimeToExt = function (mime) {
  19999. var mimes = {
  20000. 'image/jpeg': 'jpg',
  20001. 'image/jpg': 'jpg',
  20002. 'image/gif': 'gif',
  20003. 'image/png': 'png',
  20004. 'image/apng': 'apng',
  20005. 'image/avif': 'avif',
  20006. 'image/svg+xml': 'svg',
  20007. 'image/webp': 'webp',
  20008. 'image/bmp': 'bmp',
  20009. 'image/tiff': 'tiff'
  20010. };
  20011. return mimes[mime.toLowerCase()] || 'dat';
  20012. };
  20013. var create = function (o, blob, base64, name, filename) {
  20014. if (isString(o)) {
  20015. var id = o;
  20016. return toBlobInfo({
  20017. id: id,
  20018. name: name,
  20019. filename: filename,
  20020. blob: blob,
  20021. base64: base64
  20022. });
  20023. } else if (isObject(o)) {
  20024. return toBlobInfo(o);
  20025. } else {
  20026. throw new Error('Unknown input type');
  20027. }
  20028. };
  20029. var toBlobInfo = function (o) {
  20030. if (!o.blob || !o.base64) {
  20031. throw new Error('blob and base64 representations of the image are required for BlobInfo to be created');
  20032. }
  20033. var id = o.id || uuid('blobid');
  20034. var name = o.name || id;
  20035. var blob = o.blob;
  20036. return {
  20037. id: constant(id),
  20038. name: constant(name),
  20039. filename: constant(o.filename || name + '.' + mimeToExt(blob.type)),
  20040. blob: constant(blob),
  20041. base64: constant(o.base64),
  20042. blobUri: constant(o.blobUri || URL.createObjectURL(blob)),
  20043. uri: constant(o.uri)
  20044. };
  20045. };
  20046. var add = function (blobInfo) {
  20047. if (!get(blobInfo.id())) {
  20048. cache.push(blobInfo);
  20049. }
  20050. };
  20051. var findFirst = function (predicate) {
  20052. return find(cache, predicate).getOrUndefined();
  20053. };
  20054. var get = function (id) {
  20055. return findFirst(function (cachedBlobInfo) {
  20056. return cachedBlobInfo.id() === id;
  20057. });
  20058. };
  20059. var getByUri = function (blobUri) {
  20060. return findFirst(function (blobInfo) {
  20061. return blobInfo.blobUri() === blobUri;
  20062. });
  20063. };
  20064. var getByData = function (base64, type) {
  20065. return findFirst(function (blobInfo) {
  20066. return blobInfo.base64() === base64 && blobInfo.blob().type === type;
  20067. });
  20068. };
  20069. var removeByUri = function (blobUri) {
  20070. cache = filter(cache, function (blobInfo) {
  20071. if (blobInfo.blobUri() === blobUri) {
  20072. URL.revokeObjectURL(blobInfo.blobUri());
  20073. return false;
  20074. }
  20075. return true;
  20076. });
  20077. };
  20078. var destroy = function () {
  20079. each(cache, function (cachedBlobInfo) {
  20080. URL.revokeObjectURL(cachedBlobInfo.blobUri());
  20081. });
  20082. cache = [];
  20083. };
  20084. return {
  20085. create: create,
  20086. add: add,
  20087. get: get,
  20088. getByUri: getByUri,
  20089. getByData: getByData,
  20090. findFirst: findFirst,
  20091. removeByUri: removeByUri,
  20092. destroy: destroy
  20093. };
  20094. };
  20095. var UploadChangeHandler = function (editor) {
  20096. var lastChangedLevel = Cell(null);
  20097. editor.on('change AddUndo', function (e) {
  20098. lastChangedLevel.set(__assign({}, e.level));
  20099. });
  20100. var fireIfChanged = function () {
  20101. var data = editor.undoManager.data;
  20102. last(data).filter(function (level) {
  20103. return !isEq$4(lastChangedLevel.get(), level);
  20104. }).each(function (level) {
  20105. editor.setDirty(true);
  20106. editor.fire('change', {
  20107. level: level,
  20108. lastLevel: get(data, data.length - 2).getOrNull()
  20109. });
  20110. });
  20111. };
  20112. return { fireIfChanged: fireIfChanged };
  20113. };
  20114. var EditorUpload = function (editor) {
  20115. var blobCache = BlobCache();
  20116. var uploader, imageScanner;
  20117. var uploadStatus = UploadStatus();
  20118. var urlFilters = [];
  20119. var changeHandler = UploadChangeHandler(editor);
  20120. var aliveGuard = function (callback) {
  20121. return function (result) {
  20122. if (editor.selection) {
  20123. return callback(result);
  20124. }
  20125. return [];
  20126. };
  20127. };
  20128. var cacheInvalidator = function (url) {
  20129. return url + (url.indexOf('?') === -1 ? '?' : '&') + new Date().getTime();
  20130. };
  20131. var replaceString = function (content, search, replace) {
  20132. var index = 0;
  20133. do {
  20134. index = content.indexOf(search, index);
  20135. if (index !== -1) {
  20136. content = content.substring(0, index) + replace + content.substr(index + search.length);
  20137. index += replace.length - search.length + 1;
  20138. }
  20139. } while (index !== -1);
  20140. return content;
  20141. };
  20142. var replaceImageUrl = function (content, targetUrl, replacementUrl) {
  20143. var replacementString = 'src="' + replacementUrl + '"' + (replacementUrl === Env.transparentSrc ? ' data-mce-placeholder="1"' : '');
  20144. content = replaceString(content, 'src="' + targetUrl + '"', replacementString);
  20145. content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
  20146. return content;
  20147. };
  20148. var replaceUrlInUndoStack = function (targetUrl, replacementUrl) {
  20149. each(editor.undoManager.data, function (level) {
  20150. if (level.type === 'fragmented') {
  20151. level.fragments = map(level.fragments, function (fragment) {
  20152. return replaceImageUrl(fragment, targetUrl, replacementUrl);
  20153. });
  20154. } else {
  20155. level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
  20156. }
  20157. });
  20158. };
  20159. var openNotification = function () {
  20160. return editor.notificationManager.open({
  20161. text: editor.translate('Image uploading...'),
  20162. type: 'info',
  20163. timeout: -1,
  20164. progressBar: true
  20165. });
  20166. };
  20167. var replaceImageUriInView = function (image, resultUri) {
  20168. var src = editor.convertURL(resultUri, 'src');
  20169. replaceUrlInUndoStack(image.src, resultUri);
  20170. editor.$(image).attr({
  20171. 'src': shouldReuseFileName(editor) ? cacheInvalidator(resultUri) : resultUri,
  20172. 'data-mce-src': src
  20173. });
  20174. };
  20175. var uploadImages = function (callback) {
  20176. if (!uploader) {
  20177. uploader = Uploader(uploadStatus, {
  20178. url: getImageUploadUrl(editor),
  20179. basePath: getImageUploadBasePath(editor),
  20180. credentials: getImagesUploadCredentials(editor),
  20181. handler: getImagesUploadHandler(editor)
  20182. });
  20183. }
  20184. return scanForImages().then(aliveGuard(function (imageInfos) {
  20185. var blobInfos = map(imageInfos, function (imageInfo) {
  20186. return imageInfo.blobInfo;
  20187. });
  20188. return uploader.upload(blobInfos, openNotification).then(aliveGuard(function (result) {
  20189. var imagesToRemove = [];
  20190. var filteredResult = map(result, function (uploadInfo, index) {
  20191. var blobInfo = imageInfos[index].blobInfo;
  20192. var image = imageInfos[index].image;
  20193. if (uploadInfo.status && shouldReplaceBlobUris(editor)) {
  20194. blobCache.removeByUri(image.src);
  20195. replaceImageUriInView(image, uploadInfo.url);
  20196. } else if (uploadInfo.error) {
  20197. if (uploadInfo.error.options.remove) {
  20198. replaceUrlInUndoStack(image.getAttribute('src'), Env.transparentSrc);
  20199. imagesToRemove.push(image);
  20200. }
  20201. uploadError(editor, uploadInfo.error.message);
  20202. }
  20203. return {
  20204. element: image,
  20205. status: uploadInfo.status,
  20206. uploadUri: uploadInfo.url,
  20207. blobInfo: blobInfo
  20208. };
  20209. });
  20210. if (filteredResult.length > 0) {
  20211. changeHandler.fireIfChanged();
  20212. }
  20213. if (imagesToRemove.length > 0) {
  20214. if (isRtc(editor)) {
  20215. console.error('Removing images on failed uploads is currently unsupported for RTC');
  20216. } else {
  20217. editor.undoManager.transact(function () {
  20218. each(imagesToRemove, function (element) {
  20219. editor.dom.remove(element);
  20220. blobCache.removeByUri(element.src);
  20221. });
  20222. });
  20223. }
  20224. }
  20225. if (callback) {
  20226. callback(filteredResult);
  20227. }
  20228. return filteredResult;
  20229. }));
  20230. }));
  20231. };
  20232. var uploadImagesAuto = function (callback) {
  20233. if (isAutomaticUploadsEnabled(editor)) {
  20234. return uploadImages(callback);
  20235. }
  20236. };
  20237. var isValidDataUriImage = function (imgElm) {
  20238. if (forall(urlFilters, function (filter) {
  20239. return filter(imgElm);
  20240. }) === false) {
  20241. return false;
  20242. }
  20243. if (imgElm.getAttribute('src').indexOf('data:') === 0) {
  20244. var dataImgFilter = getImagesDataImgFilter(editor);
  20245. return dataImgFilter(imgElm);
  20246. }
  20247. return true;
  20248. };
  20249. var addFilter = function (filter) {
  20250. urlFilters.push(filter);
  20251. };
  20252. var scanForImages = function () {
  20253. if (!imageScanner) {
  20254. imageScanner = ImageScanner(uploadStatus, blobCache);
  20255. }
  20256. return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(function (result) {
  20257. result = filter(result, function (resultItem) {
  20258. if (typeof resultItem === 'string') {
  20259. displayError(editor, resultItem);
  20260. return false;
  20261. }
  20262. return true;
  20263. });
  20264. each(result, function (resultItem) {
  20265. replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
  20266. resultItem.image.src = resultItem.blobInfo.blobUri();
  20267. resultItem.image.removeAttribute('data-mce-src');
  20268. });
  20269. return result;
  20270. }));
  20271. };
  20272. var destroy = function () {
  20273. blobCache.destroy();
  20274. uploadStatus.destroy();
  20275. imageScanner = uploader = null;
  20276. };
  20277. var replaceBlobUris = function (content) {
  20278. return content.replace(/src="(blob:[^"]+)"/g, function (match, blobUri) {
  20279. var resultUri = uploadStatus.getResultUri(blobUri);
  20280. if (resultUri) {
  20281. return 'src="' + resultUri + '"';
  20282. }
  20283. var blobInfo = blobCache.getByUri(blobUri);
  20284. if (!blobInfo) {
  20285. blobInfo = foldl(editor.editorManager.get(), function (result, editor) {
  20286. return result || editor.editorUpload && editor.editorUpload.blobCache.getByUri(blobUri);
  20287. }, null);
  20288. }
  20289. if (blobInfo) {
  20290. var blob = blobInfo.blob();
  20291. return 'src="data:' + blob.type + ';base64,' + blobInfo.base64() + '"';
  20292. }
  20293. return match;
  20294. });
  20295. };
  20296. editor.on('SetContent', function () {
  20297. if (isAutomaticUploadsEnabled(editor)) {
  20298. uploadImagesAuto();
  20299. } else {
  20300. scanForImages();
  20301. }
  20302. });
  20303. editor.on('RawSaveContent', function (e) {
  20304. e.content = replaceBlobUris(e.content);
  20305. });
  20306. editor.on('GetContent', function (e) {
  20307. if (e.source_view || e.format === 'raw' || e.format === 'tree') {
  20308. return;
  20309. }
  20310. e.content = replaceBlobUris(e.content);
  20311. });
  20312. editor.on('PostRender', function () {
  20313. editor.parser.addNodeFilter('img', function (images) {
  20314. each(images, function (img) {
  20315. var src = img.attr('src');
  20316. if (blobCache.getByUri(src)) {
  20317. return;
  20318. }
  20319. var resultUri = uploadStatus.getResultUri(src);
  20320. if (resultUri) {
  20321. img.attr('src', resultUri);
  20322. }
  20323. });
  20324. });
  20325. });
  20326. return {
  20327. blobCache: blobCache,
  20328. addFilter: addFilter,
  20329. uploadImages: uploadImages,
  20330. uploadImagesAuto: uploadImagesAuto,
  20331. scanForImages: scanForImages,
  20332. destroy: destroy
  20333. };
  20334. };
  20335. var get$a = function (dom) {
  20336. var formats = {
  20337. valigntop: [{
  20338. selector: 'td,th',
  20339. styles: { verticalAlign: 'top' }
  20340. }],
  20341. valignmiddle: [{
  20342. selector: 'td,th',
  20343. styles: { verticalAlign: 'middle' }
  20344. }],
  20345. valignbottom: [{
  20346. selector: 'td,th',
  20347. styles: { verticalAlign: 'bottom' }
  20348. }],
  20349. alignleft: [
  20350. {
  20351. selector: 'figure.image',
  20352. collapsed: false,
  20353. classes: 'align-left',
  20354. ceFalseOverride: true,
  20355. preview: 'font-family font-size'
  20356. },
  20357. {
  20358. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20359. styles: { textAlign: 'left' },
  20360. inherit: false,
  20361. preview: false,
  20362. defaultBlock: 'div'
  20363. },
  20364. {
  20365. selector: 'img,table',
  20366. collapsed: false,
  20367. styles: { float: 'left' },
  20368. preview: 'font-family font-size'
  20369. }
  20370. ],
  20371. aligncenter: [
  20372. {
  20373. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20374. styles: { textAlign: 'center' },
  20375. inherit: false,
  20376. preview: 'font-family font-size',
  20377. defaultBlock: 'div'
  20378. },
  20379. {
  20380. selector: 'figure.image',
  20381. collapsed: false,
  20382. classes: 'align-center',
  20383. ceFalseOverride: true,
  20384. preview: 'font-family font-size'
  20385. },
  20386. {
  20387. selector: 'img',
  20388. collapsed: false,
  20389. styles: {
  20390. display: 'block',
  20391. marginLeft: 'auto',
  20392. marginRight: 'auto'
  20393. },
  20394. preview: false
  20395. },
  20396. {
  20397. selector: 'table',
  20398. collapsed: false,
  20399. styles: {
  20400. marginLeft: 'auto',
  20401. marginRight: 'auto'
  20402. },
  20403. preview: 'font-family font-size'
  20404. }
  20405. ],
  20406. alignright: [
  20407. {
  20408. selector: 'figure.image',
  20409. collapsed: false,
  20410. classes: 'align-right',
  20411. ceFalseOverride: true,
  20412. preview: 'font-family font-size'
  20413. },
  20414. {
  20415. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20416. styles: { textAlign: 'right' },
  20417. inherit: false,
  20418. preview: 'font-family font-size',
  20419. defaultBlock: 'div'
  20420. },
  20421. {
  20422. selector: 'img,table',
  20423. collapsed: false,
  20424. styles: { float: 'right' },
  20425. preview: 'font-family font-size'
  20426. }
  20427. ],
  20428. alignjustify: [{
  20429. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20430. styles: { textAlign: 'justify' },
  20431. inherit: false,
  20432. defaultBlock: 'div',
  20433. preview: 'font-family font-size'
  20434. }],
  20435. bold: [
  20436. {
  20437. inline: 'strong',
  20438. remove: 'all',
  20439. preserve_attributes: [
  20440. 'class',
  20441. 'style'
  20442. ]
  20443. },
  20444. {
  20445. inline: 'span',
  20446. styles: { fontWeight: 'bold' }
  20447. },
  20448. {
  20449. inline: 'b',
  20450. remove: 'all',
  20451. preserve_attributes: [
  20452. 'class',
  20453. 'style'
  20454. ]
  20455. }
  20456. ],
  20457. italic: [
  20458. {
  20459. inline: 'em',
  20460. remove: 'all',
  20461. preserve_attributes: [
  20462. 'class',
  20463. 'style'
  20464. ]
  20465. },
  20466. {
  20467. inline: 'span',
  20468. styles: { fontStyle: 'italic' }
  20469. },
  20470. {
  20471. inline: 'i',
  20472. remove: 'all',
  20473. preserve_attributes: [
  20474. 'class',
  20475. 'style'
  20476. ]
  20477. }
  20478. ],
  20479. underline: [
  20480. {
  20481. inline: 'span',
  20482. styles: { textDecoration: 'underline' },
  20483. exact: true
  20484. },
  20485. {
  20486. inline: 'u',
  20487. remove: 'all',
  20488. preserve_attributes: [
  20489. 'class',
  20490. 'style'
  20491. ]
  20492. }
  20493. ],
  20494. strikethrough: [
  20495. {
  20496. inline: 'span',
  20497. styles: { textDecoration: 'line-through' },
  20498. exact: true
  20499. },
  20500. {
  20501. inline: 'strike',
  20502. remove: 'all',
  20503. preserve_attributes: [
  20504. 'class',
  20505. 'style'
  20506. ]
  20507. },
  20508. {
  20509. inline: 's',
  20510. remove: 'all',
  20511. preserve_attributes: [
  20512. 'class',
  20513. 'style'
  20514. ]
  20515. }
  20516. ],
  20517. forecolor: {
  20518. inline: 'span',
  20519. styles: { color: '%value' },
  20520. links: true,
  20521. remove_similar: true,
  20522. clear_child_styles: true
  20523. },
  20524. hilitecolor: {
  20525. inline: 'span',
  20526. styles: { backgroundColor: '%value' },
  20527. links: true,
  20528. remove_similar: true,
  20529. clear_child_styles: true
  20530. },
  20531. fontname: {
  20532. inline: 'span',
  20533. toggle: false,
  20534. styles: { fontFamily: '%value' },
  20535. clear_child_styles: true
  20536. },
  20537. fontsize: {
  20538. inline: 'span',
  20539. toggle: false,
  20540. styles: { fontSize: '%value' },
  20541. clear_child_styles: true
  20542. },
  20543. lineheight: {
  20544. selector: 'h1,h2,h3,h4,h5,h6,p,li,td,th,div',
  20545. defaultBlock: 'p',
  20546. styles: { lineHeight: '%value' }
  20547. },
  20548. fontsize_class: {
  20549. inline: 'span',
  20550. attributes: { class: '%value' }
  20551. },
  20552. blockquote: {
  20553. block: 'blockquote',
  20554. wrapper: true,
  20555. remove: 'all'
  20556. },
  20557. subscript: { inline: 'sub' },
  20558. superscript: { inline: 'sup' },
  20559. code: { inline: 'code' },
  20560. link: {
  20561. inline: 'a',
  20562. selector: 'a',
  20563. remove: 'all',
  20564. split: true,
  20565. deep: true,
  20566. onmatch: function (node, _fmt, _itemName) {
  20567. return isElement$1(node) && node.hasAttribute('href');
  20568. },
  20569. onformat: function (elm, _fmt, vars) {
  20570. Tools.each(vars, function (value, key) {
  20571. dom.setAttrib(elm, key, value);
  20572. });
  20573. }
  20574. },
  20575. removeformat: [
  20576. {
  20577. selector: 'b,strong,em,i,font,u,strike,s,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins',
  20578. remove: 'all',
  20579. split: true,
  20580. expand: false,
  20581. block_expand: true,
  20582. deep: true
  20583. },
  20584. {
  20585. selector: 'span',
  20586. attributes: [
  20587. 'style',
  20588. 'class'
  20589. ],
  20590. remove: 'empty',
  20591. split: true,
  20592. expand: false,
  20593. deep: true
  20594. },
  20595. {
  20596. selector: '*',
  20597. attributes: [
  20598. 'style',
  20599. 'class'
  20600. ],
  20601. split: false,
  20602. expand: false,
  20603. deep: true
  20604. }
  20605. ]
  20606. };
  20607. Tools.each('p h1 h2 h3 h4 h5 h6 div address pre div dt dd samp'.split(/\s/), function (name) {
  20608. formats[name] = {
  20609. block: name,
  20610. remove: 'all'
  20611. };
  20612. });
  20613. return formats;
  20614. };
  20615. function FormatRegistry(editor) {
  20616. var formats = {};
  20617. var get = function (name) {
  20618. return name ? formats[name] : formats;
  20619. };
  20620. var has$1 = function (name) {
  20621. return has(formats, name);
  20622. };
  20623. var register = function (name, format) {
  20624. if (name) {
  20625. if (typeof name !== 'string') {
  20626. Tools.each(name, function (format, name) {
  20627. register(name, format);
  20628. });
  20629. } else {
  20630. if (!isArray(format)) {
  20631. format = [format];
  20632. }
  20633. Tools.each(format, function (format) {
  20634. if (typeof format.deep === 'undefined') {
  20635. format.deep = !format.selector;
  20636. }
  20637. if (typeof format.split === 'undefined') {
  20638. format.split = !format.selector || format.inline;
  20639. }
  20640. if (typeof format.remove === 'undefined' && format.selector && !format.inline) {
  20641. format.remove = 'none';
  20642. }
  20643. if (format.selector && format.inline) {
  20644. format.mixed = true;
  20645. format.block_expand = true;
  20646. }
  20647. if (typeof format.classes === 'string') {
  20648. format.classes = format.classes.split(/\s+/);
  20649. }
  20650. });
  20651. formats[name] = format;
  20652. }
  20653. }
  20654. };
  20655. var unregister = function (name) {
  20656. if (name && formats[name]) {
  20657. delete formats[name];
  20658. }
  20659. return formats;
  20660. };
  20661. register(get$a(editor.dom));
  20662. register(getFormats(editor));
  20663. return {
  20664. get: get,
  20665. has: has$1,
  20666. register: register,
  20667. unregister: unregister
  20668. };
  20669. }
  20670. var each$e = Tools.each;
  20671. var dom = DOMUtils$1.DOM;
  20672. var parsedSelectorToHtml = function (ancestry, editor) {
  20673. var elm, item, fragment;
  20674. var schema = editor && editor.schema || Schema({});
  20675. var decorate = function (elm, item) {
  20676. if (item.classes.length) {
  20677. dom.addClass(elm, item.classes.join(' '));
  20678. }
  20679. dom.setAttribs(elm, item.attrs);
  20680. };
  20681. var createElement = function (sItem) {
  20682. item = typeof sItem === 'string' ? {
  20683. name: sItem,
  20684. classes: [],
  20685. attrs: {}
  20686. } : sItem;
  20687. var elm = dom.create(item.name);
  20688. decorate(elm, item);
  20689. return elm;
  20690. };
  20691. var getRequiredParent = function (elm, candidate) {
  20692. var name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm;
  20693. var elmRule = schema.getElementRule(name);
  20694. var parentsRequired = elmRule && elmRule.parentsRequired;
  20695. if (parentsRequired && parentsRequired.length) {
  20696. return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
  20697. } else {
  20698. return false;
  20699. }
  20700. };
  20701. var wrapInHtml = function (elm, ancestry, siblings) {
  20702. var parent, parentCandidate;
  20703. var ancestor = ancestry.length > 0 && ancestry[0];
  20704. var ancestorName = ancestor && ancestor.name;
  20705. var parentRequired = getRequiredParent(elm, ancestorName);
  20706. if (parentRequired) {
  20707. if (ancestorName === parentRequired) {
  20708. parentCandidate = ancestry[0];
  20709. ancestry = ancestry.slice(1);
  20710. } else {
  20711. parentCandidate = parentRequired;
  20712. }
  20713. } else if (ancestor) {
  20714. parentCandidate = ancestry[0];
  20715. ancestry = ancestry.slice(1);
  20716. } else if (!siblings) {
  20717. return elm;
  20718. }
  20719. if (parentCandidate) {
  20720. parent = createElement(parentCandidate);
  20721. parent.appendChild(elm);
  20722. }
  20723. if (siblings) {
  20724. if (!parent) {
  20725. parent = dom.create('div');
  20726. parent.appendChild(elm);
  20727. }
  20728. Tools.each(siblings, function (sibling) {
  20729. var siblingElm = createElement(sibling);
  20730. parent.insertBefore(siblingElm, elm);
  20731. });
  20732. }
  20733. return wrapInHtml(parent, ancestry, parentCandidate && parentCandidate.siblings);
  20734. };
  20735. if (ancestry && ancestry.length) {
  20736. item = ancestry[0];
  20737. elm = createElement(item);
  20738. fragment = dom.create('div');
  20739. fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
  20740. return fragment;
  20741. } else {
  20742. return '';
  20743. }
  20744. };
  20745. var parseSelectorItem = function (item) {
  20746. var tagName;
  20747. var obj = {
  20748. classes: [],
  20749. attrs: {}
  20750. };
  20751. item = obj.selector = Tools.trim(item);
  20752. if (item !== '*') {
  20753. tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function ($0, $1, $2, $3, $4) {
  20754. switch ($1) {
  20755. case '#':
  20756. obj.attrs.id = $2;
  20757. break;
  20758. case '.':
  20759. obj.classes.push($2);
  20760. break;
  20761. case ':':
  20762. if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
  20763. obj.attrs[$2] = $2;
  20764. }
  20765. break;
  20766. }
  20767. if ($3 === '[') {
  20768. var m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
  20769. if (m) {
  20770. obj.attrs[m[1]] = m[2];
  20771. }
  20772. }
  20773. return '';
  20774. });
  20775. }
  20776. obj.name = tagName || 'div';
  20777. return obj;
  20778. };
  20779. var parseSelector = function (selector) {
  20780. if (!selector || typeof selector !== 'string') {
  20781. return [];
  20782. }
  20783. selector = selector.split(/\s*,\s*/)[0];
  20784. selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1');
  20785. return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), function (item) {
  20786. var siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
  20787. var obj = siblings.pop();
  20788. if (siblings.length) {
  20789. obj.siblings = siblings;
  20790. }
  20791. return obj;
  20792. }).reverse();
  20793. };
  20794. var getCssText = function (editor, format) {
  20795. var name, previewFrag;
  20796. var previewCss = '', parentFontSize;
  20797. var previewStyles = getPreviewStyles(editor);
  20798. if (previewStyles === '') {
  20799. return '';
  20800. }
  20801. var removeVars = function (val) {
  20802. return val.replace(/%(\w+)/g, '');
  20803. };
  20804. if (typeof format === 'string') {
  20805. format = editor.formatter.get(format);
  20806. if (!format) {
  20807. return;
  20808. }
  20809. format = format[0];
  20810. }
  20811. if ('preview' in format) {
  20812. var previewOpt = get$1(format, 'preview');
  20813. if (previewOpt.is(false)) {
  20814. return '';
  20815. } else {
  20816. previewStyles = previewOpt.getOr(previewStyles);
  20817. }
  20818. }
  20819. name = format.block || format.inline || 'span';
  20820. var items = parseSelector(format.selector);
  20821. if (items.length) {
  20822. if (!items[0].name) {
  20823. items[0].name = name;
  20824. }
  20825. name = format.selector;
  20826. previewFrag = parsedSelectorToHtml(items, editor);
  20827. } else {
  20828. previewFrag = parsedSelectorToHtml([name], editor);
  20829. }
  20830. var previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;
  20831. each$e(format.styles, function (value, name) {
  20832. var newValue = removeVars(value);
  20833. if (newValue) {
  20834. dom.setStyle(previewElm, name, newValue);
  20835. }
  20836. });
  20837. each$e(format.attributes, function (value, name) {
  20838. var newValue = removeVars(value);
  20839. if (newValue) {
  20840. dom.setAttrib(previewElm, name, newValue);
  20841. }
  20842. });
  20843. each$e(format.classes, function (value) {
  20844. var newValue = removeVars(value);
  20845. if (!dom.hasClass(previewElm, newValue)) {
  20846. dom.addClass(previewElm, newValue);
  20847. }
  20848. });
  20849. editor.fire('PreviewFormats');
  20850. dom.setStyles(previewFrag, {
  20851. position: 'absolute',
  20852. left: -65535
  20853. });
  20854. editor.getBody().appendChild(previewFrag);
  20855. parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
  20856. parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
  20857. each$e(previewStyles.split(' '), function (name) {
  20858. var value = dom.getStyle(previewElm, name, true);
  20859. if (name === 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
  20860. value = dom.getStyle(editor.getBody(), name, true);
  20861. if (dom.toHex(value).toLowerCase() === '#ffffff') {
  20862. return;
  20863. }
  20864. }
  20865. if (name === 'color') {
  20866. if (dom.toHex(value).toLowerCase() === '#000000') {
  20867. return;
  20868. }
  20869. }
  20870. if (name === 'font-size') {
  20871. if (/em|%$/.test(value)) {
  20872. if (parentFontSize === 0) {
  20873. return;
  20874. }
  20875. var numValue = parseFloat(value) / (/%$/.test(value) ? 100 : 1);
  20876. value = numValue * parentFontSize + 'px';
  20877. }
  20878. }
  20879. if (name === 'border' && value) {
  20880. previewCss += 'padding:0 2px;';
  20881. }
  20882. previewCss += name + ':' + value + ';';
  20883. });
  20884. editor.fire('AfterPreviewFormats');
  20885. dom.remove(previewFrag);
  20886. return previewCss;
  20887. };
  20888. var setup$6 = function (editor) {
  20889. editor.addShortcut('meta+b', '', 'Bold');
  20890. editor.addShortcut('meta+i', '', 'Italic');
  20891. editor.addShortcut('meta+u', '', 'Underline');
  20892. for (var i = 1; i <= 6; i++) {
  20893. editor.addShortcut('access+' + i, '', [
  20894. 'FormatBlock',
  20895. false,
  20896. 'h' + i
  20897. ]);
  20898. }
  20899. editor.addShortcut('access+7', '', [
  20900. 'FormatBlock',
  20901. false,
  20902. 'p'
  20903. ]);
  20904. editor.addShortcut('access+8', '', [
  20905. 'FormatBlock',
  20906. false,
  20907. 'div'
  20908. ]);
  20909. editor.addShortcut('access+9', '', [
  20910. 'FormatBlock',
  20911. false,
  20912. 'address'
  20913. ]);
  20914. };
  20915. var Formatter = function (editor) {
  20916. var formats = FormatRegistry(editor);
  20917. var formatChangeState = Cell(null);
  20918. setup$6(editor);
  20919. setup$3(editor);
  20920. return {
  20921. get: formats.get,
  20922. has: formats.has,
  20923. register: formats.register,
  20924. unregister: formats.unregister,
  20925. apply: function (name, vars, node) {
  20926. applyFormat$1(editor, name, vars, node);
  20927. },
  20928. remove: function (name, vars, node, similar) {
  20929. removeFormat$1(editor, name, vars, node, similar);
  20930. },
  20931. toggle: function (name, vars, node) {
  20932. toggleFormat(editor, name, vars, node);
  20933. },
  20934. match: function (name, vars, node) {
  20935. return matchFormat(editor, name, vars, node);
  20936. },
  20937. closest: function (names) {
  20938. return closestFormat(editor, names);
  20939. },
  20940. matchAll: function (names, vars) {
  20941. return matchAllFormats(editor, names, vars);
  20942. },
  20943. matchNode: function (node, names, vars, similar) {
  20944. return matchNodeFormat(editor, node, names, vars, similar);
  20945. },
  20946. canApply: function (name) {
  20947. return canApplyFormat(editor, name);
  20948. },
  20949. formatChanged: function (formats, callback, similar) {
  20950. return formatChanged(editor, formatChangeState, formats, callback, similar);
  20951. },
  20952. getCssText: curry(getCssText, editor)
  20953. };
  20954. };
  20955. var registerEvents$1 = function (editor, undoManager, locks) {
  20956. var isFirstTypedCharacter = Cell(false);
  20957. var addNonTypingUndoLevel = function (e) {
  20958. setTyping(undoManager, false, locks);
  20959. undoManager.add({}, e);
  20960. };
  20961. editor.on('init', function () {
  20962. undoManager.add();
  20963. });
  20964. editor.on('BeforeExecCommand', function (e) {
  20965. var cmd = e.command.toLowerCase();
  20966. if (cmd !== 'undo' && cmd !== 'redo' && cmd !== 'mcerepaint') {
  20967. endTyping(undoManager, locks);
  20968. undoManager.beforeChange();
  20969. }
  20970. });
  20971. editor.on('ExecCommand', function (e) {
  20972. var cmd = e.command.toLowerCase();
  20973. if (cmd !== 'undo' && cmd !== 'redo' && cmd !== 'mcerepaint') {
  20974. addNonTypingUndoLevel(e);
  20975. }
  20976. });
  20977. editor.on('ObjectResizeStart cut', function () {
  20978. undoManager.beforeChange();
  20979. });
  20980. editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
  20981. editor.on('dragend', addNonTypingUndoLevel);
  20982. editor.on('keyup', function (e) {
  20983. var keyCode = e.keyCode;
  20984. if (e.isDefaultPrevented()) {
  20985. return;
  20986. }
  20987. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45 || e.ctrlKey) {
  20988. addNonTypingUndoLevel();
  20989. editor.nodeChanged();
  20990. }
  20991. if (keyCode === 46 || keyCode === 8) {
  20992. editor.nodeChanged();
  20993. }
  20994. if (isFirstTypedCharacter.get() && undoManager.typing && isEq$4(createFromEditor(editor), undoManager.data[0]) === false) {
  20995. if (editor.isDirty() === false) {
  20996. editor.setDirty(true);
  20997. editor.fire('change', {
  20998. level: undoManager.data[0],
  20999. lastLevel: null
  21000. });
  21001. }
  21002. editor.fire('TypingUndo');
  21003. isFirstTypedCharacter.set(false);
  21004. editor.nodeChanged();
  21005. }
  21006. });
  21007. editor.on('keydown', function (e) {
  21008. var keyCode = e.keyCode;
  21009. if (e.isDefaultPrevented()) {
  21010. return;
  21011. }
  21012. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45) {
  21013. if (undoManager.typing) {
  21014. addNonTypingUndoLevel(e);
  21015. }
  21016. return;
  21017. }
  21018. var modKey = e.ctrlKey && !e.altKey || e.metaKey;
  21019. if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !undoManager.typing && !modKey) {
  21020. undoManager.beforeChange();
  21021. setTyping(undoManager, true, locks);
  21022. undoManager.add({}, e);
  21023. isFirstTypedCharacter.set(true);
  21024. }
  21025. });
  21026. editor.on('mousedown', function (e) {
  21027. if (undoManager.typing) {
  21028. addNonTypingUndoLevel(e);
  21029. }
  21030. });
  21031. var isInsertReplacementText = function (event) {
  21032. return event.inputType === 'insertReplacementText';
  21033. };
  21034. var isInsertTextDataNull = function (event) {
  21035. return event.inputType === 'insertText' && event.data === null;
  21036. };
  21037. var isInsertFromPasteOrDrop = function (event) {
  21038. return event.inputType === 'insertFromPaste' || event.inputType === 'insertFromDrop';
  21039. };
  21040. editor.on('input', function (e) {
  21041. if (e.inputType && (isInsertReplacementText(e) || isInsertTextDataNull(e) || isInsertFromPasteOrDrop(e))) {
  21042. addNonTypingUndoLevel(e);
  21043. }
  21044. });
  21045. editor.on('AddUndo Undo Redo ClearUndos', function (e) {
  21046. if (!e.isDefaultPrevented()) {
  21047. editor.nodeChanged();
  21048. }
  21049. });
  21050. };
  21051. var addKeyboardShortcuts = function (editor) {
  21052. editor.addShortcut('meta+z', '', 'Undo');
  21053. editor.addShortcut('meta+y,meta+shift+z', '', 'Redo');
  21054. };
  21055. var UndoManager = function (editor) {
  21056. var beforeBookmark = Cell(Optional.none());
  21057. var locks = Cell(0);
  21058. var index = Cell(0);
  21059. var undoManager = {
  21060. data: [],
  21061. typing: false,
  21062. beforeChange: function () {
  21063. beforeChange$1(editor, locks, beforeBookmark);
  21064. },
  21065. add: function (level, event) {
  21066. return addUndoLevel$1(editor, undoManager, index, locks, beforeBookmark, level, event);
  21067. },
  21068. undo: function () {
  21069. return undo$1(editor, undoManager, locks, index);
  21070. },
  21071. redo: function () {
  21072. return redo$1(editor, index, undoManager.data);
  21073. },
  21074. clear: function () {
  21075. clear$1(editor, undoManager, index);
  21076. },
  21077. reset: function () {
  21078. reset$1(editor, undoManager);
  21079. },
  21080. hasUndo: function () {
  21081. return hasUndo$1(editor, undoManager, index);
  21082. },
  21083. hasRedo: function () {
  21084. return hasRedo$1(editor, undoManager, index);
  21085. },
  21086. transact: function (callback) {
  21087. return transact$1(editor, undoManager, locks, callback);
  21088. },
  21089. ignore: function (callback) {
  21090. ignore$1(editor, locks, callback);
  21091. },
  21092. extra: function (callback1, callback2) {
  21093. extra$1(editor, undoManager, index, callback1, callback2);
  21094. }
  21095. };
  21096. if (!isRtc(editor)) {
  21097. registerEvents$1(editor, undoManager, locks);
  21098. }
  21099. addKeyboardShortcuts(editor);
  21100. return undoManager;
  21101. };
  21102. var nonTypingKeycodes = [
  21103. 9,
  21104. 27,
  21105. VK.HOME,
  21106. VK.END,
  21107. 19,
  21108. 20,
  21109. 44,
  21110. 144,
  21111. 145,
  21112. 33,
  21113. 34,
  21114. 45,
  21115. 16,
  21116. 17,
  21117. 18,
  21118. 91,
  21119. 92,
  21120. 93,
  21121. VK.DOWN,
  21122. VK.UP,
  21123. VK.LEFT,
  21124. VK.RIGHT
  21125. ].concat(Env.browser.isFirefox() ? [224] : []);
  21126. var placeholderAttr = 'data-mce-placeholder';
  21127. var isKeyboardEvent = function (e) {
  21128. return e.type === 'keydown' || e.type === 'keyup';
  21129. };
  21130. var isDeleteEvent = function (e) {
  21131. var keyCode = e.keyCode;
  21132. return keyCode === VK.BACKSPACE || keyCode === VK.DELETE;
  21133. };
  21134. var isNonTypingKeyboardEvent = function (e) {
  21135. if (isKeyboardEvent(e)) {
  21136. var keyCode = e.keyCode;
  21137. return !isDeleteEvent(e) && (VK.metaKeyPressed(e) || e.altKey || keyCode >= 112 && keyCode <= 123 || contains(nonTypingKeycodes, keyCode));
  21138. } else {
  21139. return false;
  21140. }
  21141. };
  21142. var isTypingKeyboardEvent = function (e) {
  21143. return isKeyboardEvent(e) && !(isDeleteEvent(e) || e.type === 'keyup' && e.keyCode === 229);
  21144. };
  21145. var isVisuallyEmpty = function (dom, rootElm, forcedRootBlock) {
  21146. if (isEmpty(SugarElement.fromDom(rootElm), false)) {
  21147. var isForcedRootBlockFalse = forcedRootBlock === '';
  21148. var firstElement = rootElm.firstElementChild;
  21149. if (!firstElement) {
  21150. return true;
  21151. } else if (dom.getStyle(rootElm.firstElementChild, 'padding-left') || dom.getStyle(rootElm.firstElementChild, 'padding-right')) {
  21152. return false;
  21153. } else {
  21154. return isForcedRootBlockFalse ? !dom.isBlock(firstElement) : forcedRootBlock === firstElement.nodeName.toLowerCase();
  21155. }
  21156. } else {
  21157. return false;
  21158. }
  21159. };
  21160. var setup$7 = function (editor) {
  21161. var dom = editor.dom;
  21162. var rootBlock = getForcedRootBlock(editor);
  21163. var placeholder = getPlaceholder(editor);
  21164. var updatePlaceholder = function (e, initial) {
  21165. if (isNonTypingKeyboardEvent(e)) {
  21166. return;
  21167. }
  21168. var body = editor.getBody();
  21169. var showPlaceholder = isTypingKeyboardEvent(e) ? false : isVisuallyEmpty(dom, body, rootBlock);
  21170. var isPlaceholderShown = dom.getAttrib(body, placeholderAttr) !== '';
  21171. if (isPlaceholderShown !== showPlaceholder || initial) {
  21172. dom.setAttrib(body, placeholderAttr, showPlaceholder ? placeholder : null);
  21173. dom.setAttrib(body, 'aria-placeholder', showPlaceholder ? placeholder : null);
  21174. firePlaceholderToggle(editor, showPlaceholder);
  21175. editor.on(showPlaceholder ? 'keydown' : 'keyup', updatePlaceholder);
  21176. editor.off(showPlaceholder ? 'keyup' : 'keydown', updatePlaceholder);
  21177. }
  21178. };
  21179. if (placeholder) {
  21180. editor.on('init', function (e) {
  21181. updatePlaceholder(e, true);
  21182. editor.on('change SetContent ExecCommand', updatePlaceholder);
  21183. editor.on('paste', function (e) {
  21184. return Delay.setEditorTimeout(editor, function () {
  21185. return updatePlaceholder(e);
  21186. });
  21187. });
  21188. });
  21189. }
  21190. };
  21191. var strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
  21192. var hasStrongRtl = function (text) {
  21193. return strongRtl.test(text);
  21194. };
  21195. var isInlineTarget = function (editor, elm) {
  21196. return is$1(SugarElement.fromDom(elm), getInlineBoundarySelector(editor));
  21197. };
  21198. var isRtl$1 = function (element) {
  21199. return DOMUtils$1.DOM.getStyle(element, 'direction', true) === 'rtl' || hasStrongRtl(element.textContent);
  21200. };
  21201. var findInlineParents = function (isInlineTarget, rootNode, pos) {
  21202. return filter(DOMUtils$1.DOM.getParents(pos.container(), '*', rootNode), isInlineTarget);
  21203. };
  21204. var findRootInline = function (isInlineTarget, rootNode, pos) {
  21205. var parents = findInlineParents(isInlineTarget, rootNode, pos);
  21206. return Optional.from(parents[parents.length - 1]);
  21207. };
  21208. var hasSameParentBlock = function (rootNode, node1, node2) {
  21209. var block1 = getParentBlock(node1, rootNode);
  21210. var block2 = getParentBlock(node2, rootNode);
  21211. return block1 && block1 === block2;
  21212. };
  21213. var isAtZwsp = function (pos) {
  21214. return isBeforeInline(pos) || isAfterInline(pos);
  21215. };
  21216. var normalizePosition = function (forward, pos) {
  21217. if (!pos) {
  21218. return pos;
  21219. }
  21220. var container = pos.container(), offset = pos.offset();
  21221. if (forward) {
  21222. if (isCaretContainerInline(container)) {
  21223. if (isText$1(container.nextSibling)) {
  21224. return CaretPosition$1(container.nextSibling, 0);
  21225. } else {
  21226. return CaretPosition$1.after(container);
  21227. }
  21228. } else {
  21229. return isBeforeInline(pos) ? CaretPosition$1(container, offset + 1) : pos;
  21230. }
  21231. } else {
  21232. if (isCaretContainerInline(container)) {
  21233. if (isText$1(container.previousSibling)) {
  21234. return CaretPosition$1(container.previousSibling, container.previousSibling.data.length);
  21235. } else {
  21236. return CaretPosition$1.before(container);
  21237. }
  21238. } else {
  21239. return isAfterInline(pos) ? CaretPosition$1(container, offset - 1) : pos;
  21240. }
  21241. }
  21242. };
  21243. var normalizeForwards = curry(normalizePosition, true);
  21244. var normalizeBackwards = curry(normalizePosition, false);
  21245. var isBeforeRoot = function (rootNode) {
  21246. return function (elm) {
  21247. return eq$2(rootNode, SugarElement.fromDom(elm.dom.parentNode));
  21248. };
  21249. };
  21250. var getParentBlock$1 = function (rootNode, elm) {
  21251. return contains$2(rootNode, elm) ? closest(elm, function (element) {
  21252. return isTextBlock(element) || isListItem(element);
  21253. }, isBeforeRoot(rootNode)) : Optional.none();
  21254. };
  21255. var placeCaretInEmptyBody = function (editor) {
  21256. var body = editor.getBody();
  21257. var node = body.firstChild && editor.dom.isBlock(body.firstChild) ? body.firstChild : body;
  21258. editor.selection.setCursorLocation(node, 0);
  21259. };
  21260. var paddEmptyBody = function (editor) {
  21261. if (editor.dom.isEmpty(editor.getBody())) {
  21262. editor.setContent('');
  21263. placeCaretInEmptyBody(editor);
  21264. }
  21265. };
  21266. var willDeleteLastPositionInElement = function (forward, fromPos, elm) {
  21267. return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  21268. var normalizedFirstPos = normalizePosition(true, firstPos);
  21269. var normalizedLastPos = normalizePosition(false, lastPos);
  21270. var normalizedFromPos = normalizePosition(false, fromPos);
  21271. if (forward) {
  21272. return nextPosition(elm, normalizedFromPos).exists(function (nextPos) {
  21273. return nextPos.isEqual(normalizedLastPos) && fromPos.isEqual(normalizedFirstPos);
  21274. });
  21275. } else {
  21276. return prevPosition(elm, normalizedFromPos).exists(function (prevPos) {
  21277. return prevPos.isEqual(normalizedFirstPos) && fromPos.isEqual(normalizedLastPos);
  21278. });
  21279. }
  21280. }).getOr(true);
  21281. };
  21282. var blockPosition = function (block, position) {
  21283. return {
  21284. block: block,
  21285. position: position
  21286. };
  21287. };
  21288. var blockBoundary = function (from, to) {
  21289. return {
  21290. from: from,
  21291. to: to
  21292. };
  21293. };
  21294. var getBlockPosition = function (rootNode, pos) {
  21295. var rootElm = SugarElement.fromDom(rootNode);
  21296. var containerElm = SugarElement.fromDom(pos.container());
  21297. return getParentBlock$1(rootElm, containerElm).map(function (block) {
  21298. return blockPosition(block, pos);
  21299. });
  21300. };
  21301. var isDifferentBlocks = function (blockBoundary) {
  21302. return eq$2(blockBoundary.from.block, blockBoundary.to.block) === false;
  21303. };
  21304. var hasSameParent = function (blockBoundary) {
  21305. return parent(blockBoundary.from.block).bind(function (parent1) {
  21306. return parent(blockBoundary.to.block).filter(function (parent2) {
  21307. return eq$2(parent1, parent2);
  21308. });
  21309. }).isSome();
  21310. };
  21311. var isEditable = function (blockBoundary) {
  21312. return isContentEditableFalse(blockBoundary.from.block.dom) === false && isContentEditableFalse(blockBoundary.to.block.dom) === false;
  21313. };
  21314. var skipLastBr = function (rootNode, forward, blockPosition) {
  21315. if (isBr(blockPosition.position.getNode()) && isEmpty(blockPosition.block) === false) {
  21316. return positionIn(false, blockPosition.block.dom).bind(function (lastPositionInBlock) {
  21317. if (lastPositionInBlock.isEqual(blockPosition.position)) {
  21318. return fromPosition(forward, rootNode, lastPositionInBlock).bind(function (to) {
  21319. return getBlockPosition(rootNode, to);
  21320. });
  21321. } else {
  21322. return Optional.some(blockPosition);
  21323. }
  21324. }).getOr(blockPosition);
  21325. } else {
  21326. return blockPosition;
  21327. }
  21328. };
  21329. var readFromRange = function (rootNode, forward, rng) {
  21330. var fromBlockPos = getBlockPosition(rootNode, CaretPosition$1.fromRangeStart(rng));
  21331. var toBlockPos = fromBlockPos.bind(function (blockPos) {
  21332. return fromPosition(forward, rootNode, blockPos.position).bind(function (to) {
  21333. return getBlockPosition(rootNode, to).map(function (blockPos) {
  21334. return skipLastBr(rootNode, forward, blockPos);
  21335. });
  21336. });
  21337. });
  21338. return lift2(fromBlockPos, toBlockPos, blockBoundary).filter(function (blockBoundary) {
  21339. return isDifferentBlocks(blockBoundary) && hasSameParent(blockBoundary) && isEditable(blockBoundary);
  21340. });
  21341. };
  21342. var read$3 = function (rootNode, forward, rng) {
  21343. return rng.collapsed ? readFromRange(rootNode, forward, rng) : Optional.none();
  21344. };
  21345. var getChildrenUntilBlockBoundary = function (block) {
  21346. var children$1 = children(block);
  21347. return findIndex(children$1, isBlock).fold(function () {
  21348. return children$1;
  21349. }, function (index) {
  21350. return children$1.slice(0, index);
  21351. });
  21352. };
  21353. var extractChildren = function (block) {
  21354. var children = getChildrenUntilBlockBoundary(block);
  21355. each(children, remove);
  21356. return children;
  21357. };
  21358. var removeEmptyRoot = function (rootNode, block) {
  21359. var parents = parentsAndSelf(block, rootNode);
  21360. return find(parents.reverse(), function (element) {
  21361. return isEmpty(element);
  21362. }).each(remove);
  21363. };
  21364. var isEmptyBefore = function (el) {
  21365. return filter(prevSiblings(el), function (el) {
  21366. return !isEmpty(el);
  21367. }).length === 0;
  21368. };
  21369. var nestedBlockMerge = function (rootNode, fromBlock, toBlock, insertionPoint) {
  21370. if (isEmpty(toBlock)) {
  21371. fillWithPaddingBr(toBlock);
  21372. return firstPositionIn(toBlock.dom);
  21373. }
  21374. if (isEmptyBefore(insertionPoint) && isEmpty(fromBlock)) {
  21375. before(insertionPoint, SugarElement.fromTag('br'));
  21376. }
  21377. var position = prevPosition(toBlock.dom, CaretPosition$1.before(insertionPoint.dom));
  21378. each(extractChildren(fromBlock), function (child) {
  21379. before(insertionPoint, child);
  21380. });
  21381. removeEmptyRoot(rootNode, fromBlock);
  21382. return position;
  21383. };
  21384. var sidelongBlockMerge = function (rootNode, fromBlock, toBlock) {
  21385. if (isEmpty(toBlock)) {
  21386. remove(toBlock);
  21387. if (isEmpty(fromBlock)) {
  21388. fillWithPaddingBr(fromBlock);
  21389. }
  21390. return firstPositionIn(fromBlock.dom);
  21391. }
  21392. var position = lastPositionIn(toBlock.dom);
  21393. each(extractChildren(fromBlock), function (child) {
  21394. append(toBlock, child);
  21395. });
  21396. removeEmptyRoot(rootNode, fromBlock);
  21397. return position;
  21398. };
  21399. var findInsertionPoint = function (toBlock, block) {
  21400. var parentsAndSelf$1 = parentsAndSelf(block, toBlock);
  21401. return Optional.from(parentsAndSelf$1[parentsAndSelf$1.length - 1]);
  21402. };
  21403. var getInsertionPoint = function (fromBlock, toBlock) {
  21404. return contains$2(toBlock, fromBlock) ? findInsertionPoint(toBlock, fromBlock) : Optional.none();
  21405. };
  21406. var trimBr = function (first, block) {
  21407. positionIn(first, block.dom).map(function (position) {
  21408. return position.getNode();
  21409. }).map(SugarElement.fromDom).filter(isBr$1).each(remove);
  21410. };
  21411. var mergeBlockInto = function (rootNode, fromBlock, toBlock) {
  21412. trimBr(true, fromBlock);
  21413. trimBr(false, toBlock);
  21414. return getInsertionPoint(fromBlock, toBlock).fold(curry(sidelongBlockMerge, rootNode, fromBlock, toBlock), curry(nestedBlockMerge, rootNode, fromBlock, toBlock));
  21415. };
  21416. var mergeBlocks = function (rootNode, forward, block1, block2) {
  21417. return forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
  21418. };
  21419. var backspaceDelete$1 = function (editor, forward) {
  21420. var rootNode = SugarElement.fromDom(editor.getBody());
  21421. var position = read$3(rootNode.dom, forward, editor.selection.getRng()).bind(function (blockBoundary) {
  21422. return mergeBlocks(rootNode, forward, blockBoundary.from.block, blockBoundary.to.block);
  21423. });
  21424. position.each(function (pos) {
  21425. editor.selection.setRng(pos.toRange());
  21426. });
  21427. return position.isSome();
  21428. };
  21429. var deleteRangeMergeBlocks = function (rootNode, selection) {
  21430. var rng = selection.getRng();
  21431. return lift2(getParentBlock$1(rootNode, SugarElement.fromDom(rng.startContainer)), getParentBlock$1(rootNode, SugarElement.fromDom(rng.endContainer)), function (block1, block2) {
  21432. if (eq$2(block1, block2) === false) {
  21433. rng.deleteContents();
  21434. mergeBlocks(rootNode, true, block1, block2).each(function (pos) {
  21435. selection.setRng(pos.toRange());
  21436. });
  21437. return true;
  21438. } else {
  21439. return false;
  21440. }
  21441. }).getOr(false);
  21442. };
  21443. var isRawNodeInTable = function (root, rawNode) {
  21444. var node = SugarElement.fromDom(rawNode);
  21445. var isRoot = curry(eq$2, root);
  21446. return ancestor(node, isTableCell$1, isRoot).isSome();
  21447. };
  21448. var isSelectionInTable = function (root, rng) {
  21449. return isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
  21450. };
  21451. var isEverythingSelected = function (root, rng) {
  21452. var noPrevious = prevPosition(root.dom, CaretPosition$1.fromRangeStart(rng)).isNone();
  21453. var noNext = nextPosition(root.dom, CaretPosition$1.fromRangeEnd(rng)).isNone();
  21454. return !isSelectionInTable(root, rng) && noPrevious && noNext;
  21455. };
  21456. var emptyEditor = function (editor) {
  21457. editor.setContent('');
  21458. editor.selection.setCursorLocation();
  21459. return true;
  21460. };
  21461. var deleteRange$1 = function (editor) {
  21462. var rootNode = SugarElement.fromDom(editor.getBody());
  21463. var rng = editor.selection.getRng();
  21464. return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
  21465. };
  21466. var backspaceDelete$2 = function (editor, _forward) {
  21467. return editor.selection.isCollapsed() ? false : deleteRange$1(editor);
  21468. };
  21469. var isContentEditableTrue$2 = isContentEditableTrue;
  21470. var isContentEditableFalse$7 = isContentEditableFalse;
  21471. var showCaret = function (direction, editor, node, before, scrollIntoView) {
  21472. return Optional.from(editor._selectionOverrides.showCaret(direction, node, before, scrollIntoView));
  21473. };
  21474. var getNodeRange = function (node) {
  21475. var rng = node.ownerDocument.createRange();
  21476. rng.selectNode(node);
  21477. return rng;
  21478. };
  21479. var selectNode = function (editor, node) {
  21480. var e = editor.fire('BeforeObjectSelected', { target: node });
  21481. if (e.isDefaultPrevented()) {
  21482. return Optional.none();
  21483. }
  21484. return Optional.some(getNodeRange(node));
  21485. };
  21486. var renderCaretAtRange = function (editor, range, scrollIntoView) {
  21487. var normalizedRange = normalizeRange(1, editor.getBody(), range);
  21488. var caretPosition = CaretPosition$1.fromRangeStart(normalizedRange);
  21489. var caretPositionNode = caretPosition.getNode();
  21490. if (isInlineFakeCaretTarget(caretPositionNode)) {
  21491. return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
  21492. }
  21493. var caretPositionBeforeNode = caretPosition.getNode(true);
  21494. if (isInlineFakeCaretTarget(caretPositionBeforeNode)) {
  21495. return showCaret(1, editor, caretPositionBeforeNode, false, false);
  21496. }
  21497. var ceRoot = editor.dom.getParent(caretPosition.getNode(), function (node) {
  21498. return isContentEditableFalse$7(node) || isContentEditableTrue$2(node);
  21499. });
  21500. if (isInlineFakeCaretTarget(ceRoot)) {
  21501. return showCaret(1, editor, ceRoot, false, scrollIntoView);
  21502. }
  21503. return Optional.none();
  21504. };
  21505. var renderRangeCaret = function (editor, range, scrollIntoView) {
  21506. return range.collapsed ? renderCaretAtRange(editor, range, scrollIntoView).getOr(range) : range;
  21507. };
  21508. var isBeforeBoundary = function (pos) {
  21509. return isBeforeContentEditableFalse(pos) || isBeforeMedia(pos);
  21510. };
  21511. var isAfterBoundary = function (pos) {
  21512. return isAfterContentEditableFalse(pos) || isAfterMedia(pos);
  21513. };
  21514. var trimEmptyTextNode$1 = function (dom, node) {
  21515. if (isText$1(node) && node.data.length === 0) {
  21516. dom.remove(node);
  21517. }
  21518. };
  21519. var deleteContentAndShowCaret = function (editor, range, node, direction, forward, peekCaretPosition) {
  21520. showCaret(direction, editor, peekCaretPosition.getNode(!forward), forward, true).each(function (caretRange) {
  21521. if (range.collapsed) {
  21522. var deleteRange = range.cloneRange();
  21523. if (forward) {
  21524. deleteRange.setEnd(caretRange.startContainer, caretRange.startOffset);
  21525. } else {
  21526. deleteRange.setStart(caretRange.endContainer, caretRange.endOffset);
  21527. }
  21528. deleteRange.deleteContents();
  21529. } else {
  21530. range.deleteContents();
  21531. }
  21532. editor.selection.setRng(caretRange);
  21533. });
  21534. trimEmptyTextNode$1(editor.dom, node);
  21535. return true;
  21536. };
  21537. var deleteBoundaryText = function (editor, forward) {
  21538. var range = editor.selection.getRng();
  21539. if (!isText$1(range.commonAncestorContainer)) {
  21540. return false;
  21541. }
  21542. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  21543. var caretWalker = CaretWalker(editor.getBody());
  21544. var getNextPosFn = curry(getVisualCaretPosition, forward ? caretWalker.next : caretWalker.prev);
  21545. var isBeforeFn = forward ? isBeforeBoundary : isAfterBoundary;
  21546. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  21547. var nextCaretPosition = normalizePosition(forward, getNextPosFn(caretPosition));
  21548. if (!nextCaretPosition || !isMoveInsideSameBlock(caretPosition, nextCaretPosition)) {
  21549. return false;
  21550. } else if (isBeforeFn(nextCaretPosition)) {
  21551. return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, nextCaretPosition);
  21552. }
  21553. var peekCaretPosition = getNextPosFn(nextCaretPosition);
  21554. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  21555. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  21556. return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, peekCaretPosition);
  21557. }
  21558. }
  21559. return false;
  21560. };
  21561. var backspaceDelete$3 = function (editor, forward) {
  21562. return deleteBoundaryText(editor, forward);
  21563. };
  21564. var isCompoundElement = function (node) {
  21565. return isTableCell$1(SugarElement.fromDom(node)) || isListItem(SugarElement.fromDom(node));
  21566. };
  21567. var DeleteAction = Adt.generate([
  21568. { remove: ['element'] },
  21569. { moveToElement: ['element'] },
  21570. { moveToPosition: ['position'] }
  21571. ]);
  21572. var isAtContentEditableBlockCaret = function (forward, from) {
  21573. var elm = from.getNode(forward === false);
  21574. var caretLocation = forward ? 'after' : 'before';
  21575. return isElement$1(elm) && elm.getAttribute('data-mce-caret') === caretLocation;
  21576. };
  21577. var isDeleteFromCefDifferentBlocks = function (root, forward, from, to) {
  21578. var inSameBlock = function (elm) {
  21579. return isInline(SugarElement.fromDom(elm)) && !isInSameBlock(from, to, root);
  21580. };
  21581. return getRelativeCefElm(!forward, from).fold(function () {
  21582. return getRelativeCefElm(forward, to).fold(never, inSameBlock);
  21583. }, inSameBlock);
  21584. };
  21585. var deleteEmptyBlockOrMoveToCef = function (root, forward, from, to) {
  21586. var toCefElm = to.getNode(forward === false);
  21587. return getParentBlock$1(SugarElement.fromDom(root), SugarElement.fromDom(from.getNode())).map(function (blockElm) {
  21588. return isEmpty(blockElm) ? DeleteAction.remove(blockElm.dom) : DeleteAction.moveToElement(toCefElm);
  21589. }).orThunk(function () {
  21590. return Optional.some(DeleteAction.moveToElement(toCefElm));
  21591. });
  21592. };
  21593. var findCefPosition = function (root, forward, from) {
  21594. return fromPosition(forward, root, from).bind(function (to) {
  21595. if (isCompoundElement(to.getNode())) {
  21596. return Optional.none();
  21597. } else if (isDeleteFromCefDifferentBlocks(root, forward, from, to)) {
  21598. return Optional.none();
  21599. } else if (forward && isContentEditableFalse(to.getNode())) {
  21600. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  21601. } else if (forward === false && isContentEditableFalse(to.getNode(true))) {
  21602. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  21603. } else if (forward && isAfterContentEditableFalse(from)) {
  21604. return Optional.some(DeleteAction.moveToPosition(to));
  21605. } else if (forward === false && isBeforeContentEditableFalse(from)) {
  21606. return Optional.some(DeleteAction.moveToPosition(to));
  21607. } else {
  21608. return Optional.none();
  21609. }
  21610. });
  21611. };
  21612. var getContentEditableBlockAction = function (forward, elm) {
  21613. if (forward && isContentEditableFalse(elm.nextSibling)) {
  21614. return Optional.some(DeleteAction.moveToElement(elm.nextSibling));
  21615. } else if (forward === false && isContentEditableFalse(elm.previousSibling)) {
  21616. return Optional.some(DeleteAction.moveToElement(elm.previousSibling));
  21617. } else {
  21618. return Optional.none();
  21619. }
  21620. };
  21621. var skipMoveToActionFromInlineCefToContent = function (root, from, deleteAction) {
  21622. return deleteAction.fold(function (elm) {
  21623. return Optional.some(DeleteAction.remove(elm));
  21624. }, function (elm) {
  21625. return Optional.some(DeleteAction.moveToElement(elm));
  21626. }, function (to) {
  21627. if (isInSameBlock(from, to, root)) {
  21628. return Optional.none();
  21629. } else {
  21630. return Optional.some(DeleteAction.moveToPosition(to));
  21631. }
  21632. });
  21633. };
  21634. var getContentEditableAction = function (root, forward, from) {
  21635. if (isAtContentEditableBlockCaret(forward, from)) {
  21636. return getContentEditableBlockAction(forward, from.getNode(forward === false)).fold(function () {
  21637. return findCefPosition(root, forward, from);
  21638. }, Optional.some);
  21639. } else {
  21640. return findCefPosition(root, forward, from).bind(function (deleteAction) {
  21641. return skipMoveToActionFromInlineCefToContent(root, from, deleteAction);
  21642. });
  21643. }
  21644. };
  21645. var read$4 = function (root, forward, rng) {
  21646. var normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
  21647. var from = CaretPosition$1.fromRangeStart(normalizedRange);
  21648. var rootElement = SugarElement.fromDom(root);
  21649. if (forward === false && isAfterContentEditableFalse(from)) {
  21650. return Optional.some(DeleteAction.remove(from.getNode(true)));
  21651. } else if (forward && isBeforeContentEditableFalse(from)) {
  21652. return Optional.some(DeleteAction.remove(from.getNode()));
  21653. } else if (forward === false && isBeforeContentEditableFalse(from) && isAfterBr(rootElement, from)) {
  21654. return findPreviousBr(rootElement, from).map(function (br) {
  21655. return DeleteAction.remove(br.getNode());
  21656. });
  21657. } else if (forward && isAfterContentEditableFalse(from) && isBeforeBr(rootElement, from)) {
  21658. return findNextBr(rootElement, from).map(function (br) {
  21659. return DeleteAction.remove(br.getNode());
  21660. });
  21661. } else {
  21662. return getContentEditableAction(root, forward, from);
  21663. }
  21664. };
  21665. var deleteElement$1 = function (editor, forward) {
  21666. return function (element) {
  21667. editor._selectionOverrides.hideFakeCaret();
  21668. deleteElement(editor, forward, SugarElement.fromDom(element));
  21669. return true;
  21670. };
  21671. };
  21672. var moveToElement = function (editor, forward) {
  21673. return function (element) {
  21674. var pos = forward ? CaretPosition$1.before(element) : CaretPosition$1.after(element);
  21675. editor.selection.setRng(pos.toRange());
  21676. return true;
  21677. };
  21678. };
  21679. var moveToPosition = function (editor) {
  21680. return function (pos) {
  21681. editor.selection.setRng(pos.toRange());
  21682. return true;
  21683. };
  21684. };
  21685. var getAncestorCe = function (editor, node) {
  21686. return Optional.from(getContentEditableRoot(editor.getBody(), node));
  21687. };
  21688. var backspaceDeleteCaret = function (editor, forward) {
  21689. var selectedNode = editor.selection.getNode();
  21690. return getAncestorCe(editor, selectedNode).filter(isContentEditableFalse).fold(function () {
  21691. return read$4(editor.getBody(), forward, editor.selection.getRng()).exists(function (deleteAction) {
  21692. return deleteAction.fold(deleteElement$1(editor, forward), moveToElement(editor, forward), moveToPosition(editor));
  21693. });
  21694. }, always);
  21695. };
  21696. var deleteOffscreenSelection = function (rootElement) {
  21697. each(descendants$1(rootElement, '.mce-offscreen-selection'), remove);
  21698. };
  21699. var backspaceDeleteRange = function (editor, forward) {
  21700. var selectedNode = editor.selection.getNode();
  21701. if (isContentEditableFalse(selectedNode)) {
  21702. var hasCefAncestor = getAncestorCe(editor, selectedNode.parentNode).filter(isContentEditableFalse);
  21703. return hasCefAncestor.fold(function () {
  21704. deleteOffscreenSelection(SugarElement.fromDom(editor.getBody()));
  21705. deleteElement(editor, forward, SugarElement.fromDom(editor.selection.getNode()));
  21706. paddEmptyBody(editor);
  21707. return true;
  21708. }, function () {
  21709. return true;
  21710. });
  21711. }
  21712. return false;
  21713. };
  21714. var paddEmptyElement = function (editor) {
  21715. var dom = editor.dom, selection = editor.selection;
  21716. var ceRoot = getContentEditableRoot(editor.getBody(), selection.getNode());
  21717. if (isContentEditableTrue(ceRoot) && dom.isBlock(ceRoot) && dom.isEmpty(ceRoot)) {
  21718. var br = dom.create('br', { 'data-mce-bogus': '1' });
  21719. dom.setHTML(ceRoot, '');
  21720. ceRoot.appendChild(br);
  21721. selection.setRng(CaretPosition$1.before(br).toRange());
  21722. }
  21723. return true;
  21724. };
  21725. var backspaceDelete$4 = function (editor, forward) {
  21726. if (editor.selection.isCollapsed()) {
  21727. return backspaceDeleteCaret(editor, forward);
  21728. } else {
  21729. return backspaceDeleteRange(editor, forward);
  21730. }
  21731. };
  21732. var deleteCaret$1 = function (editor, forward) {
  21733. var fromPos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  21734. return fromPosition(forward, editor.getBody(), fromPos).filter(function (pos) {
  21735. return forward ? isBeforeImageBlock(pos) : isAfterImageBlock(pos);
  21736. }).bind(function (pos) {
  21737. return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, pos));
  21738. }).exists(function (elm) {
  21739. editor.selection.select(elm);
  21740. return true;
  21741. });
  21742. };
  21743. var backspaceDelete$5 = function (editor, forward) {
  21744. return editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : false;
  21745. };
  21746. var isText$8 = isText$1;
  21747. var startsWithCaretContainer$1 = function (node) {
  21748. return isText$8(node) && node.data[0] === ZWSP;
  21749. };
  21750. var endsWithCaretContainer$1 = function (node) {
  21751. return isText$8(node) && node.data[node.data.length - 1] === ZWSP;
  21752. };
  21753. var createZwsp = function (node) {
  21754. return node.ownerDocument.createTextNode(ZWSP);
  21755. };
  21756. var insertBefore$1 = function (node) {
  21757. if (isText$8(node.previousSibling)) {
  21758. if (endsWithCaretContainer$1(node.previousSibling)) {
  21759. return node.previousSibling;
  21760. } else {
  21761. node.previousSibling.appendData(ZWSP);
  21762. return node.previousSibling;
  21763. }
  21764. } else if (isText$8(node)) {
  21765. if (startsWithCaretContainer$1(node)) {
  21766. return node;
  21767. } else {
  21768. node.insertData(0, ZWSP);
  21769. return node;
  21770. }
  21771. } else {
  21772. var newNode = createZwsp(node);
  21773. node.parentNode.insertBefore(newNode, node);
  21774. return newNode;
  21775. }
  21776. };
  21777. var insertAfter$1 = function (node) {
  21778. if (isText$8(node.nextSibling)) {
  21779. if (startsWithCaretContainer$1(node.nextSibling)) {
  21780. return node.nextSibling;
  21781. } else {
  21782. node.nextSibling.insertData(0, ZWSP);
  21783. return node.nextSibling;
  21784. }
  21785. } else if (isText$8(node)) {
  21786. if (endsWithCaretContainer$1(node)) {
  21787. return node;
  21788. } else {
  21789. node.appendData(ZWSP);
  21790. return node;
  21791. }
  21792. } else {
  21793. var newNode = createZwsp(node);
  21794. if (node.nextSibling) {
  21795. node.parentNode.insertBefore(newNode, node.nextSibling);
  21796. } else {
  21797. node.parentNode.appendChild(newNode);
  21798. }
  21799. return newNode;
  21800. }
  21801. };
  21802. var insertInline$1 = function (before, node) {
  21803. return before ? insertBefore$1(node) : insertAfter$1(node);
  21804. };
  21805. var insertInlineBefore = curry(insertInline$1, true);
  21806. var insertInlineAfter = curry(insertInline$1, false);
  21807. var insertInlinePos = function (pos, before) {
  21808. if (isText$1(pos.container())) {
  21809. return insertInline$1(before, pos.container());
  21810. } else {
  21811. return insertInline$1(before, pos.getNode());
  21812. }
  21813. };
  21814. var isPosCaretContainer = function (pos, caret) {
  21815. var caretNode = caret.get();
  21816. return caretNode && pos.container() === caretNode && isCaretContainerInline(caretNode);
  21817. };
  21818. var renderCaret = function (caret, location) {
  21819. return location.fold(function (element) {
  21820. remove$5(caret.get());
  21821. var text = insertInlineBefore(element);
  21822. caret.set(text);
  21823. return Optional.some(CaretPosition$1(text, text.length - 1));
  21824. }, function (element) {
  21825. return firstPositionIn(element).map(function (pos) {
  21826. if (!isPosCaretContainer(pos, caret)) {
  21827. remove$5(caret.get());
  21828. var text = insertInlinePos(pos, true);
  21829. caret.set(text);
  21830. return CaretPosition$1(text, 1);
  21831. } else {
  21832. return CaretPosition$1(caret.get(), 1);
  21833. }
  21834. });
  21835. }, function (element) {
  21836. return lastPositionIn(element).map(function (pos) {
  21837. if (!isPosCaretContainer(pos, caret)) {
  21838. remove$5(caret.get());
  21839. var text = insertInlinePos(pos, false);
  21840. caret.set(text);
  21841. return CaretPosition$1(text, text.length - 1);
  21842. } else {
  21843. return CaretPosition$1(caret.get(), caret.get().length - 1);
  21844. }
  21845. });
  21846. }, function (element) {
  21847. remove$5(caret.get());
  21848. var text = insertInlineAfter(element);
  21849. caret.set(text);
  21850. return Optional.some(CaretPosition$1(text, 1));
  21851. });
  21852. };
  21853. var evaluateUntil = function (fns, args) {
  21854. for (var i = 0; i < fns.length; i++) {
  21855. var result = fns[i].apply(null, args);
  21856. if (result.isSome()) {
  21857. return result;
  21858. }
  21859. }
  21860. return Optional.none();
  21861. };
  21862. var Location = Adt.generate([
  21863. { before: ['element'] },
  21864. { start: ['element'] },
  21865. { end: ['element'] },
  21866. { after: ['element'] }
  21867. ]);
  21868. var rescope = function (rootNode, node) {
  21869. var parentBlock = getParentBlock(node, rootNode);
  21870. return parentBlock ? parentBlock : rootNode;
  21871. };
  21872. var before$4 = function (isInlineTarget, rootNode, pos) {
  21873. var nPos = normalizeForwards(pos);
  21874. var scope = rescope(rootNode, nPos.container());
  21875. return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  21876. return nextPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  21877. return Location.before(inline);
  21878. });
  21879. }, Optional.none);
  21880. };
  21881. var isNotInsideFormatCaretContainer = function (rootNode, elm) {
  21882. return getParentCaretContainer(rootNode, elm) === null;
  21883. };
  21884. var findInsideRootInline = function (isInlineTarget, rootNode, pos) {
  21885. return findRootInline(isInlineTarget, rootNode, pos).filter(curry(isNotInsideFormatCaretContainer, rootNode));
  21886. };
  21887. var start = function (isInlineTarget, rootNode, pos) {
  21888. var nPos = normalizeBackwards(pos);
  21889. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  21890. var prevPos = prevPosition(inline, nPos);
  21891. return prevPos.isNone() ? Optional.some(Location.start(inline)) : Optional.none();
  21892. });
  21893. };
  21894. var end = function (isInlineTarget, rootNode, pos) {
  21895. var nPos = normalizeForwards(pos);
  21896. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  21897. var nextPos = nextPosition(inline, nPos);
  21898. return nextPos.isNone() ? Optional.some(Location.end(inline)) : Optional.none();
  21899. });
  21900. };
  21901. var after$3 = function (isInlineTarget, rootNode, pos) {
  21902. var nPos = normalizeBackwards(pos);
  21903. var scope = rescope(rootNode, nPos.container());
  21904. return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  21905. return prevPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  21906. return Location.after(inline);
  21907. });
  21908. }, Optional.none);
  21909. };
  21910. var isValidLocation = function (location) {
  21911. return isRtl$1(getElement(location)) === false;
  21912. };
  21913. var readLocation = function (isInlineTarget, rootNode, pos) {
  21914. var location = evaluateUntil([
  21915. before$4,
  21916. start,
  21917. end,
  21918. after$3
  21919. ], [
  21920. isInlineTarget,
  21921. rootNode,
  21922. pos
  21923. ]);
  21924. return location.filter(isValidLocation);
  21925. };
  21926. var getElement = function (location) {
  21927. return location.fold(identity, identity, identity, identity);
  21928. };
  21929. var getName = function (location) {
  21930. return location.fold(constant('before'), constant('start'), constant('end'), constant('after'));
  21931. };
  21932. var outside = function (location) {
  21933. return location.fold(Location.before, Location.before, Location.after, Location.after);
  21934. };
  21935. var inside = function (location) {
  21936. return location.fold(Location.start, Location.start, Location.end, Location.end);
  21937. };
  21938. var isEq$5 = function (location1, location2) {
  21939. return getName(location1) === getName(location2) && getElement(location1) === getElement(location2);
  21940. };
  21941. var betweenInlines = function (forward, isInlineTarget, rootNode, from, to, location) {
  21942. return lift2(findRootInline(isInlineTarget, rootNode, from), findRootInline(isInlineTarget, rootNode, to), function (fromInline, toInline) {
  21943. if (fromInline !== toInline && hasSameParentBlock(rootNode, fromInline, toInline)) {
  21944. return Location.after(forward ? fromInline : toInline);
  21945. } else {
  21946. return location;
  21947. }
  21948. }).getOr(location);
  21949. };
  21950. var skipNoMovement = function (fromLocation, toLocation) {
  21951. return fromLocation.fold(always, function (fromLocation) {
  21952. return !isEq$5(fromLocation, toLocation);
  21953. });
  21954. };
  21955. var findLocationTraverse = function (forward, isInlineTarget, rootNode, fromLocation, pos) {
  21956. var from = normalizePosition(forward, pos);
  21957. var to = fromPosition(forward, rootNode, from).map(curry(normalizePosition, forward));
  21958. var location = to.fold(function () {
  21959. return fromLocation.map(outside);
  21960. }, function (to) {
  21961. return readLocation(isInlineTarget, rootNode, to).map(curry(betweenInlines, forward, isInlineTarget, rootNode, from, to)).filter(curry(skipNoMovement, fromLocation));
  21962. });
  21963. return location.filter(isValidLocation);
  21964. };
  21965. var findLocationSimple = function (forward, location) {
  21966. if (forward) {
  21967. return location.fold(compose(Optional.some, Location.start), Optional.none, compose(Optional.some, Location.after), Optional.none);
  21968. } else {
  21969. return location.fold(Optional.none, compose(Optional.some, Location.before), Optional.none, compose(Optional.some, Location.end));
  21970. }
  21971. };
  21972. var findLocation = function (forward, isInlineTarget, rootNode, pos) {
  21973. var from = normalizePosition(forward, pos);
  21974. var fromLocation = readLocation(isInlineTarget, rootNode, from);
  21975. return readLocation(isInlineTarget, rootNode, from).bind(curry(findLocationSimple, forward)).orThunk(function () {
  21976. return findLocationTraverse(forward, isInlineTarget, rootNode, fromLocation, pos);
  21977. });
  21978. };
  21979. var prevLocation = curry(findLocation, false);
  21980. var nextLocation = curry(findLocation, true);
  21981. var hasSelectionModifyApi = function (editor) {
  21982. return isFunction(editor.selection.getSel().modify);
  21983. };
  21984. var moveRel = function (forward, selection, pos) {
  21985. var delta = forward ? 1 : -1;
  21986. selection.setRng(CaretPosition$1(pos.container(), pos.offset() + delta).toRange());
  21987. selection.getSel().modify('move', forward ? 'forward' : 'backward', 'word');
  21988. return true;
  21989. };
  21990. var moveByWord = function (forward, editor) {
  21991. var rng = editor.selection.getRng();
  21992. var pos = forward ? CaretPosition$1.fromRangeEnd(rng) : CaretPosition$1.fromRangeStart(rng);
  21993. if (!hasSelectionModifyApi(editor)) {
  21994. return false;
  21995. } else if (forward && isBeforeInline(pos)) {
  21996. return moveRel(true, editor.selection, pos);
  21997. } else if (!forward && isAfterInline(pos)) {
  21998. return moveRel(false, editor.selection, pos);
  21999. } else {
  22000. return false;
  22001. }
  22002. };
  22003. var setCaretPosition = function (editor, pos) {
  22004. var rng = editor.dom.createRng();
  22005. rng.setStart(pos.container(), pos.offset());
  22006. rng.setEnd(pos.container(), pos.offset());
  22007. editor.selection.setRng(rng);
  22008. };
  22009. var setSelected = function (state, elm) {
  22010. if (state) {
  22011. elm.setAttribute('data-mce-selected', 'inline-boundary');
  22012. } else {
  22013. elm.removeAttribute('data-mce-selected');
  22014. }
  22015. };
  22016. var renderCaretLocation = function (editor, caret, location) {
  22017. return renderCaret(caret, location).map(function (pos) {
  22018. setCaretPosition(editor, pos);
  22019. return location;
  22020. });
  22021. };
  22022. var findLocation$1 = function (editor, caret, forward) {
  22023. var rootNode = editor.getBody();
  22024. var from = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  22025. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22026. var location = findLocation(forward, isInlineTarget$1, rootNode, from);
  22027. return location.bind(function (location) {
  22028. return renderCaretLocation(editor, caret, location);
  22029. });
  22030. };
  22031. var toggleInlines = function (isInlineTarget, dom, elms) {
  22032. var inlineBoundaries = map(descendants$1(SugarElement.fromDom(dom.getRoot()), '*[data-mce-selected="inline-boundary"]'), function (e) {
  22033. return e.dom;
  22034. });
  22035. var selectedInlines = filter(inlineBoundaries, isInlineTarget);
  22036. var targetInlines = filter(elms, isInlineTarget);
  22037. each(difference(selectedInlines, targetInlines), curry(setSelected, false));
  22038. each(difference(targetInlines, selectedInlines), curry(setSelected, true));
  22039. };
  22040. var safeRemoveCaretContainer = function (editor, caret) {
  22041. if (editor.selection.isCollapsed() && editor.composing !== true && caret.get()) {
  22042. var pos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  22043. if (CaretPosition$1.isTextPosition(pos) && isAtZwsp(pos) === false) {
  22044. setCaretPosition(editor, removeAndReposition(caret.get(), pos));
  22045. caret.set(null);
  22046. }
  22047. }
  22048. };
  22049. var renderInsideInlineCaret = function (isInlineTarget, editor, caret, elms) {
  22050. if (editor.selection.isCollapsed()) {
  22051. var inlines = filter(elms, isInlineTarget);
  22052. each(inlines, function (_inline) {
  22053. var pos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  22054. readLocation(isInlineTarget, editor.getBody(), pos).bind(function (location) {
  22055. return renderCaretLocation(editor, caret, location);
  22056. });
  22057. });
  22058. }
  22059. };
  22060. var move = function (editor, caret, forward) {
  22061. return isInlineBoundariesEnabled(editor) ? findLocation$1(editor, caret, forward).isSome() : false;
  22062. };
  22063. var moveWord = function (forward, editor, _caret) {
  22064. return isInlineBoundariesEnabled(editor) ? moveByWord(forward, editor) : false;
  22065. };
  22066. var setupSelectedState = function (editor) {
  22067. var caret = Cell(null);
  22068. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22069. editor.on('NodeChange', function (e) {
  22070. if (isInlineBoundariesEnabled(editor) && !(Env.browser.isIE() && e.initial)) {
  22071. toggleInlines(isInlineTarget$1, editor.dom, e.parents);
  22072. safeRemoveCaretContainer(editor, caret);
  22073. renderInsideInlineCaret(isInlineTarget$1, editor, caret, e.parents);
  22074. }
  22075. });
  22076. return caret;
  22077. };
  22078. var moveNextWord = curry(moveWord, true);
  22079. var movePrevWord = curry(moveWord, false);
  22080. var rangeFromPositions = function (from, to) {
  22081. var range = document.createRange();
  22082. range.setStart(from.container(), from.offset());
  22083. range.setEnd(to.container(), to.offset());
  22084. return range;
  22085. };
  22086. var hasOnlyTwoOrLessPositionsLeft = function (elm) {
  22087. return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  22088. var normalizedFirstPos = normalizePosition(true, firstPos);
  22089. var normalizedLastPos = normalizePosition(false, lastPos);
  22090. return nextPosition(elm, normalizedFirstPos).forall(function (pos) {
  22091. return pos.isEqual(normalizedLastPos);
  22092. });
  22093. }).getOr(true);
  22094. };
  22095. var setCaretLocation = function (editor, caret) {
  22096. return function (location) {
  22097. return renderCaret(caret, location).exists(function (pos) {
  22098. setCaretPosition(editor, pos);
  22099. return true;
  22100. });
  22101. };
  22102. };
  22103. var deleteFromTo = function (editor, caret, from, to) {
  22104. var rootNode = editor.getBody();
  22105. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22106. editor.undoManager.ignore(function () {
  22107. editor.selection.setRng(rangeFromPositions(from, to));
  22108. editor.execCommand('Delete');
  22109. readLocation(isInlineTarget$1, rootNode, CaretPosition$1.fromRangeStart(editor.selection.getRng())).map(inside).map(setCaretLocation(editor, caret));
  22110. });
  22111. editor.nodeChanged();
  22112. };
  22113. var rescope$1 = function (rootNode, node) {
  22114. var parentBlock = getParentBlock(node, rootNode);
  22115. return parentBlock ? parentBlock : rootNode;
  22116. };
  22117. var backspaceDeleteCollapsed = function (editor, caret, forward, from) {
  22118. var rootNode = rescope$1(editor.getBody(), from.container());
  22119. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22120. var fromLocation = readLocation(isInlineTarget$1, rootNode, from);
  22121. return fromLocation.bind(function (location) {
  22122. if (forward) {
  22123. return location.fold(constant(Optional.some(inside(location))), Optional.none, constant(Optional.some(outside(location))), Optional.none);
  22124. } else {
  22125. return location.fold(Optional.none, constant(Optional.some(outside(location))), Optional.none, constant(Optional.some(inside(location))));
  22126. }
  22127. }).map(setCaretLocation(editor, caret)).getOrThunk(function () {
  22128. var toPosition = navigate(forward, rootNode, from);
  22129. var toLocation = toPosition.bind(function (pos) {
  22130. return readLocation(isInlineTarget$1, rootNode, pos);
  22131. });
  22132. return lift2(fromLocation, toLocation, function () {
  22133. return findRootInline(isInlineTarget$1, rootNode, from).exists(function (elm) {
  22134. if (hasOnlyTwoOrLessPositionsLeft(elm)) {
  22135. deleteElement(editor, forward, SugarElement.fromDom(elm));
  22136. return true;
  22137. } else {
  22138. return false;
  22139. }
  22140. });
  22141. }).orThunk(function () {
  22142. return toLocation.bind(function (_) {
  22143. return toPosition.map(function (to) {
  22144. if (forward) {
  22145. deleteFromTo(editor, caret, from, to);
  22146. } else {
  22147. deleteFromTo(editor, caret, to, from);
  22148. }
  22149. return true;
  22150. });
  22151. });
  22152. }).getOr(false);
  22153. });
  22154. };
  22155. var backspaceDelete$6 = function (editor, caret, forward) {
  22156. if (editor.selection.isCollapsed() && isInlineBoundariesEnabled(editor)) {
  22157. var from = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  22158. return backspaceDeleteCollapsed(editor, caret, forward, from);
  22159. }
  22160. return false;
  22161. };
  22162. var getParentInlines = function (rootElm, startElm) {
  22163. var parents = parentsAndSelf(startElm, rootElm);
  22164. return findIndex(parents, isBlock).fold(constant(parents), function (index) {
  22165. return parents.slice(0, index);
  22166. });
  22167. };
  22168. var hasOnlyOneChild$1 = function (elm) {
  22169. return children(elm).length === 1;
  22170. };
  22171. var deleteLastPosition = function (forward, editor, target, parentInlines) {
  22172. var isFormatElement$1 = curry(isFormatElement, editor);
  22173. var formatNodes = map(filter(parentInlines, isFormatElement$1), function (elm) {
  22174. return elm.dom;
  22175. });
  22176. if (formatNodes.length === 0) {
  22177. deleteElement(editor, forward, target);
  22178. } else {
  22179. var pos = replaceWithCaretFormat(target.dom, formatNodes);
  22180. editor.selection.setRng(pos.toRange());
  22181. }
  22182. };
  22183. var deleteCaret$2 = function (editor, forward) {
  22184. var rootElm = SugarElement.fromDom(editor.getBody());
  22185. var startElm = SugarElement.fromDom(editor.selection.getStart());
  22186. var parentInlines = filter(getParentInlines(rootElm, startElm), hasOnlyOneChild$1);
  22187. return last(parentInlines).exists(function (target) {
  22188. var fromPos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  22189. if (willDeleteLastPositionInElement(forward, fromPos, target.dom) && !isEmptyCaretFormatElement(target)) {
  22190. deleteLastPosition(forward, editor, target, parentInlines);
  22191. return true;
  22192. } else {
  22193. return false;
  22194. }
  22195. });
  22196. };
  22197. var backspaceDelete$7 = function (editor, forward) {
  22198. return editor.selection.isCollapsed() ? deleteCaret$2(editor, forward) : false;
  22199. };
  22200. var deleteElement$2 = function (editor, forward, element) {
  22201. editor._selectionOverrides.hideFakeCaret();
  22202. deleteElement(editor, forward, SugarElement.fromDom(element));
  22203. return true;
  22204. };
  22205. var deleteCaret$3 = function (editor, forward) {
  22206. var isNearMedia = forward ? isBeforeMedia : isAfterMedia;
  22207. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  22208. var fromPos = getNormalizedRangeEndPoint(direction, editor.getBody(), editor.selection.getRng());
  22209. if (isNearMedia(fromPos)) {
  22210. return deleteElement$2(editor, forward, fromPos.getNode(!forward));
  22211. } else {
  22212. return Optional.from(normalizePosition(forward, fromPos)).filter(function (pos) {
  22213. return isNearMedia(pos) && isMoveInsideSameBlock(fromPos, pos);
  22214. }).exists(function (pos) {
  22215. return deleteElement$2(editor, forward, pos.getNode(!forward));
  22216. });
  22217. }
  22218. };
  22219. var deleteRange$2 = function (editor, forward) {
  22220. var selectedNode = editor.selection.getNode();
  22221. return isMedia(selectedNode) ? deleteElement$2(editor, forward, selectedNode) : false;
  22222. };
  22223. var backspaceDelete$8 = function (editor, forward) {
  22224. return editor.selection.isCollapsed() ? deleteCaret$3(editor, forward) : deleteRange$2(editor, forward);
  22225. };
  22226. var isEditable$1 = function (target) {
  22227. return closest(target, function (elm) {
  22228. return isContentEditableTrue(elm.dom) || isContentEditableFalse(elm.dom);
  22229. }).exists(function (elm) {
  22230. return isContentEditableTrue(elm.dom);
  22231. });
  22232. };
  22233. var parseIndentValue = function (value) {
  22234. var number = parseInt(value, 10);
  22235. return isNaN(number) ? 0 : number;
  22236. };
  22237. var getIndentStyleName = function (useMargin, element) {
  22238. var indentStyleName = useMargin || isTable$1(element) ? 'margin' : 'padding';
  22239. var suffix = get$5(element, 'direction') === 'rtl' ? '-right' : '-left';
  22240. return indentStyleName + suffix;
  22241. };
  22242. var indentElement = function (dom, command, useMargin, value, unit, element) {
  22243. var indentStyleName = getIndentStyleName(useMargin, SugarElement.fromDom(element));
  22244. if (command === 'outdent') {
  22245. var styleValue = Math.max(0, parseIndentValue(element.style[indentStyleName]) - value);
  22246. dom.setStyle(element, indentStyleName, styleValue ? styleValue + unit : '');
  22247. } else {
  22248. var styleValue = parseIndentValue(element.style[indentStyleName]) + value + unit;
  22249. dom.setStyle(element, indentStyleName, styleValue);
  22250. }
  22251. };
  22252. var validateBlocks = function (editor, blocks) {
  22253. return forall(blocks, function (block) {
  22254. var indentStyleName = getIndentStyleName(shouldIndentUseMargin(editor), block);
  22255. var intentValue = getRaw(block, indentStyleName).map(parseIndentValue).getOr(0);
  22256. var contentEditable = editor.dom.getContentEditable(block.dom);
  22257. return contentEditable !== 'false' && intentValue > 0;
  22258. });
  22259. };
  22260. var canOutdent = function (editor) {
  22261. var blocks = getBlocksToIndent(editor);
  22262. return !editor.mode.isReadOnly() && (blocks.length > 1 || validateBlocks(editor, blocks));
  22263. };
  22264. var isListComponent = function (el) {
  22265. return isList(el) || isListItem(el);
  22266. };
  22267. var parentIsListComponent = function (el) {
  22268. return parent(el).map(isListComponent).getOr(false);
  22269. };
  22270. var getBlocksToIndent = function (editor) {
  22271. return filter(map(editor.selection.getSelectedBlocks(), SugarElement.fromDom), function (el) {
  22272. return !isListComponent(el) && !parentIsListComponent(el) && isEditable$1(el);
  22273. });
  22274. };
  22275. var handle = function (editor, command) {
  22276. var dom = editor.dom, selection = editor.selection, formatter = editor.formatter;
  22277. var indentation = getIndentation(editor);
  22278. var indentUnit = /[a-z%]+$/i.exec(indentation)[0];
  22279. var indentValue = parseInt(indentation, 10);
  22280. var useMargin = shouldIndentUseMargin(editor);
  22281. var forcedRootBlock = getForcedRootBlock(editor);
  22282. if (!editor.queryCommandState('InsertUnorderedList') && !editor.queryCommandState('InsertOrderedList')) {
  22283. if (forcedRootBlock === '' && !dom.getParent(selection.getNode(), dom.isBlock)) {
  22284. formatter.apply('div');
  22285. }
  22286. }
  22287. each(getBlocksToIndent(editor), function (block) {
  22288. indentElement(dom, command, useMargin, indentValue, indentUnit, block.dom);
  22289. });
  22290. };
  22291. var backspaceDelete$9 = function (editor, _forward) {
  22292. if (editor.selection.isCollapsed() && canOutdent(editor)) {
  22293. var dom = editor.dom;
  22294. var rng = editor.selection.getRng();
  22295. var pos = CaretPosition$1.fromRangeStart(rng);
  22296. var block = dom.getParent(rng.startContainer, dom.isBlock);
  22297. if (block !== null && isAtStartOfBlock(SugarElement.fromDom(block), pos)) {
  22298. handle(editor, 'outdent');
  22299. return true;
  22300. }
  22301. }
  22302. return false;
  22303. };
  22304. var nativeCommand = function (editor, command) {
  22305. editor.getDoc().execCommand(command, false, null);
  22306. };
  22307. var deleteCommand = function (editor, caret) {
  22308. if (backspaceDelete$9(editor)) {
  22309. return;
  22310. } else if (backspaceDelete$4(editor, false)) {
  22311. return;
  22312. } else if (backspaceDelete$3(editor, false)) {
  22313. return;
  22314. } else if (backspaceDelete$6(editor, caret, false)) {
  22315. return;
  22316. } else if (backspaceDelete$1(editor, false)) {
  22317. return;
  22318. } else if (backspaceDelete(editor)) {
  22319. return;
  22320. } else if (backspaceDelete$5(editor, false)) {
  22321. return;
  22322. } else if (backspaceDelete$8(editor, false)) {
  22323. return;
  22324. } else if (backspaceDelete$2(editor)) {
  22325. return;
  22326. } else if (backspaceDelete$7(editor, false)) {
  22327. return;
  22328. } else {
  22329. nativeCommand(editor, 'Delete');
  22330. paddEmptyBody(editor);
  22331. }
  22332. };
  22333. var forwardDeleteCommand = function (editor, caret) {
  22334. if (backspaceDelete$4(editor, true)) {
  22335. return;
  22336. } else if (backspaceDelete$3(editor, true)) {
  22337. return;
  22338. } else if (backspaceDelete$6(editor, caret, true)) {
  22339. return;
  22340. } else if (backspaceDelete$1(editor, true)) {
  22341. return;
  22342. } else if (backspaceDelete(editor)) {
  22343. return;
  22344. } else if (backspaceDelete$5(editor, true)) {
  22345. return;
  22346. } else if (backspaceDelete$8(editor, true)) {
  22347. return;
  22348. } else if (backspaceDelete$2(editor)) {
  22349. return;
  22350. } else if (backspaceDelete$7(editor, true)) {
  22351. return;
  22352. } else {
  22353. nativeCommand(editor, 'ForwardDelete');
  22354. }
  22355. };
  22356. var setup$8 = function (editor, caret) {
  22357. editor.addCommand('delete', function () {
  22358. deleteCommand(editor, caret);
  22359. });
  22360. editor.addCommand('forwardDelete', function () {
  22361. forwardDeleteCommand(editor, caret);
  22362. });
  22363. };
  22364. var SIGNIFICANT_MOVE = 5;
  22365. var LONGPRESS_DELAY = 400;
  22366. var getTouch = function (event) {
  22367. if (event.touches === undefined || event.touches.length !== 1) {
  22368. return Optional.none();
  22369. }
  22370. return Optional.some(event.touches[0]);
  22371. };
  22372. var isFarEnough = function (touch, data) {
  22373. var distX = Math.abs(touch.clientX - data.x);
  22374. var distY = Math.abs(touch.clientY - data.y);
  22375. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  22376. };
  22377. var setup$9 = function (editor) {
  22378. var startData = Cell(Optional.none());
  22379. var longpressFired = Cell(false);
  22380. var debounceLongpress = last$2(function (e) {
  22381. editor.fire('longpress', __assign(__assign({}, e), { type: 'longpress' }));
  22382. longpressFired.set(true);
  22383. }, LONGPRESS_DELAY);
  22384. editor.on('touchstart', function (e) {
  22385. getTouch(e).each(function (touch) {
  22386. debounceLongpress.cancel();
  22387. var data = {
  22388. x: touch.clientX,
  22389. y: touch.clientY,
  22390. target: e.target
  22391. };
  22392. debounceLongpress.throttle(e);
  22393. longpressFired.set(false);
  22394. startData.set(Optional.some(data));
  22395. });
  22396. }, true);
  22397. editor.on('touchmove', function (e) {
  22398. debounceLongpress.cancel();
  22399. getTouch(e).each(function (touch) {
  22400. startData.get().each(function (data) {
  22401. if (isFarEnough(touch, data)) {
  22402. startData.set(Optional.none());
  22403. longpressFired.set(false);
  22404. editor.fire('longpresscancel');
  22405. }
  22406. });
  22407. });
  22408. }, true);
  22409. editor.on('touchend touchcancel', function (e) {
  22410. debounceLongpress.cancel();
  22411. if (e.type === 'touchcancel') {
  22412. return;
  22413. }
  22414. startData.get().filter(function (data) {
  22415. return data.target.isEqualNode(e.target);
  22416. }).each(function () {
  22417. if (longpressFired.get()) {
  22418. e.preventDefault();
  22419. } else {
  22420. editor.fire('tap', __assign(__assign({}, e), { type: 'tap' }));
  22421. }
  22422. });
  22423. }, true);
  22424. };
  22425. var isBlockElement = function (blockElements, node) {
  22426. return blockElements.hasOwnProperty(node.nodeName);
  22427. };
  22428. var isValidTarget = function (blockElements, node) {
  22429. if (isText$1(node)) {
  22430. return true;
  22431. } else if (isElement$1(node)) {
  22432. return !isBlockElement(blockElements, node) && !isBookmarkNode$1(node);
  22433. } else {
  22434. return false;
  22435. }
  22436. };
  22437. var hasBlockParent = function (blockElements, root, node) {
  22438. return exists(parents$1(SugarElement.fromDom(node), SugarElement.fromDom(root)), function (elm) {
  22439. return isBlockElement(blockElements, elm.dom);
  22440. });
  22441. };
  22442. var shouldRemoveTextNode = function (blockElements, node) {
  22443. if (isText$1(node)) {
  22444. if (node.nodeValue.length === 0) {
  22445. return true;
  22446. } else if (/^\s+$/.test(node.nodeValue) && (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
  22447. return true;
  22448. }
  22449. }
  22450. return false;
  22451. };
  22452. var addRootBlocks = function (editor) {
  22453. var dom = editor.dom, selection = editor.selection;
  22454. var schema = editor.schema, blockElements = schema.getBlockElements();
  22455. var node = selection.getStart();
  22456. var rootNode = editor.getBody();
  22457. var rootBlockNode, tempNode, wrapped;
  22458. var forcedRootBlock = getForcedRootBlock(editor);
  22459. if (!node || !isElement$1(node) || !forcedRootBlock) {
  22460. return;
  22461. }
  22462. var rootNodeName = rootNode.nodeName.toLowerCase();
  22463. if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, node)) {
  22464. return;
  22465. }
  22466. var rng = selection.getRng();
  22467. var startContainer = rng.startContainer;
  22468. var startOffset = rng.startOffset;
  22469. var endContainer = rng.endContainer;
  22470. var endOffset = rng.endOffset;
  22471. var restoreSelection = hasFocus$1(editor);
  22472. node = rootNode.firstChild;
  22473. while (node) {
  22474. if (isValidTarget(blockElements, node)) {
  22475. if (shouldRemoveTextNode(blockElements, node)) {
  22476. tempNode = node;
  22477. node = node.nextSibling;
  22478. dom.remove(tempNode);
  22479. continue;
  22480. }
  22481. if (!rootBlockNode) {
  22482. rootBlockNode = dom.create(forcedRootBlock, getForcedRootBlockAttrs(editor));
  22483. node.parentNode.insertBefore(rootBlockNode, node);
  22484. wrapped = true;
  22485. }
  22486. tempNode = node;
  22487. node = node.nextSibling;
  22488. rootBlockNode.appendChild(tempNode);
  22489. } else {
  22490. rootBlockNode = null;
  22491. node = node.nextSibling;
  22492. }
  22493. }
  22494. if (wrapped && restoreSelection) {
  22495. rng.setStart(startContainer, startOffset);
  22496. rng.setEnd(endContainer, endOffset);
  22497. selection.setRng(rng);
  22498. editor.nodeChanged();
  22499. }
  22500. };
  22501. var setup$a = function (editor) {
  22502. if (getForcedRootBlock(editor)) {
  22503. editor.on('NodeChange', curry(addRootBlocks, editor));
  22504. }
  22505. };
  22506. var findBlockCaretContainer = function (editor) {
  22507. return descendant(SugarElement.fromDom(editor.getBody()), '*[data-mce-caret]').fold(constant(null), function (elm) {
  22508. return elm.dom;
  22509. });
  22510. };
  22511. var removeIeControlRect = function (editor) {
  22512. editor.selection.setRng(editor.selection.getRng());
  22513. };
  22514. var showBlockCaretContainer = function (editor, blockCaretContainer) {
  22515. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  22516. showCaretContainerBlock(blockCaretContainer);
  22517. removeIeControlRect(editor);
  22518. editor.selection.scrollIntoView(blockCaretContainer);
  22519. }
  22520. };
  22521. var handleBlockContainer = function (editor, e) {
  22522. var blockCaretContainer = findBlockCaretContainer(editor);
  22523. if (!blockCaretContainer) {
  22524. return;
  22525. }
  22526. if (e.type === 'compositionstart') {
  22527. e.preventDefault();
  22528. e.stopPropagation();
  22529. showBlockCaretContainer(editor, blockCaretContainer);
  22530. return;
  22531. }
  22532. if (hasContent(blockCaretContainer)) {
  22533. showBlockCaretContainer(editor, blockCaretContainer);
  22534. editor.undoManager.add();
  22535. }
  22536. };
  22537. var setup$b = function (editor) {
  22538. editor.on('keyup compositionstart', curry(handleBlockContainer, editor));
  22539. };
  22540. var BreakType;
  22541. (function (BreakType) {
  22542. BreakType[BreakType['Br'] = 0] = 'Br';
  22543. BreakType[BreakType['Block'] = 1] = 'Block';
  22544. BreakType[BreakType['Wrap'] = 2] = 'Wrap';
  22545. BreakType[BreakType['Eol'] = 3] = 'Eol';
  22546. }(BreakType || (BreakType = {})));
  22547. var flip = function (direction, positions) {
  22548. return direction === HDirection.Backwards ? reverse(positions) : positions;
  22549. };
  22550. var walk$3 = function (direction, caretWalker, pos) {
  22551. return direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
  22552. };
  22553. var getBreakType = function (scope, direction, currentPos, nextPos) {
  22554. if (isBr(nextPos.getNode(direction === HDirection.Forwards))) {
  22555. return BreakType.Br;
  22556. } else if (isInSameBlock(currentPos, nextPos) === false) {
  22557. return BreakType.Block;
  22558. } else {
  22559. return BreakType.Wrap;
  22560. }
  22561. };
  22562. var getPositionsUntil = function (predicate, direction, scope, start) {
  22563. var caretWalker = CaretWalker(scope);
  22564. var currentPos = start, nextPos;
  22565. var positions = [];
  22566. while (currentPos) {
  22567. nextPos = walk$3(direction, caretWalker, currentPos);
  22568. if (!nextPos) {
  22569. break;
  22570. }
  22571. if (isBr(nextPos.getNode(false))) {
  22572. if (direction === HDirection.Forwards) {
  22573. return {
  22574. positions: flip(direction, positions).concat([nextPos]),
  22575. breakType: BreakType.Br,
  22576. breakAt: Optional.some(nextPos)
  22577. };
  22578. } else {
  22579. return {
  22580. positions: flip(direction, positions),
  22581. breakType: BreakType.Br,
  22582. breakAt: Optional.some(nextPos)
  22583. };
  22584. }
  22585. }
  22586. if (!nextPos.isVisible()) {
  22587. currentPos = nextPos;
  22588. continue;
  22589. }
  22590. if (predicate(currentPos, nextPos)) {
  22591. var breakType = getBreakType(scope, direction, currentPos, nextPos);
  22592. return {
  22593. positions: flip(direction, positions),
  22594. breakType: breakType,
  22595. breakAt: Optional.some(nextPos)
  22596. };
  22597. }
  22598. positions.push(nextPos);
  22599. currentPos = nextPos;
  22600. }
  22601. return {
  22602. positions: flip(direction, positions),
  22603. breakType: BreakType.Eol,
  22604. breakAt: Optional.none()
  22605. };
  22606. };
  22607. var getAdjacentLinePositions = function (direction, getPositionsUntilBreak, scope, start) {
  22608. return getPositionsUntilBreak(scope, start).breakAt.map(function (pos) {
  22609. var positions = getPositionsUntilBreak(scope, pos).positions;
  22610. return direction === HDirection.Backwards ? positions.concat(pos) : [pos].concat(positions);
  22611. }).getOr([]);
  22612. };
  22613. var findClosestHorizontalPositionFromPoint = function (positions, x) {
  22614. return foldl(positions, function (acc, newPos) {
  22615. return acc.fold(function () {
  22616. return Optional.some(newPos);
  22617. }, function (lastPos) {
  22618. return lift2(head(lastPos.getClientRects()), head(newPos.getClientRects()), function (lastRect, newRect) {
  22619. var lastDist = Math.abs(x - lastRect.left);
  22620. var newDist = Math.abs(x - newRect.left);
  22621. return newDist <= lastDist ? newPos : lastPos;
  22622. }).or(acc);
  22623. });
  22624. }, Optional.none());
  22625. };
  22626. var findClosestHorizontalPosition = function (positions, pos) {
  22627. return head(pos.getClientRects()).bind(function (targetRect) {
  22628. return findClosestHorizontalPositionFromPoint(positions, targetRect.left);
  22629. });
  22630. };
  22631. var getPositionsUntilPreviousLine = curry(getPositionsUntil, CaretPosition.isAbove, -1);
  22632. var getPositionsUntilNextLine = curry(getPositionsUntil, CaretPosition.isBelow, 1);
  22633. var isAtFirstLine = function (scope, pos) {
  22634. return getPositionsUntilPreviousLine(scope, pos).breakAt.isNone();
  22635. };
  22636. var isAtLastLine = function (scope, pos) {
  22637. return getPositionsUntilNextLine(scope, pos).breakAt.isNone();
  22638. };
  22639. var getPositionsAbove = curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
  22640. var getPositionsBelow = curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
  22641. var getFirstLinePositions = function (scope) {
  22642. return firstPositionIn(scope).map(function (pos) {
  22643. return [pos].concat(getPositionsUntilNextLine(scope, pos).positions);
  22644. }).getOr([]);
  22645. };
  22646. var getLastLinePositions = function (scope) {
  22647. return lastPositionIn(scope).map(function (pos) {
  22648. return getPositionsUntilPreviousLine(scope, pos).positions.concat(pos);
  22649. }).getOr([]);
  22650. };
  22651. var getNodeClientRects = function (node) {
  22652. var toArrayWithNode = function (clientRects) {
  22653. return map(clientRects, function (clientRect) {
  22654. clientRect = clone$2(clientRect);
  22655. clientRect.node = node;
  22656. return clientRect;
  22657. });
  22658. };
  22659. if (isElement$1(node)) {
  22660. return toArrayWithNode(node.getClientRects());
  22661. }
  22662. if (isText$1(node)) {
  22663. var rng = node.ownerDocument.createRange();
  22664. rng.setStart(node, 0);
  22665. rng.setEnd(node, node.data.length);
  22666. return toArrayWithNode(rng.getClientRects());
  22667. }
  22668. };
  22669. var getClientRects = function (nodes) {
  22670. return bind(nodes, getNodeClientRects);
  22671. };
  22672. var VDirection;
  22673. (function (VDirection) {
  22674. VDirection[VDirection['Up'] = -1] = 'Up';
  22675. VDirection[VDirection['Down'] = 1] = 'Down';
  22676. }(VDirection || (VDirection = {})));
  22677. var findUntil$1 = function (direction, root, predicateFn, node) {
  22678. while (node = findNode(node, direction, isEditableCaretCandidate, root)) {
  22679. if (predicateFn(node)) {
  22680. return;
  22681. }
  22682. }
  22683. };
  22684. var walkUntil = function (direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) {
  22685. var line = 0;
  22686. var result = [];
  22687. var add = function (node) {
  22688. var i, clientRect, clientRects;
  22689. clientRects = getClientRects([node]);
  22690. if (direction === -1) {
  22691. clientRects = clientRects.reverse();
  22692. }
  22693. for (i = 0; i < clientRects.length; i++) {
  22694. clientRect = clientRects[i];
  22695. if (isBeflowFn(clientRect, targetClientRect)) {
  22696. continue;
  22697. }
  22698. if (result.length > 0 && isAboveFn(clientRect, last$1(result))) {
  22699. line++;
  22700. }
  22701. clientRect.line = line;
  22702. if (predicateFn(clientRect)) {
  22703. return true;
  22704. }
  22705. result.push(clientRect);
  22706. }
  22707. };
  22708. var targetClientRect = last$1(caretPosition.getClientRects());
  22709. if (!targetClientRect) {
  22710. return result;
  22711. }
  22712. var node = caretPosition.getNode();
  22713. add(node);
  22714. findUntil$1(direction, root, add, node);
  22715. return result;
  22716. };
  22717. var aboveLineNumber = function (lineNumber, clientRect) {
  22718. return clientRect.line > lineNumber;
  22719. };
  22720. var isLineNumber = function (lineNumber, clientRect) {
  22721. return clientRect.line === lineNumber;
  22722. };
  22723. var upUntil = curry(walkUntil, VDirection.Up, isAbove, isBelow);
  22724. var downUntil = curry(walkUntil, VDirection.Down, isBelow, isAbove);
  22725. var positionsUntil = function (direction, root, predicateFn, node) {
  22726. var caretWalker = CaretWalker(root);
  22727. var walkFn, isBelowFn, isAboveFn, caretPosition;
  22728. var result = [];
  22729. var line = 0, clientRect;
  22730. var getClientRect = function (caretPosition) {
  22731. if (direction === 1) {
  22732. return last$1(caretPosition.getClientRects());
  22733. }
  22734. return last$1(caretPosition.getClientRects());
  22735. };
  22736. if (direction === 1) {
  22737. walkFn = caretWalker.next;
  22738. isBelowFn = isBelow;
  22739. isAboveFn = isAbove;
  22740. caretPosition = CaretPosition$1.after(node);
  22741. } else {
  22742. walkFn = caretWalker.prev;
  22743. isBelowFn = isAbove;
  22744. isAboveFn = isBelow;
  22745. caretPosition = CaretPosition$1.before(node);
  22746. }
  22747. var targetClientRect = getClientRect(caretPosition);
  22748. do {
  22749. if (!caretPosition.isVisible()) {
  22750. continue;
  22751. }
  22752. clientRect = getClientRect(caretPosition);
  22753. if (isAboveFn(clientRect, targetClientRect)) {
  22754. continue;
  22755. }
  22756. if (result.length > 0 && isBelowFn(clientRect, last$1(result))) {
  22757. line++;
  22758. }
  22759. clientRect = clone$2(clientRect);
  22760. clientRect.position = caretPosition;
  22761. clientRect.line = line;
  22762. if (predicateFn(clientRect)) {
  22763. return result;
  22764. }
  22765. result.push(clientRect);
  22766. } while (caretPosition = walkFn(caretPosition));
  22767. return result;
  22768. };
  22769. var isAboveLine = function (lineNumber) {
  22770. return function (clientRect) {
  22771. return aboveLineNumber(lineNumber, clientRect);
  22772. };
  22773. };
  22774. var isLine = function (lineNumber) {
  22775. return function (clientRect) {
  22776. return isLineNumber(lineNumber, clientRect);
  22777. };
  22778. };
  22779. var isContentEditableFalse$8 = isContentEditableFalse;
  22780. var findNode$1 = findNode;
  22781. var distanceToRectLeft = function (clientRect, clientX) {
  22782. return Math.abs(clientRect.left - clientX);
  22783. };
  22784. var distanceToRectRight = function (clientRect, clientX) {
  22785. return Math.abs(clientRect.right - clientX);
  22786. };
  22787. var isInsideX = function (clientX, clientRect) {
  22788. return clientX >= clientRect.left && clientX <= clientRect.right;
  22789. };
  22790. var isInsideY = function (clientY, clientRect) {
  22791. return clientY >= clientRect.top && clientY <= clientRect.bottom;
  22792. };
  22793. var findClosestClientRect = function (clientRects, clientX) {
  22794. return reduce(clientRects, function (oldClientRect, clientRect) {
  22795. var oldDistance = Math.min(distanceToRectLeft(oldClientRect, clientX), distanceToRectRight(oldClientRect, clientX));
  22796. var newDistance = Math.min(distanceToRectLeft(clientRect, clientX), distanceToRectRight(clientRect, clientX));
  22797. if (isInsideX(clientX, clientRect)) {
  22798. return clientRect;
  22799. }
  22800. if (isInsideX(clientX, oldClientRect)) {
  22801. return oldClientRect;
  22802. }
  22803. if (newDistance === oldDistance && isContentEditableFalse$8(clientRect.node)) {
  22804. return clientRect;
  22805. }
  22806. if (newDistance < oldDistance) {
  22807. return clientRect;
  22808. }
  22809. return oldClientRect;
  22810. });
  22811. };
  22812. var walkUntil$1 = function (direction, root, predicateFn, startNode, includeChildren) {
  22813. var node = findNode$1(startNode, direction, isEditableCaretCandidate, root, !includeChildren);
  22814. do {
  22815. if (!node || predicateFn(node)) {
  22816. return;
  22817. }
  22818. } while (node = findNode$1(node, direction, isEditableCaretCandidate, root));
  22819. };
  22820. var findLineNodeRects = function (root, targetNodeRect, includeChildren) {
  22821. if (includeChildren === void 0) {
  22822. includeChildren = true;
  22823. }
  22824. var clientRects = [];
  22825. var collect = function (checkPosFn, node) {
  22826. var lineRects = filter(getClientRects([node]), function (clientRect) {
  22827. return !checkPosFn(clientRect, targetNodeRect);
  22828. });
  22829. clientRects = clientRects.concat(lineRects);
  22830. return lineRects.length === 0;
  22831. };
  22832. clientRects.push(targetNodeRect);
  22833. walkUntil$1(VDirection.Up, root, curry(collect, isAbove), targetNodeRect.node, includeChildren);
  22834. walkUntil$1(VDirection.Down, root, curry(collect, isBelow), targetNodeRect.node, includeChildren);
  22835. return clientRects;
  22836. };
  22837. var getFakeCaretTargets = function (root) {
  22838. return filter(from$1(root.getElementsByTagName('*')), isFakeCaretTarget);
  22839. };
  22840. var caretInfo = function (clientRect, clientX) {
  22841. return {
  22842. node: clientRect.node,
  22843. before: distanceToRectLeft(clientRect, clientX) < distanceToRectRight(clientRect, clientX)
  22844. };
  22845. };
  22846. var closestFakeCaret = function (root, clientX, clientY) {
  22847. var fakeTargetNodeRects = getClientRects(getFakeCaretTargets(root));
  22848. var targetNodeRects = filter(fakeTargetNodeRects, curry(isInsideY, clientY));
  22849. var closestNodeRect = findClosestClientRect(targetNodeRects, clientX);
  22850. if (closestNodeRect) {
  22851. var includeChildren = !isTable(closestNodeRect.node) && !isMedia(closestNodeRect.node);
  22852. closestNodeRect = findClosestClientRect(findLineNodeRects(root, closestNodeRect, includeChildren), clientX);
  22853. if (closestNodeRect && isFakeCaretTarget(closestNodeRect.node)) {
  22854. return caretInfo(closestNodeRect, clientX);
  22855. }
  22856. }
  22857. return null;
  22858. };
  22859. var moveToRange = function (editor, rng) {
  22860. editor.selection.setRng(rng);
  22861. scrollRangeIntoView(editor, editor.selection.getRng());
  22862. };
  22863. var renderRangeCaretOpt = function (editor, range, scrollIntoView) {
  22864. return Optional.some(renderRangeCaret(editor, range, scrollIntoView));
  22865. };
  22866. var moveHorizontally = function (editor, direction, range, isBefore, isAfter, isElement) {
  22867. var forwards = direction === HDirection.Forwards;
  22868. var caretWalker = CaretWalker(editor.getBody());
  22869. var getNextPosFn = curry(getVisualCaretPosition, forwards ? caretWalker.next : caretWalker.prev);
  22870. var isBeforeFn = forwards ? isBefore : isAfter;
  22871. if (!range.collapsed) {
  22872. var node = getSelectedNode(range);
  22873. if (isElement(node)) {
  22874. return showCaret(direction, editor, node, direction === HDirection.Backwards, false);
  22875. }
  22876. }
  22877. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22878. if (isBeforeFn(caretPosition)) {
  22879. return selectNode(editor, caretPosition.getNode(!forwards));
  22880. }
  22881. var nextCaretPosition = normalizePosition(forwards, getNextPosFn(caretPosition));
  22882. var rangeIsInContainerBlock = isRangeInCaretContainerBlock(range);
  22883. if (!nextCaretPosition) {
  22884. return rangeIsInContainerBlock ? Optional.some(range) : Optional.none();
  22885. }
  22886. if (isBeforeFn(nextCaretPosition)) {
  22887. return showCaret(direction, editor, nextCaretPosition.getNode(!forwards), forwards, false);
  22888. }
  22889. var peekCaretPosition = getNextPosFn(nextCaretPosition);
  22890. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  22891. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  22892. return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, false);
  22893. }
  22894. }
  22895. if (rangeIsInContainerBlock) {
  22896. return renderRangeCaretOpt(editor, nextCaretPosition.toRange(), false);
  22897. }
  22898. return Optional.none();
  22899. };
  22900. var moveVertically = function (editor, direction, range, isBefore, isAfter, isElement) {
  22901. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22902. var caretClientRect = last$1(caretPosition.getClientRects());
  22903. var forwards = direction === VDirection.Down;
  22904. if (!caretClientRect) {
  22905. return Optional.none();
  22906. }
  22907. var walkerFn = forwards ? downUntil : upUntil;
  22908. var linePositions = walkerFn(editor.getBody(), isAboveLine(1), caretPosition);
  22909. var nextLinePositions = filter(linePositions, isLine(1));
  22910. var clientX = caretClientRect.left;
  22911. var nextLineRect = findClosestClientRect(nextLinePositions, clientX);
  22912. if (nextLineRect && isElement(nextLineRect.node)) {
  22913. var dist1 = Math.abs(clientX - nextLineRect.left);
  22914. var dist2 = Math.abs(clientX - nextLineRect.right);
  22915. return showCaret(direction, editor, nextLineRect.node, dist1 < dist2, false);
  22916. }
  22917. var currentNode;
  22918. if (isBefore(caretPosition)) {
  22919. currentNode = caretPosition.getNode();
  22920. } else if (isAfter(caretPosition)) {
  22921. currentNode = caretPosition.getNode(true);
  22922. } else {
  22923. currentNode = getSelectedNode(range);
  22924. }
  22925. if (currentNode) {
  22926. var caretPositions = positionsUntil(direction, editor.getBody(), isAboveLine(1), currentNode);
  22927. var closestNextLineRect = findClosestClientRect(filter(caretPositions, isLine(1)), clientX);
  22928. if (closestNextLineRect) {
  22929. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  22930. }
  22931. closestNextLineRect = last$1(filter(caretPositions, isLine(0)));
  22932. if (closestNextLineRect) {
  22933. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  22934. }
  22935. }
  22936. if (nextLinePositions.length === 0) {
  22937. return getLineEndPoint(editor, forwards).filter(forwards ? isAfter : isBefore).map(function (pos) {
  22938. return renderRangeCaret(editor, pos.toRange(), false);
  22939. });
  22940. }
  22941. return Optional.none();
  22942. };
  22943. var getLineEndPoint = function (editor, forward) {
  22944. var rng = editor.selection.getRng();
  22945. var body = editor.getBody();
  22946. if (forward) {
  22947. var from = CaretPosition$1.fromRangeEnd(rng);
  22948. var result = getPositionsUntilNextLine(body, from);
  22949. return last(result.positions);
  22950. } else {
  22951. var from = CaretPosition$1.fromRangeStart(rng);
  22952. var result = getPositionsUntilPreviousLine(body, from);
  22953. return head(result.positions);
  22954. }
  22955. };
  22956. var moveToLineEndPoint = function (editor, forward, isElementPosition) {
  22957. return getLineEndPoint(editor, forward).filter(isElementPosition).exists(function (pos) {
  22958. editor.selection.setRng(pos.toRange());
  22959. return true;
  22960. });
  22961. };
  22962. var isContentEditableFalse$9 = isContentEditableFalse;
  22963. var moveToCeFalseHorizontally = function (direction, editor, range) {
  22964. return moveHorizontally(editor, direction, range, isBeforeContentEditableFalse, isAfterContentEditableFalse, isContentEditableFalse$9);
  22965. };
  22966. var moveToCeFalseVertically = function (direction, editor, range) {
  22967. var isBefore = function (caretPosition) {
  22968. return isBeforeContentEditableFalse(caretPosition) || isBeforeTable(caretPosition);
  22969. };
  22970. var isAfter = function (caretPosition) {
  22971. return isAfterContentEditableFalse(caretPosition) || isAfterTable(caretPosition);
  22972. };
  22973. return moveVertically(editor, direction, range, isBefore, isAfter, isContentEditableFalse$9);
  22974. };
  22975. var createTextBlock = function (editor) {
  22976. var textBlock = editor.dom.create(getForcedRootBlock(editor));
  22977. if (!Env.ie || Env.ie >= 11) {
  22978. textBlock.innerHTML = '<br data-mce-bogus="1">';
  22979. }
  22980. return textBlock;
  22981. };
  22982. var exitPreBlock = function (editor, direction, range) {
  22983. var caretWalker = CaretWalker(editor.getBody());
  22984. var getVisualCaretPosition$1 = curry(getVisualCaretPosition, direction === 1 ? caretWalker.next : caretWalker.prev);
  22985. if (range.collapsed && hasForcedRootBlock(editor)) {
  22986. var pre = editor.dom.getParent(range.startContainer, 'PRE');
  22987. if (!pre) {
  22988. return;
  22989. }
  22990. var caretPos = getVisualCaretPosition$1(CaretPosition$1.fromRangeStart(range));
  22991. if (!caretPos) {
  22992. var newBlock = createTextBlock(editor);
  22993. if (direction === 1) {
  22994. editor.$(pre).after(newBlock);
  22995. } else {
  22996. editor.$(pre).before(newBlock);
  22997. }
  22998. editor.selection.select(newBlock, true);
  22999. editor.selection.collapse();
  23000. }
  23001. }
  23002. };
  23003. var getHorizontalRange = function (editor, forward) {
  23004. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23005. var range = editor.selection.getRng();
  23006. return moveToCeFalseHorizontally(direction, editor, range).orThunk(function () {
  23007. exitPreBlock(editor, direction, range);
  23008. return Optional.none();
  23009. });
  23010. };
  23011. var getVerticalRange = function (editor, down) {
  23012. var direction = down ? 1 : -1;
  23013. var range = editor.selection.getRng();
  23014. return moveToCeFalseVertically(direction, editor, range).orThunk(function () {
  23015. exitPreBlock(editor, direction, range);
  23016. return Optional.none();
  23017. });
  23018. };
  23019. var moveH = function (editor, forward) {
  23020. return getHorizontalRange(editor, forward).exists(function (newRange) {
  23021. moveToRange(editor, newRange);
  23022. return true;
  23023. });
  23024. };
  23025. var moveV = function (editor, down) {
  23026. return getVerticalRange(editor, down).exists(function (newRange) {
  23027. moveToRange(editor, newRange);
  23028. return true;
  23029. });
  23030. };
  23031. var moveToLineEndPoint$1 = function (editor, forward) {
  23032. var isCefPosition = forward ? isAfterContentEditableFalse : isBeforeContentEditableFalse;
  23033. return moveToLineEndPoint(editor, forward, isCefPosition);
  23034. };
  23035. var isTarget = function (node) {
  23036. return contains(['figcaption'], name(node));
  23037. };
  23038. var rangeBefore = function (target) {
  23039. var rng = document.createRange();
  23040. rng.setStartBefore(target.dom);
  23041. rng.setEndBefore(target.dom);
  23042. return rng;
  23043. };
  23044. var insertElement = function (root, elm, forward) {
  23045. if (forward) {
  23046. append(root, elm);
  23047. } else {
  23048. prepend(root, elm);
  23049. }
  23050. };
  23051. var insertBr = function (root, forward) {
  23052. var br = SugarElement.fromTag('br');
  23053. insertElement(root, br, forward);
  23054. return rangeBefore(br);
  23055. };
  23056. var insertBlock$1 = function (root, forward, blockName, attrs) {
  23057. var block = SugarElement.fromTag(blockName);
  23058. var br = SugarElement.fromTag('br');
  23059. setAll(block, attrs);
  23060. append(block, br);
  23061. insertElement(root, block, forward);
  23062. return rangeBefore(br);
  23063. };
  23064. var insertEmptyLine = function (root, rootBlockName, attrs, forward) {
  23065. if (rootBlockName === '') {
  23066. return insertBr(root, forward);
  23067. } else {
  23068. return insertBlock$1(root, forward, rootBlockName, attrs);
  23069. }
  23070. };
  23071. var getClosestTargetBlock = function (pos, root) {
  23072. var isRoot = curry(eq$2, root);
  23073. return closest(SugarElement.fromDom(pos.container()), isBlock, isRoot).filter(isTarget);
  23074. };
  23075. var isAtFirstOrLastLine = function (root, forward, pos) {
  23076. return forward ? isAtLastLine(root.dom, pos) : isAtFirstLine(root.dom, pos);
  23077. };
  23078. var moveCaretToNewEmptyLine = function (editor, forward) {
  23079. var root = SugarElement.fromDom(editor.getBody());
  23080. var pos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  23081. var rootBlock = getForcedRootBlock(editor);
  23082. var rootBlockAttrs = getForcedRootBlockAttrs(editor);
  23083. return getClosestTargetBlock(pos, root).exists(function () {
  23084. if (isAtFirstOrLastLine(root, forward, pos)) {
  23085. var rng = insertEmptyLine(root, rootBlock, rootBlockAttrs, forward);
  23086. editor.selection.setRng(rng);
  23087. return true;
  23088. } else {
  23089. return false;
  23090. }
  23091. });
  23092. };
  23093. var moveV$1 = function (editor, forward) {
  23094. if (editor.selection.isCollapsed()) {
  23095. return moveCaretToNewEmptyLine(editor, forward);
  23096. } else {
  23097. return false;
  23098. }
  23099. };
  23100. var defaultPatterns = function (patterns) {
  23101. return map(patterns, function (pattern) {
  23102. return __assign({
  23103. shiftKey: false,
  23104. altKey: false,
  23105. ctrlKey: false,
  23106. metaKey: false,
  23107. keyCode: 0,
  23108. action: noop
  23109. }, pattern);
  23110. });
  23111. };
  23112. var matchesEvent = function (pattern, evt) {
  23113. return evt.keyCode === pattern.keyCode && evt.shiftKey === pattern.shiftKey && evt.altKey === pattern.altKey && evt.ctrlKey === pattern.ctrlKey && evt.metaKey === pattern.metaKey;
  23114. };
  23115. var match$1 = function (patterns, evt) {
  23116. return bind(defaultPatterns(patterns), function (pattern) {
  23117. return matchesEvent(pattern, evt) ? [pattern] : [];
  23118. });
  23119. };
  23120. var action = function (f) {
  23121. var x = [];
  23122. for (var _i = 1; _i < arguments.length; _i++) {
  23123. x[_i - 1] = arguments[_i];
  23124. }
  23125. return function () {
  23126. return f.apply(null, x);
  23127. };
  23128. };
  23129. var execute = function (patterns, evt) {
  23130. return find(match$1(patterns, evt), function (pattern) {
  23131. return pattern.action();
  23132. });
  23133. };
  23134. var moveH$1 = function (editor, forward) {
  23135. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23136. var range = editor.selection.getRng();
  23137. return moveHorizontally(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia).exists(function (newRange) {
  23138. moveToRange(editor, newRange);
  23139. return true;
  23140. });
  23141. };
  23142. var moveV$2 = function (editor, down) {
  23143. var direction = down ? 1 : -1;
  23144. var range = editor.selection.getRng();
  23145. return moveVertically(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia).exists(function (newRange) {
  23146. moveToRange(editor, newRange);
  23147. return true;
  23148. });
  23149. };
  23150. var moveToLineEndPoint$2 = function (editor, forward) {
  23151. var isNearMedia = forward ? isAfterMedia : isBeforeMedia;
  23152. return moveToLineEndPoint(editor, forward, isNearMedia);
  23153. };
  23154. var deflate = function (rect, delta) {
  23155. return {
  23156. left: rect.left - delta,
  23157. top: rect.top - delta,
  23158. right: rect.right + delta * 2,
  23159. bottom: rect.bottom + delta * 2,
  23160. width: rect.width + delta,
  23161. height: rect.height + delta
  23162. };
  23163. };
  23164. var getCorners = function (getYAxisValue, tds) {
  23165. return bind(tds, function (td) {
  23166. var rect = deflate(clone$2(td.getBoundingClientRect()), -1);
  23167. return [
  23168. {
  23169. x: rect.left,
  23170. y: getYAxisValue(rect),
  23171. cell: td
  23172. },
  23173. {
  23174. x: rect.right,
  23175. y: getYAxisValue(rect),
  23176. cell: td
  23177. }
  23178. ];
  23179. });
  23180. };
  23181. var findClosestCorner = function (corners, x, y) {
  23182. return foldl(corners, function (acc, newCorner) {
  23183. return acc.fold(function () {
  23184. return Optional.some(newCorner);
  23185. }, function (oldCorner) {
  23186. var oldDist = Math.sqrt(Math.abs(oldCorner.x - x) + Math.abs(oldCorner.y - y));
  23187. var newDist = Math.sqrt(Math.abs(newCorner.x - x) + Math.abs(newCorner.y - y));
  23188. return Optional.some(newDist < oldDist ? newCorner : oldCorner);
  23189. });
  23190. }, Optional.none());
  23191. };
  23192. var getClosestCell$1 = function (getYAxisValue, isTargetCorner, table, x, y) {
  23193. var cells = descendants$1(SugarElement.fromDom(table), 'td,th,caption').map(function (e) {
  23194. return e.dom;
  23195. });
  23196. var corners = filter(getCorners(getYAxisValue, cells), function (corner) {
  23197. return isTargetCorner(corner, y);
  23198. });
  23199. return findClosestCorner(corners, x, y).map(function (corner) {
  23200. return corner.cell;
  23201. });
  23202. };
  23203. var getBottomValue = function (rect) {
  23204. return rect.bottom;
  23205. };
  23206. var getTopValue = function (rect) {
  23207. return rect.top;
  23208. };
  23209. var isAbove$1 = function (corner, y) {
  23210. return corner.y < y;
  23211. };
  23212. var isBelow$1 = function (corner, y) {
  23213. return corner.y > y;
  23214. };
  23215. var getClosestCellAbove = curry(getClosestCell$1, getBottomValue, isAbove$1);
  23216. var getClosestCellBelow = curry(getClosestCell$1, getTopValue, isBelow$1);
  23217. var findClosestPositionInAboveCell = function (table, pos) {
  23218. return head(pos.getClientRects()).bind(function (rect) {
  23219. return getClosestCellAbove(table, rect.left, rect.top);
  23220. }).bind(function (cell) {
  23221. return findClosestHorizontalPosition(getLastLinePositions(cell), pos);
  23222. });
  23223. };
  23224. var findClosestPositionInBelowCell = function (table, pos) {
  23225. return last(pos.getClientRects()).bind(function (rect) {
  23226. return getClosestCellBelow(table, rect.left, rect.top);
  23227. }).bind(function (cell) {
  23228. return findClosestHorizontalPosition(getFirstLinePositions(cell), pos);
  23229. });
  23230. };
  23231. var hasNextBreak = function (getPositionsUntil, scope, lineInfo) {
  23232. return lineInfo.breakAt.exists(function (breakPos) {
  23233. return getPositionsUntil(scope, breakPos).breakAt.isSome();
  23234. });
  23235. };
  23236. var startsWithWrapBreak = function (lineInfo) {
  23237. return lineInfo.breakType === BreakType.Wrap && lineInfo.positions.length === 0;
  23238. };
  23239. var startsWithBrBreak = function (lineInfo) {
  23240. return lineInfo.breakType === BreakType.Br && lineInfo.positions.length === 1;
  23241. };
  23242. var isAtTableCellLine = function (getPositionsUntil, scope, pos) {
  23243. var lineInfo = getPositionsUntil(scope, pos);
  23244. if (startsWithWrapBreak(lineInfo) || !isBr(pos.getNode()) && startsWithBrBreak(lineInfo)) {
  23245. return !hasNextBreak(getPositionsUntil, scope, lineInfo);
  23246. } else {
  23247. return lineInfo.breakAt.isNone();
  23248. }
  23249. };
  23250. var isAtFirstTableCellLine = curry(isAtTableCellLine, getPositionsUntilPreviousLine);
  23251. var isAtLastTableCellLine = curry(isAtTableCellLine, getPositionsUntilNextLine);
  23252. var isCaretAtStartOrEndOfTable = function (forward, rng, table) {
  23253. var caretPos = CaretPosition$1.fromRangeStart(rng);
  23254. return positionIn(!forward, table).exists(function (pos) {
  23255. return pos.isEqual(caretPos);
  23256. });
  23257. };
  23258. var navigateHorizontally = function (editor, forward, table, _td) {
  23259. var rng = editor.selection.getRng();
  23260. var direction = forward ? 1 : -1;
  23261. if (isFakeCaretTableBrowser() && isCaretAtStartOrEndOfTable(forward, rng, table)) {
  23262. showCaret(direction, editor, table, !forward, false).each(function (newRng) {
  23263. moveToRange(editor, newRng);
  23264. });
  23265. return true;
  23266. }
  23267. return false;
  23268. };
  23269. var getClosestAbovePosition = function (root, table, start) {
  23270. return findClosestPositionInAboveCell(table, start).orThunk(function () {
  23271. return head(start.getClientRects()).bind(function (rect) {
  23272. return findClosestHorizontalPositionFromPoint(getPositionsAbove(root, CaretPosition$1.before(table)), rect.left);
  23273. });
  23274. }).getOr(CaretPosition$1.before(table));
  23275. };
  23276. var getClosestBelowPosition = function (root, table, start) {
  23277. return findClosestPositionInBelowCell(table, start).orThunk(function () {
  23278. return head(start.getClientRects()).bind(function (rect) {
  23279. return findClosestHorizontalPositionFromPoint(getPositionsBelow(root, CaretPosition$1.after(table)), rect.left);
  23280. });
  23281. }).getOr(CaretPosition$1.after(table));
  23282. };
  23283. var getTable = function (previous, pos) {
  23284. var node = pos.getNode(previous);
  23285. return isElement$1(node) && node.nodeName === 'TABLE' ? Optional.some(node) : Optional.none();
  23286. };
  23287. var renderBlock = function (down, editor, table, pos) {
  23288. var forcedRootBlock = getForcedRootBlock(editor);
  23289. if (forcedRootBlock) {
  23290. editor.undoManager.transact(function () {
  23291. var element = SugarElement.fromTag(forcedRootBlock);
  23292. setAll(element, getForcedRootBlockAttrs(editor));
  23293. append(element, SugarElement.fromTag('br'));
  23294. if (down) {
  23295. after(SugarElement.fromDom(table), element);
  23296. } else {
  23297. before(SugarElement.fromDom(table), element);
  23298. }
  23299. var rng = editor.dom.createRng();
  23300. rng.setStart(element.dom, 0);
  23301. rng.setEnd(element.dom, 0);
  23302. moveToRange(editor, rng);
  23303. });
  23304. } else {
  23305. moveToRange(editor, pos.toRange());
  23306. }
  23307. };
  23308. var moveCaret = function (editor, down, pos) {
  23309. var table = down ? getTable(true, pos) : getTable(false, pos);
  23310. var last = down === false;
  23311. table.fold(function () {
  23312. return moveToRange(editor, pos.toRange());
  23313. }, function (table) {
  23314. return positionIn(last, editor.getBody()).filter(function (lastPos) {
  23315. return lastPos.isEqual(pos);
  23316. }).fold(function () {
  23317. return moveToRange(editor, pos.toRange());
  23318. }, function (_) {
  23319. return renderBlock(down, editor, table, pos);
  23320. });
  23321. });
  23322. };
  23323. var navigateVertically = function (editor, down, table, td) {
  23324. var rng = editor.selection.getRng();
  23325. var pos = CaretPosition$1.fromRangeStart(rng);
  23326. var root = editor.getBody();
  23327. if (!down && isAtFirstTableCellLine(td, pos)) {
  23328. var newPos = getClosestAbovePosition(root, table, pos);
  23329. moveCaret(editor, down, newPos);
  23330. return true;
  23331. } else if (down && isAtLastTableCellLine(td, pos)) {
  23332. var newPos = getClosestBelowPosition(root, table, pos);
  23333. moveCaret(editor, down, newPos);
  23334. return true;
  23335. } else {
  23336. return false;
  23337. }
  23338. };
  23339. var move$1 = function (editor, forward, mover) {
  23340. return Optional.from(editor.dom.getParent(editor.selection.getNode(), 'td,th')).bind(function (td) {
  23341. return Optional.from(editor.dom.getParent(td, 'table')).map(function (table) {
  23342. return mover(editor, forward, table, td);
  23343. });
  23344. }).getOr(false);
  23345. };
  23346. var moveH$2 = function (editor, forward) {
  23347. return move$1(editor, forward, navigateHorizontally);
  23348. };
  23349. var moveV$3 = function (editor, forward) {
  23350. return move$1(editor, forward, navigateVertically);
  23351. };
  23352. var executeKeydownOverride = function (editor, caret, evt) {
  23353. var os = detect$3().os;
  23354. execute([
  23355. {
  23356. keyCode: VK.RIGHT,
  23357. action: action(moveH, editor, true)
  23358. },
  23359. {
  23360. keyCode: VK.LEFT,
  23361. action: action(moveH, editor, false)
  23362. },
  23363. {
  23364. keyCode: VK.UP,
  23365. action: action(moveV, editor, false)
  23366. },
  23367. {
  23368. keyCode: VK.DOWN,
  23369. action: action(moveV, editor, true)
  23370. },
  23371. {
  23372. keyCode: VK.RIGHT,
  23373. action: action(moveH$2, editor, true)
  23374. },
  23375. {
  23376. keyCode: VK.LEFT,
  23377. action: action(moveH$2, editor, false)
  23378. },
  23379. {
  23380. keyCode: VK.UP,
  23381. action: action(moveV$3, editor, false)
  23382. },
  23383. {
  23384. keyCode: VK.DOWN,
  23385. action: action(moveV$3, editor, true)
  23386. },
  23387. {
  23388. keyCode: VK.RIGHT,
  23389. action: action(moveH$1, editor, true)
  23390. },
  23391. {
  23392. keyCode: VK.LEFT,
  23393. action: action(moveH$1, editor, false)
  23394. },
  23395. {
  23396. keyCode: VK.UP,
  23397. action: action(moveV$2, editor, false)
  23398. },
  23399. {
  23400. keyCode: VK.DOWN,
  23401. action: action(moveV$2, editor, true)
  23402. },
  23403. {
  23404. keyCode: VK.RIGHT,
  23405. action: action(move, editor, caret, true)
  23406. },
  23407. {
  23408. keyCode: VK.LEFT,
  23409. action: action(move, editor, caret, false)
  23410. },
  23411. {
  23412. keyCode: VK.RIGHT,
  23413. ctrlKey: !os.isOSX(),
  23414. altKey: os.isOSX(),
  23415. action: action(moveNextWord, editor, caret)
  23416. },
  23417. {
  23418. keyCode: VK.LEFT,
  23419. ctrlKey: !os.isOSX(),
  23420. altKey: os.isOSX(),
  23421. action: action(movePrevWord, editor, caret)
  23422. },
  23423. {
  23424. keyCode: VK.UP,
  23425. action: action(moveV$1, editor, false)
  23426. },
  23427. {
  23428. keyCode: VK.DOWN,
  23429. action: action(moveV$1, editor, true)
  23430. }
  23431. ], evt).each(function (_) {
  23432. evt.preventDefault();
  23433. });
  23434. };
  23435. var setup$c = function (editor, caret) {
  23436. editor.on('keydown', function (evt) {
  23437. if (evt.isDefaultPrevented() === false) {
  23438. executeKeydownOverride(editor, caret, evt);
  23439. }
  23440. });
  23441. };
  23442. var executeKeydownOverride$1 = function (editor, caret, evt) {
  23443. execute([
  23444. {
  23445. keyCode: VK.BACKSPACE,
  23446. action: action(backspaceDelete$9, editor, false)
  23447. },
  23448. {
  23449. keyCode: VK.BACKSPACE,
  23450. action: action(backspaceDelete$4, editor, false)
  23451. },
  23452. {
  23453. keyCode: VK.DELETE,
  23454. action: action(backspaceDelete$4, editor, true)
  23455. },
  23456. {
  23457. keyCode: VK.BACKSPACE,
  23458. action: action(backspaceDelete$3, editor, false)
  23459. },
  23460. {
  23461. keyCode: VK.DELETE,
  23462. action: action(backspaceDelete$3, editor, true)
  23463. },
  23464. {
  23465. keyCode: VK.BACKSPACE,
  23466. action: action(backspaceDelete$6, editor, caret, false)
  23467. },
  23468. {
  23469. keyCode: VK.DELETE,
  23470. action: action(backspaceDelete$6, editor, caret, true)
  23471. },
  23472. {
  23473. keyCode: VK.BACKSPACE,
  23474. action: action(backspaceDelete, editor, false)
  23475. },
  23476. {
  23477. keyCode: VK.DELETE,
  23478. action: action(backspaceDelete, editor, true)
  23479. },
  23480. {
  23481. keyCode: VK.BACKSPACE,
  23482. action: action(backspaceDelete$5, editor, false)
  23483. },
  23484. {
  23485. keyCode: VK.DELETE,
  23486. action: action(backspaceDelete$5, editor, true)
  23487. },
  23488. {
  23489. keyCode: VK.BACKSPACE,
  23490. action: action(backspaceDelete$8, editor, false)
  23491. },
  23492. {
  23493. keyCode: VK.DELETE,
  23494. action: action(backspaceDelete$8, editor, true)
  23495. },
  23496. {
  23497. keyCode: VK.BACKSPACE,
  23498. action: action(backspaceDelete$2, editor, false)
  23499. },
  23500. {
  23501. keyCode: VK.DELETE,
  23502. action: action(backspaceDelete$2, editor, true)
  23503. },
  23504. {
  23505. keyCode: VK.BACKSPACE,
  23506. action: action(backspaceDelete$1, editor, false)
  23507. },
  23508. {
  23509. keyCode: VK.DELETE,
  23510. action: action(backspaceDelete$1, editor, true)
  23511. },
  23512. {
  23513. keyCode: VK.BACKSPACE,
  23514. action: action(backspaceDelete$7, editor, false)
  23515. },
  23516. {
  23517. keyCode: VK.DELETE,
  23518. action: action(backspaceDelete$7, editor, true)
  23519. }
  23520. ], evt).each(function (_) {
  23521. evt.preventDefault();
  23522. });
  23523. };
  23524. var executeKeyupOverride = function (editor, evt) {
  23525. execute([
  23526. {
  23527. keyCode: VK.BACKSPACE,
  23528. action: action(paddEmptyElement, editor)
  23529. },
  23530. {
  23531. keyCode: VK.DELETE,
  23532. action: action(paddEmptyElement, editor)
  23533. }
  23534. ], evt);
  23535. };
  23536. var setup$d = function (editor, caret) {
  23537. editor.on('keydown', function (evt) {
  23538. if (evt.isDefaultPrevented() === false) {
  23539. executeKeydownOverride$1(editor, caret, evt);
  23540. }
  23541. });
  23542. editor.on('keyup', function (evt) {
  23543. if (evt.isDefaultPrevented() === false) {
  23544. executeKeyupOverride(editor, evt);
  23545. }
  23546. });
  23547. };
  23548. var firstNonWhiteSpaceNodeSibling = function (node) {
  23549. while (node) {
  23550. if (node.nodeType === 1 || node.nodeType === 3 && node.data && /[\r\n\s]/.test(node.data)) {
  23551. return node;
  23552. }
  23553. node = node.nextSibling;
  23554. }
  23555. };
  23556. var moveToCaretPosition = function (editor, root) {
  23557. var node, lastNode = root;
  23558. var dom = editor.dom;
  23559. var moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
  23560. if (!root) {
  23561. return;
  23562. }
  23563. if (/^(LI|DT|DD)$/.test(root.nodeName)) {
  23564. var firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild);
  23565. if (firstChild && /^(UL|OL|DL)$/.test(firstChild.nodeName)) {
  23566. root.insertBefore(dom.doc.createTextNode(nbsp), root.firstChild);
  23567. }
  23568. }
  23569. var rng = dom.createRng();
  23570. root.normalize();
  23571. if (root.hasChildNodes()) {
  23572. var walker = new DomTreeWalker(root, root);
  23573. while (node = walker.current()) {
  23574. if (isText$1(node)) {
  23575. rng.setStart(node, 0);
  23576. rng.setEnd(node, 0);
  23577. break;
  23578. }
  23579. if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) {
  23580. rng.setStartBefore(node);
  23581. rng.setEndBefore(node);
  23582. break;
  23583. }
  23584. lastNode = node;
  23585. node = walker.next();
  23586. }
  23587. if (!node) {
  23588. rng.setStart(lastNode, 0);
  23589. rng.setEnd(lastNode, 0);
  23590. }
  23591. } else {
  23592. if (isBr(root)) {
  23593. if (root.nextSibling && dom.isBlock(root.nextSibling)) {
  23594. rng.setStartBefore(root);
  23595. rng.setEndBefore(root);
  23596. } else {
  23597. rng.setStartAfter(root);
  23598. rng.setEndAfter(root);
  23599. }
  23600. } else {
  23601. rng.setStart(root, 0);
  23602. rng.setEnd(root, 0);
  23603. }
  23604. }
  23605. editor.selection.setRng(rng);
  23606. scrollRangeIntoView(editor, rng);
  23607. };
  23608. var getEditableRoot = function (dom, node) {
  23609. var root = dom.getRoot();
  23610. var parent, editableRoot;
  23611. parent = node;
  23612. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  23613. if (dom.getContentEditable(parent) === 'true') {
  23614. editableRoot = parent;
  23615. }
  23616. parent = parent.parentNode;
  23617. }
  23618. return parent !== root ? editableRoot : root;
  23619. };
  23620. var getParentBlock$2 = function (editor) {
  23621. return Optional.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
  23622. };
  23623. var getParentBlockName = function (editor) {
  23624. return getParentBlock$2(editor).fold(constant(''), function (parentBlock) {
  23625. return parentBlock.nodeName.toUpperCase();
  23626. });
  23627. };
  23628. var isListItemParentBlock = function (editor) {
  23629. return getParentBlock$2(editor).filter(function (elm) {
  23630. return isListItem(SugarElement.fromDom(elm));
  23631. }).isSome();
  23632. };
  23633. var hasFirstChild = function (elm, name) {
  23634. return elm.firstChild && elm.firstChild.nodeName === name;
  23635. };
  23636. var hasParent$1 = function (elm, parentName) {
  23637. return elm && elm.parentNode && elm.parentNode.nodeName === parentName;
  23638. };
  23639. var isListBlock = function (elm) {
  23640. return elm && /^(OL|UL|LI)$/.test(elm.nodeName);
  23641. };
  23642. var isNestedList = function (elm) {
  23643. return isListBlock(elm) && isListBlock(elm.parentNode);
  23644. };
  23645. var getContainerBlock = function (containerBlock) {
  23646. var containerBlockParent = containerBlock.parentNode;
  23647. if (/^(LI|DT|DD)$/.test(containerBlockParent.nodeName)) {
  23648. return containerBlockParent;
  23649. }
  23650. return containerBlock;
  23651. };
  23652. var isFirstOrLastLi = function (containerBlock, parentBlock, first) {
  23653. var node = containerBlock[first ? 'firstChild' : 'lastChild'];
  23654. while (node) {
  23655. if (isElement$1(node)) {
  23656. break;
  23657. }
  23658. node = node[first ? 'nextSibling' : 'previousSibling'];
  23659. }
  23660. return node === parentBlock;
  23661. };
  23662. var insert = function (editor, createNewBlock, containerBlock, parentBlock, newBlockName) {
  23663. var dom = editor.dom;
  23664. var rng = editor.selection.getRng();
  23665. if (containerBlock === editor.getBody()) {
  23666. return;
  23667. }
  23668. if (isNestedList(containerBlock)) {
  23669. newBlockName = 'LI';
  23670. }
  23671. var newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR');
  23672. if (isFirstOrLastLi(containerBlock, parentBlock, true) && isFirstOrLastLi(containerBlock, parentBlock, false)) {
  23673. if (hasParent$1(containerBlock, 'LI')) {
  23674. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  23675. } else {
  23676. dom.replace(newBlock, containerBlock);
  23677. }
  23678. } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
  23679. if (hasParent$1(containerBlock, 'LI')) {
  23680. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  23681. newBlock.appendChild(dom.doc.createTextNode(' '));
  23682. newBlock.appendChild(containerBlock);
  23683. } else {
  23684. containerBlock.parentNode.insertBefore(newBlock, containerBlock);
  23685. }
  23686. } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
  23687. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  23688. } else {
  23689. containerBlock = getContainerBlock(containerBlock);
  23690. var tmpRng = rng.cloneRange();
  23691. tmpRng.setStartAfter(parentBlock);
  23692. tmpRng.setEndAfter(containerBlock);
  23693. var fragment = tmpRng.extractContents();
  23694. if (newBlockName === 'LI' && hasFirstChild(fragment, 'LI')) {
  23695. newBlock = fragment.firstChild;
  23696. dom.insertAfter(fragment, containerBlock);
  23697. } else {
  23698. dom.insertAfter(fragment, containerBlock);
  23699. dom.insertAfter(newBlock, containerBlock);
  23700. }
  23701. }
  23702. dom.remove(parentBlock);
  23703. moveToCaretPosition(editor, newBlock);
  23704. };
  23705. var trimZwsp = function (fragment) {
  23706. each(descendants(SugarElement.fromDom(fragment), isText), function (text) {
  23707. var rawNode = text.dom;
  23708. rawNode.nodeValue = trim$2(rawNode.nodeValue);
  23709. });
  23710. };
  23711. var isEmptyAnchor = function (dom, elm) {
  23712. return elm && elm.nodeName === 'A' && dom.isEmpty(elm);
  23713. };
  23714. var isTableCell$5 = function (node) {
  23715. return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  23716. };
  23717. var emptyBlock = function (elm) {
  23718. elm.innerHTML = '<br data-mce-bogus="1">';
  23719. };
  23720. var containerAndSiblingName = function (container, nodeName) {
  23721. return container.nodeName === nodeName || container.previousSibling && container.previousSibling.nodeName === nodeName;
  23722. };
  23723. var canSplitBlock = function (dom, node) {
  23724. return node && dom.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.getContentEditable(node) !== 'true';
  23725. };
  23726. var trimInlineElementsOnLeftSideOfBlock = function (dom, nonEmptyElementsMap, block) {
  23727. var node = block;
  23728. var firstChilds = [];
  23729. var i;
  23730. if (!node) {
  23731. return;
  23732. }
  23733. while (node = node.firstChild) {
  23734. if (dom.isBlock(node)) {
  23735. return;
  23736. }
  23737. if (isElement$1(node) && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  23738. firstChilds.push(node);
  23739. }
  23740. }
  23741. i = firstChilds.length;
  23742. while (i--) {
  23743. node = firstChilds[i];
  23744. if (!node.hasChildNodes() || node.firstChild === node.lastChild && node.firstChild.nodeValue === '') {
  23745. dom.remove(node);
  23746. } else {
  23747. if (isEmptyAnchor(dom, node)) {
  23748. dom.remove(node);
  23749. }
  23750. }
  23751. }
  23752. };
  23753. var normalizeZwspOffset = function (start, container, offset) {
  23754. if (isText$1(container) === false) {
  23755. return offset;
  23756. } else if (start) {
  23757. return offset === 1 && container.data.charAt(offset - 1) === ZWSP ? 0 : offset;
  23758. } else {
  23759. return offset === container.data.length - 1 && container.data.charAt(offset) === ZWSP ? container.data.length : offset;
  23760. }
  23761. };
  23762. var includeZwspInRange = function (rng) {
  23763. var newRng = rng.cloneRange();
  23764. newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
  23765. newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
  23766. return newRng;
  23767. };
  23768. var trimLeadingLineBreaks = function (node) {
  23769. do {
  23770. if (isText$1(node)) {
  23771. node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
  23772. }
  23773. node = node.firstChild;
  23774. } while (node);
  23775. };
  23776. var getEditableRoot$1 = function (dom, node) {
  23777. var root = dom.getRoot();
  23778. var parent, editableRoot;
  23779. parent = node;
  23780. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  23781. if (dom.getContentEditable(parent) === 'true') {
  23782. editableRoot = parent;
  23783. }
  23784. parent = parent.parentNode;
  23785. }
  23786. return parent !== root ? editableRoot : root;
  23787. };
  23788. var applyAttributes = function (editor, node, forcedRootBlockAttrs) {
  23789. var dom = editor.dom;
  23790. Optional.from(forcedRootBlockAttrs.style).map(dom.parseStyle).each(function (attrStyles) {
  23791. var currentStyles = getAllRaw(SugarElement.fromDom(node));
  23792. var newStyles = __assign(__assign({}, currentStyles), attrStyles);
  23793. dom.setStyles(node, newStyles);
  23794. });
  23795. var attrClassesOpt = Optional.from(forcedRootBlockAttrs.class).map(function (attrClasses) {
  23796. return attrClasses.split(/\s+/);
  23797. });
  23798. var currentClassesOpt = Optional.from(node.className).map(function (currentClasses) {
  23799. return filter(currentClasses.split(/\s+/), function (clazz) {
  23800. return clazz !== '';
  23801. });
  23802. });
  23803. lift2(attrClassesOpt, currentClassesOpt, function (attrClasses, currentClasses) {
  23804. var filteredClasses = filter(currentClasses, function (clazz) {
  23805. return !contains(attrClasses, clazz);
  23806. });
  23807. var newClasses = __spreadArrays(attrClasses, filteredClasses);
  23808. dom.setAttrib(node, 'class', newClasses.join(' '));
  23809. });
  23810. var appliedAttrs = [
  23811. 'style',
  23812. 'class'
  23813. ];
  23814. var remainingAttrs = filter$1(forcedRootBlockAttrs, function (_, attrs) {
  23815. return !contains(appliedAttrs, attrs);
  23816. });
  23817. dom.setAttribs(node, remainingAttrs);
  23818. };
  23819. var setForcedBlockAttrs = function (editor, node) {
  23820. var forcedRootBlockName = getForcedRootBlock(editor);
  23821. if (forcedRootBlockName && forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
  23822. var forcedRootBlockAttrs = getForcedRootBlockAttrs(editor);
  23823. applyAttributes(editor, node, forcedRootBlockAttrs);
  23824. }
  23825. };
  23826. var wrapSelfAndSiblingsInDefaultBlock = function (editor, newBlockName, rng, container, offset) {
  23827. var newBlock, parentBlock, startNode, node, next, rootBlockName;
  23828. var blockName = newBlockName || 'P';
  23829. var dom = editor.dom, editableRoot = getEditableRoot$1(dom, container);
  23830. parentBlock = dom.getParent(container, dom.isBlock);
  23831. if (!parentBlock || !canSplitBlock(dom, parentBlock)) {
  23832. parentBlock = parentBlock || editableRoot;
  23833. if (parentBlock === editor.getBody() || isTableCell$5(parentBlock)) {
  23834. rootBlockName = parentBlock.nodeName.toLowerCase();
  23835. } else {
  23836. rootBlockName = parentBlock.parentNode.nodeName.toLowerCase();
  23837. }
  23838. if (!parentBlock.hasChildNodes()) {
  23839. newBlock = dom.create(blockName);
  23840. setForcedBlockAttrs(editor, newBlock);
  23841. parentBlock.appendChild(newBlock);
  23842. rng.setStart(newBlock, 0);
  23843. rng.setEnd(newBlock, 0);
  23844. return newBlock;
  23845. }
  23846. node = container;
  23847. while (node.parentNode !== parentBlock) {
  23848. node = node.parentNode;
  23849. }
  23850. while (node && !dom.isBlock(node)) {
  23851. startNode = node;
  23852. node = node.previousSibling;
  23853. }
  23854. if (startNode && editor.schema.isValidChild(rootBlockName, blockName.toLowerCase())) {
  23855. newBlock = dom.create(blockName);
  23856. setForcedBlockAttrs(editor, newBlock);
  23857. startNode.parentNode.insertBefore(newBlock, startNode);
  23858. node = startNode;
  23859. while (node && !dom.isBlock(node)) {
  23860. next = node.nextSibling;
  23861. newBlock.appendChild(node);
  23862. node = next;
  23863. }
  23864. rng.setStart(container, offset);
  23865. rng.setEnd(container, offset);
  23866. }
  23867. }
  23868. return container;
  23869. };
  23870. var addBrToBlockIfNeeded = function (dom, block) {
  23871. block.normalize();
  23872. var lastChild = block.lastChild;
  23873. if (!lastChild || /^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true))) {
  23874. dom.add(block, 'br');
  23875. }
  23876. };
  23877. var insert$1 = function (editor, evt) {
  23878. var tmpRng, container, offset, parentBlock;
  23879. var newBlock, fragment, containerBlock, parentBlockName, newBlockName, isAfterLastNodeInContainer;
  23880. var dom = editor.dom;
  23881. var schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
  23882. var rng = editor.selection.getRng();
  23883. var createNewBlock = function (name) {
  23884. var node = container, block, clonedNode, caretNode;
  23885. var textInlineElements = schema.getTextInlineElements();
  23886. if (name || parentBlockName === 'TABLE' || parentBlockName === 'HR') {
  23887. block = dom.create(name || newBlockName);
  23888. } else {
  23889. block = parentBlock.cloneNode(false);
  23890. }
  23891. caretNode = block;
  23892. if (shouldKeepStyles(editor) === false) {
  23893. dom.setAttrib(block, 'style', null);
  23894. dom.setAttrib(block, 'class', null);
  23895. } else {
  23896. do {
  23897. if (textInlineElements[node.nodeName]) {
  23898. if (isCaretNode(node) || isBookmarkNode$1(node)) {
  23899. continue;
  23900. }
  23901. clonedNode = node.cloneNode(false);
  23902. dom.setAttrib(clonedNode, 'id', '');
  23903. if (block.hasChildNodes()) {
  23904. clonedNode.appendChild(block.firstChild);
  23905. block.appendChild(clonedNode);
  23906. } else {
  23907. caretNode = clonedNode;
  23908. block.appendChild(clonedNode);
  23909. }
  23910. }
  23911. } while ((node = node.parentNode) && node !== editableRoot);
  23912. }
  23913. setForcedBlockAttrs(editor, block);
  23914. emptyBlock(caretNode);
  23915. return block;
  23916. };
  23917. var isCaretAtStartOrEndOfBlock = function (start) {
  23918. var node, name;
  23919. var normalizedOffset = normalizeZwspOffset(start, container, offset);
  23920. if (isText$1(container) && (start ? normalizedOffset > 0 : normalizedOffset < container.nodeValue.length)) {
  23921. return false;
  23922. }
  23923. if (container.parentNode === parentBlock && isAfterLastNodeInContainer && !start) {
  23924. return true;
  23925. }
  23926. if (start && isElement$1(container) && container === parentBlock.firstChild) {
  23927. return true;
  23928. }
  23929. if (containerAndSiblingName(container, 'TABLE') || containerAndSiblingName(container, 'HR')) {
  23930. return isAfterLastNodeInContainer && !start || !isAfterLastNodeInContainer && start;
  23931. }
  23932. var walker = new DomTreeWalker(container, parentBlock);
  23933. if (isText$1(container)) {
  23934. if (start && normalizedOffset === 0) {
  23935. walker.prev();
  23936. } else if (!start && normalizedOffset === container.nodeValue.length) {
  23937. walker.next();
  23938. }
  23939. }
  23940. while (node = walker.current()) {
  23941. if (isElement$1(node)) {
  23942. if (!node.getAttribute('data-mce-bogus')) {
  23943. name = node.nodeName.toLowerCase();
  23944. if (nonEmptyElementsMap[name] && name !== 'br') {
  23945. return false;
  23946. }
  23947. }
  23948. } else if (isText$1(node) && !isWhitespaceText(node.nodeValue)) {
  23949. return false;
  23950. }
  23951. if (start) {
  23952. walker.prev();
  23953. } else {
  23954. walker.next();
  23955. }
  23956. }
  23957. return true;
  23958. };
  23959. var insertNewBlockAfter = function () {
  23960. if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName !== 'HGROUP') {
  23961. newBlock = createNewBlock(newBlockName);
  23962. } else {
  23963. newBlock = createNewBlock();
  23964. }
  23965. if (shouldEndContainerOnEmptyBlock(editor) && canSplitBlock(dom, containerBlock) && dom.isEmpty(parentBlock)) {
  23966. newBlock = dom.split(containerBlock, parentBlock);
  23967. } else {
  23968. dom.insertAfter(newBlock, parentBlock);
  23969. }
  23970. moveToCaretPosition(editor, newBlock);
  23971. };
  23972. normalize(dom, rng).each(function (normRng) {
  23973. rng.setStart(normRng.startContainer, normRng.startOffset);
  23974. rng.setEnd(normRng.endContainer, normRng.endOffset);
  23975. });
  23976. container = rng.startContainer;
  23977. offset = rng.startOffset;
  23978. newBlockName = getForcedRootBlock(editor);
  23979. var shiftKey = !!(evt && evt.shiftKey);
  23980. var ctrlKey = !!(evt && evt.ctrlKey);
  23981. if (isElement$1(container) && container.hasChildNodes()) {
  23982. isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  23983. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  23984. if (isAfterLastNodeInContainer && isText$1(container)) {
  23985. offset = container.nodeValue.length;
  23986. } else {
  23987. offset = 0;
  23988. }
  23989. }
  23990. var editableRoot = getEditableRoot$1(dom, container);
  23991. if (!editableRoot) {
  23992. return;
  23993. }
  23994. if (newBlockName && !shiftKey || !newBlockName && shiftKey) {
  23995. container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset);
  23996. }
  23997. parentBlock = dom.getParent(container, dom.isBlock);
  23998. containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  23999. parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : '';
  24000. var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  24001. if (containerBlockName === 'LI' && !ctrlKey) {
  24002. parentBlock = containerBlock;
  24003. containerBlock = containerBlock.parentNode;
  24004. parentBlockName = containerBlockName;
  24005. }
  24006. if (/^(LI|DT|DD)$/.test(parentBlockName)) {
  24007. if (dom.isEmpty(parentBlock)) {
  24008. insert(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
  24009. return;
  24010. }
  24011. }
  24012. if (newBlockName && parentBlock === editor.getBody()) {
  24013. return;
  24014. }
  24015. newBlockName = newBlockName || 'P';
  24016. if (isCaretContainerBlock(parentBlock)) {
  24017. newBlock = showCaretContainerBlock(parentBlock);
  24018. if (dom.isEmpty(parentBlock)) {
  24019. emptyBlock(parentBlock);
  24020. }
  24021. setForcedBlockAttrs(editor, newBlock);
  24022. moveToCaretPosition(editor, newBlock);
  24023. } else if (isCaretAtStartOrEndOfBlock()) {
  24024. insertNewBlockAfter();
  24025. } else if (isCaretAtStartOrEndOfBlock(true)) {
  24026. newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
  24027. moveToCaretPosition(editor, containerAndSiblingName(parentBlock, 'HR') ? newBlock : parentBlock);
  24028. } else {
  24029. tmpRng = includeZwspInRange(rng).cloneRange();
  24030. tmpRng.setEndAfter(parentBlock);
  24031. fragment = tmpRng.extractContents();
  24032. trimZwsp(fragment);
  24033. trimLeadingLineBreaks(fragment);
  24034. newBlock = fragment.firstChild;
  24035. dom.insertAfter(fragment, parentBlock);
  24036. trimInlineElementsOnLeftSideOfBlock(dom, nonEmptyElementsMap, newBlock);
  24037. addBrToBlockIfNeeded(dom, parentBlock);
  24038. if (dom.isEmpty(parentBlock)) {
  24039. emptyBlock(parentBlock);
  24040. }
  24041. newBlock.normalize();
  24042. if (dom.isEmpty(newBlock)) {
  24043. dom.remove(newBlock);
  24044. insertNewBlockAfter();
  24045. } else {
  24046. setForcedBlockAttrs(editor, newBlock);
  24047. moveToCaretPosition(editor, newBlock);
  24048. }
  24049. }
  24050. dom.setAttrib(newBlock, 'id', '');
  24051. editor.fire('NewBlock', { newBlock: newBlock });
  24052. };
  24053. var hasRightSideContent = function (schema, container, parentBlock) {
  24054. var walker = new DomTreeWalker(container, parentBlock);
  24055. var node;
  24056. var nonEmptyElementsMap = schema.getNonEmptyElements();
  24057. while (node = walker.next()) {
  24058. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
  24059. return true;
  24060. }
  24061. }
  24062. };
  24063. var scrollToBr = function (dom, selection, brElm) {
  24064. var marker = dom.create('span', {}, '&nbsp;');
  24065. brElm.parentNode.insertBefore(marker, brElm);
  24066. selection.scrollIntoView(marker);
  24067. dom.remove(marker);
  24068. };
  24069. var moveSelectionToBr = function (dom, selection, brElm, extraBr) {
  24070. var rng = dom.createRng();
  24071. if (!extraBr) {
  24072. rng.setStartAfter(brElm);
  24073. rng.setEndAfter(brElm);
  24074. } else {
  24075. rng.setStartBefore(brElm);
  24076. rng.setEndBefore(brElm);
  24077. }
  24078. selection.setRng(rng);
  24079. };
  24080. var insertBrAtCaret = function (editor, evt) {
  24081. var selection = editor.selection;
  24082. var dom = editor.dom;
  24083. var rng = selection.getRng();
  24084. var brElm;
  24085. var extraBr;
  24086. normalize(dom, rng).each(function (normRng) {
  24087. rng.setStart(normRng.startContainer, normRng.startOffset);
  24088. rng.setEnd(normRng.endContainer, normRng.endOffset);
  24089. });
  24090. var offset = rng.startOffset;
  24091. var container = rng.startContainer;
  24092. if (container.nodeType === 1 && container.hasChildNodes()) {
  24093. var isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  24094. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  24095. if (isAfterLastNodeInContainer && container.nodeType === 3) {
  24096. offset = container.nodeValue.length;
  24097. } else {
  24098. offset = 0;
  24099. }
  24100. }
  24101. var parentBlock = dom.getParent(container, dom.isBlock);
  24102. var containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  24103. var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  24104. var isControlKey = !!(evt && evt.ctrlKey);
  24105. if (containerBlockName === 'LI' && !isControlKey) {
  24106. parentBlock = containerBlock;
  24107. }
  24108. if (container && container.nodeType === 3 && offset >= container.nodeValue.length) {
  24109. if (!hasRightSideContent(editor.schema, container, parentBlock)) {
  24110. brElm = dom.create('br');
  24111. rng.insertNode(brElm);
  24112. rng.setStartAfter(brElm);
  24113. rng.setEndAfter(brElm);
  24114. extraBr = true;
  24115. }
  24116. }
  24117. brElm = dom.create('br');
  24118. rangeInsertNode(dom, rng, brElm);
  24119. scrollToBr(dom, selection, brElm);
  24120. moveSelectionToBr(dom, selection, brElm, extraBr);
  24121. editor.undoManager.add();
  24122. };
  24123. var insertBrBefore = function (editor, inline) {
  24124. var br = SugarElement.fromTag('br');
  24125. before(SugarElement.fromDom(inline), br);
  24126. editor.undoManager.add();
  24127. };
  24128. var insertBrAfter = function (editor, inline) {
  24129. if (!hasBrAfter(editor.getBody(), inline)) {
  24130. after(SugarElement.fromDom(inline), SugarElement.fromTag('br'));
  24131. }
  24132. var br = SugarElement.fromTag('br');
  24133. after(SugarElement.fromDom(inline), br);
  24134. scrollToBr(editor.dom, editor.selection, br.dom);
  24135. moveSelectionToBr(editor.dom, editor.selection, br.dom, false);
  24136. editor.undoManager.add();
  24137. };
  24138. var isBeforeBr$1 = function (pos) {
  24139. return isBr(pos.getNode());
  24140. };
  24141. var hasBrAfter = function (rootNode, startNode) {
  24142. if (isBeforeBr$1(CaretPosition$1.after(startNode))) {
  24143. return true;
  24144. } else {
  24145. return nextPosition(rootNode, CaretPosition$1.after(startNode)).map(function (pos) {
  24146. return isBr(pos.getNode());
  24147. }).getOr(false);
  24148. }
  24149. };
  24150. var isAnchorLink = function (elm) {
  24151. return elm && elm.nodeName === 'A' && 'href' in elm;
  24152. };
  24153. var isInsideAnchor = function (location) {
  24154. return location.fold(never, isAnchorLink, isAnchorLink, never);
  24155. };
  24156. var readInlineAnchorLocation = function (editor) {
  24157. var isInlineTarget$1 = curry(isInlineTarget, editor);
  24158. var position = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  24159. return readLocation(isInlineTarget$1, editor.getBody(), position).filter(isInsideAnchor);
  24160. };
  24161. var insertBrOutsideAnchor = function (editor, location) {
  24162. location.fold(noop, curry(insertBrBefore, editor), curry(insertBrAfter, editor), noop);
  24163. };
  24164. var insert$2 = function (editor, evt) {
  24165. var anchorLocation = readInlineAnchorLocation(editor);
  24166. if (anchorLocation.isSome()) {
  24167. anchorLocation.each(curry(insertBrOutsideAnchor, editor));
  24168. } else {
  24169. insertBrAtCaret(editor, evt);
  24170. }
  24171. };
  24172. var matchesSelector = function (editor, selector) {
  24173. return getParentBlock$2(editor).filter(function (parentBlock) {
  24174. return selector.length > 0 && is$1(SugarElement.fromDom(parentBlock), selector);
  24175. }).isSome();
  24176. };
  24177. var shouldInsertBr = function (editor) {
  24178. return matchesSelector(editor, getBrNewLineSelector(editor));
  24179. };
  24180. var shouldBlockNewLine = function (editor) {
  24181. return matchesSelector(editor, getNoNewLineSelector(editor));
  24182. };
  24183. var newLineAction = Adt.generate([
  24184. { br: [] },
  24185. { block: [] },
  24186. { none: [] }
  24187. ]);
  24188. var shouldBlockNewLine$1 = function (editor, _shiftKey) {
  24189. return shouldBlockNewLine(editor);
  24190. };
  24191. var isBrMode = function (requiredState) {
  24192. return function (editor, _shiftKey) {
  24193. var brMode = getForcedRootBlock(editor) === '';
  24194. return brMode === requiredState;
  24195. };
  24196. };
  24197. var inListBlock = function (requiredState) {
  24198. return function (editor, _shiftKey) {
  24199. return isListItemParentBlock(editor) === requiredState;
  24200. };
  24201. };
  24202. var inBlock = function (blockName, requiredState) {
  24203. return function (editor, _shiftKey) {
  24204. var state = getParentBlockName(editor) === blockName.toUpperCase();
  24205. return state === requiredState;
  24206. };
  24207. };
  24208. var inPreBlock = function (requiredState) {
  24209. return inBlock('pre', requiredState);
  24210. };
  24211. var inSummaryBlock = function () {
  24212. return inBlock('summary', true);
  24213. };
  24214. var shouldPutBrInPre$1 = function (requiredState) {
  24215. return function (editor, _shiftKey) {
  24216. return shouldPutBrInPre(editor) === requiredState;
  24217. };
  24218. };
  24219. var inBrContext = function (editor, _shiftKey) {
  24220. return shouldInsertBr(editor);
  24221. };
  24222. var hasShiftKey = function (_editor, shiftKey) {
  24223. return shiftKey;
  24224. };
  24225. var canInsertIntoEditableRoot = function (editor) {
  24226. var forcedRootBlock = getForcedRootBlock(editor);
  24227. var rootEditable = getEditableRoot(editor.dom, editor.selection.getStart());
  24228. return rootEditable && editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock ? forcedRootBlock : 'P');
  24229. };
  24230. var match$2 = function (predicates, action) {
  24231. return function (editor, shiftKey) {
  24232. var isMatch = foldl(predicates, function (res, p) {
  24233. return res && p(editor, shiftKey);
  24234. }, true);
  24235. return isMatch ? Optional.some(action) : Optional.none();
  24236. };
  24237. };
  24238. var getAction$1 = function (editor, evt) {
  24239. return evaluateUntil([
  24240. match$2([shouldBlockNewLine$1], newLineAction.none()),
  24241. match$2([inSummaryBlock()], newLineAction.br()),
  24242. match$2([
  24243. inPreBlock(true),
  24244. shouldPutBrInPre$1(false),
  24245. hasShiftKey
  24246. ], newLineAction.br()),
  24247. match$2([
  24248. inPreBlock(true),
  24249. shouldPutBrInPre$1(false)
  24250. ], newLineAction.block()),
  24251. match$2([
  24252. inPreBlock(true),
  24253. shouldPutBrInPre$1(true),
  24254. hasShiftKey
  24255. ], newLineAction.block()),
  24256. match$2([
  24257. inPreBlock(true),
  24258. shouldPutBrInPre$1(true)
  24259. ], newLineAction.br()),
  24260. match$2([
  24261. inListBlock(true),
  24262. hasShiftKey
  24263. ], newLineAction.br()),
  24264. match$2([inListBlock(true)], newLineAction.block()),
  24265. match$2([
  24266. isBrMode(true),
  24267. hasShiftKey,
  24268. canInsertIntoEditableRoot
  24269. ], newLineAction.block()),
  24270. match$2([isBrMode(true)], newLineAction.br()),
  24271. match$2([inBrContext], newLineAction.br()),
  24272. match$2([
  24273. isBrMode(false),
  24274. hasShiftKey
  24275. ], newLineAction.br()),
  24276. match$2([canInsertIntoEditableRoot], newLineAction.block())
  24277. ], [
  24278. editor,
  24279. !!(evt && evt.shiftKey)
  24280. ]).getOr(newLineAction.none());
  24281. };
  24282. var insert$3 = function (editor, evt) {
  24283. getAction$1(editor, evt).fold(function () {
  24284. insert$2(editor, evt);
  24285. }, function () {
  24286. insert$1(editor, evt);
  24287. }, noop);
  24288. };
  24289. var handleEnterKeyEvent = function (editor, event) {
  24290. if (event.isDefaultPrevented()) {
  24291. return;
  24292. }
  24293. event.preventDefault();
  24294. endTypingLevelIgnoreLocks(editor.undoManager);
  24295. editor.undoManager.transact(function () {
  24296. if (editor.selection.isCollapsed() === false) {
  24297. editor.execCommand('Delete');
  24298. }
  24299. insert$3(editor, event);
  24300. });
  24301. };
  24302. var setup$e = function (editor) {
  24303. editor.on('keydown', function (event) {
  24304. if (event.keyCode === VK.ENTER) {
  24305. handleEnterKeyEvent(editor, event);
  24306. }
  24307. });
  24308. };
  24309. var executeKeydownOverride$2 = function (editor, evt) {
  24310. execute([
  24311. {
  24312. keyCode: VK.END,
  24313. action: action(moveToLineEndPoint$1, editor, true)
  24314. },
  24315. {
  24316. keyCode: VK.HOME,
  24317. action: action(moveToLineEndPoint$1, editor, false)
  24318. },
  24319. {
  24320. keyCode: VK.END,
  24321. action: action(moveToLineEndPoint$2, editor, true)
  24322. },
  24323. {
  24324. keyCode: VK.HOME,
  24325. action: action(moveToLineEndPoint$2, editor, false)
  24326. }
  24327. ], evt).each(function (_) {
  24328. evt.preventDefault();
  24329. });
  24330. };
  24331. var setup$f = function (editor) {
  24332. editor.on('keydown', function (evt) {
  24333. if (evt.isDefaultPrevented() === false) {
  24334. executeKeydownOverride$2(editor, evt);
  24335. }
  24336. });
  24337. };
  24338. var browser$4 = detect$3().browser;
  24339. var setupIeInput = function (editor) {
  24340. var keypressThrotter = first(function () {
  24341. if (!editor.composing) {
  24342. normalizeNbspsInEditor(editor);
  24343. }
  24344. }, 0);
  24345. if (browser$4.isIE()) {
  24346. editor.on('keypress', function (_e) {
  24347. keypressThrotter.throttle();
  24348. });
  24349. editor.on('remove', function (_e) {
  24350. keypressThrotter.cancel();
  24351. });
  24352. }
  24353. };
  24354. var setup$g = function (editor) {
  24355. setupIeInput(editor);
  24356. editor.on('input', function (e) {
  24357. if (e.isComposing === false) {
  24358. normalizeNbspsInEditor(editor);
  24359. }
  24360. });
  24361. };
  24362. var insertTextAtPosition = function (text, pos) {
  24363. var container = pos.container();
  24364. var offset = pos.offset();
  24365. if (isText$1(container)) {
  24366. container.insertData(offset, text);
  24367. return Optional.some(CaretPosition(container, offset + text.length));
  24368. } else {
  24369. return getElementFromPosition(pos).map(function (elm) {
  24370. var textNode = SugarElement.fromText(text);
  24371. if (pos.isAtEnd()) {
  24372. after(elm, textNode);
  24373. } else {
  24374. before(elm, textNode);
  24375. }
  24376. return CaretPosition(textNode.dom, text.length);
  24377. });
  24378. }
  24379. };
  24380. var insertNbspAtPosition = curry(insertTextAtPosition, nbsp);
  24381. var insertSpaceAtPosition = curry(insertTextAtPosition, ' ');
  24382. var locationToCaretPosition = function (root) {
  24383. return function (location) {
  24384. return location.fold(function (element) {
  24385. return prevPosition(root.dom, CaretPosition$1.before(element));
  24386. }, function (element) {
  24387. return firstPositionIn(element);
  24388. }, function (element) {
  24389. return lastPositionIn(element);
  24390. }, function (element) {
  24391. return nextPosition(root.dom, CaretPosition$1.after(element));
  24392. });
  24393. };
  24394. };
  24395. var insertInlineBoundarySpaceOrNbsp = function (root, pos) {
  24396. return function (checkPos) {
  24397. return needsToHaveNbsp(root, checkPos) ? insertNbspAtPosition(pos) : insertSpaceAtPosition(pos);
  24398. };
  24399. };
  24400. var setSelection$1 = function (editor) {
  24401. return function (pos) {
  24402. editor.selection.setRng(pos.toRange());
  24403. editor.nodeChanged();
  24404. return true;
  24405. };
  24406. };
  24407. var insertSpaceOrNbspAtSelection = function (editor) {
  24408. var pos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  24409. var root = SugarElement.fromDom(editor.getBody());
  24410. if (editor.selection.isCollapsed()) {
  24411. var isInlineTarget$1 = curry(isInlineTarget, editor);
  24412. var caretPosition = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  24413. return readLocation(isInlineTarget$1, editor.getBody(), caretPosition).bind(locationToCaretPosition(root)).bind(insertInlineBoundarySpaceOrNbsp(root, pos)).exists(setSelection$1(editor));
  24414. } else {
  24415. return false;
  24416. }
  24417. };
  24418. var executeKeydownOverride$3 = function (editor, evt) {
  24419. execute([{
  24420. keyCode: VK.SPACEBAR,
  24421. action: action(insertSpaceOrNbspAtSelection, editor)
  24422. }], evt).each(function (_) {
  24423. evt.preventDefault();
  24424. });
  24425. };
  24426. var setup$h = function (editor) {
  24427. editor.on('keydown', function (evt) {
  24428. if (evt.isDefaultPrevented() === false) {
  24429. executeKeydownOverride$3(editor, evt);
  24430. }
  24431. });
  24432. };
  24433. var registerKeyboardOverrides = function (editor) {
  24434. var caret = setupSelectedState(editor);
  24435. setup$b(editor);
  24436. setup$c(editor, caret);
  24437. setup$d(editor, caret);
  24438. setup$e(editor);
  24439. setup$h(editor);
  24440. setup$g(editor);
  24441. setup$f(editor);
  24442. return caret;
  24443. };
  24444. var setup$i = function (editor) {
  24445. if (!isRtc(editor)) {
  24446. return registerKeyboardOverrides(editor);
  24447. } else {
  24448. return Cell(null);
  24449. }
  24450. };
  24451. var NodeChange = function () {
  24452. function NodeChange(editor) {
  24453. this.lastPath = [];
  24454. this.editor = editor;
  24455. var lastRng;
  24456. var self = this;
  24457. if (!('onselectionchange' in editor.getDoc())) {
  24458. editor.on('NodeChange click mouseup keyup focus', function (e) {
  24459. var nativeRng = editor.selection.getRng();
  24460. var fakeRng = {
  24461. startContainer: nativeRng.startContainer,
  24462. startOffset: nativeRng.startOffset,
  24463. endContainer: nativeRng.endContainer,
  24464. endOffset: nativeRng.endOffset
  24465. };
  24466. if (e.type === 'nodechange' || !isEq$1(fakeRng, lastRng)) {
  24467. editor.fire('SelectionChange');
  24468. }
  24469. lastRng = fakeRng;
  24470. });
  24471. }
  24472. editor.on('contextmenu', function () {
  24473. editor.fire('SelectionChange');
  24474. });
  24475. editor.on('SelectionChange', function () {
  24476. var startElm = editor.selection.getStart(true);
  24477. if (!startElm || !Env.range && editor.selection.isCollapsed()) {
  24478. return;
  24479. }
  24480. if (hasAnyRanges(editor) && !self.isSameElementPath(startElm) && editor.dom.isChildOf(startElm, editor.getBody())) {
  24481. editor.nodeChanged({ selectionChange: true });
  24482. }
  24483. });
  24484. editor.on('mouseup', function (e) {
  24485. if (!e.isDefaultPrevented() && hasAnyRanges(editor)) {
  24486. if (editor.selection.getNode().nodeName === 'IMG') {
  24487. Delay.setEditorTimeout(editor, function () {
  24488. editor.nodeChanged();
  24489. });
  24490. } else {
  24491. editor.nodeChanged();
  24492. }
  24493. }
  24494. });
  24495. }
  24496. NodeChange.prototype.nodeChanged = function (args) {
  24497. var selection = this.editor.selection;
  24498. var node, parents, root;
  24499. if (this.editor.initialized && selection && !shouldDisableNodeChange(this.editor) && !this.editor.mode.isReadOnly()) {
  24500. root = this.editor.getBody();
  24501. node = selection.getStart(true) || root;
  24502. if (node.ownerDocument !== this.editor.getDoc() || !this.editor.dom.isChildOf(node, root)) {
  24503. node = root;
  24504. }
  24505. parents = [];
  24506. this.editor.dom.getParent(node, function (node) {
  24507. if (node === root) {
  24508. return true;
  24509. }
  24510. parents.push(node);
  24511. });
  24512. args = args || {};
  24513. args.element = node;
  24514. args.parents = parents;
  24515. this.editor.fire('NodeChange', args);
  24516. }
  24517. };
  24518. NodeChange.prototype.isSameElementPath = function (startElm) {
  24519. var i;
  24520. var currentPath = this.editor.$(startElm).parentsUntil(this.editor.getBody()).add(startElm);
  24521. if (currentPath.length === this.lastPath.length) {
  24522. for (i = currentPath.length; i >= 0; i--) {
  24523. if (currentPath[i] !== this.lastPath[i]) {
  24524. break;
  24525. }
  24526. }
  24527. if (i === -1) {
  24528. this.lastPath = currentPath;
  24529. return true;
  24530. }
  24531. }
  24532. this.lastPath = currentPath;
  24533. return false;
  24534. };
  24535. return NodeChange;
  24536. }();
  24537. var preventSummaryToggle = function (editor) {
  24538. editor.on('click', function (e) {
  24539. if (editor.dom.getParent(e.target, 'details')) {
  24540. e.preventDefault();
  24541. }
  24542. });
  24543. };
  24544. var filterDetails = function (editor) {
  24545. editor.parser.addNodeFilter('details', function (elms) {
  24546. each(elms, function (details) {
  24547. details.attr('data-mce-open', details.attr('open'));
  24548. details.attr('open', 'open');
  24549. });
  24550. });
  24551. editor.serializer.addNodeFilter('details', function (elms) {
  24552. each(elms, function (details) {
  24553. var open = details.attr('data-mce-open');
  24554. details.attr('open', isString(open) ? open : null);
  24555. details.attr('data-mce-open', null);
  24556. });
  24557. });
  24558. };
  24559. var setup$j = function (editor) {
  24560. preventSummaryToggle(editor);
  24561. filterDetails(editor);
  24562. };
  24563. var isTextBlockNode = function (node) {
  24564. return isElement$1(node) && isTextBlock(SugarElement.fromDom(node));
  24565. };
  24566. var normalizeSelection$1 = function (editor) {
  24567. var rng = editor.selection.getRng();
  24568. var startPos = CaretPosition.fromRangeStart(rng);
  24569. var endPos = CaretPosition.fromRangeEnd(rng);
  24570. if (CaretPosition.isElementPosition(startPos)) {
  24571. var container = startPos.container();
  24572. if (isTextBlockNode(container)) {
  24573. firstPositionIn(container).each(function (pos) {
  24574. return rng.setStart(pos.container(), pos.offset());
  24575. });
  24576. }
  24577. }
  24578. if (CaretPosition.isElementPosition(endPos)) {
  24579. var container = startPos.container();
  24580. if (isTextBlockNode(container)) {
  24581. lastPositionIn(container).each(function (pos) {
  24582. return rng.setEnd(pos.container(), pos.offset());
  24583. });
  24584. }
  24585. }
  24586. editor.selection.setRng(normalize$2(rng));
  24587. };
  24588. var setup$k = function (editor) {
  24589. editor.on('click', function (e) {
  24590. if (e.detail >= 3) {
  24591. normalizeSelection$1(editor);
  24592. }
  24593. });
  24594. };
  24595. var value$1 = function () {
  24596. var subject = Cell(Optional.none());
  24597. var clear = function () {
  24598. return subject.set(Optional.none());
  24599. };
  24600. var set = function (s) {
  24601. return subject.set(Optional.some(s));
  24602. };
  24603. var isSet = function () {
  24604. return subject.get().isSome();
  24605. };
  24606. var on = function (f) {
  24607. return subject.get().each(f);
  24608. };
  24609. return {
  24610. clear: clear,
  24611. set: set,
  24612. isSet: isSet,
  24613. on: on
  24614. };
  24615. };
  24616. var getAbsolutePosition = function (elm) {
  24617. var clientRect = elm.getBoundingClientRect();
  24618. var doc = elm.ownerDocument;
  24619. var docElem = doc.documentElement;
  24620. var win = doc.defaultView;
  24621. return {
  24622. top: clientRect.top + win.pageYOffset - docElem.clientTop,
  24623. left: clientRect.left + win.pageXOffset - docElem.clientLeft
  24624. };
  24625. };
  24626. var getBodyPosition = function (editor) {
  24627. return editor.inline ? getAbsolutePosition(editor.getBody()) : {
  24628. left: 0,
  24629. top: 0
  24630. };
  24631. };
  24632. var getScrollPosition = function (editor) {
  24633. var body = editor.getBody();
  24634. return editor.inline ? {
  24635. left: body.scrollLeft,
  24636. top: body.scrollTop
  24637. } : {
  24638. left: 0,
  24639. top: 0
  24640. };
  24641. };
  24642. var getBodyScroll = function (editor) {
  24643. var body = editor.getBody(), docElm = editor.getDoc().documentElement;
  24644. var inlineScroll = {
  24645. left: body.scrollLeft,
  24646. top: body.scrollTop
  24647. };
  24648. var iframeScroll = {
  24649. left: body.scrollLeft || docElm.scrollLeft,
  24650. top: body.scrollTop || docElm.scrollTop
  24651. };
  24652. return editor.inline ? inlineScroll : iframeScroll;
  24653. };
  24654. var getMousePosition = function (editor, event) {
  24655. if (event.target.ownerDocument !== editor.getDoc()) {
  24656. var iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
  24657. var scrollPosition = getBodyScroll(editor);
  24658. return {
  24659. left: event.pageX - iframePosition.left + scrollPosition.left,
  24660. top: event.pageY - iframePosition.top + scrollPosition.top
  24661. };
  24662. }
  24663. return {
  24664. left: event.pageX,
  24665. top: event.pageY
  24666. };
  24667. };
  24668. var calculatePosition = function (bodyPosition, scrollPosition, mousePosition) {
  24669. return {
  24670. pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
  24671. pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
  24672. };
  24673. };
  24674. var calc = function (editor, event) {
  24675. return calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
  24676. };
  24677. var isContentEditableFalse$a = isContentEditableFalse, isContentEditableTrue$3 = isContentEditableTrue;
  24678. var isDraggable = function (rootElm, elm) {
  24679. return isContentEditableFalse$a(elm) && elm !== rootElm;
  24680. };
  24681. var isValidDropTarget = function (editor, targetElement, dragElement) {
  24682. if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
  24683. return false;
  24684. }
  24685. return !isContentEditableFalse$a(targetElement);
  24686. };
  24687. var cloneElement = function (elm) {
  24688. var cloneElm = elm.cloneNode(true);
  24689. cloneElm.removeAttribute('data-mce-selected');
  24690. return cloneElm;
  24691. };
  24692. var createGhost = function (editor, elm, width, height) {
  24693. var dom = editor.dom;
  24694. var clonedElm = elm.cloneNode(true);
  24695. dom.setStyles(clonedElm, {
  24696. width: width,
  24697. height: height
  24698. });
  24699. dom.setAttrib(clonedElm, 'data-mce-selected', null);
  24700. var ghostElm = dom.create('div', {
  24701. 'class': 'mce-drag-container',
  24702. 'data-mce-bogus': 'all',
  24703. 'unselectable': 'on',
  24704. 'contenteditable': 'false'
  24705. });
  24706. dom.setStyles(ghostElm, {
  24707. position: 'absolute',
  24708. opacity: 0.5,
  24709. overflow: 'hidden',
  24710. border: 0,
  24711. padding: 0,
  24712. margin: 0,
  24713. width: width,
  24714. height: height
  24715. });
  24716. dom.setStyles(clonedElm, {
  24717. margin: 0,
  24718. boxSizing: 'border-box'
  24719. });
  24720. ghostElm.appendChild(clonedElm);
  24721. return ghostElm;
  24722. };
  24723. var appendGhostToBody = function (ghostElm, bodyElm) {
  24724. if (ghostElm.parentNode !== bodyElm) {
  24725. bodyElm.appendChild(ghostElm);
  24726. }
  24727. };
  24728. var moveGhost = function (ghostElm, position, width, height, maxX, maxY) {
  24729. var overflowX = 0, overflowY = 0;
  24730. ghostElm.style.left = position.pageX + 'px';
  24731. ghostElm.style.top = position.pageY + 'px';
  24732. if (position.pageX + width > maxX) {
  24733. overflowX = position.pageX + width - maxX;
  24734. }
  24735. if (position.pageY + height > maxY) {
  24736. overflowY = position.pageY + height - maxY;
  24737. }
  24738. ghostElm.style.width = width - overflowX + 'px';
  24739. ghostElm.style.height = height - overflowY + 'px';
  24740. };
  24741. var removeElement = function (elm) {
  24742. if (elm && elm.parentNode) {
  24743. elm.parentNode.removeChild(elm);
  24744. }
  24745. };
  24746. var isLeftMouseButtonPressed = function (e) {
  24747. return e.button === 0;
  24748. };
  24749. var applyRelPos = function (state, position) {
  24750. return {
  24751. pageX: position.pageX - state.relX,
  24752. pageY: position.pageY + 5
  24753. };
  24754. };
  24755. var start$1 = function (state, editor) {
  24756. return function (e) {
  24757. if (isLeftMouseButtonPressed(e)) {
  24758. var ceElm = find(editor.dom.getParents(e.target), or(isContentEditableFalse$a, isContentEditableTrue$3)).getOr(null);
  24759. if (isDraggable(editor.getBody(), ceElm)) {
  24760. var elmPos = editor.dom.getPos(ceElm);
  24761. var bodyElm = editor.getBody();
  24762. var docElm = editor.getDoc().documentElement;
  24763. state.set({
  24764. element: ceElm,
  24765. dragging: false,
  24766. screenX: e.screenX,
  24767. screenY: e.screenY,
  24768. maxX: (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2,
  24769. maxY: (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2,
  24770. relX: e.pageX - elmPos.x,
  24771. relY: e.pageY - elmPos.y,
  24772. width: ceElm.offsetWidth,
  24773. height: ceElm.offsetHeight,
  24774. ghost: createGhost(editor, ceElm, ceElm.offsetWidth, ceElm.offsetHeight)
  24775. });
  24776. }
  24777. }
  24778. };
  24779. };
  24780. var move$2 = function (state, editor) {
  24781. var throttledPlaceCaretAt = Delay.throttle(function (clientX, clientY) {
  24782. editor._selectionOverrides.hideFakeCaret();
  24783. editor.selection.placeCaretAt(clientX, clientY);
  24784. }, 0);
  24785. editor.on('remove', throttledPlaceCaretAt.stop);
  24786. return function (e) {
  24787. return state.on(function (state) {
  24788. var movement = Math.max(Math.abs(e.screenX - state.screenX), Math.abs(e.screenY - state.screenY));
  24789. if (!state.dragging && movement > 10) {
  24790. var args = editor.fire('dragstart', { target: state.element });
  24791. if (args.isDefaultPrevented()) {
  24792. return;
  24793. }
  24794. state.dragging = true;
  24795. editor.focus();
  24796. }
  24797. if (state.dragging) {
  24798. var targetPos = applyRelPos(state, calc(editor, e));
  24799. appendGhostToBody(state.ghost, editor.getBody());
  24800. moveGhost(state.ghost, targetPos, state.width, state.height, state.maxX, state.maxY);
  24801. throttledPlaceCaretAt(e.clientX, e.clientY);
  24802. }
  24803. });
  24804. };
  24805. };
  24806. var getRawTarget = function (selection) {
  24807. var rng = selection.getSel().getRangeAt(0);
  24808. var startContainer = rng.startContainer;
  24809. return startContainer.nodeType === 3 ? startContainer.parentNode : startContainer;
  24810. };
  24811. var drop = function (state, editor) {
  24812. return function (e) {
  24813. state.on(function (state) {
  24814. if (state.dragging) {
  24815. if (isValidDropTarget(editor, getRawTarget(editor.selection), state.element)) {
  24816. var targetClone_1 = cloneElement(state.element);
  24817. var args = editor.fire('drop', {
  24818. clientX: e.clientX,
  24819. clientY: e.clientY
  24820. });
  24821. if (!args.isDefaultPrevented()) {
  24822. editor.undoManager.transact(function () {
  24823. removeElement(state.element);
  24824. editor.insertContent(editor.dom.getOuterHTML(targetClone_1));
  24825. editor._selectionOverrides.hideFakeCaret();
  24826. });
  24827. }
  24828. }
  24829. }
  24830. });
  24831. removeDragState(state);
  24832. };
  24833. };
  24834. var stop = function (state, editor) {
  24835. return function () {
  24836. state.on(function (state) {
  24837. if (state.dragging) {
  24838. editor.fire('dragend');
  24839. }
  24840. });
  24841. removeDragState(state);
  24842. };
  24843. };
  24844. var removeDragState = function (state) {
  24845. state.on(function (state) {
  24846. removeElement(state.ghost);
  24847. });
  24848. state.clear();
  24849. };
  24850. var bindFakeDragEvents = function (editor) {
  24851. var state = value$1();
  24852. var pageDom = DOMUtils$1.DOM;
  24853. var rootDocument = document;
  24854. var dragStartHandler = start$1(state, editor);
  24855. var dragHandler = move$2(state, editor);
  24856. var dropHandler = drop(state, editor);
  24857. var dragEndHandler = stop(state, editor);
  24858. editor.on('mousedown', dragStartHandler);
  24859. editor.on('mousemove', dragHandler);
  24860. editor.on('mouseup', dropHandler);
  24861. pageDom.bind(rootDocument, 'mousemove', dragHandler);
  24862. pageDom.bind(rootDocument, 'mouseup', dragEndHandler);
  24863. editor.on('remove', function () {
  24864. pageDom.unbind(rootDocument, 'mousemove', dragHandler);
  24865. pageDom.unbind(rootDocument, 'mouseup', dragEndHandler);
  24866. });
  24867. };
  24868. var blockIeDrop = function (editor) {
  24869. editor.on('drop', function (e) {
  24870. var realTarget = typeof e.clientX !== 'undefined' ? editor.getDoc().elementFromPoint(e.clientX, e.clientY) : null;
  24871. if (isContentEditableFalse$a(realTarget) || editor.dom.getContentEditableParent(realTarget) === 'false') {
  24872. e.preventDefault();
  24873. }
  24874. });
  24875. };
  24876. var blockUnsupportedFileDrop = function (editor) {
  24877. var preventFileDrop = function (e) {
  24878. if (!e.defaultPrevented) {
  24879. var dataTransfer = e.dataTransfer;
  24880. if (dataTransfer && (contains(dataTransfer.types, 'Files') || dataTransfer.files.length > 0)) {
  24881. e.preventDefault();
  24882. if (e.type === 'drop') {
  24883. displayError(editor, 'Dropped file type is not supported');
  24884. }
  24885. }
  24886. }
  24887. };
  24888. var preventFileDropIfUIElement = function (e) {
  24889. if (isUIElement(editor, e.target)) {
  24890. preventFileDrop(e);
  24891. }
  24892. };
  24893. var setup = function () {
  24894. var pageDom = DOMUtils$1.DOM;
  24895. var dom = editor.dom;
  24896. var doc = document;
  24897. var editorRoot = editor.inline ? editor.getBody() : editor.getDoc();
  24898. var eventNames = [
  24899. 'drop',
  24900. 'dragover'
  24901. ];
  24902. each(eventNames, function (name) {
  24903. pageDom.bind(doc, name, preventFileDropIfUIElement);
  24904. dom.bind(editorRoot, name, preventFileDrop);
  24905. });
  24906. editor.on('remove', function () {
  24907. each(eventNames, function (name) {
  24908. pageDom.unbind(doc, name, preventFileDropIfUIElement);
  24909. dom.unbind(editorRoot, name, preventFileDrop);
  24910. });
  24911. });
  24912. };
  24913. editor.on('init', function () {
  24914. Delay.setEditorTimeout(editor, setup, 0);
  24915. });
  24916. };
  24917. var init = function (editor) {
  24918. bindFakeDragEvents(editor);
  24919. blockIeDrop(editor);
  24920. if (shouldBlockUnsupportedDrop(editor)) {
  24921. blockUnsupportedFileDrop(editor);
  24922. }
  24923. };
  24924. var setup$l = function (editor) {
  24925. var renderFocusCaret = first(function () {
  24926. if (!editor.removed && editor.getBody().contains(document.activeElement)) {
  24927. var rng = editor.selection.getRng();
  24928. if (rng.collapsed) {
  24929. var caretRange = renderRangeCaret(editor, rng, false);
  24930. editor.selection.setRng(caretRange);
  24931. }
  24932. }
  24933. }, 0);
  24934. editor.on('focus', function () {
  24935. renderFocusCaret.throttle();
  24936. });
  24937. editor.on('blur', function () {
  24938. renderFocusCaret.cancel();
  24939. });
  24940. };
  24941. var setup$m = function (editor) {
  24942. editor.on('init', function () {
  24943. editor.on('focusin', function (e) {
  24944. var target = e.target;
  24945. if (isMedia(target)) {
  24946. var ceRoot = getContentEditableRoot(editor.getBody(), target);
  24947. var node = isContentEditableFalse(ceRoot) ? ceRoot : target;
  24948. if (editor.selection.getNode() !== node) {
  24949. selectNode(editor, node).each(function (rng) {
  24950. return editor.selection.setRng(rng);
  24951. });
  24952. }
  24953. }
  24954. });
  24955. });
  24956. };
  24957. var isContentEditableTrue$4 = isContentEditableTrue;
  24958. var isContentEditableFalse$b = isContentEditableFalse;
  24959. var getContentEditableRoot$1 = function (editor, node) {
  24960. return getContentEditableRoot(editor.getBody(), node);
  24961. };
  24962. var SelectionOverrides = function (editor) {
  24963. var selection = editor.selection, dom = editor.dom;
  24964. var isBlock = dom.isBlock;
  24965. var rootNode = editor.getBody();
  24966. var fakeCaret = FakeCaret(editor, rootNode, isBlock, function () {
  24967. return hasFocus$1(editor);
  24968. });
  24969. var realSelectionId = 'sel-' + dom.uniqueId();
  24970. var elementSelectionAttr = 'data-mce-selected';
  24971. var selectedElement;
  24972. var isFakeSelectionElement = function (node) {
  24973. return dom.hasClass(node, 'mce-offscreen-selection');
  24974. };
  24975. var isFakeSelectionTargetElement = function (node) {
  24976. return node !== rootNode && (isContentEditableFalse$b(node) || isMedia(node)) && dom.isChildOf(node, rootNode);
  24977. };
  24978. var isNearFakeSelectionElement = function (pos) {
  24979. return isBeforeContentEditableFalse(pos) || isAfterContentEditableFalse(pos) || isBeforeMedia(pos) || isAfterMedia(pos);
  24980. };
  24981. var getRealSelectionElement = function () {
  24982. var container = dom.get(realSelectionId);
  24983. return container ? container.getElementsByTagName('*')[0] : container;
  24984. };
  24985. var setRange = function (range) {
  24986. if (range) {
  24987. selection.setRng(range);
  24988. }
  24989. };
  24990. var getRange = selection.getRng;
  24991. var showCaret = function (direction, node, before, scrollIntoView) {
  24992. if (scrollIntoView === void 0) {
  24993. scrollIntoView = true;
  24994. }
  24995. var e = editor.fire('ShowCaret', {
  24996. target: node,
  24997. direction: direction,
  24998. before: before
  24999. });
  25000. if (e.isDefaultPrevented()) {
  25001. return null;
  25002. }
  25003. if (scrollIntoView) {
  25004. selection.scrollIntoView(node, direction === -1);
  25005. }
  25006. return fakeCaret.show(before, node);
  25007. };
  25008. var showBlockCaretContainer = function (blockCaretContainer) {
  25009. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  25010. showCaretContainerBlock(blockCaretContainer);
  25011. setRange(getRange());
  25012. selection.scrollIntoView(blockCaretContainer);
  25013. }
  25014. };
  25015. var registerEvents = function () {
  25016. editor.on('mouseup', function (e) {
  25017. var range = getRange();
  25018. if (range.collapsed && isXYInContentArea(editor, e.clientX, e.clientY)) {
  25019. renderCaretAtRange(editor, range, false).each(setRange);
  25020. }
  25021. });
  25022. editor.on('click', function (e) {
  25023. var contentEditableRoot = getContentEditableRoot$1(editor, e.target);
  25024. if (contentEditableRoot) {
  25025. if (isContentEditableFalse$b(contentEditableRoot)) {
  25026. e.preventDefault();
  25027. editor.focus();
  25028. }
  25029. if (isContentEditableTrue$4(contentEditableRoot)) {
  25030. if (dom.isChildOf(contentEditableRoot, selection.getNode())) {
  25031. removeElementSelection();
  25032. }
  25033. }
  25034. }
  25035. });
  25036. editor.on('blur NewBlock', removeElementSelection);
  25037. editor.on('ResizeWindow FullscreenStateChanged', fakeCaret.reposition);
  25038. var hasNormalCaretPosition = function (elm) {
  25039. var caretWalker = CaretWalker(elm);
  25040. if (!elm.firstChild) {
  25041. return false;
  25042. }
  25043. var startPos = CaretPosition$1.before(elm.firstChild);
  25044. var newPos = caretWalker.next(startPos);
  25045. return newPos && !isNearFakeSelectionElement(newPos);
  25046. };
  25047. var isInSameBlock = function (node1, node2) {
  25048. var block1 = dom.getParent(node1, isBlock);
  25049. var block2 = dom.getParent(node2, isBlock);
  25050. return block1 === block2;
  25051. };
  25052. var hasBetterMouseTarget = function (targetNode, caretNode) {
  25053. var targetBlock = dom.getParent(targetNode, isBlock);
  25054. var caretBlock = dom.getParent(caretNode, isBlock);
  25055. if (targetBlock && targetNode !== caretBlock && dom.isChildOf(targetBlock, caretBlock) && isContentEditableFalse$b(getContentEditableRoot$1(editor, targetBlock)) === false) {
  25056. return true;
  25057. }
  25058. return targetBlock && !isInSameBlock(targetBlock, caretBlock) && hasNormalCaretPosition(targetBlock);
  25059. };
  25060. editor.on('tap', function (e) {
  25061. var targetElm = e.target;
  25062. var contentEditableRoot = getContentEditableRoot$1(editor, targetElm);
  25063. if (isContentEditableFalse$b(contentEditableRoot)) {
  25064. e.preventDefault();
  25065. selectNode(editor, contentEditableRoot).each(setElementSelection);
  25066. } else if (isFakeSelectionTargetElement(targetElm)) {
  25067. selectNode(editor, targetElm).each(setElementSelection);
  25068. }
  25069. }, true);
  25070. editor.on('mousedown', function (e) {
  25071. var targetElm = e.target;
  25072. if (targetElm !== rootNode && targetElm.nodeName !== 'HTML' && !dom.isChildOf(targetElm, rootNode)) {
  25073. return;
  25074. }
  25075. if (isXYInContentArea(editor, e.clientX, e.clientY) === false) {
  25076. return;
  25077. }
  25078. var contentEditableRoot = getContentEditableRoot$1(editor, targetElm);
  25079. if (contentEditableRoot) {
  25080. if (isContentEditableFalse$b(contentEditableRoot)) {
  25081. e.preventDefault();
  25082. selectNode(editor, contentEditableRoot).each(setElementSelection);
  25083. } else {
  25084. removeElementSelection();
  25085. if (!(isContentEditableTrue$4(contentEditableRoot) && e.shiftKey) && !isXYWithinRange(e.clientX, e.clientY, selection.getRng())) {
  25086. hideFakeCaret();
  25087. selection.placeCaretAt(e.clientX, e.clientY);
  25088. }
  25089. }
  25090. } else if (isFakeSelectionTargetElement(targetElm)) {
  25091. selectNode(editor, targetElm).each(setElementSelection);
  25092. } else if (isFakeCaretTarget(targetElm) === false) {
  25093. removeElementSelection();
  25094. hideFakeCaret();
  25095. var fakeCaretInfo = closestFakeCaret(rootNode, e.clientX, e.clientY);
  25096. if (fakeCaretInfo) {
  25097. if (!hasBetterMouseTarget(targetElm, fakeCaretInfo.node)) {
  25098. e.preventDefault();
  25099. var range = showCaret(1, fakeCaretInfo.node, fakeCaretInfo.before, false);
  25100. editor.getBody().focus();
  25101. setRange(range);
  25102. }
  25103. }
  25104. }
  25105. });
  25106. editor.on('keypress', function (e) {
  25107. if (VK.modifierPressed(e)) {
  25108. return;
  25109. }
  25110. if (isContentEditableFalse$b(selection.getNode())) {
  25111. e.preventDefault();
  25112. }
  25113. });
  25114. editor.on('GetSelectionRange', function (e) {
  25115. var rng = e.range;
  25116. if (selectedElement) {
  25117. if (!selectedElement.parentNode) {
  25118. selectedElement = null;
  25119. return;
  25120. }
  25121. rng = rng.cloneRange();
  25122. rng.selectNode(selectedElement);
  25123. e.range = rng;
  25124. }
  25125. });
  25126. editor.on('SetSelectionRange', function (e) {
  25127. e.range = normalizeShortEndedElementSelection(e.range);
  25128. var rng = setElementSelection(e.range, e.forward);
  25129. if (rng) {
  25130. e.range = rng;
  25131. }
  25132. });
  25133. var isPasteBin = function (node) {
  25134. return node.id === 'mcepastebin';
  25135. };
  25136. editor.on('AfterSetSelectionRange', function (e) {
  25137. var rng = e.range;
  25138. var parentNode = rng.startContainer.parentNode;
  25139. if (!isRangeInCaretContainer(rng) && !isPasteBin(parentNode)) {
  25140. hideFakeCaret();
  25141. }
  25142. if (!isFakeSelectionElement(parentNode)) {
  25143. removeElementSelection();
  25144. }
  25145. });
  25146. editor.on('copy', function (e) {
  25147. var clipboardData = e.clipboardData;
  25148. if (!e.isDefaultPrevented() && e.clipboardData && !Env.ie) {
  25149. var realSelectionElement = getRealSelectionElement();
  25150. if (realSelectionElement) {
  25151. e.preventDefault();
  25152. clipboardData.clearData();
  25153. clipboardData.setData('text/html', realSelectionElement.outerHTML);
  25154. clipboardData.setData('text/plain', realSelectionElement.outerText || realSelectionElement.innerText);
  25155. }
  25156. }
  25157. });
  25158. init(editor);
  25159. setup$l(editor);
  25160. setup$m(editor);
  25161. };
  25162. var isWithinCaretContainer = function (node) {
  25163. return isCaretContainer(node) || startsWithCaretContainer(node) || endsWithCaretContainer(node);
  25164. };
  25165. var isRangeInCaretContainer = function (rng) {
  25166. return isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
  25167. };
  25168. var normalizeShortEndedElementSelection = function (rng) {
  25169. var shortEndedElements = editor.schema.getShortEndedElements();
  25170. var newRng = dom.createRng();
  25171. var startContainer = rng.startContainer;
  25172. var startOffset = rng.startOffset;
  25173. var endContainer = rng.endContainer;
  25174. var endOffset = rng.endOffset;
  25175. if (has(shortEndedElements, startContainer.nodeName.toLowerCase())) {
  25176. if (startOffset === 0) {
  25177. newRng.setStartBefore(startContainer);
  25178. } else {
  25179. newRng.setStartAfter(startContainer);
  25180. }
  25181. } else {
  25182. newRng.setStart(startContainer, startOffset);
  25183. }
  25184. if (has(shortEndedElements, endContainer.nodeName.toLowerCase())) {
  25185. if (endOffset === 0) {
  25186. newRng.setEndBefore(endContainer);
  25187. } else {
  25188. newRng.setEndAfter(endContainer);
  25189. }
  25190. } else {
  25191. newRng.setEnd(endContainer, endOffset);
  25192. }
  25193. return newRng;
  25194. };
  25195. var setupOffscreenSelection = function (node, targetClone, origTargetClone) {
  25196. var $ = editor.$;
  25197. var $realSelectionContainer = descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).fold(function () {
  25198. return $([]);
  25199. }, function (elm) {
  25200. return $([elm.dom]);
  25201. });
  25202. if ($realSelectionContainer.length === 0) {
  25203. $realSelectionContainer = $('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>').attr('id', realSelectionId);
  25204. $realSelectionContainer.appendTo(editor.getBody());
  25205. }
  25206. var newRange = dom.createRng();
  25207. if (targetClone === origTargetClone && Env.ie) {
  25208. $realSelectionContainer.empty().append('<p style="font-size: 0" data-mce-bogus="all">\xA0</p>').append(targetClone);
  25209. newRange.setStartAfter($realSelectionContainer[0].firstChild.firstChild);
  25210. newRange.setEndAfter(targetClone);
  25211. } else {
  25212. $realSelectionContainer.empty().append(nbsp).append(targetClone).append(nbsp);
  25213. newRange.setStart($realSelectionContainer[0].firstChild, 1);
  25214. newRange.setEnd($realSelectionContainer[0].lastChild, 0);
  25215. }
  25216. $realSelectionContainer.css({ top: dom.getPos(node, editor.getBody()).y });
  25217. $realSelectionContainer[0].focus();
  25218. var sel = selection.getSel();
  25219. sel.removeAllRanges();
  25220. sel.addRange(newRange);
  25221. return newRange;
  25222. };
  25223. var selectElement = function (elm) {
  25224. var targetClone = elm.cloneNode(true);
  25225. var e = editor.fire('ObjectSelected', {
  25226. target: elm,
  25227. targetClone: targetClone
  25228. });
  25229. if (e.isDefaultPrevented()) {
  25230. return null;
  25231. }
  25232. var range = setupOffscreenSelection(elm, e.targetClone, targetClone);
  25233. var nodeElm = SugarElement.fromDom(elm);
  25234. each(descendants$1(SugarElement.fromDom(editor.getBody()), '*[data-mce-selected]'), function (elm) {
  25235. if (!eq$2(nodeElm, elm)) {
  25236. remove$1(elm, elementSelectionAttr);
  25237. }
  25238. });
  25239. if (!dom.getAttrib(elm, elementSelectionAttr)) {
  25240. elm.setAttribute(elementSelectionAttr, '1');
  25241. }
  25242. selectedElement = elm;
  25243. hideFakeCaret();
  25244. return range;
  25245. };
  25246. var setElementSelection = function (range, forward) {
  25247. if (!range) {
  25248. return null;
  25249. }
  25250. if (range.collapsed) {
  25251. if (!isRangeInCaretContainer(range)) {
  25252. var dir = forward ? 1 : -1;
  25253. var caretPosition = getNormalizedRangeEndPoint(dir, rootNode, range);
  25254. var beforeNode = caretPosition.getNode(!forward);
  25255. if (isFakeCaretTarget(beforeNode)) {
  25256. return showCaret(dir, beforeNode, forward ? !caretPosition.isAtEnd() : false, false);
  25257. }
  25258. var afterNode = caretPosition.getNode(forward);
  25259. if (isFakeCaretTarget(afterNode)) {
  25260. return showCaret(dir, afterNode, forward ? false : !caretPosition.isAtEnd(), false);
  25261. }
  25262. }
  25263. return null;
  25264. }
  25265. var startContainer = range.startContainer;
  25266. var startOffset = range.startOffset;
  25267. var endOffset = range.endOffset;
  25268. if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse$b(startContainer.parentNode)) {
  25269. startContainer = startContainer.parentNode;
  25270. startOffset = dom.nodeIndex(startContainer);
  25271. startContainer = startContainer.parentNode;
  25272. }
  25273. if (startContainer.nodeType !== 1) {
  25274. return null;
  25275. }
  25276. if (endOffset === startOffset + 1 && startContainer === range.endContainer) {
  25277. var node = startContainer.childNodes[startOffset];
  25278. if (isFakeSelectionTargetElement(node)) {
  25279. return selectElement(node);
  25280. }
  25281. }
  25282. return null;
  25283. };
  25284. var removeElementSelection = function () {
  25285. if (selectedElement) {
  25286. selectedElement.removeAttribute(elementSelectionAttr);
  25287. }
  25288. descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).each(remove);
  25289. selectedElement = null;
  25290. };
  25291. var destroy = function () {
  25292. fakeCaret.destroy();
  25293. selectedElement = null;
  25294. };
  25295. var hideFakeCaret = function () {
  25296. fakeCaret.hide();
  25297. };
  25298. if (Env.ceFalse) {
  25299. registerEvents();
  25300. }
  25301. return {
  25302. showCaret: showCaret,
  25303. showBlockCaretContainer: showBlockCaretContainer,
  25304. hideFakeCaret: hideFakeCaret,
  25305. destroy: destroy
  25306. };
  25307. };
  25308. var Quirks = function (editor) {
  25309. var each = Tools.each;
  25310. var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, parser = editor.parser;
  25311. var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit;
  25312. var mceInternalUrlPrefix = 'data:text/mce-internal,';
  25313. var mceInternalDataType = isIE ? 'Text' : 'URL';
  25314. var setEditorCommandState = function (cmd, state) {
  25315. try {
  25316. editor.getDoc().execCommand(cmd, false, state);
  25317. } catch (ex) {
  25318. }
  25319. };
  25320. var isDefaultPrevented = function (e) {
  25321. return e.isDefaultPrevented();
  25322. };
  25323. var setMceInternalContent = function (e) {
  25324. var selectionHtml, internalContent;
  25325. if (e.dataTransfer) {
  25326. if (editor.selection.isCollapsed() && e.target.tagName === 'IMG') {
  25327. selection.select(e.target);
  25328. }
  25329. selectionHtml = editor.selection.getContent();
  25330. if (selectionHtml.length > 0) {
  25331. internalContent = mceInternalUrlPrefix + escape(editor.id) + ',' + escape(selectionHtml);
  25332. e.dataTransfer.setData(mceInternalDataType, internalContent);
  25333. }
  25334. }
  25335. };
  25336. var getMceInternalContent = function (e) {
  25337. var internalContent;
  25338. if (e.dataTransfer) {
  25339. internalContent = e.dataTransfer.getData(mceInternalDataType);
  25340. if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) {
  25341. internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(',');
  25342. return {
  25343. id: unescape(internalContent[0]),
  25344. html: unescape(internalContent[1])
  25345. };
  25346. }
  25347. }
  25348. return null;
  25349. };
  25350. var insertClipboardContents = function (content, internal) {
  25351. if (editor.queryCommandSupported('mceInsertClipboardContent')) {
  25352. editor.execCommand('mceInsertClipboardContent', false, {
  25353. content: content,
  25354. internal: internal
  25355. });
  25356. } else {
  25357. editor.execCommand('mceInsertContent', false, content);
  25358. }
  25359. };
  25360. var emptyEditorWhenDeleting = function () {
  25361. var serializeRng = function (rng) {
  25362. var body = dom.create('body');
  25363. var contents = rng.cloneContents();
  25364. body.appendChild(contents);
  25365. return selection.serializer.serialize(body, { format: 'html' });
  25366. };
  25367. var allContentsSelected = function (rng) {
  25368. var selection = serializeRng(rng);
  25369. var allRng = dom.createRng();
  25370. allRng.selectNode(editor.getBody());
  25371. var allSelection = serializeRng(allRng);
  25372. return selection === allSelection;
  25373. };
  25374. editor.on('keydown', function (e) {
  25375. var keyCode = e.keyCode;
  25376. var isCollapsed, body;
  25377. if (!isDefaultPrevented(e) && (keyCode === DELETE || keyCode === BACKSPACE)) {
  25378. isCollapsed = editor.selection.isCollapsed();
  25379. body = editor.getBody();
  25380. if (isCollapsed && !dom.isEmpty(body)) {
  25381. return;
  25382. }
  25383. if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
  25384. return;
  25385. }
  25386. e.preventDefault();
  25387. editor.setContent('');
  25388. if (body.firstChild && dom.isBlock(body.firstChild)) {
  25389. editor.selection.setCursorLocation(body.firstChild, 0);
  25390. } else {
  25391. editor.selection.setCursorLocation(body, 0);
  25392. }
  25393. editor.nodeChanged();
  25394. }
  25395. });
  25396. };
  25397. var selectAll = function () {
  25398. editor.shortcuts.add('meta+a', null, 'SelectAll');
  25399. };
  25400. var inputMethodFocus = function () {
  25401. if (!editor.inline) {
  25402. dom.bind(editor.getDoc(), 'mousedown mouseup', function (e) {
  25403. var rng;
  25404. if (e.target === editor.getDoc().documentElement) {
  25405. rng = selection.getRng();
  25406. editor.getBody().focus();
  25407. if (e.type === 'mousedown') {
  25408. if (isCaretContainer(rng.startContainer)) {
  25409. return;
  25410. }
  25411. selection.placeCaretAt(e.clientX, e.clientY);
  25412. } else {
  25413. selection.setRng(rng);
  25414. }
  25415. }
  25416. });
  25417. }
  25418. };
  25419. var removeHrOnBackspace = function () {
  25420. editor.on('keydown', function (e) {
  25421. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25422. if (!editor.getBody().getElementsByTagName('hr').length) {
  25423. return;
  25424. }
  25425. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25426. var node = selection.getNode();
  25427. var previousSibling = node.previousSibling;
  25428. if (node.nodeName === 'HR') {
  25429. dom.remove(node);
  25430. e.preventDefault();
  25431. return;
  25432. }
  25433. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'hr') {
  25434. dom.remove(previousSibling);
  25435. e.preventDefault();
  25436. }
  25437. }
  25438. }
  25439. });
  25440. };
  25441. var focusBody = function () {
  25442. if (!Range.prototype.getClientRects) {
  25443. editor.on('mousedown', function (e) {
  25444. if (!isDefaultPrevented(e) && e.target.nodeName === 'HTML') {
  25445. var body_1 = editor.getBody();
  25446. body_1.blur();
  25447. Delay.setEditorTimeout(editor, function () {
  25448. body_1.focus();
  25449. });
  25450. }
  25451. });
  25452. }
  25453. };
  25454. var selectControlElements = function () {
  25455. editor.on('click', function (e) {
  25456. var target = e.target;
  25457. if (/^(IMG|HR)$/.test(target.nodeName) && dom.getContentEditableParent(target) !== 'false') {
  25458. e.preventDefault();
  25459. editor.selection.select(target);
  25460. editor.nodeChanged();
  25461. }
  25462. if (target.nodeName === 'A' && dom.hasClass(target, 'mce-item-anchor')) {
  25463. e.preventDefault();
  25464. selection.select(target);
  25465. }
  25466. });
  25467. };
  25468. var removeStylesWhenDeletingAcrossBlockElements = function () {
  25469. var getAttributeApplyFunction = function () {
  25470. var template = dom.getAttribs(selection.getStart().cloneNode(false));
  25471. return function () {
  25472. var target = selection.getStart();
  25473. if (target !== editor.getBody()) {
  25474. dom.setAttrib(target, 'style', null);
  25475. each(template, function (attr) {
  25476. target.setAttributeNode(attr.cloneNode(true));
  25477. });
  25478. }
  25479. };
  25480. };
  25481. var isSelectionAcrossElements = function () {
  25482. return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock);
  25483. };
  25484. editor.on('keypress', function (e) {
  25485. var applyAttributes;
  25486. if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) {
  25487. applyAttributes = getAttributeApplyFunction();
  25488. editor.getDoc().execCommand('delete', false, null);
  25489. applyAttributes();
  25490. e.preventDefault();
  25491. return false;
  25492. }
  25493. });
  25494. dom.bind(editor.getDoc(), 'cut', function (e) {
  25495. var applyAttributes;
  25496. if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
  25497. applyAttributes = getAttributeApplyFunction();
  25498. Delay.setEditorTimeout(editor, function () {
  25499. applyAttributes();
  25500. });
  25501. }
  25502. });
  25503. };
  25504. var disableBackspaceIntoATable = function () {
  25505. editor.on('keydown', function (e) {
  25506. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25507. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25508. var previousSibling = selection.getNode().previousSibling;
  25509. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'table') {
  25510. e.preventDefault();
  25511. return false;
  25512. }
  25513. }
  25514. }
  25515. });
  25516. };
  25517. var removeBlockQuoteOnBackSpace = function () {
  25518. editor.on('keydown', function (e) {
  25519. var rng, parent;
  25520. if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) {
  25521. return;
  25522. }
  25523. rng = selection.getRng();
  25524. var container = rng.startContainer;
  25525. var offset = rng.startOffset;
  25526. var root = dom.getRoot();
  25527. parent = container;
  25528. if (!rng.collapsed || offset !== 0) {
  25529. return;
  25530. }
  25531. while (parent && parent.parentNode && parent.parentNode.firstChild === parent && parent.parentNode !== root) {
  25532. parent = parent.parentNode;
  25533. }
  25534. if (parent.tagName === 'BLOCKQUOTE') {
  25535. editor.formatter.toggle('blockquote', null, parent);
  25536. rng = dom.createRng();
  25537. rng.setStart(container, 0);
  25538. rng.setEnd(container, 0);
  25539. selection.setRng(rng);
  25540. }
  25541. });
  25542. };
  25543. var setGeckoEditingOptions = function () {
  25544. var setOpts = function () {
  25545. setEditorCommandState('StyleWithCSS', false);
  25546. setEditorCommandState('enableInlineTableEditing', false);
  25547. if (!getObjectResizing(editor)) {
  25548. setEditorCommandState('enableObjectResizing', false);
  25549. }
  25550. };
  25551. if (!isReadOnly(editor)) {
  25552. editor.on('BeforeExecCommand mousedown', setOpts);
  25553. }
  25554. };
  25555. var addBrAfterLastLinks = function () {
  25556. var fixLinks = function () {
  25557. each(dom.select('a'), function (node) {
  25558. var parentNode = node.parentNode;
  25559. var root = dom.getRoot();
  25560. if (parentNode.lastChild === node) {
  25561. while (parentNode && !dom.isBlock(parentNode)) {
  25562. if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
  25563. return;
  25564. }
  25565. parentNode = parentNode.parentNode;
  25566. }
  25567. dom.add(parentNode, 'br', { 'data-mce-bogus': 1 });
  25568. }
  25569. });
  25570. };
  25571. editor.on('SetContent ExecCommand', function (e) {
  25572. if (e.type === 'setcontent' || e.command === 'mceInsertLink') {
  25573. fixLinks();
  25574. }
  25575. });
  25576. };
  25577. var setDefaultBlockType = function () {
  25578. if (getForcedRootBlock(editor)) {
  25579. editor.on('init', function () {
  25580. setEditorCommandState('DefaultParagraphSeparator', getForcedRootBlock(editor));
  25581. });
  25582. }
  25583. };
  25584. var normalizeSelection = function () {
  25585. editor.on('keyup focusin mouseup', function (e) {
  25586. if (!VK.modifierPressed(e)) {
  25587. selection.normalize();
  25588. }
  25589. }, true);
  25590. };
  25591. var showBrokenImageIcon = function () {
  25592. editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}');
  25593. };
  25594. var restoreFocusOnKeyDown = function () {
  25595. if (!editor.inline) {
  25596. editor.on('keydown', function () {
  25597. if (document.activeElement === document.body) {
  25598. editor.getWin().focus();
  25599. }
  25600. });
  25601. }
  25602. };
  25603. var bodyHeight = function () {
  25604. if (!editor.inline) {
  25605. editor.contentStyles.push('body {min-height: 150px}');
  25606. editor.on('click', function (e) {
  25607. var rng;
  25608. if (e.target.nodeName === 'HTML') {
  25609. if (Env.ie > 11) {
  25610. editor.getBody().focus();
  25611. return;
  25612. }
  25613. rng = editor.selection.getRng();
  25614. editor.getBody().focus();
  25615. editor.selection.setRng(rng);
  25616. editor.selection.normalize();
  25617. editor.nodeChanged();
  25618. }
  25619. });
  25620. }
  25621. };
  25622. var blockCmdArrowNavigation = function () {
  25623. if (Env.mac) {
  25624. editor.on('keydown', function (e) {
  25625. if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) {
  25626. e.preventDefault();
  25627. var selection_1 = editor.selection.getSel();
  25628. selection_1.modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary');
  25629. }
  25630. });
  25631. }
  25632. };
  25633. var disableAutoUrlDetect = function () {
  25634. setEditorCommandState('AutoUrlDetect', false);
  25635. };
  25636. var tapLinksAndImages = function () {
  25637. editor.on('click', function (e) {
  25638. var elm = e.target;
  25639. do {
  25640. if (elm.tagName === 'A') {
  25641. e.preventDefault();
  25642. return;
  25643. }
  25644. } while (elm = elm.parentNode);
  25645. });
  25646. editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
  25647. };
  25648. var blockFormSubmitInsideEditor = function () {
  25649. editor.on('init', function () {
  25650. editor.dom.bind(editor.getBody(), 'submit', function (e) {
  25651. e.preventDefault();
  25652. });
  25653. });
  25654. };
  25655. var removeAppleInterchangeBrs = function () {
  25656. parser.addNodeFilter('br', function (nodes) {
  25657. var i = nodes.length;
  25658. while (i--) {
  25659. if (nodes[i].attr('class') === 'Apple-interchange-newline') {
  25660. nodes[i].remove();
  25661. }
  25662. }
  25663. });
  25664. };
  25665. var ieInternalDragAndDrop = function () {
  25666. editor.on('dragstart', function (e) {
  25667. setMceInternalContent(e);
  25668. });
  25669. editor.on('drop', function (e) {
  25670. if (!isDefaultPrevented(e)) {
  25671. var internalContent = getMceInternalContent(e);
  25672. if (internalContent && internalContent.id !== editor.id) {
  25673. e.preventDefault();
  25674. var rng = fromPoint$1(e.x, e.y, editor.getDoc());
  25675. selection.setRng(rng);
  25676. insertClipboardContents(internalContent.html, true);
  25677. }
  25678. }
  25679. });
  25680. };
  25681. var refreshContentEditable = function () {
  25682. };
  25683. var isHidden = function () {
  25684. if (!isGecko || editor.removed) {
  25685. return false;
  25686. }
  25687. var sel = editor.selection.getSel();
  25688. return !sel || !sel.rangeCount || sel.rangeCount === 0;
  25689. };
  25690. removeBlockQuoteOnBackSpace();
  25691. emptyEditorWhenDeleting();
  25692. if (!Env.windowsPhone) {
  25693. normalizeSelection();
  25694. }
  25695. if (isWebKit) {
  25696. inputMethodFocus();
  25697. selectControlElements();
  25698. setDefaultBlockType();
  25699. blockFormSubmitInsideEditor();
  25700. disableBackspaceIntoATable();
  25701. removeAppleInterchangeBrs();
  25702. if (Env.iOS) {
  25703. restoreFocusOnKeyDown();
  25704. bodyHeight();
  25705. tapLinksAndImages();
  25706. } else {
  25707. selectAll();
  25708. }
  25709. }
  25710. if (Env.ie >= 11) {
  25711. bodyHeight();
  25712. disableBackspaceIntoATable();
  25713. }
  25714. if (Env.ie) {
  25715. selectAll();
  25716. disableAutoUrlDetect();
  25717. ieInternalDragAndDrop();
  25718. }
  25719. if (isGecko) {
  25720. removeHrOnBackspace();
  25721. focusBody();
  25722. removeStylesWhenDeletingAcrossBlockElements();
  25723. setGeckoEditingOptions();
  25724. addBrAfterLastLinks();
  25725. showBrokenImageIcon();
  25726. blockCmdArrowNavigation();
  25727. disableBackspaceIntoATable();
  25728. }
  25729. return {
  25730. refreshContentEditable: refreshContentEditable,
  25731. isHidden: isHidden
  25732. };
  25733. };
  25734. var DOM$4 = DOMUtils$1.DOM;
  25735. var appendStyle = function (editor, text) {
  25736. var body = SugarElement.fromDom(editor.getBody());
  25737. var container = getStyleContainer(getRootNode(body));
  25738. var style = SugarElement.fromTag('style');
  25739. set(style, 'type', 'text/css');
  25740. append(style, SugarElement.fromText(text));
  25741. append(container, style);
  25742. editor.on('remove', function () {
  25743. remove(style);
  25744. });
  25745. };
  25746. var getRootName = function (editor) {
  25747. return editor.inline ? editor.getElement().nodeName.toLowerCase() : undefined;
  25748. };
  25749. var removeUndefined = function (obj) {
  25750. return filter$1(obj, function (v) {
  25751. return isUndefined(v) === false;
  25752. });
  25753. };
  25754. var mkParserSettings = function (editor) {
  25755. var settings = editor.settings;
  25756. var blobCache = editor.editorUpload.blobCache;
  25757. return removeUndefined({
  25758. allow_conditional_comments: settings.allow_conditional_comments,
  25759. allow_html_data_urls: settings.allow_html_data_urls,
  25760. allow_svg_data_urls: settings.allow_svg_data_urls,
  25761. allow_html_in_named_anchor: settings.allow_html_in_named_anchor,
  25762. allow_script_urls: settings.allow_script_urls,
  25763. allow_unsafe_link_target: settings.allow_unsafe_link_target,
  25764. convert_fonts_to_spans: settings.convert_fonts_to_spans,
  25765. fix_list_elements: settings.fix_list_elements,
  25766. font_size_legacy_values: settings.font_size_legacy_values,
  25767. forced_root_block: settings.forced_root_block,
  25768. forced_root_block_attrs: settings.forced_root_block_attrs,
  25769. padd_empty_with_br: settings.padd_empty_with_br,
  25770. preserve_cdata: settings.preserve_cdata,
  25771. remove_trailing_brs: settings.remove_trailing_brs,
  25772. inline_styles: settings.inline_styles,
  25773. root_name: getRootName(editor),
  25774. validate: true,
  25775. blob_cache: blobCache,
  25776. images_dataimg_filter: settings.images_dataimg_filter
  25777. });
  25778. };
  25779. var mkSerializerSettings = function (editor) {
  25780. var settings = editor.settings;
  25781. return __assign(__assign({}, mkParserSettings(editor)), removeUndefined({
  25782. url_converter: settings.url_converter,
  25783. url_converter_scope: settings.url_converter_scope,
  25784. element_format: settings.element_format,
  25785. entities: settings.entities,
  25786. entity_encoding: settings.entity_encoding,
  25787. indent: settings.indent,
  25788. indent_after: settings.indent_after,
  25789. indent_before: settings.indent_before,
  25790. block_elements: settings.block_elements,
  25791. boolean_attributes: settings.boolean_attributes,
  25792. custom_elements: settings.custom_elements,
  25793. extended_valid_elements: settings.extended_valid_elements,
  25794. invalid_elements: settings.invalid_elements,
  25795. invalid_styles: settings.invalid_styles,
  25796. move_caret_before_on_enter_elements: settings.move_caret_before_on_enter_elements,
  25797. non_empty_elements: settings.non_empty_elements,
  25798. schema: settings.schema,
  25799. self_closing_elements: settings.self_closing_elements,
  25800. short_ended_elements: settings.short_ended_elements,
  25801. special: settings.special,
  25802. text_block_elements: settings.text_block_elements,
  25803. text_inline_elements: settings.text_inline_elements,
  25804. valid_children: settings.valid_children,
  25805. valid_classes: settings.valid_classes,
  25806. valid_elements: settings.valid_elements,
  25807. valid_styles: settings.valid_styles,
  25808. verify_html: settings.verify_html,
  25809. whitespace_elements: settings.whitespace_elements
  25810. }));
  25811. };
  25812. var createParser = function (editor) {
  25813. var parser = DomParser(mkParserSettings(editor), editor.schema);
  25814. parser.addAttributeFilter('src,href,style,tabindex', function (nodes, name) {
  25815. var i = nodes.length, node, value;
  25816. var dom = editor.dom;
  25817. var internalName = 'data-mce-' + name;
  25818. while (i--) {
  25819. node = nodes[i];
  25820. value = node.attr(name);
  25821. if (value && !node.attr(internalName)) {
  25822. if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) {
  25823. continue;
  25824. }
  25825. if (name === 'style') {
  25826. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  25827. if (!value.length) {
  25828. value = null;
  25829. }
  25830. node.attr(internalName, value);
  25831. node.attr(name, value);
  25832. } else if (name === 'tabindex') {
  25833. node.attr(internalName, value);
  25834. node.attr(name, null);
  25835. } else {
  25836. node.attr(internalName, editor.convertURL(value, name, node.name));
  25837. }
  25838. }
  25839. }
  25840. });
  25841. parser.addNodeFilter('script', function (nodes) {
  25842. var i = nodes.length;
  25843. while (i--) {
  25844. var node = nodes[i];
  25845. var type = node.attr('type') || 'no/type';
  25846. if (type.indexOf('mce-') !== 0) {
  25847. node.attr('type', 'mce-' + type);
  25848. }
  25849. }
  25850. });
  25851. if (editor.settings.preserve_cdata) {
  25852. parser.addNodeFilter('#cdata', function (nodes) {
  25853. var i = nodes.length;
  25854. while (i--) {
  25855. var node = nodes[i];
  25856. node.type = 8;
  25857. node.name = '#comment';
  25858. node.value = '[CDATA[' + editor.dom.encode(node.value) + ']]';
  25859. }
  25860. });
  25861. }
  25862. parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function (nodes) {
  25863. var i = nodes.length;
  25864. var nonEmptyElements = editor.schema.getNonEmptyElements();
  25865. while (i--) {
  25866. var node = nodes[i];
  25867. if (node.isEmpty(nonEmptyElements) && node.getAll('br').length === 0) {
  25868. node.append(new AstNode('br', 1)).shortEnded = true;
  25869. }
  25870. }
  25871. });
  25872. return parser;
  25873. };
  25874. var autoFocus = function (editor) {
  25875. if (editor.settings.auto_focus) {
  25876. Delay.setEditorTimeout(editor, function () {
  25877. var focusEditor;
  25878. if (editor.settings.auto_focus === true) {
  25879. focusEditor = editor;
  25880. } else {
  25881. focusEditor = editor.editorManager.get(editor.settings.auto_focus);
  25882. }
  25883. if (!focusEditor.destroyed) {
  25884. focusEditor.focus();
  25885. }
  25886. }, 100);
  25887. }
  25888. };
  25889. var moveSelectionToFirstCaretPosition = function (editor) {
  25890. var root = editor.dom.getRoot();
  25891. if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) {
  25892. firstPositionIn(root).each(function (pos) {
  25893. var node = pos.getNode();
  25894. var caretPos = isTable(node) ? firstPositionIn(node).getOr(pos) : pos;
  25895. if (Env.browser.isIE()) {
  25896. storeNative(editor, caretPos.toRange());
  25897. } else {
  25898. editor.selection.setRng(caretPos.toRange());
  25899. }
  25900. });
  25901. }
  25902. };
  25903. var initEditor = function (editor) {
  25904. editor.bindPendingEventDelegates();
  25905. editor.initialized = true;
  25906. fireInit(editor);
  25907. editor.focus(true);
  25908. moveSelectionToFirstCaretPosition(editor);
  25909. editor.nodeChanged({ initial: true });
  25910. editor.execCallback('init_instance_callback', editor);
  25911. autoFocus(editor);
  25912. };
  25913. var getStyleSheetLoader = function (editor) {
  25914. return editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader;
  25915. };
  25916. var loadContentCss = function (editor, css) {
  25917. var styleSheetLoader = getStyleSheetLoader(editor);
  25918. var loaded = function () {
  25919. editor.on('remove', function () {
  25920. return styleSheetLoader.unloadAll(css);
  25921. });
  25922. initEditor(editor);
  25923. };
  25924. styleSheetLoader.loadAll(css, loaded, loaded);
  25925. };
  25926. var preInit = function (editor, rtcMode) {
  25927. var settings = editor.settings, doc = editor.getDoc(), body = editor.getBody();
  25928. if (!settings.browser_spellcheck && !settings.gecko_spellcheck) {
  25929. doc.body.spellcheck = false;
  25930. DOM$4.setAttrib(body, 'spellcheck', 'false');
  25931. }
  25932. editor.quirks = Quirks(editor);
  25933. firePostRender(editor);
  25934. var directionality = getDirectionality(editor);
  25935. if (directionality !== undefined) {
  25936. body.dir = directionality;
  25937. }
  25938. if (settings.protect) {
  25939. editor.on('BeforeSetContent', function (e) {
  25940. Tools.each(settings.protect, function (pattern) {
  25941. e.content = e.content.replace(pattern, function (str) {
  25942. return '<!--mce:protected ' + escape(str) + '-->';
  25943. });
  25944. });
  25945. });
  25946. }
  25947. editor.on('SetContent', function () {
  25948. editor.addVisual(editor.getBody());
  25949. });
  25950. if (rtcMode === false) {
  25951. editor.load({
  25952. initial: true,
  25953. format: 'html'
  25954. });
  25955. }
  25956. editor.startContent = editor.getContent({ format: 'raw' });
  25957. editor.on('compositionstart compositionend', function (e) {
  25958. editor.composing = e.type === 'compositionstart';
  25959. });
  25960. if (editor.contentStyles.length > 0) {
  25961. var contentCssText_1 = '';
  25962. Tools.each(editor.contentStyles, function (style) {
  25963. contentCssText_1 += style + '\r\n';
  25964. });
  25965. editor.dom.addStyle(contentCssText_1);
  25966. }
  25967. loadContentCss(editor, editor.contentCSS);
  25968. if (settings.content_style) {
  25969. appendStyle(editor, settings.content_style);
  25970. }
  25971. };
  25972. var initContentBody = function (editor, skipWrite) {
  25973. var settings = editor.settings;
  25974. var targetElm = editor.getElement();
  25975. var doc = editor.getDoc();
  25976. if (!settings.inline) {
  25977. editor.getElement().style.visibility = editor.orgVisibility;
  25978. }
  25979. if (!skipWrite && !editor.inline) {
  25980. doc.open();
  25981. doc.write(editor.iframeHTML);
  25982. doc.close();
  25983. }
  25984. if (editor.inline) {
  25985. DOM$4.addClass(targetElm, 'mce-content-body');
  25986. editor.contentDocument = doc = document;
  25987. editor.contentWindow = window;
  25988. editor.bodyElement = targetElm;
  25989. editor.contentAreaContainer = targetElm;
  25990. }
  25991. var body = editor.getBody();
  25992. body.disabled = true;
  25993. editor.readonly = !!settings.readonly;
  25994. if (!editor.readonly) {
  25995. if (editor.inline && DOM$4.getStyle(body, 'position', true) === 'static') {
  25996. body.style.position = 'relative';
  25997. }
  25998. body.contentEditable = editor.getParam('content_editable_state', true);
  25999. }
  26000. body.disabled = false;
  26001. editor.editorUpload = EditorUpload(editor);
  26002. editor.schema = Schema(settings);
  26003. editor.dom = DOMUtils$1(doc, {
  26004. keep_values: true,
  26005. url_converter: editor.convertURL,
  26006. url_converter_scope: editor,
  26007. hex_colors: settings.force_hex_style_colors,
  26008. update_styles: true,
  26009. root_element: editor.inline ? editor.getBody() : null,
  26010. collect: function () {
  26011. return editor.inline;
  26012. },
  26013. schema: editor.schema,
  26014. contentCssCors: shouldUseContentCssCors(editor),
  26015. referrerPolicy: getReferrerPolicy(editor),
  26016. onSetAttrib: function (e) {
  26017. editor.fire('SetAttrib', e);
  26018. }
  26019. });
  26020. editor.parser = createParser(editor);
  26021. editor.serializer = DomSerializer(mkSerializerSettings(editor), editor);
  26022. editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor);
  26023. editor.annotator = Annotator(editor);
  26024. editor.formatter = Formatter(editor);
  26025. editor.undoManager = UndoManager(editor);
  26026. editor._nodeChangeDispatcher = new NodeChange(editor);
  26027. editor._selectionOverrides = SelectionOverrides(editor);
  26028. setup$9(editor);
  26029. setup$j(editor);
  26030. if (!isRtc(editor)) {
  26031. setup$k(editor);
  26032. }
  26033. var caret = setup$i(editor);
  26034. setup$8(editor, caret);
  26035. setup$a(editor);
  26036. setup$7(editor);
  26037. firePreInit(editor);
  26038. setup$5(editor).fold(function () {
  26039. preInit(editor, false);
  26040. }, function (loadingRtc) {
  26041. editor.setProgressState(true);
  26042. loadingRtc.then(function (rtcMode) {
  26043. editor.setProgressState(false);
  26044. preInit(editor, rtcMode);
  26045. });
  26046. });
  26047. };
  26048. var DOM$5 = DOMUtils$1.DOM;
  26049. var relaxDomain = function (editor, ifr) {
  26050. if (document.domain !== window.location.hostname && Env.browser.isIE()) {
  26051. var bodyUuid = uuid('mce');
  26052. editor[bodyUuid] = function () {
  26053. initContentBody(editor);
  26054. };
  26055. 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);})()';
  26056. DOM$5.setAttrib(ifr, 'src', domainRelaxUrl);
  26057. return true;
  26058. }
  26059. return false;
  26060. };
  26061. var createIframeElement = function (id, title, height, customAttrs) {
  26062. var iframe = SugarElement.fromTag('iframe');
  26063. setAll(iframe, customAttrs);
  26064. setAll(iframe, {
  26065. id: id + '_ifr',
  26066. frameBorder: '0',
  26067. allowTransparency: 'true',
  26068. title: title
  26069. });
  26070. add$3(iframe, 'tox-edit-area__iframe');
  26071. return iframe;
  26072. };
  26073. var getIframeHtml = function (editor) {
  26074. var iframeHTML = getDocType(editor) + '<html><head>';
  26075. if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
  26076. iframeHTML += '<base href="' + editor.documentBaseURI.getURI() + '" />';
  26077. }
  26078. iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
  26079. var bodyId = getBodyId(editor);
  26080. var bodyClass = getBodyClass(editor);
  26081. if (getContentSecurityPolicy(editor)) {
  26082. iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + getContentSecurityPolicy(editor) + '" />';
  26083. }
  26084. iframeHTML += '</head><body id="' + bodyId + '" class="mce-content-body ' + bodyClass + '" data-id="' + editor.id + '"><br></body></html>';
  26085. return iframeHTML;
  26086. };
  26087. var createIframe = function (editor, o) {
  26088. var title = editor.editorManager.translate('Rich Text Area. Press ALT-0 for help.');
  26089. var ifr = createIframeElement(editor.id, title, o.height, getIframeAttrs(editor)).dom;
  26090. ifr.onload = function () {
  26091. ifr.onload = null;
  26092. editor.fire('load');
  26093. };
  26094. var isDomainRelaxed = relaxDomain(editor, ifr);
  26095. editor.contentAreaContainer = o.iframeContainer;
  26096. editor.iframeElement = ifr;
  26097. editor.iframeHTML = getIframeHtml(editor);
  26098. DOM$5.add(o.iframeContainer, ifr);
  26099. return isDomainRelaxed;
  26100. };
  26101. var init$1 = function (editor, boxInfo) {
  26102. var isDomainRelaxed = createIframe(editor, boxInfo);
  26103. if (boxInfo.editorContainer) {
  26104. DOM$5.get(boxInfo.editorContainer).style.display = editor.orgDisplay;
  26105. editor.hidden = DOM$5.isHidden(boxInfo.editorContainer);
  26106. }
  26107. editor.getElement().style.display = 'none';
  26108. DOM$5.setAttrib(editor.id, 'aria-hidden', 'true');
  26109. if (!isDomainRelaxed) {
  26110. initContentBody(editor);
  26111. }
  26112. };
  26113. var DOM$6 = DOMUtils$1.DOM;
  26114. var initPlugin = function (editor, initializedPlugins, plugin) {
  26115. var Plugin = PluginManager.get(plugin);
  26116. var pluginUrl = PluginManager.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, '');
  26117. plugin = Tools.trim(plugin);
  26118. if (Plugin && Tools.inArray(initializedPlugins, plugin) === -1) {
  26119. Tools.each(PluginManager.dependencies(plugin), function (dep) {
  26120. initPlugin(editor, initializedPlugins, dep);
  26121. });
  26122. if (editor.plugins[plugin]) {
  26123. return;
  26124. }
  26125. try {
  26126. var pluginInstance = new Plugin(editor, pluginUrl, editor.$);
  26127. editor.plugins[plugin] = pluginInstance;
  26128. if (pluginInstance.init) {
  26129. pluginInstance.init(editor, pluginUrl);
  26130. initializedPlugins.push(plugin);
  26131. }
  26132. } catch (e) {
  26133. pluginInitError(editor, plugin, e);
  26134. }
  26135. }
  26136. };
  26137. var trimLegacyPrefix = function (name) {
  26138. return name.replace(/^\-/, '');
  26139. };
  26140. var initPlugins = function (editor) {
  26141. var initializedPlugins = [];
  26142. Tools.each(getPlugins(editor).split(/[ ,]/), function (name) {
  26143. initPlugin(editor, initializedPlugins, trimLegacyPrefix(name));
  26144. });
  26145. };
  26146. var initIcons = function (editor) {
  26147. var iconPackName = Tools.trim(getIconPackName(editor));
  26148. var currentIcons = editor.ui.registry.getAll().icons;
  26149. var loadIcons = __assign(__assign({}, IconManager.get('default').icons), IconManager.get(iconPackName).icons);
  26150. each$1(loadIcons, function (svgData, icon) {
  26151. if (!has(currentIcons, icon)) {
  26152. editor.ui.registry.addIcon(icon, svgData);
  26153. }
  26154. });
  26155. };
  26156. var initTheme = function (editor) {
  26157. var theme = getTheme(editor);
  26158. if (isString(theme)) {
  26159. editor.settings.theme = trimLegacyPrefix(theme);
  26160. var Theme = ThemeManager.get(theme);
  26161. editor.theme = new Theme(editor, ThemeManager.urls[theme]);
  26162. if (editor.theme.init) {
  26163. editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ''), editor.$);
  26164. }
  26165. } else {
  26166. editor.theme = {};
  26167. }
  26168. };
  26169. var renderFromLoadedTheme = function (editor) {
  26170. return editor.theme.renderUI();
  26171. };
  26172. var renderFromThemeFunc = function (editor) {
  26173. var elm = editor.getElement();
  26174. var theme = getTheme(editor);
  26175. var info = theme(editor, elm);
  26176. if (info.editorContainer.nodeType) {
  26177. info.editorContainer.id = info.editorContainer.id || editor.id + '_parent';
  26178. }
  26179. if (info.iframeContainer && info.iframeContainer.nodeType) {
  26180. info.iframeContainer.id = info.iframeContainer.id || editor.id + '_iframecontainer';
  26181. }
  26182. info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
  26183. return info;
  26184. };
  26185. var createThemeFalseResult = function (element) {
  26186. return {
  26187. editorContainer: element,
  26188. iframeContainer: element,
  26189. api: {}
  26190. };
  26191. };
  26192. var renderThemeFalseIframe = function (targetElement) {
  26193. var iframeContainer = DOM$6.create('div');
  26194. DOM$6.insertAfter(iframeContainer, targetElement);
  26195. return createThemeFalseResult(iframeContainer);
  26196. };
  26197. var renderThemeFalse = function (editor) {
  26198. var targetElement = editor.getElement();
  26199. return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
  26200. };
  26201. var renderThemeUi = function (editor) {
  26202. var elm = editor.getElement();
  26203. editor.orgDisplay = elm.style.display;
  26204. if (isString(getTheme(editor))) {
  26205. return renderFromLoadedTheme(editor);
  26206. } else if (isFunction(getTheme(editor))) {
  26207. return renderFromThemeFunc(editor);
  26208. } else {
  26209. return renderThemeFalse(editor);
  26210. }
  26211. };
  26212. var augmentEditorUiApi = function (editor, api) {
  26213. var uiApiFacade = {
  26214. show: Optional.from(api.show).getOr(noop),
  26215. hide: Optional.from(api.hide).getOr(noop),
  26216. disable: Optional.from(api.disable).getOr(noop),
  26217. isDisabled: Optional.from(api.isDisabled).getOr(never),
  26218. enable: function () {
  26219. if (!editor.mode.isReadOnly()) {
  26220. Optional.from(api.enable).map(call);
  26221. }
  26222. }
  26223. };
  26224. editor.ui = __assign(__assign({}, editor.ui), uiApiFacade);
  26225. };
  26226. var init$2 = function (editor) {
  26227. editor.fire('ScriptsLoaded');
  26228. initIcons(editor);
  26229. initTheme(editor);
  26230. initPlugins(editor);
  26231. var renderInfo = renderThemeUi(editor);
  26232. augmentEditorUiApi(editor, Optional.from(renderInfo.api).getOr({}));
  26233. var boxInfo = {
  26234. editorContainer: renderInfo.editorContainer,
  26235. iframeContainer: renderInfo.iframeContainer
  26236. };
  26237. editor.editorContainer = boxInfo.editorContainer ? boxInfo.editorContainer : null;
  26238. appendContentCssFromSettings(editor);
  26239. if (editor.inline) {
  26240. return initContentBody(editor);
  26241. } else {
  26242. return init$1(editor, boxInfo);
  26243. }
  26244. };
  26245. var DOM$7 = DOMUtils$1.DOM;
  26246. var hasSkipLoadPrefix = function (name) {
  26247. return name.charAt(0) === '-';
  26248. };
  26249. var loadLanguage = function (scriptLoader, editor) {
  26250. var languageCode = getLanguageCode(editor);
  26251. var languageUrl = getLanguageUrl(editor);
  26252. if (I18n.hasCode(languageCode) === false && languageCode !== 'en') {
  26253. var url_1 = languageUrl !== '' ? languageUrl : editor.editorManager.baseURL + '/langs/' + languageCode + '.js';
  26254. scriptLoader.add(url_1, noop, undefined, function () {
  26255. languageLoadError(editor, url_1, languageCode);
  26256. });
  26257. }
  26258. };
  26259. var loadTheme = function (scriptLoader, editor, suffix, callback) {
  26260. var theme = getTheme(editor);
  26261. if (isString(theme)) {
  26262. if (!hasSkipLoadPrefix(theme) && !ThemeManager.urls.hasOwnProperty(theme)) {
  26263. var themeUrl = getThemeUrl(editor);
  26264. if (themeUrl) {
  26265. ThemeManager.load(theme, editor.documentBaseURI.toAbsolute(themeUrl));
  26266. } else {
  26267. ThemeManager.load(theme, 'themes/' + theme + '/theme' + suffix + '.js');
  26268. }
  26269. }
  26270. scriptLoader.loadQueue(function () {
  26271. ThemeManager.waitFor(theme, callback);
  26272. });
  26273. } else {
  26274. callback();
  26275. }
  26276. };
  26277. var getIconsUrlMetaFromUrl = function (editor) {
  26278. return Optional.from(getIconsUrl(editor)).filter(function (url) {
  26279. return url.length > 0;
  26280. }).map(function (url) {
  26281. return {
  26282. url: url,
  26283. name: Optional.none()
  26284. };
  26285. });
  26286. };
  26287. var getIconsUrlMetaFromName = function (editor, name, suffix) {
  26288. return Optional.from(name).filter(function (name) {
  26289. return name.length > 0 && !IconManager.has(name);
  26290. }).map(function (name) {
  26291. return {
  26292. url: editor.editorManager.baseURL + '/icons/' + name + '/icons' + suffix + '.js',
  26293. name: Optional.some(name)
  26294. };
  26295. });
  26296. };
  26297. var loadIcons = function (scriptLoader, editor, suffix) {
  26298. var defaultIconsUrl = getIconsUrlMetaFromName(editor, 'default', suffix);
  26299. var customIconsUrl = getIconsUrlMetaFromUrl(editor).orThunk(function () {
  26300. return getIconsUrlMetaFromName(editor, getIconPackName(editor), '');
  26301. });
  26302. each(cat([
  26303. defaultIconsUrl,
  26304. customIconsUrl
  26305. ]), function (urlMeta) {
  26306. scriptLoader.add(urlMeta.url, noop, undefined, function () {
  26307. iconsLoadError(editor, urlMeta.url, urlMeta.name.getOrUndefined());
  26308. });
  26309. });
  26310. };
  26311. var loadPlugins = function (editor, suffix) {
  26312. Tools.each(getExternalPlugins(editor), function (url, name) {
  26313. PluginManager.load(name, url, noop, undefined, function () {
  26314. pluginLoadError(editor, url, name);
  26315. });
  26316. editor.settings.plugins += ' ' + name;
  26317. });
  26318. Tools.each(getPlugins(editor).split(/[ ,]/), function (plugin) {
  26319. plugin = Tools.trim(plugin);
  26320. if (plugin && !PluginManager.urls[plugin]) {
  26321. if (hasSkipLoadPrefix(plugin)) {
  26322. plugin = plugin.substr(1, plugin.length);
  26323. var dependencies = PluginManager.dependencies(plugin);
  26324. Tools.each(dependencies, function (depPlugin) {
  26325. var defaultSettings = {
  26326. prefix: 'plugins/',
  26327. resource: depPlugin,
  26328. suffix: '/plugin' + suffix + '.js'
  26329. };
  26330. var dep = PluginManager.createUrl(defaultSettings, depPlugin);
  26331. PluginManager.load(dep.resource, dep, noop, undefined, function () {
  26332. pluginLoadError(editor, dep.prefix + dep.resource + dep.suffix, dep.resource);
  26333. });
  26334. });
  26335. } else {
  26336. var url_2 = {
  26337. prefix: 'plugins/',
  26338. resource: plugin,
  26339. suffix: '/plugin' + suffix + '.js'
  26340. };
  26341. PluginManager.load(plugin, url_2, noop, undefined, function () {
  26342. pluginLoadError(editor, url_2.prefix + url_2.resource + url_2.suffix, plugin);
  26343. });
  26344. }
  26345. }
  26346. });
  26347. };
  26348. var loadScripts = function (editor, suffix) {
  26349. var scriptLoader = ScriptLoader.ScriptLoader;
  26350. loadTheme(scriptLoader, editor, suffix, function () {
  26351. loadLanguage(scriptLoader, editor);
  26352. loadIcons(scriptLoader, editor, suffix);
  26353. loadPlugins(editor, suffix);
  26354. scriptLoader.loadQueue(function () {
  26355. if (!editor.removed) {
  26356. init$2(editor);
  26357. }
  26358. }, editor, function () {
  26359. if (!editor.removed) {
  26360. init$2(editor);
  26361. }
  26362. });
  26363. });
  26364. };
  26365. var getStyleSheetLoader$1 = function (element, editor) {
  26366. return instance.forElement(element, {
  26367. contentCssCors: hasContentCssCors(editor),
  26368. referrerPolicy: getReferrerPolicy(editor)
  26369. });
  26370. };
  26371. var render = function (editor) {
  26372. var id = editor.id;
  26373. I18n.setCode(getLanguageCode(editor));
  26374. var readyHandler = function () {
  26375. DOM$7.unbind(window, 'ready', readyHandler);
  26376. editor.render();
  26377. };
  26378. if (!EventUtils.Event.domLoaded) {
  26379. DOM$7.bind(window, 'ready', readyHandler);
  26380. return;
  26381. }
  26382. if (!editor.getElement()) {
  26383. return;
  26384. }
  26385. if (!Env.contentEditable) {
  26386. return;
  26387. }
  26388. var element = SugarElement.fromDom(editor.getElement());
  26389. var snapshot = clone(element);
  26390. editor.on('remove', function () {
  26391. eachr(element.dom.attributes, function (attr) {
  26392. return remove$1(element, attr.name);
  26393. });
  26394. setAll(element, snapshot);
  26395. });
  26396. editor.ui.styleSheetLoader = getStyleSheetLoader$1(element, editor);
  26397. if (!isInline$1(editor)) {
  26398. editor.orgVisibility = editor.getElement().style.visibility;
  26399. editor.getElement().style.visibility = 'hidden';
  26400. } else {
  26401. editor.inline = true;
  26402. }
  26403. var form = editor.getElement().form || DOM$7.getParent(id, 'form');
  26404. if (form) {
  26405. editor.formElement = form;
  26406. if (hasHiddenInput(editor) && !isTextareaOrInput(editor.getElement())) {
  26407. DOM$7.insertAfter(DOM$7.create('input', {
  26408. type: 'hidden',
  26409. name: id
  26410. }), id);
  26411. editor.hasHiddenInput = true;
  26412. }
  26413. editor.formEventDelegate = function (e) {
  26414. editor.fire(e.type, e);
  26415. };
  26416. DOM$7.bind(form, 'submit reset', editor.formEventDelegate);
  26417. editor.on('reset', function () {
  26418. editor.resetContent();
  26419. });
  26420. if (shouldPatchSubmit(editor) && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
  26421. form._mceOldSubmit = form.submit;
  26422. form.submit = function () {
  26423. editor.editorManager.triggerSave();
  26424. editor.setDirty(false);
  26425. return form._mceOldSubmit(form);
  26426. };
  26427. }
  26428. }
  26429. editor.windowManager = WindowManager(editor);
  26430. editor.notificationManager = NotificationManager(editor);
  26431. if (isEncodingXml(editor)) {
  26432. editor.on('GetContent', function (e) {
  26433. if (e.save) {
  26434. e.content = DOM$7.encode(e.content);
  26435. }
  26436. });
  26437. }
  26438. if (shouldAddFormSubmitTrigger(editor)) {
  26439. editor.on('submit', function () {
  26440. if (editor.initialized) {
  26441. editor.save();
  26442. }
  26443. });
  26444. }
  26445. if (shouldAddUnloadTrigger(editor)) {
  26446. editor._beforeUnload = function () {
  26447. if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
  26448. editor.save({
  26449. format: 'raw',
  26450. no_events: true,
  26451. set_dirty: false
  26452. });
  26453. }
  26454. };
  26455. editor.editorManager.on('BeforeUnload', editor._beforeUnload);
  26456. }
  26457. editor.editorManager.add(editor);
  26458. loadScripts(editor, editor.suffix);
  26459. };
  26460. var addVisual$1 = function (editor, elm) {
  26461. return addVisual(editor, elm);
  26462. };
  26463. var legacyPropNames = {
  26464. 'font-size': 'size',
  26465. 'font-family': 'face'
  26466. };
  26467. var getSpecifiedFontProp = function (propName, rootElm, elm) {
  26468. var getProperty = function (elm) {
  26469. return getRaw(elm, propName).orThunk(function () {
  26470. if (name(elm) === 'font') {
  26471. return get$1(legacyPropNames, propName).bind(function (legacyPropName) {
  26472. return getOpt(elm, legacyPropName);
  26473. });
  26474. } else {
  26475. return Optional.none();
  26476. }
  26477. });
  26478. };
  26479. var isRoot = function (elm) {
  26480. return eq$2(SugarElement.fromDom(rootElm), elm);
  26481. };
  26482. return closest$2(SugarElement.fromDom(elm), function (elm) {
  26483. return getProperty(elm);
  26484. }, isRoot);
  26485. };
  26486. var normalizeFontFamily = function (fontFamily) {
  26487. return fontFamily.replace(/[\'\"\\]/g, '').replace(/,\s+/g, ',');
  26488. };
  26489. var getComputedFontProp = function (propName, elm) {
  26490. return Optional.from(DOMUtils$1.DOM.getStyle(elm, propName, true));
  26491. };
  26492. var getFontProp = function (propName) {
  26493. return function (rootElm, elm) {
  26494. return Optional.from(elm).map(SugarElement.fromDom).filter(isElement).bind(function (element) {
  26495. return getSpecifiedFontProp(propName, rootElm, element.dom).or(getComputedFontProp(propName, element.dom));
  26496. }).getOr('');
  26497. };
  26498. };
  26499. var getFontSize = getFontProp('font-size');
  26500. var getFontFamily = compose(normalizeFontFamily, getFontProp('font-family'));
  26501. var findFirstCaretElement = function (editor) {
  26502. return firstPositionIn(editor.getBody()).map(function (caret) {
  26503. var container = caret.container();
  26504. return isText$1(container) ? container.parentNode : container;
  26505. });
  26506. };
  26507. var getCaretElement = function (editor) {
  26508. return Optional.from(editor.selection.getRng()).bind(function (rng) {
  26509. var root = editor.getBody();
  26510. var atStartOfNode = rng.startContainer === root && rng.startOffset === 0;
  26511. return atStartOfNode ? Optional.none() : Optional.from(editor.selection.getStart(true));
  26512. });
  26513. };
  26514. var mapRange = function (editor, mapper) {
  26515. return getCaretElement(editor).orThunk(curry(findFirstCaretElement, editor)).map(SugarElement.fromDom).filter(isElement).map(mapper);
  26516. };
  26517. var fromFontSizeNumber = function (editor, value) {
  26518. if (/^[0-9.]+$/.test(value)) {
  26519. var fontSizeNumber = parseInt(value, 10);
  26520. if (fontSizeNumber >= 1 && fontSizeNumber <= 7) {
  26521. var fontSizes = getFontStyleValues(editor);
  26522. var fontClasses = getFontSizeClasses(editor);
  26523. if (fontClasses) {
  26524. return fontClasses[fontSizeNumber - 1] || value;
  26525. } else {
  26526. return fontSizes[fontSizeNumber - 1] || value;
  26527. }
  26528. } else {
  26529. return value;
  26530. }
  26531. } else {
  26532. return value;
  26533. }
  26534. };
  26535. var normalizeFontNames = function (font) {
  26536. var fonts = font.split(/\s*,\s*/);
  26537. return map(fonts, function (font) {
  26538. if (font.indexOf(' ') !== -1 && !(startsWith(font, '"') || startsWith(font, '\''))) {
  26539. return '\'' + font + '\'';
  26540. } else {
  26541. return font;
  26542. }
  26543. }).join(',');
  26544. };
  26545. var fontNameAction = function (editor, value) {
  26546. var font = fromFontSizeNumber(editor, value);
  26547. editor.formatter.toggle('fontname', { value: normalizeFontNames(font) });
  26548. editor.nodeChanged();
  26549. };
  26550. var fontNameQuery = function (editor) {
  26551. return mapRange(editor, function (elm) {
  26552. return getFontFamily(editor.getBody(), elm.dom);
  26553. }).getOr('');
  26554. };
  26555. var fontSizeAction = function (editor, value) {
  26556. editor.formatter.toggle('fontsize', { value: fromFontSizeNumber(editor, value) });
  26557. editor.nodeChanged();
  26558. };
  26559. var fontSizeQuery = function (editor) {
  26560. return mapRange(editor, function (elm) {
  26561. return getFontSize(editor.getBody(), elm.dom);
  26562. }).getOr('');
  26563. };
  26564. var lineHeightQuery = function (editor) {
  26565. return mapRange(editor, function (elm) {
  26566. var root = SugarElement.fromDom(editor.getBody());
  26567. var specifiedStyle = closest$2(elm, function (elm) {
  26568. return getRaw(elm, 'line-height');
  26569. }, curry(eq$2, root));
  26570. var computedStyle = function () {
  26571. var lineHeight = parseFloat(get$5(elm, 'line-height'));
  26572. var fontSize = parseFloat(get$5(elm, 'font-size'));
  26573. return String(lineHeight / fontSize);
  26574. };
  26575. return specifiedStyle.getOrThunk(computedStyle);
  26576. }).getOr('');
  26577. };
  26578. var lineHeightAction = function (editor, lineHeight) {
  26579. editor.undoManager.transact(function () {
  26580. editor.formatter.toggle('lineheight', { value: String(lineHeight) });
  26581. editor.nodeChanged();
  26582. });
  26583. };
  26584. var processValue = function (value) {
  26585. var details;
  26586. if (typeof value !== 'string') {
  26587. details = Tools.extend({
  26588. paste: value.paste,
  26589. data: { paste: value.paste }
  26590. }, value);
  26591. return {
  26592. content: value.content,
  26593. details: details
  26594. };
  26595. }
  26596. return {
  26597. content: value,
  26598. details: {}
  26599. };
  26600. };
  26601. var insertAtCaret$1 = function (editor, value) {
  26602. var result = processValue(value);
  26603. insertContent(editor, result.content, result.details);
  26604. };
  26605. var each$f = Tools.each;
  26606. var map$3 = Tools.map, inArray$2 = Tools.inArray;
  26607. var EditorCommands = function () {
  26608. function EditorCommands(editor) {
  26609. this.commands = {
  26610. state: {},
  26611. exec: {},
  26612. value: {}
  26613. };
  26614. this.editor = editor;
  26615. this.setupCommands(editor);
  26616. }
  26617. EditorCommands.prototype.execCommand = function (command, ui, value, args) {
  26618. var func, state = false;
  26619. var self = this;
  26620. if (self.editor.removed) {
  26621. return;
  26622. }
  26623. if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) {
  26624. self.editor.focus();
  26625. } else {
  26626. restore(self.editor);
  26627. }
  26628. args = self.editor.fire('BeforeExecCommand', {
  26629. command: command,
  26630. ui: ui,
  26631. value: value
  26632. });
  26633. if (args.isDefaultPrevented()) {
  26634. return false;
  26635. }
  26636. var customCommand = command.toLowerCase();
  26637. if (func = self.commands.exec[customCommand]) {
  26638. func(customCommand, ui, value);
  26639. self.editor.fire('ExecCommand', {
  26640. command: command,
  26641. ui: ui,
  26642. value: value
  26643. });
  26644. return true;
  26645. }
  26646. each$f(this.editor.plugins, function (p) {
  26647. if (p.execCommand && p.execCommand(command, ui, value)) {
  26648. self.editor.fire('ExecCommand', {
  26649. command: command,
  26650. ui: ui,
  26651. value: value
  26652. });
  26653. state = true;
  26654. return false;
  26655. }
  26656. });
  26657. if (state) {
  26658. return state;
  26659. }
  26660. if (self.editor.theme && self.editor.theme.execCommand && self.editor.theme.execCommand(command, ui, value)) {
  26661. self.editor.fire('ExecCommand', {
  26662. command: command,
  26663. ui: ui,
  26664. value: value
  26665. });
  26666. return true;
  26667. }
  26668. try {
  26669. state = self.editor.getDoc().execCommand(command, ui, value);
  26670. } catch (ex) {
  26671. }
  26672. if (state) {
  26673. self.editor.fire('ExecCommand', {
  26674. command: command,
  26675. ui: ui,
  26676. value: value
  26677. });
  26678. return true;
  26679. }
  26680. return false;
  26681. };
  26682. EditorCommands.prototype.queryCommandState = function (command) {
  26683. var func;
  26684. if (this.editor.quirks.isHidden() || this.editor.removed) {
  26685. return;
  26686. }
  26687. command = command.toLowerCase();
  26688. if (func = this.commands.state[command]) {
  26689. return func(command);
  26690. }
  26691. try {
  26692. return this.editor.getDoc().queryCommandState(command);
  26693. } catch (ex) {
  26694. }
  26695. return false;
  26696. };
  26697. EditorCommands.prototype.queryCommandValue = function (command) {
  26698. var func;
  26699. if (this.editor.quirks.isHidden() || this.editor.removed) {
  26700. return;
  26701. }
  26702. command = command.toLowerCase();
  26703. if (func = this.commands.value[command]) {
  26704. return func(command);
  26705. }
  26706. try {
  26707. return this.editor.getDoc().queryCommandValue(command);
  26708. } catch (ex) {
  26709. }
  26710. };
  26711. EditorCommands.prototype.addCommands = function (commandList, type) {
  26712. if (type === void 0) {
  26713. type = 'exec';
  26714. }
  26715. var self = this;
  26716. each$f(commandList, function (callback, command) {
  26717. each$f(command.toLowerCase().split(','), function (command) {
  26718. self.commands[type][command] = callback;
  26719. });
  26720. });
  26721. };
  26722. EditorCommands.prototype.addCommand = function (command, callback, scope) {
  26723. var _this = this;
  26724. command = command.toLowerCase();
  26725. this.commands.exec[command] = function (command, ui, value, args) {
  26726. return callback.call(scope || _this.editor, ui, value, args);
  26727. };
  26728. };
  26729. EditorCommands.prototype.queryCommandSupported = function (command) {
  26730. command = command.toLowerCase();
  26731. if (this.commands.exec[command]) {
  26732. return true;
  26733. }
  26734. try {
  26735. return this.editor.getDoc().queryCommandSupported(command);
  26736. } catch (ex) {
  26737. }
  26738. return false;
  26739. };
  26740. EditorCommands.prototype.addQueryStateHandler = function (command, callback, scope) {
  26741. var _this = this;
  26742. command = command.toLowerCase();
  26743. this.commands.state[command] = function () {
  26744. return callback.call(scope || _this.editor);
  26745. };
  26746. };
  26747. EditorCommands.prototype.addQueryValueHandler = function (command, callback, scope) {
  26748. var _this = this;
  26749. command = command.toLowerCase();
  26750. this.commands.value[command] = function () {
  26751. return callback.call(scope || _this.editor);
  26752. };
  26753. };
  26754. EditorCommands.prototype.hasCustomCommand = function (command) {
  26755. command = command.toLowerCase();
  26756. return !!this.commands.exec[command];
  26757. };
  26758. EditorCommands.prototype.execNativeCommand = function (command, ui, value) {
  26759. if (ui === undefined) {
  26760. ui = false;
  26761. }
  26762. if (value === undefined) {
  26763. value = null;
  26764. }
  26765. return this.editor.getDoc().execCommand(command, ui, value);
  26766. };
  26767. EditorCommands.prototype.isFormatMatch = function (name) {
  26768. return this.editor.formatter.match(name);
  26769. };
  26770. EditorCommands.prototype.toggleFormat = function (name, value) {
  26771. this.editor.formatter.toggle(name, value ? { value: value } : undefined);
  26772. this.editor.nodeChanged();
  26773. };
  26774. EditorCommands.prototype.storeSelection = function (type) {
  26775. this.selectionBookmark = this.editor.selection.getBookmark(type);
  26776. };
  26777. EditorCommands.prototype.restoreSelection = function () {
  26778. this.editor.selection.moveToBookmark(this.selectionBookmark);
  26779. };
  26780. EditorCommands.prototype.setupCommands = function (editor) {
  26781. var self = this;
  26782. this.addCommands({
  26783. 'mceResetDesignMode,mceBeginUndoLevel': function () {
  26784. },
  26785. 'mceEndUndoLevel,mceAddUndoLevel': function () {
  26786. editor.undoManager.add();
  26787. },
  26788. 'Cut,Copy,Paste': function (command) {
  26789. var doc = editor.getDoc();
  26790. var failed;
  26791. try {
  26792. self.execNativeCommand(command);
  26793. } catch (ex) {
  26794. failed = true;
  26795. }
  26796. if (command === 'paste' && !doc.queryCommandEnabled(command)) {
  26797. failed = true;
  26798. }
  26799. if (failed || !doc.queryCommandSupported(command)) {
  26800. var msg = editor.translate('Your browser doesn\'t support direct access to the clipboard. ' + 'Please use the Ctrl+X/C/V keyboard shortcuts instead.');
  26801. if (Env.mac) {
  26802. msg = msg.replace(/Ctrl\+/g, '\u2318+');
  26803. }
  26804. editor.notificationManager.open({
  26805. text: msg,
  26806. type: 'error'
  26807. });
  26808. }
  26809. },
  26810. 'unlink': function () {
  26811. if (editor.selection.isCollapsed()) {
  26812. var elm = editor.dom.getParent(editor.selection.getStart(), 'a');
  26813. if (elm) {
  26814. editor.dom.remove(elm, true);
  26815. }
  26816. return;
  26817. }
  26818. editor.formatter.remove('link');
  26819. },
  26820. 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone': function (command) {
  26821. var align = command.substring(7);
  26822. if (align === 'full') {
  26823. align = 'justify';
  26824. }
  26825. each$f('left,center,right,justify'.split(','), function (name) {
  26826. if (align !== name) {
  26827. editor.formatter.remove('align' + name);
  26828. }
  26829. });
  26830. if (align !== 'none') {
  26831. self.toggleFormat('align' + align);
  26832. }
  26833. },
  26834. 'InsertUnorderedList,InsertOrderedList': function (command) {
  26835. var listParent;
  26836. self.execNativeCommand(command);
  26837. var listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
  26838. if (listElm) {
  26839. listParent = listElm.parentNode;
  26840. if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
  26841. self.storeSelection();
  26842. editor.dom.split(listParent, listElm);
  26843. self.restoreSelection();
  26844. }
  26845. }
  26846. },
  26847. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  26848. self.toggleFormat(command);
  26849. },
  26850. 'ForeColor,HiliteColor': function (command, ui, value) {
  26851. self.toggleFormat(command, value);
  26852. },
  26853. 'FontName': function (command, ui, value) {
  26854. fontNameAction(editor, value);
  26855. },
  26856. 'FontSize': function (command, ui, value) {
  26857. fontSizeAction(editor, value);
  26858. },
  26859. 'LineHeight': function (command, ui, value) {
  26860. lineHeightAction(editor, value);
  26861. },
  26862. 'RemoveFormat': function (command) {
  26863. editor.formatter.remove(command);
  26864. },
  26865. 'mceBlockQuote': function () {
  26866. self.toggleFormat('blockquote');
  26867. },
  26868. 'FormatBlock': function (command, ui, value) {
  26869. return self.toggleFormat(value || 'p');
  26870. },
  26871. 'mceCleanup': function () {
  26872. var bookmark = editor.selection.getBookmark();
  26873. editor.setContent(editor.getContent());
  26874. editor.selection.moveToBookmark(bookmark);
  26875. },
  26876. 'mceRemoveNode': function (command, ui, value) {
  26877. var node = value || editor.selection.getNode();
  26878. if (node !== editor.getBody()) {
  26879. self.storeSelection();
  26880. editor.dom.remove(node, true);
  26881. self.restoreSelection();
  26882. }
  26883. },
  26884. 'mceSelectNodeDepth': function (command, ui, value) {
  26885. var counter = 0;
  26886. editor.dom.getParent(editor.selection.getNode(), function (node) {
  26887. if (node.nodeType === 1 && counter++ === value) {
  26888. editor.selection.select(node);
  26889. return false;
  26890. }
  26891. }, editor.getBody());
  26892. },
  26893. 'mceSelectNode': function (command, ui, value) {
  26894. editor.selection.select(value);
  26895. },
  26896. 'mceInsertContent': function (command, ui, value) {
  26897. insertAtCaret$1(editor, value);
  26898. },
  26899. 'mceInsertRawHTML': function (command, ui, value) {
  26900. editor.selection.setContent('tiny_mce_marker');
  26901. var content = editor.getContent();
  26902. editor.setContent(content.replace(/tiny_mce_marker/g, function () {
  26903. return value;
  26904. }));
  26905. },
  26906. 'mceInsertNewLine': function (command, ui, value) {
  26907. insert$3(editor, value);
  26908. },
  26909. 'mceToggleFormat': function (command, ui, value) {
  26910. self.toggleFormat(value);
  26911. },
  26912. 'mceSetContent': function (command, ui, value) {
  26913. editor.setContent(value);
  26914. },
  26915. 'Indent,Outdent': function (command) {
  26916. handle(editor, command);
  26917. },
  26918. 'mceRepaint': function () {
  26919. },
  26920. 'InsertHorizontalRule': function () {
  26921. editor.execCommand('mceInsertContent', false, '<hr />');
  26922. },
  26923. 'mceToggleVisualAid': function () {
  26924. editor.hasVisual = !editor.hasVisual;
  26925. editor.addVisual();
  26926. },
  26927. 'mceReplaceContent': function (command, ui, value) {
  26928. editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, editor.selection.getContent({ format: 'text' })));
  26929. },
  26930. 'mceInsertLink': function (command, ui, value) {
  26931. if (typeof value === 'string') {
  26932. value = { href: value };
  26933. }
  26934. var anchor = editor.dom.getParent(editor.selection.getNode(), 'a');
  26935. value.href = value.href.replace(/ /g, '%20');
  26936. if (!anchor || !value.href) {
  26937. editor.formatter.remove('link');
  26938. }
  26939. if (value.href) {
  26940. editor.formatter.apply('link', value, anchor);
  26941. }
  26942. },
  26943. 'selectAll': function () {
  26944. var editingHost = editor.dom.getParent(editor.selection.getStart(), isContentEditableTrue);
  26945. if (editingHost) {
  26946. var rng = editor.dom.createRng();
  26947. rng.selectNodeContents(editingHost);
  26948. editor.selection.setRng(rng);
  26949. }
  26950. },
  26951. 'mceNewDocument': function () {
  26952. editor.setContent('');
  26953. },
  26954. 'InsertLineBreak': function (command, ui, value) {
  26955. insert$2(editor, value);
  26956. return true;
  26957. }
  26958. });
  26959. var alignStates = function (name) {
  26960. return function () {
  26961. var selection = editor.selection;
  26962. var nodes = selection.isCollapsed() ? [editor.dom.getParent(selection.getNode(), editor.dom.isBlock)] : selection.getSelectedBlocks();
  26963. var matches = map$3(nodes, function (node) {
  26964. return !!editor.formatter.matchNode(node, name);
  26965. });
  26966. return inArray$2(matches, true) !== -1;
  26967. };
  26968. };
  26969. self.addCommands({
  26970. 'JustifyLeft': alignStates('alignleft'),
  26971. 'JustifyCenter': alignStates('aligncenter'),
  26972. 'JustifyRight': alignStates('alignright'),
  26973. 'JustifyFull': alignStates('alignjustify'),
  26974. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  26975. return self.isFormatMatch(command);
  26976. },
  26977. 'mceBlockQuote': function () {
  26978. return self.isFormatMatch('blockquote');
  26979. },
  26980. 'Outdent': function () {
  26981. return canOutdent(editor);
  26982. },
  26983. 'InsertUnorderedList,InsertOrderedList': function (command) {
  26984. var list = editor.dom.getParent(editor.selection.getNode(), 'ul,ol');
  26985. return list && (command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL');
  26986. }
  26987. }, 'state');
  26988. self.addCommands({
  26989. Undo: function () {
  26990. editor.undoManager.undo();
  26991. },
  26992. Redo: function () {
  26993. editor.undoManager.redo();
  26994. }
  26995. });
  26996. self.addQueryValueHandler('FontName', function () {
  26997. return fontNameQuery(editor);
  26998. }, this);
  26999. self.addQueryValueHandler('FontSize', function () {
  27000. return fontSizeQuery(editor);
  27001. }, this);
  27002. self.addQueryValueHandler('LineHeight', function () {
  27003. return lineHeightQuery(editor);
  27004. }, this);
  27005. };
  27006. return EditorCommands;
  27007. }();
  27008. var internalContentEditableAttr = 'data-mce-contenteditable';
  27009. var toggleClass = function (elm, cls, state) {
  27010. if (has$2(elm, cls) && state === false) {
  27011. remove$4(elm, cls);
  27012. } else if (state) {
  27013. add$3(elm, cls);
  27014. }
  27015. };
  27016. var setEditorCommandState = function (editor, cmd, state) {
  27017. try {
  27018. editor.getDoc().execCommand(cmd, false, String(state));
  27019. } catch (ex) {
  27020. }
  27021. };
  27022. var setContentEditable = function (elm, state) {
  27023. elm.dom.contentEditable = state ? 'true' : 'false';
  27024. };
  27025. var switchOffContentEditableTrue = function (elm) {
  27026. each(descendants$1(elm, '*[contenteditable="true"]'), function (elm) {
  27027. set(elm, internalContentEditableAttr, 'true');
  27028. setContentEditable(elm, false);
  27029. });
  27030. };
  27031. var switchOnContentEditableTrue = function (elm) {
  27032. each(descendants$1(elm, '*[' + internalContentEditableAttr + '="true"]'), function (elm) {
  27033. remove$1(elm, internalContentEditableAttr);
  27034. setContentEditable(elm, true);
  27035. });
  27036. };
  27037. var removeFakeSelection = function (editor) {
  27038. Optional.from(editor.selection.getNode()).each(function (elm) {
  27039. elm.removeAttribute('data-mce-selected');
  27040. });
  27041. };
  27042. var restoreFakeSelection = function (editor) {
  27043. editor.selection.setRng(editor.selection.getRng());
  27044. };
  27045. var toggleReadOnly = function (editor, state) {
  27046. var body = SugarElement.fromDom(editor.getBody());
  27047. toggleClass(body, 'mce-content-readonly', state);
  27048. if (state) {
  27049. editor.selection.controlSelection.hideResizeRect();
  27050. editor._selectionOverrides.hideFakeCaret();
  27051. removeFakeSelection(editor);
  27052. editor.readonly = true;
  27053. setContentEditable(body, false);
  27054. switchOffContentEditableTrue(body);
  27055. } else {
  27056. editor.readonly = false;
  27057. setContentEditable(body, true);
  27058. switchOnContentEditableTrue(body);
  27059. setEditorCommandState(editor, 'StyleWithCSS', false);
  27060. setEditorCommandState(editor, 'enableInlineTableEditing', false);
  27061. setEditorCommandState(editor, 'enableObjectResizing', false);
  27062. if (hasEditorOrUiFocus(editor)) {
  27063. editor.focus();
  27064. }
  27065. restoreFakeSelection(editor);
  27066. editor.nodeChanged();
  27067. }
  27068. };
  27069. var isReadOnly$1 = function (editor) {
  27070. return editor.readonly;
  27071. };
  27072. var registerFilters = function (editor) {
  27073. editor.parser.addAttributeFilter('contenteditable', function (nodes) {
  27074. if (isReadOnly$1(editor)) {
  27075. each(nodes, function (node) {
  27076. node.attr(internalContentEditableAttr, node.attr('contenteditable'));
  27077. node.attr('contenteditable', 'false');
  27078. });
  27079. }
  27080. });
  27081. editor.serializer.addAttributeFilter(internalContentEditableAttr, function (nodes) {
  27082. if (isReadOnly$1(editor)) {
  27083. each(nodes, function (node) {
  27084. node.attr('contenteditable', node.attr(internalContentEditableAttr));
  27085. });
  27086. }
  27087. });
  27088. editor.serializer.addTempAttr(internalContentEditableAttr);
  27089. };
  27090. var registerReadOnlyContentFilters = function (editor) {
  27091. if (editor.serializer) {
  27092. registerFilters(editor);
  27093. } else {
  27094. editor.on('PreInit', function () {
  27095. registerFilters(editor);
  27096. });
  27097. }
  27098. };
  27099. var isClickEvent = function (e) {
  27100. return e.type === 'click';
  27101. };
  27102. var getAnchorHrefOpt = function (editor, elm) {
  27103. var isRoot = function (elm) {
  27104. return eq$2(elm, SugarElement.fromDom(editor.getBody()));
  27105. };
  27106. return closest$1(elm, 'a', isRoot).bind(function (a) {
  27107. return getOpt(a, 'href');
  27108. });
  27109. };
  27110. var processReadonlyEvents = function (editor, e) {
  27111. if (isClickEvent(e) && !VK.metaKeyPressed(e)) {
  27112. var elm = SugarElement.fromDom(e.target);
  27113. getAnchorHrefOpt(editor, elm).each(function (href) {
  27114. e.preventDefault();
  27115. if (/^#/.test(href)) {
  27116. var targetEl = editor.dom.select(href + ',[name="' + removeLeading(href, '#') + '"]');
  27117. if (targetEl.length) {
  27118. editor.selection.scrollIntoView(targetEl[0], true);
  27119. }
  27120. } else {
  27121. window.open(href, '_blank', 'rel=noopener noreferrer,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes,scrollbars=yes');
  27122. }
  27123. });
  27124. }
  27125. };
  27126. var registerReadOnlySelectionBlockers = function (editor) {
  27127. editor.on('ShowCaret', function (e) {
  27128. if (isReadOnly$1(editor)) {
  27129. e.preventDefault();
  27130. }
  27131. });
  27132. editor.on('ObjectSelected', function (e) {
  27133. if (isReadOnly$1(editor)) {
  27134. e.preventDefault();
  27135. }
  27136. });
  27137. };
  27138. 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', ' ');
  27139. var EventDispatcher = function () {
  27140. function EventDispatcher(settings) {
  27141. this.bindings = {};
  27142. this.settings = settings || {};
  27143. this.scope = this.settings.scope || this;
  27144. this.toggleEvent = this.settings.toggleEvent || never;
  27145. }
  27146. EventDispatcher.isNative = function (name) {
  27147. return !!nativeEvents[name.toLowerCase()];
  27148. };
  27149. EventDispatcher.prototype.fire = function (nameIn, argsIn) {
  27150. var name = nameIn.toLowerCase();
  27151. var args = argsIn || {};
  27152. args.type = name;
  27153. if (!args.target) {
  27154. args.target = this.scope;
  27155. }
  27156. if (!args.preventDefault) {
  27157. args.preventDefault = function () {
  27158. args.isDefaultPrevented = always;
  27159. };
  27160. args.stopPropagation = function () {
  27161. args.isPropagationStopped = always;
  27162. };
  27163. args.stopImmediatePropagation = function () {
  27164. args.isImmediatePropagationStopped = always;
  27165. };
  27166. args.isDefaultPrevented = never;
  27167. args.isPropagationStopped = never;
  27168. args.isImmediatePropagationStopped = never;
  27169. }
  27170. if (this.settings.beforeFire) {
  27171. this.settings.beforeFire(args);
  27172. }
  27173. var handlers = this.bindings[name];
  27174. if (handlers) {
  27175. for (var i = 0, l = handlers.length; i < l; i++) {
  27176. var callback = handlers[i];
  27177. if (callback.once) {
  27178. this.off(name, callback.func);
  27179. }
  27180. if (args.isImmediatePropagationStopped()) {
  27181. args.stopPropagation();
  27182. return args;
  27183. }
  27184. if (callback.func.call(this.scope, args) === false) {
  27185. args.preventDefault();
  27186. return args;
  27187. }
  27188. }
  27189. }
  27190. return args;
  27191. };
  27192. EventDispatcher.prototype.on = function (name, callback, prepend, extra) {
  27193. if (callback === false) {
  27194. callback = never;
  27195. }
  27196. if (callback) {
  27197. var wrappedCallback = { func: callback };
  27198. if (extra) {
  27199. Tools.extend(wrappedCallback, extra);
  27200. }
  27201. var names = name.toLowerCase().split(' ');
  27202. var i = names.length;
  27203. while (i--) {
  27204. var currentName = names[i];
  27205. var handlers = this.bindings[currentName];
  27206. if (!handlers) {
  27207. handlers = this.bindings[currentName] = [];
  27208. this.toggleEvent(currentName, true);
  27209. }
  27210. if (prepend) {
  27211. handlers.unshift(wrappedCallback);
  27212. } else {
  27213. handlers.push(wrappedCallback);
  27214. }
  27215. }
  27216. }
  27217. return this;
  27218. };
  27219. EventDispatcher.prototype.off = function (name, callback) {
  27220. var _this = this;
  27221. if (name) {
  27222. var names = name.toLowerCase().split(' ');
  27223. var i = names.length;
  27224. while (i--) {
  27225. var currentName = names[i];
  27226. var handlers = this.bindings[currentName];
  27227. if (!currentName) {
  27228. each$1(this.bindings, function (_value, bindingName) {
  27229. _this.toggleEvent(bindingName, false);
  27230. delete _this.bindings[bindingName];
  27231. });
  27232. return this;
  27233. }
  27234. if (handlers) {
  27235. if (!callback) {
  27236. handlers.length = 0;
  27237. } else {
  27238. var hi = handlers.length;
  27239. while (hi--) {
  27240. if (handlers[hi].func === callback) {
  27241. handlers = handlers.slice(0, hi).concat(handlers.slice(hi + 1));
  27242. this.bindings[currentName] = handlers;
  27243. }
  27244. }
  27245. }
  27246. if (!handlers.length) {
  27247. this.toggleEvent(name, false);
  27248. delete this.bindings[currentName];
  27249. }
  27250. }
  27251. }
  27252. } else {
  27253. each$1(this.bindings, function (_value, name) {
  27254. _this.toggleEvent(name, false);
  27255. });
  27256. this.bindings = {};
  27257. }
  27258. return this;
  27259. };
  27260. EventDispatcher.prototype.once = function (name, callback, prepend) {
  27261. return this.on(name, callback, prepend, { once: true });
  27262. };
  27263. EventDispatcher.prototype.has = function (name) {
  27264. name = name.toLowerCase();
  27265. return !(!this.bindings[name] || this.bindings[name].length === 0);
  27266. };
  27267. return EventDispatcher;
  27268. }();
  27269. var getEventDispatcher = function (obj) {
  27270. if (!obj._eventDispatcher) {
  27271. obj._eventDispatcher = new EventDispatcher({
  27272. scope: obj,
  27273. toggleEvent: function (name, state) {
  27274. if (EventDispatcher.isNative(name) && obj.toggleNativeEvent) {
  27275. obj.toggleNativeEvent(name, state);
  27276. }
  27277. }
  27278. });
  27279. }
  27280. return obj._eventDispatcher;
  27281. };
  27282. var Observable = {
  27283. fire: function (name, args, bubble) {
  27284. var self = this;
  27285. if (self.removed && name !== 'remove' && name !== 'detach') {
  27286. return args;
  27287. }
  27288. var dispatcherArgs = getEventDispatcher(self).fire(name, args);
  27289. if (bubble !== false && self.parent) {
  27290. var parent_1 = self.parent();
  27291. while (parent_1 && !dispatcherArgs.isPropagationStopped()) {
  27292. parent_1.fire(name, dispatcherArgs, false);
  27293. parent_1 = parent_1.parent();
  27294. }
  27295. }
  27296. return dispatcherArgs;
  27297. },
  27298. on: function (name, callback, prepend) {
  27299. return getEventDispatcher(this).on(name, callback, prepend);
  27300. },
  27301. off: function (name, callback) {
  27302. return getEventDispatcher(this).off(name, callback);
  27303. },
  27304. once: function (name, callback) {
  27305. return getEventDispatcher(this).once(name, callback);
  27306. },
  27307. hasEventListeners: function (name) {
  27308. return getEventDispatcher(this).has(name);
  27309. }
  27310. };
  27311. var DOM$8 = DOMUtils$1.DOM;
  27312. var customEventRootDelegates;
  27313. var getEventTarget = function (editor, eventName) {
  27314. if (eventName === 'selectionchange') {
  27315. return editor.getDoc();
  27316. }
  27317. if (!editor.inline && /^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(eventName)) {
  27318. return editor.getDoc().documentElement;
  27319. }
  27320. var eventRoot = getEventRoot(editor);
  27321. if (eventRoot) {
  27322. if (!editor.eventRoot) {
  27323. editor.eventRoot = DOM$8.select(eventRoot)[0];
  27324. }
  27325. return editor.eventRoot;
  27326. }
  27327. return editor.getBody();
  27328. };
  27329. var isListening = function (editor) {
  27330. return !editor.hidden && !isReadOnly$1(editor);
  27331. };
  27332. var fireEvent = function (editor, eventName, e) {
  27333. if (isListening(editor)) {
  27334. editor.fire(eventName, e);
  27335. } else if (isReadOnly$1(editor)) {
  27336. processReadonlyEvents(editor, e);
  27337. }
  27338. };
  27339. var bindEventDelegate = function (editor, eventName) {
  27340. var delegate;
  27341. if (!editor.delegates) {
  27342. editor.delegates = {};
  27343. }
  27344. if (editor.delegates[eventName] || editor.removed) {
  27345. return;
  27346. }
  27347. var eventRootElm = getEventTarget(editor, eventName);
  27348. if (getEventRoot(editor)) {
  27349. if (!customEventRootDelegates) {
  27350. customEventRootDelegates = {};
  27351. editor.editorManager.on('removeEditor', function () {
  27352. if (!editor.editorManager.activeEditor) {
  27353. if (customEventRootDelegates) {
  27354. each$1(customEventRootDelegates, function (_value, name) {
  27355. editor.dom.unbind(getEventTarget(editor, name));
  27356. });
  27357. customEventRootDelegates = null;
  27358. }
  27359. }
  27360. });
  27361. }
  27362. if (customEventRootDelegates[eventName]) {
  27363. return;
  27364. }
  27365. delegate = function (e) {
  27366. var target = e.target;
  27367. var editors = editor.editorManager.get();
  27368. var i = editors.length;
  27369. while (i--) {
  27370. var body = editors[i].getBody();
  27371. if (body === target || DOM$8.isChildOf(target, body)) {
  27372. fireEvent(editors[i], eventName, e);
  27373. }
  27374. }
  27375. };
  27376. customEventRootDelegates[eventName] = delegate;
  27377. DOM$8.bind(eventRootElm, eventName, delegate);
  27378. } else {
  27379. delegate = function (e) {
  27380. fireEvent(editor, eventName, e);
  27381. };
  27382. DOM$8.bind(eventRootElm, eventName, delegate);
  27383. editor.delegates[eventName] = delegate;
  27384. }
  27385. };
  27386. var EditorObservable = __assign(__assign({}, Observable), {
  27387. bindPendingEventDelegates: function () {
  27388. var self = this;
  27389. Tools.each(self._pendingNativeEvents, function (name) {
  27390. bindEventDelegate(self, name);
  27391. });
  27392. },
  27393. toggleNativeEvent: function (name, state) {
  27394. var self = this;
  27395. if (name === 'focus' || name === 'blur') {
  27396. return;
  27397. }
  27398. if (state) {
  27399. if (self.initialized) {
  27400. bindEventDelegate(self, name);
  27401. } else {
  27402. if (!self._pendingNativeEvents) {
  27403. self._pendingNativeEvents = [name];
  27404. } else {
  27405. self._pendingNativeEvents.push(name);
  27406. }
  27407. }
  27408. } else if (self.initialized) {
  27409. self.dom.unbind(getEventTarget(self, name), name, self.delegates[name]);
  27410. delete self.delegates[name];
  27411. }
  27412. },
  27413. unbindAllNativeEvents: function () {
  27414. var self = this;
  27415. var body = self.getBody();
  27416. var dom = self.dom;
  27417. if (self.delegates) {
  27418. each$1(self.delegates, function (value, name) {
  27419. self.dom.unbind(getEventTarget(self, name), name, value);
  27420. });
  27421. delete self.delegates;
  27422. }
  27423. if (!self.inline && body && dom) {
  27424. body.onload = null;
  27425. dom.unbind(self.getWin());
  27426. dom.unbind(self.getDoc());
  27427. }
  27428. if (dom) {
  27429. dom.unbind(body);
  27430. dom.unbind(self.getContainer());
  27431. }
  27432. }
  27433. });
  27434. var defaultModes = [
  27435. 'design',
  27436. 'readonly'
  27437. ];
  27438. var switchToMode = function (editor, activeMode, availableModes, mode) {
  27439. var oldMode = availableModes[activeMode.get()];
  27440. var newMode = availableModes[mode];
  27441. try {
  27442. newMode.activate();
  27443. } catch (e) {
  27444. console.error('problem while activating editor mode ' + mode + ':', e);
  27445. return;
  27446. }
  27447. oldMode.deactivate();
  27448. if (oldMode.editorReadOnly !== newMode.editorReadOnly) {
  27449. toggleReadOnly(editor, newMode.editorReadOnly);
  27450. }
  27451. activeMode.set(mode);
  27452. fireSwitchMode(editor, mode);
  27453. };
  27454. var setMode = function (editor, availableModes, activeMode, mode) {
  27455. if (mode === activeMode.get()) {
  27456. return;
  27457. } else if (!has(availableModes, mode)) {
  27458. throw new Error('Editor mode \'' + mode + '\' is invalid');
  27459. }
  27460. if (editor.initialized) {
  27461. switchToMode(editor, activeMode, availableModes, mode);
  27462. } else {
  27463. editor.on('init', function () {
  27464. return switchToMode(editor, activeMode, availableModes, mode);
  27465. });
  27466. }
  27467. };
  27468. var registerMode = function (availableModes, mode, api) {
  27469. var _a;
  27470. if (contains(defaultModes, mode)) {
  27471. throw new Error('Cannot override default mode ' + mode);
  27472. }
  27473. return __assign(__assign({}, availableModes), (_a = {}, _a[mode] = __assign(__assign({}, api), {
  27474. deactivate: function () {
  27475. try {
  27476. api.deactivate();
  27477. } catch (e) {
  27478. console.error('problem while deactivating editor mode ' + mode + ':', e);
  27479. }
  27480. }
  27481. }), _a));
  27482. };
  27483. var create$5 = function (editor) {
  27484. var activeMode = Cell('design');
  27485. var availableModes = Cell({
  27486. design: {
  27487. activate: noop,
  27488. deactivate: noop,
  27489. editorReadOnly: false
  27490. },
  27491. readonly: {
  27492. activate: noop,
  27493. deactivate: noop,
  27494. editorReadOnly: true
  27495. }
  27496. });
  27497. registerReadOnlyContentFilters(editor);
  27498. registerReadOnlySelectionBlockers(editor);
  27499. return {
  27500. isReadOnly: function () {
  27501. return isReadOnly$1(editor);
  27502. },
  27503. set: function (mode) {
  27504. return setMode(editor, availableModes.get(), activeMode, mode);
  27505. },
  27506. get: function () {
  27507. return activeMode.get();
  27508. },
  27509. register: function (mode, api) {
  27510. availableModes.set(registerMode(availableModes.get(), mode, api));
  27511. }
  27512. };
  27513. };
  27514. var each$g = Tools.each, explode$3 = Tools.explode;
  27515. var keyCodeLookup = {
  27516. f1: 112,
  27517. f2: 113,
  27518. f3: 114,
  27519. f4: 115,
  27520. f5: 116,
  27521. f6: 117,
  27522. f7: 118,
  27523. f8: 119,
  27524. f9: 120,
  27525. f10: 121,
  27526. f11: 122,
  27527. f12: 123
  27528. };
  27529. var modifierNames = Tools.makeMap('alt,ctrl,shift,meta,access');
  27530. var Shortcuts = function () {
  27531. function Shortcuts(editor) {
  27532. this.shortcuts = {};
  27533. this.pendingPatterns = [];
  27534. this.editor = editor;
  27535. var self = this;
  27536. editor.on('keyup keypress keydown', function (e) {
  27537. if ((self.hasModifier(e) || self.isFunctionKey(e)) && !e.isDefaultPrevented()) {
  27538. each$g(self.shortcuts, function (shortcut) {
  27539. if (self.matchShortcut(e, shortcut)) {
  27540. self.pendingPatterns = shortcut.subpatterns.slice(0);
  27541. if (e.type === 'keydown') {
  27542. self.executeShortcutAction(shortcut);
  27543. }
  27544. return true;
  27545. }
  27546. });
  27547. if (self.matchShortcut(e, self.pendingPatterns[0])) {
  27548. if (self.pendingPatterns.length === 1) {
  27549. if (e.type === 'keydown') {
  27550. self.executeShortcutAction(self.pendingPatterns[0]);
  27551. }
  27552. }
  27553. self.pendingPatterns.shift();
  27554. }
  27555. }
  27556. });
  27557. }
  27558. Shortcuts.prototype.add = function (pattern, desc, cmdFunc, scope) {
  27559. var self = this;
  27560. var func = self.normalizeCommandFunc(cmdFunc);
  27561. each$g(explode$3(Tools.trim(pattern)), function (pattern) {
  27562. var shortcut = self.createShortcut(pattern, desc, func, scope);
  27563. self.shortcuts[shortcut.id] = shortcut;
  27564. });
  27565. return true;
  27566. };
  27567. Shortcuts.prototype.remove = function (pattern) {
  27568. var shortcut = this.createShortcut(pattern);
  27569. if (this.shortcuts[shortcut.id]) {
  27570. delete this.shortcuts[shortcut.id];
  27571. return true;
  27572. }
  27573. return false;
  27574. };
  27575. Shortcuts.prototype.normalizeCommandFunc = function (cmdFunc) {
  27576. var self = this;
  27577. var cmd = cmdFunc;
  27578. if (typeof cmd === 'string') {
  27579. return function () {
  27580. self.editor.execCommand(cmd, false, null);
  27581. };
  27582. } else if (Tools.isArray(cmd)) {
  27583. return function () {
  27584. self.editor.execCommand(cmd[0], cmd[1], cmd[2]);
  27585. };
  27586. } else {
  27587. return cmd;
  27588. }
  27589. };
  27590. Shortcuts.prototype.parseShortcut = function (pattern) {
  27591. var key;
  27592. var shortcut = {};
  27593. each$g(explode$3(pattern.toLowerCase(), '+'), function (value) {
  27594. if (value in modifierNames) {
  27595. shortcut[value] = true;
  27596. } else {
  27597. if (/^[0-9]{2,}$/.test(value)) {
  27598. shortcut.keyCode = parseInt(value, 10);
  27599. } else {
  27600. shortcut.charCode = value.charCodeAt(0);
  27601. shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);
  27602. }
  27603. }
  27604. });
  27605. var id = [shortcut.keyCode];
  27606. for (key in modifierNames) {
  27607. if (shortcut[key]) {
  27608. id.push(key);
  27609. } else {
  27610. shortcut[key] = false;
  27611. }
  27612. }
  27613. shortcut.id = id.join(',');
  27614. if (shortcut.access) {
  27615. shortcut.alt = true;
  27616. if (Env.mac) {
  27617. shortcut.ctrl = true;
  27618. } else {
  27619. shortcut.shift = true;
  27620. }
  27621. }
  27622. if (shortcut.meta) {
  27623. if (Env.mac) {
  27624. shortcut.meta = true;
  27625. } else {
  27626. shortcut.ctrl = true;
  27627. shortcut.meta = false;
  27628. }
  27629. }
  27630. return shortcut;
  27631. };
  27632. Shortcuts.prototype.createShortcut = function (pattern, desc, cmdFunc, scope) {
  27633. var shortcuts = Tools.map(explode$3(pattern, '>'), this.parseShortcut);
  27634. shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {
  27635. func: cmdFunc,
  27636. scope: scope || this.editor
  27637. });
  27638. return Tools.extend(shortcuts[0], {
  27639. desc: this.editor.translate(desc),
  27640. subpatterns: shortcuts.slice(1)
  27641. });
  27642. };
  27643. Shortcuts.prototype.hasModifier = function (e) {
  27644. return e.altKey || e.ctrlKey || e.metaKey;
  27645. };
  27646. Shortcuts.prototype.isFunctionKey = function (e) {
  27647. return e.type === 'keydown' && e.keyCode >= 112 && e.keyCode <= 123;
  27648. };
  27649. Shortcuts.prototype.matchShortcut = function (e, shortcut) {
  27650. if (!shortcut) {
  27651. return false;
  27652. }
  27653. if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
  27654. return false;
  27655. }
  27656. if (shortcut.alt !== e.altKey || shortcut.shift !== e.shiftKey) {
  27657. return false;
  27658. }
  27659. if (e.keyCode === shortcut.keyCode || e.charCode && e.charCode === shortcut.charCode) {
  27660. e.preventDefault();
  27661. return true;
  27662. }
  27663. return false;
  27664. };
  27665. Shortcuts.prototype.executeShortcutAction = function (shortcut) {
  27666. return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
  27667. };
  27668. return Shortcuts;
  27669. }();
  27670. var create$6 = function () {
  27671. var buttons = {};
  27672. var menuItems = {};
  27673. var popups = {};
  27674. var icons = {};
  27675. var contextMenus = {};
  27676. var contextToolbars = {};
  27677. var sidebars = {};
  27678. var add = function (collection, type) {
  27679. return function (name, spec) {
  27680. return collection[name.toLowerCase()] = __assign(__assign({}, spec), { type: type });
  27681. };
  27682. };
  27683. var addIcon = function (name, svgData) {
  27684. return icons[name.toLowerCase()] = svgData;
  27685. };
  27686. return {
  27687. addButton: add(buttons, 'button'),
  27688. addGroupToolbarButton: add(buttons, 'grouptoolbarbutton'),
  27689. addToggleButton: add(buttons, 'togglebutton'),
  27690. addMenuButton: add(buttons, 'menubutton'),
  27691. addSplitButton: add(buttons, 'splitbutton'),
  27692. addMenuItem: add(menuItems, 'menuitem'),
  27693. addNestedMenuItem: add(menuItems, 'nestedmenuitem'),
  27694. addToggleMenuItem: add(menuItems, 'togglemenuitem'),
  27695. addAutocompleter: add(popups, 'autocompleter'),
  27696. addContextMenu: add(contextMenus, 'contextmenu'),
  27697. addContextToolbar: add(contextToolbars, 'contexttoolbar'),
  27698. addContextForm: add(contextToolbars, 'contextform'),
  27699. addSidebar: add(sidebars, 'sidebar'),
  27700. addIcon: addIcon,
  27701. getAll: function () {
  27702. return {
  27703. buttons: buttons,
  27704. menuItems: menuItems,
  27705. icons: icons,
  27706. popups: popups,
  27707. contextMenus: contextMenus,
  27708. contextToolbars: contextToolbars,
  27709. sidebars: sidebars
  27710. };
  27711. }
  27712. };
  27713. };
  27714. var registry = function () {
  27715. var bridge = create$6();
  27716. return {
  27717. addAutocompleter: bridge.addAutocompleter,
  27718. addButton: bridge.addButton,
  27719. addContextForm: bridge.addContextForm,
  27720. addContextMenu: bridge.addContextMenu,
  27721. addContextToolbar: bridge.addContextToolbar,
  27722. addIcon: bridge.addIcon,
  27723. addMenuButton: bridge.addMenuButton,
  27724. addMenuItem: bridge.addMenuItem,
  27725. addNestedMenuItem: bridge.addNestedMenuItem,
  27726. addSidebar: bridge.addSidebar,
  27727. addSplitButton: bridge.addSplitButton,
  27728. addToggleButton: bridge.addToggleButton,
  27729. addGroupToolbarButton: bridge.addGroupToolbarButton,
  27730. addToggleMenuItem: bridge.addToggleMenuItem,
  27731. getAll: bridge.getAll
  27732. };
  27733. };
  27734. var each$h = Tools.each, trim$4 = Tools.trim;
  27735. var queryParts = 'source protocol authority userInfo user password host port relative path directory file query anchor'.split(' ');
  27736. var DEFAULT_PORTS = {
  27737. ftp: 21,
  27738. http: 80,
  27739. https: 443,
  27740. mailto: 25
  27741. };
  27742. var URI = function () {
  27743. function URI(url, settings) {
  27744. url = trim$4(url);
  27745. this.settings = settings || {};
  27746. var baseUri = this.settings.base_uri;
  27747. var self = this;
  27748. if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
  27749. self.source = url;
  27750. return;
  27751. }
  27752. var isProtocolRelative = url.indexOf('//') === 0;
  27753. if (url.indexOf('/') === 0 && !isProtocolRelative) {
  27754. url = (baseUri ? baseUri.protocol || 'http' : 'http') + '://mce_host' + url;
  27755. }
  27756. if (!/^[\w\-]*:?\/\//.test(url)) {
  27757. var baseUrl = this.settings.base_uri ? this.settings.base_uri.path : new URI(document.location.href).directory;
  27758. if (this.settings.base_uri && this.settings.base_uri.protocol == '') {
  27759. url = '//mce_host' + self.toAbsPath(baseUrl, url);
  27760. } else {
  27761. var match = /([^#?]*)([#?]?.*)/.exec(url);
  27762. url = (baseUri && baseUri.protocol || 'http') + '://mce_host' + self.toAbsPath(baseUrl, match[1]) + match[2];
  27763. }
  27764. }
  27765. url = url.replace(/@@/g, '(mce_at)');
  27766. var urlMatch = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
  27767. each$h(queryParts, function (v, i) {
  27768. var part = urlMatch[i];
  27769. if (part) {
  27770. part = part.replace(/\(mce_at\)/g, '@@');
  27771. }
  27772. self[v] = part;
  27773. });
  27774. if (baseUri) {
  27775. if (!self.protocol) {
  27776. self.protocol = baseUri.protocol;
  27777. }
  27778. if (!self.userInfo) {
  27779. self.userInfo = baseUri.userInfo;
  27780. }
  27781. if (!self.port && self.host === 'mce_host') {
  27782. self.port = baseUri.port;
  27783. }
  27784. if (!self.host || self.host === 'mce_host') {
  27785. self.host = baseUri.host;
  27786. }
  27787. self.source = '';
  27788. }
  27789. if (isProtocolRelative) {
  27790. self.protocol = '';
  27791. }
  27792. }
  27793. URI.parseDataUri = function (uri) {
  27794. var type;
  27795. var uriComponents = decodeURIComponent(uri).split(',');
  27796. var matches = /data:([^;]+)/.exec(uriComponents[0]);
  27797. if (matches) {
  27798. type = matches[1];
  27799. }
  27800. return {
  27801. type: type,
  27802. data: uriComponents[1]
  27803. };
  27804. };
  27805. URI.getDocumentBaseUrl = function (loc) {
  27806. var baseUrl;
  27807. if (loc.protocol.indexOf('http') !== 0 && loc.protocol !== 'file:') {
  27808. baseUrl = loc.href;
  27809. } else {
  27810. baseUrl = loc.protocol + '//' + loc.host + loc.pathname;
  27811. }
  27812. if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
  27813. baseUrl = baseUrl.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  27814. if (!/[\/\\]$/.test(baseUrl)) {
  27815. baseUrl += '/';
  27816. }
  27817. }
  27818. return baseUrl;
  27819. };
  27820. URI.prototype.setPath = function (path) {
  27821. var pathMatch = /^(.*?)\/?(\w+)?$/.exec(path);
  27822. this.path = pathMatch[0];
  27823. this.directory = pathMatch[1];
  27824. this.file = pathMatch[2];
  27825. this.source = '';
  27826. this.getURI();
  27827. };
  27828. URI.prototype.toRelative = function (uri) {
  27829. var output;
  27830. if (uri === './') {
  27831. return uri;
  27832. }
  27833. var relativeUri = new URI(uri, { base_uri: this });
  27834. if (relativeUri.host !== 'mce_host' && this.host !== relativeUri.host && relativeUri.host || this.port !== relativeUri.port || this.protocol !== relativeUri.protocol && relativeUri.protocol !== '') {
  27835. return relativeUri.getURI();
  27836. }
  27837. var tu = this.getURI(), uu = relativeUri.getURI();
  27838. if (tu === uu || tu.charAt(tu.length - 1) === '/' && tu.substr(0, tu.length - 1) === uu) {
  27839. return tu;
  27840. }
  27841. output = this.toRelPath(this.path, relativeUri.path);
  27842. if (relativeUri.query) {
  27843. output += '?' + relativeUri.query;
  27844. }
  27845. if (relativeUri.anchor) {
  27846. output += '#' + relativeUri.anchor;
  27847. }
  27848. return output;
  27849. };
  27850. URI.prototype.toAbsolute = function (uri, noHost) {
  27851. var absoluteUri = new URI(uri, { base_uri: this });
  27852. return absoluteUri.getURI(noHost && this.isSameOrigin(absoluteUri));
  27853. };
  27854. URI.prototype.isSameOrigin = function (uri) {
  27855. if (this.host == uri.host && this.protocol == uri.protocol) {
  27856. if (this.port == uri.port) {
  27857. return true;
  27858. }
  27859. var defaultPort = DEFAULT_PORTS[this.protocol];
  27860. if (defaultPort && (this.port || defaultPort) == (uri.port || defaultPort)) {
  27861. return true;
  27862. }
  27863. }
  27864. return false;
  27865. };
  27866. URI.prototype.toRelPath = function (base, path) {
  27867. var breakPoint = 0, out = '', i, l;
  27868. var normalizedBase = base.substring(0, base.lastIndexOf('/')).split('/');
  27869. var items = path.split('/');
  27870. if (normalizedBase.length >= items.length) {
  27871. for (i = 0, l = normalizedBase.length; i < l; i++) {
  27872. if (i >= items.length || normalizedBase[i] !== items[i]) {
  27873. breakPoint = i + 1;
  27874. break;
  27875. }
  27876. }
  27877. }
  27878. if (normalizedBase.length < items.length) {
  27879. for (i = 0, l = items.length; i < l; i++) {
  27880. if (i >= normalizedBase.length || normalizedBase[i] !== items[i]) {
  27881. breakPoint = i + 1;
  27882. break;
  27883. }
  27884. }
  27885. }
  27886. if (breakPoint === 1) {
  27887. return path;
  27888. }
  27889. for (i = 0, l = normalizedBase.length - (breakPoint - 1); i < l; i++) {
  27890. out += '../';
  27891. }
  27892. for (i = breakPoint - 1, l = items.length; i < l; i++) {
  27893. if (i !== breakPoint - 1) {
  27894. out += '/' + items[i];
  27895. } else {
  27896. out += items[i];
  27897. }
  27898. }
  27899. return out;
  27900. };
  27901. URI.prototype.toAbsPath = function (base, path) {
  27902. var i, nb = 0, o = [], outPath;
  27903. var tr = /\/$/.test(path) ? '/' : '';
  27904. var normalizedBase = base.split('/');
  27905. var normalizedPath = path.split('/');
  27906. each$h(normalizedBase, function (k) {
  27907. if (k) {
  27908. o.push(k);
  27909. }
  27910. });
  27911. normalizedBase = o;
  27912. for (i = normalizedPath.length - 1, o = []; i >= 0; i--) {
  27913. if (normalizedPath[i].length === 0 || normalizedPath[i] === '.') {
  27914. continue;
  27915. }
  27916. if (normalizedPath[i] === '..') {
  27917. nb++;
  27918. continue;
  27919. }
  27920. if (nb > 0) {
  27921. nb--;
  27922. continue;
  27923. }
  27924. o.push(normalizedPath[i]);
  27925. }
  27926. i = normalizedBase.length - nb;
  27927. if (i <= 0) {
  27928. outPath = reverse(o).join('/');
  27929. } else {
  27930. outPath = normalizedBase.slice(0, i).join('/') + '/' + reverse(o).join('/');
  27931. }
  27932. if (outPath.indexOf('/') !== 0) {
  27933. outPath = '/' + outPath;
  27934. }
  27935. if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) {
  27936. outPath += tr;
  27937. }
  27938. return outPath;
  27939. };
  27940. URI.prototype.getURI = function (noProtoHost) {
  27941. if (noProtoHost === void 0) {
  27942. noProtoHost = false;
  27943. }
  27944. var s;
  27945. if (!this.source || noProtoHost) {
  27946. s = '';
  27947. if (!noProtoHost) {
  27948. if (this.protocol) {
  27949. s += this.protocol + '://';
  27950. } else {
  27951. s += '//';
  27952. }
  27953. if (this.userInfo) {
  27954. s += this.userInfo + '@';
  27955. }
  27956. if (this.host) {
  27957. s += this.host;
  27958. }
  27959. if (this.port) {
  27960. s += ':' + this.port;
  27961. }
  27962. }
  27963. if (this.path) {
  27964. s += this.path;
  27965. }
  27966. if (this.query) {
  27967. s += '?' + this.query;
  27968. }
  27969. if (this.anchor) {
  27970. s += '#' + this.anchor;
  27971. }
  27972. this.source = s;
  27973. }
  27974. return this.source;
  27975. };
  27976. return URI;
  27977. }();
  27978. var DOM$9 = DOMUtils$1.DOM;
  27979. var extend$3 = Tools.extend, each$i = Tools.each;
  27980. var resolve$3 = Tools.resolve;
  27981. var ie$1 = Env.ie;
  27982. var Editor = function () {
  27983. function Editor(id, settings, editorManager) {
  27984. var _this = this;
  27985. this.plugins = {};
  27986. this.contentCSS = [];
  27987. this.contentStyles = [];
  27988. this.loadedCSS = {};
  27989. this.isNotDirty = false;
  27990. this.editorManager = editorManager;
  27991. this.documentBaseUrl = editorManager.documentBaseURL;
  27992. extend$3(this, EditorObservable);
  27993. this.settings = getEditorSettings(this, id, this.documentBaseUrl, editorManager.defaultSettings, settings);
  27994. if (this.settings.suffix) {
  27995. editorManager.suffix = this.settings.suffix;
  27996. }
  27997. this.suffix = editorManager.suffix;
  27998. if (this.settings.base_url) {
  27999. editorManager._setBaseUrl(this.settings.base_url);
  28000. }
  28001. this.baseUri = editorManager.baseURI;
  28002. if (this.settings.referrer_policy) {
  28003. ScriptLoader.ScriptLoader._setReferrerPolicy(this.settings.referrer_policy);
  28004. DOMUtils$1.DOM.styleSheetLoader._setReferrerPolicy(this.settings.referrer_policy);
  28005. }
  28006. AddOnManager$1.languageLoad = this.settings.language_load;
  28007. AddOnManager$1.baseURL = editorManager.baseURL;
  28008. this.id = id;
  28009. this.setDirty(false);
  28010. this.documentBaseURI = new URI(this.settings.document_base_url, { base_uri: this.baseUri });
  28011. this.baseURI = this.baseUri;
  28012. this.inline = !!this.settings.inline;
  28013. this.shortcuts = new Shortcuts(this);
  28014. this.editorCommands = new EditorCommands(this);
  28015. if (this.settings.cache_suffix) {
  28016. Env.cacheSuffix = this.settings.cache_suffix.replace(/^[\?\&]+/, '');
  28017. }
  28018. this.ui = {
  28019. registry: registry(),
  28020. styleSheetLoader: undefined,
  28021. show: noop,
  28022. hide: noop,
  28023. enable: noop,
  28024. disable: noop,
  28025. isDisabled: never
  28026. };
  28027. var self = this;
  28028. var modeInstance = create$5(self);
  28029. this.mode = modeInstance;
  28030. this.setMode = modeInstance.set;
  28031. editorManager.fire('SetupEditor', { editor: this });
  28032. this.execCallback('setup', this);
  28033. this.$ = DomQuery.overrideDefaults(function () {
  28034. return {
  28035. context: _this.inline ? _this.getBody() : _this.getDoc(),
  28036. element: _this.getBody()
  28037. };
  28038. });
  28039. }
  28040. Editor.prototype.render = function () {
  28041. render(this);
  28042. };
  28043. Editor.prototype.focus = function (skipFocus) {
  28044. focus$1(this, skipFocus);
  28045. };
  28046. Editor.prototype.hasFocus = function () {
  28047. return hasFocus$1(this);
  28048. };
  28049. Editor.prototype.execCallback = function (name) {
  28050. var x = [];
  28051. for (var _i = 1; _i < arguments.length; _i++) {
  28052. x[_i - 1] = arguments[_i];
  28053. }
  28054. var self = this;
  28055. var callback = self.settings[name], scope;
  28056. if (!callback) {
  28057. return;
  28058. }
  28059. if (self.callbackLookup && (scope = self.callbackLookup[name])) {
  28060. callback = scope.func;
  28061. scope = scope.scope;
  28062. }
  28063. if (typeof callback === 'string') {
  28064. scope = callback.replace(/\.\w+$/, '');
  28065. scope = scope ? resolve$3(scope) : 0;
  28066. callback = resolve$3(callback);
  28067. self.callbackLookup = self.callbackLookup || {};
  28068. self.callbackLookup[name] = {
  28069. func: callback,
  28070. scope: scope
  28071. };
  28072. }
  28073. return callback.apply(scope || self, x);
  28074. };
  28075. Editor.prototype.translate = function (text) {
  28076. return I18n.translate(text);
  28077. };
  28078. Editor.prototype.getParam = function (name, defaultVal, type) {
  28079. return getParam(this, name, defaultVal, type);
  28080. };
  28081. Editor.prototype.hasPlugin = function (name, loaded) {
  28082. var hasPlugin = contains(getPlugins(this).split(/[ ,]/), name);
  28083. if (hasPlugin) {
  28084. return loaded ? PluginManager.get(name) !== undefined : true;
  28085. } else {
  28086. return false;
  28087. }
  28088. };
  28089. Editor.prototype.nodeChanged = function (args) {
  28090. this._nodeChangeDispatcher.nodeChanged(args);
  28091. };
  28092. Editor.prototype.addCommand = function (name, callback, scope) {
  28093. this.editorCommands.addCommand(name, callback, scope);
  28094. };
  28095. Editor.prototype.addQueryStateHandler = function (name, callback, scope) {
  28096. this.editorCommands.addQueryStateHandler(name, callback, scope);
  28097. };
  28098. Editor.prototype.addQueryValueHandler = function (name, callback, scope) {
  28099. this.editorCommands.addQueryValueHandler(name, callback, scope);
  28100. };
  28101. Editor.prototype.addShortcut = function (pattern, desc, cmdFunc, scope) {
  28102. this.shortcuts.add(pattern, desc, cmdFunc, scope);
  28103. };
  28104. Editor.prototype.execCommand = function (cmd, ui, value, args) {
  28105. return this.editorCommands.execCommand(cmd, ui, value, args);
  28106. };
  28107. Editor.prototype.queryCommandState = function (cmd) {
  28108. return this.editorCommands.queryCommandState(cmd);
  28109. };
  28110. Editor.prototype.queryCommandValue = function (cmd) {
  28111. return this.editorCommands.queryCommandValue(cmd);
  28112. };
  28113. Editor.prototype.queryCommandSupported = function (cmd) {
  28114. return this.editorCommands.queryCommandSupported(cmd);
  28115. };
  28116. Editor.prototype.show = function () {
  28117. var self = this;
  28118. if (self.hidden) {
  28119. self.hidden = false;
  28120. if (self.inline) {
  28121. self.getBody().contentEditable = 'true';
  28122. } else {
  28123. DOM$9.show(self.getContainer());
  28124. DOM$9.hide(self.id);
  28125. }
  28126. self.load();
  28127. self.fire('show');
  28128. }
  28129. };
  28130. Editor.prototype.hide = function () {
  28131. var self = this, doc = self.getDoc();
  28132. if (!self.hidden) {
  28133. if (ie$1 && doc && !self.inline) {
  28134. doc.execCommand('SelectAll');
  28135. }
  28136. self.save();
  28137. if (self.inline) {
  28138. self.getBody().contentEditable = 'false';
  28139. if (self === self.editorManager.focusedEditor) {
  28140. self.editorManager.focusedEditor = null;
  28141. }
  28142. } else {
  28143. DOM$9.hide(self.getContainer());
  28144. DOM$9.setStyle(self.id, 'display', self.orgDisplay);
  28145. }
  28146. self.hidden = true;
  28147. self.fire('hide');
  28148. }
  28149. };
  28150. Editor.prototype.isHidden = function () {
  28151. return !!this.hidden;
  28152. };
  28153. Editor.prototype.setProgressState = function (state, time) {
  28154. this.fire('ProgressState', {
  28155. state: state,
  28156. time: time
  28157. });
  28158. };
  28159. Editor.prototype.load = function (args) {
  28160. var self = this;
  28161. var elm = self.getElement(), html;
  28162. if (self.removed) {
  28163. return '';
  28164. }
  28165. if (elm) {
  28166. args = args || {};
  28167. args.load = true;
  28168. var value = isTextareaOrInput(elm) ? elm.value : elm.innerHTML;
  28169. html = self.setContent(value, args);
  28170. args.element = elm;
  28171. if (!args.no_events) {
  28172. self.fire('LoadContent', args);
  28173. }
  28174. args.element = elm = null;
  28175. return html;
  28176. }
  28177. };
  28178. Editor.prototype.save = function (args) {
  28179. var self = this;
  28180. var elm = self.getElement(), html, form;
  28181. if (!elm || !self.initialized || self.removed) {
  28182. return;
  28183. }
  28184. args = args || {};
  28185. args.save = true;
  28186. args.element = elm;
  28187. html = args.content = self.getContent(args);
  28188. if (!args.no_events) {
  28189. self.fire('SaveContent', args);
  28190. }
  28191. if (args.format === 'raw') {
  28192. self.fire('RawSaveContent', args);
  28193. }
  28194. html = args.content;
  28195. if (!isTextareaOrInput(elm)) {
  28196. if (args.is_removing || !self.inline) {
  28197. elm.innerHTML = html;
  28198. }
  28199. if (form = DOM$9.getParent(self.id, 'form')) {
  28200. each$i(form.elements, function (elm) {
  28201. if (elm.name === self.id) {
  28202. elm.value = html;
  28203. return false;
  28204. }
  28205. });
  28206. }
  28207. } else {
  28208. elm.value = html;
  28209. }
  28210. args.element = elm = null;
  28211. if (args.set_dirty !== false) {
  28212. self.setDirty(false);
  28213. }
  28214. return html;
  28215. };
  28216. Editor.prototype.setContent = function (content, args) {
  28217. return setContent$2(this, content, args);
  28218. };
  28219. Editor.prototype.getContent = function (args) {
  28220. return getContent$2(this, args);
  28221. };
  28222. Editor.prototype.insertContent = function (content, args) {
  28223. if (args) {
  28224. content = extend$3({ content: content }, args);
  28225. }
  28226. this.execCommand('mceInsertContent', false, content);
  28227. };
  28228. Editor.prototype.resetContent = function (initialContent) {
  28229. if (initialContent === undefined) {
  28230. setContent$2(this, this.startContent, { format: 'raw' });
  28231. } else {
  28232. setContent$2(this, initialContent);
  28233. }
  28234. this.undoManager.reset();
  28235. this.setDirty(false);
  28236. this.nodeChanged();
  28237. };
  28238. Editor.prototype.isDirty = function () {
  28239. return !this.isNotDirty;
  28240. };
  28241. Editor.prototype.setDirty = function (state) {
  28242. var oldState = !this.isNotDirty;
  28243. this.isNotDirty = !state;
  28244. if (state && state !== oldState) {
  28245. this.fire('dirty');
  28246. }
  28247. };
  28248. Editor.prototype.getContainer = function () {
  28249. var self = this;
  28250. if (!self.container) {
  28251. self.container = DOM$9.get(self.editorContainer || self.id + '_parent');
  28252. }
  28253. return self.container;
  28254. };
  28255. Editor.prototype.getContentAreaContainer = function () {
  28256. return this.contentAreaContainer;
  28257. };
  28258. Editor.prototype.getElement = function () {
  28259. if (!this.targetElm) {
  28260. this.targetElm = DOM$9.get(this.id);
  28261. }
  28262. return this.targetElm;
  28263. };
  28264. Editor.prototype.getWin = function () {
  28265. var self = this;
  28266. var elm;
  28267. if (!self.contentWindow) {
  28268. elm = self.iframeElement;
  28269. if (elm) {
  28270. self.contentWindow = elm.contentWindow;
  28271. }
  28272. }
  28273. return self.contentWindow;
  28274. };
  28275. Editor.prototype.getDoc = function () {
  28276. var self = this;
  28277. var win;
  28278. if (!self.contentDocument) {
  28279. win = self.getWin();
  28280. if (win) {
  28281. self.contentDocument = win.document;
  28282. }
  28283. }
  28284. return self.contentDocument;
  28285. };
  28286. Editor.prototype.getBody = function () {
  28287. var doc = this.getDoc();
  28288. return this.bodyElement || (doc ? doc.body : null);
  28289. };
  28290. Editor.prototype.convertURL = function (url, name, elm) {
  28291. var self = this, settings = self.settings;
  28292. if (settings.urlconverter_callback) {
  28293. return self.execCallback('urlconverter_callback', url, elm, true, name);
  28294. }
  28295. if (!settings.convert_urls || elm && elm.nodeName === 'LINK' || url.indexOf('file:') === 0 || url.length === 0) {
  28296. return url;
  28297. }
  28298. if (settings.relative_urls) {
  28299. return self.documentBaseURI.toRelative(url);
  28300. }
  28301. url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host);
  28302. return url;
  28303. };
  28304. Editor.prototype.addVisual = function (elm) {
  28305. addVisual$1(this, elm);
  28306. };
  28307. Editor.prototype.remove = function () {
  28308. remove$7(this);
  28309. };
  28310. Editor.prototype.destroy = function (automatic) {
  28311. destroy(this, automatic);
  28312. };
  28313. Editor.prototype.uploadImages = function (callback) {
  28314. return this.editorUpload.uploadImages(callback);
  28315. };
  28316. Editor.prototype._scanForImages = function () {
  28317. return this.editorUpload.scanForImages();
  28318. };
  28319. Editor.prototype.addButton = function () {
  28320. 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');
  28321. };
  28322. Editor.prototype.addSidebar = function () {
  28323. throw new Error('editor.addSidebar has been removed in tinymce 5x, use editor.ui.registry.addSidebar instead');
  28324. };
  28325. Editor.prototype.addMenuItem = function () {
  28326. throw new Error('editor.addMenuItem has been removed in tinymce 5x, use editor.ui.registry.addMenuItem instead');
  28327. };
  28328. Editor.prototype.addContextToolbar = function () {
  28329. throw new Error('editor.addContextToolbar has been removed in tinymce 5x, use editor.ui.registry.addContextToolbar instead');
  28330. };
  28331. return Editor;
  28332. }();
  28333. var DOM$a = DOMUtils$1.DOM;
  28334. var explode$4 = Tools.explode, each$j = Tools.each, extend$4 = Tools.extend;
  28335. var instanceCounter = 0, boundGlobalEvents = false;
  28336. var beforeUnloadDelegate;
  28337. var legacyEditors = [];
  28338. var editors = [];
  28339. var isValidLegacyKey = function (id) {
  28340. return id !== 'length';
  28341. };
  28342. var globalEventDelegate = function (e) {
  28343. var type = e.type;
  28344. each$j(EditorManager.get(), function (editor) {
  28345. switch (type) {
  28346. case 'scroll':
  28347. editor.fire('ScrollWindow', e);
  28348. break;
  28349. case 'resize':
  28350. editor.fire('ResizeWindow', e);
  28351. break;
  28352. }
  28353. });
  28354. };
  28355. var toggleGlobalEvents = function (state) {
  28356. if (state !== boundGlobalEvents) {
  28357. if (state) {
  28358. DomQuery(window).on('resize scroll', globalEventDelegate);
  28359. } else {
  28360. DomQuery(window).off('resize scroll', globalEventDelegate);
  28361. }
  28362. boundGlobalEvents = state;
  28363. }
  28364. };
  28365. var removeEditorFromList = function (targetEditor) {
  28366. var oldEditors = editors;
  28367. delete legacyEditors[targetEditor.id];
  28368. for (var i = 0; i < legacyEditors.length; i++) {
  28369. if (legacyEditors[i] === targetEditor) {
  28370. legacyEditors.splice(i, 1);
  28371. break;
  28372. }
  28373. }
  28374. editors = filter(editors, function (editor) {
  28375. return targetEditor !== editor;
  28376. });
  28377. if (EditorManager.activeEditor === targetEditor) {
  28378. EditorManager.activeEditor = editors.length > 0 ? editors[0] : null;
  28379. }
  28380. if (EditorManager.focusedEditor === targetEditor) {
  28381. EditorManager.focusedEditor = null;
  28382. }
  28383. return oldEditors.length !== editors.length;
  28384. };
  28385. var purgeDestroyedEditor = function (editor) {
  28386. if (editor && editor.initialized && !(editor.getContainer() || editor.getBody()).parentNode) {
  28387. removeEditorFromList(editor);
  28388. editor.unbindAllNativeEvents();
  28389. editor.destroy(true);
  28390. editor.removed = true;
  28391. editor = null;
  28392. }
  28393. return editor;
  28394. };
  28395. var isQuirksMode = document.compatMode !== 'CSS1Compat';
  28396. var EditorManager = __assign(__assign({}, Observable), {
  28397. baseURI: null,
  28398. baseURL: null,
  28399. defaultSettings: {},
  28400. documentBaseURL: null,
  28401. suffix: null,
  28402. $: DomQuery,
  28403. majorVersion: '5',
  28404. minorVersion: '6.2',
  28405. releaseDate: '2020-12-08',
  28406. editors: legacyEditors,
  28407. i18n: I18n,
  28408. activeEditor: null,
  28409. focusedEditor: null,
  28410. settings: {},
  28411. setup: function () {
  28412. var self = this;
  28413. var baseURL, documentBaseURL, suffix = '';
  28414. documentBaseURL = URI.getDocumentBaseUrl(document.location);
  28415. if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
  28416. documentBaseURL = documentBaseURL.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  28417. if (!/[\/\\]$/.test(documentBaseURL)) {
  28418. documentBaseURL += '/';
  28419. }
  28420. }
  28421. var preInit = window.tinymce || window.tinyMCEPreInit;
  28422. if (preInit) {
  28423. baseURL = preInit.base || preInit.baseURL;
  28424. suffix = preInit.suffix;
  28425. } else {
  28426. var scripts = document.getElementsByTagName('script');
  28427. for (var i = 0; i < scripts.length; i++) {
  28428. var src = scripts[i].src || '';
  28429. if (src === '') {
  28430. continue;
  28431. }
  28432. var srcScript = src.substring(src.lastIndexOf('/'));
  28433. if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
  28434. if (srcScript.indexOf('.min') !== -1) {
  28435. suffix = '.min';
  28436. }
  28437. baseURL = src.substring(0, src.lastIndexOf('/'));
  28438. break;
  28439. }
  28440. }
  28441. if (!baseURL && document.currentScript) {
  28442. var src = document.currentScript.src;
  28443. if (src.indexOf('.min') !== -1) {
  28444. suffix = '.min';
  28445. }
  28446. baseURL = src.substring(0, src.lastIndexOf('/'));
  28447. }
  28448. }
  28449. self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
  28450. self.documentBaseURL = documentBaseURL;
  28451. self.baseURI = new URI(self.baseURL);
  28452. self.suffix = suffix;
  28453. setup$2(self);
  28454. },
  28455. overrideDefaults: function (defaultSettings) {
  28456. var baseUrl = defaultSettings.base_url;
  28457. if (baseUrl) {
  28458. this._setBaseUrl(baseUrl);
  28459. }
  28460. var suffix = defaultSettings.suffix;
  28461. if (defaultSettings.suffix) {
  28462. this.suffix = suffix;
  28463. }
  28464. this.defaultSettings = defaultSettings;
  28465. var pluginBaseUrls = defaultSettings.plugin_base_urls;
  28466. if (pluginBaseUrls !== undefined) {
  28467. each$1(pluginBaseUrls, function (pluginBaseUrl, pluginName) {
  28468. AddOnManager$1.PluginManager.urls[pluginName] = pluginBaseUrl;
  28469. });
  28470. }
  28471. },
  28472. init: function (settings) {
  28473. var self = this;
  28474. var result;
  28475. 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', ' ');
  28476. var isInvalidInlineTarget = function (settings, elm) {
  28477. return settings.inline && elm.tagName.toLowerCase() in invalidInlineTargets;
  28478. };
  28479. var createId = function (elm) {
  28480. var id = elm.id;
  28481. if (!id) {
  28482. id = get$1(elm, 'name').filter(function (name) {
  28483. return !DOM$a.get(name);
  28484. }).getOrThunk(DOM$a.uniqueId);
  28485. elm.setAttribute('id', id);
  28486. }
  28487. return id;
  28488. };
  28489. var execCallback = function (name) {
  28490. var callback = settings[name];
  28491. if (!callback) {
  28492. return;
  28493. }
  28494. return callback.apply(self, Array.prototype.slice.call(arguments, 2));
  28495. };
  28496. var hasClass = function (elm, className) {
  28497. return className.constructor === RegExp ? className.test(elm.className) : DOM$a.hasClass(elm, className);
  28498. };
  28499. var findTargets = function (settings) {
  28500. var targets = [];
  28501. if (Env.browser.isIE() && Env.browser.version.major < 11) {
  28502. 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/');
  28503. return [];
  28504. } else if (isQuirksMode) {
  28505. initError('Failed to initialize the editor as the document is not in standards mode. ' + 'TinyMCE requires standards mode.');
  28506. return [];
  28507. }
  28508. if (settings.types) {
  28509. each$j(settings.types, function (type) {
  28510. targets = targets.concat(DOM$a.select(type.selector));
  28511. });
  28512. return targets;
  28513. } else if (settings.selector) {
  28514. return DOM$a.select(settings.selector);
  28515. } else if (settings.target) {
  28516. return [settings.target];
  28517. }
  28518. switch (settings.mode) {
  28519. case 'exact':
  28520. var l = settings.elements || '';
  28521. if (l.length > 0) {
  28522. each$j(explode$4(l), function (id) {
  28523. var elm = DOM$a.get(id);
  28524. if (elm) {
  28525. targets.push(elm);
  28526. } else {
  28527. each$j(document.forms, function (f) {
  28528. each$j(f.elements, function (e) {
  28529. if (e.name === id) {
  28530. id = 'mce_editor_' + instanceCounter++;
  28531. DOM$a.setAttrib(e, 'id', id);
  28532. targets.push(e);
  28533. }
  28534. });
  28535. });
  28536. }
  28537. });
  28538. }
  28539. break;
  28540. case 'textareas':
  28541. case 'specific_textareas':
  28542. each$j(DOM$a.select('textarea'), function (elm) {
  28543. if (settings.editor_deselector && hasClass(elm, settings.editor_deselector)) {
  28544. return;
  28545. }
  28546. if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) {
  28547. targets.push(elm);
  28548. }
  28549. });
  28550. break;
  28551. }
  28552. return targets;
  28553. };
  28554. var provideResults = function (editors) {
  28555. result = editors;
  28556. };
  28557. var initEditors = function () {
  28558. var initCount = 0;
  28559. var editors = [];
  28560. var targets;
  28561. var createEditor = function (id, settings, targetElm) {
  28562. var editor = new Editor(id, settings, self);
  28563. editors.push(editor);
  28564. editor.on('init', function () {
  28565. if (++initCount === targets.length) {
  28566. provideResults(editors);
  28567. }
  28568. });
  28569. editor.targetElm = editor.targetElm || targetElm;
  28570. editor.render();
  28571. };
  28572. DOM$a.unbind(window, 'ready', initEditors);
  28573. execCallback('onpageload');
  28574. targets = DomQuery.unique(findTargets(settings));
  28575. if (settings.types) {
  28576. each$j(settings.types, function (type) {
  28577. Tools.each(targets, function (elm) {
  28578. if (DOM$a.is(elm, type.selector)) {
  28579. createEditor(createId(elm), extend$4({}, settings, type), elm);
  28580. return false;
  28581. }
  28582. return true;
  28583. });
  28584. });
  28585. return;
  28586. }
  28587. Tools.each(targets, function (elm) {
  28588. purgeDestroyedEditor(self.get(elm.id));
  28589. });
  28590. targets = Tools.grep(targets, function (elm) {
  28591. return !self.get(elm.id);
  28592. });
  28593. if (targets.length === 0) {
  28594. provideResults([]);
  28595. } else {
  28596. each$j(targets, function (elm) {
  28597. if (isInvalidInlineTarget(settings, elm)) {
  28598. initError('Could not initialize inline editor on invalid inline target element', elm);
  28599. } else {
  28600. createEditor(createId(elm), settings, elm);
  28601. }
  28602. });
  28603. }
  28604. };
  28605. self.settings = settings;
  28606. DOM$a.bind(window, 'ready', initEditors);
  28607. return new promiseObj(function (resolve) {
  28608. if (result) {
  28609. resolve(result);
  28610. } else {
  28611. provideResults = function (editors) {
  28612. resolve(editors);
  28613. };
  28614. }
  28615. });
  28616. },
  28617. get: function (id) {
  28618. if (arguments.length === 0) {
  28619. return editors.slice(0);
  28620. } else if (isString(id)) {
  28621. return find(editors, function (editor) {
  28622. return editor.id === id;
  28623. }).getOr(null);
  28624. } else if (isNumber(id)) {
  28625. return editors[id] ? editors[id] : null;
  28626. } else {
  28627. return null;
  28628. }
  28629. },
  28630. add: function (editor) {
  28631. var self = this;
  28632. var existingEditor = legacyEditors[editor.id];
  28633. if (existingEditor === editor) {
  28634. return editor;
  28635. }
  28636. if (self.get(editor.id) === null) {
  28637. if (isValidLegacyKey(editor.id)) {
  28638. legacyEditors[editor.id] = editor;
  28639. }
  28640. legacyEditors.push(editor);
  28641. editors.push(editor);
  28642. }
  28643. toggleGlobalEvents(true);
  28644. self.activeEditor = editor;
  28645. self.fire('AddEditor', { editor: editor });
  28646. if (!beforeUnloadDelegate) {
  28647. beforeUnloadDelegate = function (e) {
  28648. var event = self.fire('BeforeUnload');
  28649. if (event.returnValue) {
  28650. e.preventDefault();
  28651. e.returnValue = event.returnValue;
  28652. return event.returnValue;
  28653. }
  28654. };
  28655. window.addEventListener('beforeunload', beforeUnloadDelegate);
  28656. }
  28657. return editor;
  28658. },
  28659. createEditor: function (id, settings) {
  28660. return this.add(new Editor(id, settings, this));
  28661. },
  28662. remove: function (selector) {
  28663. var self = this;
  28664. var i, editor;
  28665. if (!selector) {
  28666. for (i = editors.length - 1; i >= 0; i--) {
  28667. self.remove(editors[i]);
  28668. }
  28669. return;
  28670. }
  28671. if (isString(selector)) {
  28672. each$j(DOM$a.select(selector), function (elm) {
  28673. editor = self.get(elm.id);
  28674. if (editor) {
  28675. self.remove(editor);
  28676. }
  28677. });
  28678. return;
  28679. }
  28680. editor = selector;
  28681. if (isNull(self.get(editor.id))) {
  28682. return null;
  28683. }
  28684. if (removeEditorFromList(editor)) {
  28685. self.fire('RemoveEditor', { editor: editor });
  28686. }
  28687. if (editors.length === 0) {
  28688. window.removeEventListener('beforeunload', beforeUnloadDelegate);
  28689. }
  28690. editor.remove();
  28691. toggleGlobalEvents(editors.length > 0);
  28692. return editor;
  28693. },
  28694. execCommand: function (cmd, ui, value) {
  28695. var self = this, editor = self.get(value);
  28696. switch (cmd) {
  28697. case 'mceAddEditor':
  28698. if (!self.get(value)) {
  28699. new Editor(value, self.settings, self).render();
  28700. }
  28701. return true;
  28702. case 'mceRemoveEditor':
  28703. if (editor) {
  28704. editor.remove();
  28705. }
  28706. return true;
  28707. case 'mceToggleEditor':
  28708. if (!editor) {
  28709. self.execCommand('mceAddEditor', 0, value);
  28710. return true;
  28711. }
  28712. if (editor.isHidden()) {
  28713. editor.show();
  28714. } else {
  28715. editor.hide();
  28716. }
  28717. return true;
  28718. }
  28719. if (self.activeEditor) {
  28720. return self.activeEditor.execCommand(cmd, ui, value);
  28721. }
  28722. return false;
  28723. },
  28724. triggerSave: function () {
  28725. each$j(editors, function (editor) {
  28726. editor.save();
  28727. });
  28728. },
  28729. addI18n: function (code, items) {
  28730. I18n.add(code, items);
  28731. },
  28732. translate: function (text) {
  28733. return I18n.translate(text);
  28734. },
  28735. setActive: function (editor) {
  28736. var activeEditor = this.activeEditor;
  28737. if (this.activeEditor !== editor) {
  28738. if (activeEditor) {
  28739. activeEditor.fire('deactivate', { relatedTarget: editor });
  28740. }
  28741. editor.fire('activate', { relatedTarget: activeEditor });
  28742. }
  28743. this.activeEditor = editor;
  28744. },
  28745. _setBaseUrl: function (baseUrl) {
  28746. this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ''));
  28747. this.baseURI = new URI(this.baseURL);
  28748. }
  28749. });
  28750. EditorManager.setup();
  28751. var min = Math.min, max = Math.max, round$1 = Math.round;
  28752. var relativePosition = function (rect, targetRect, rel) {
  28753. var x = targetRect.x;
  28754. var y = targetRect.y;
  28755. var w = rect.w;
  28756. var h = rect.h;
  28757. var targetW = targetRect.w;
  28758. var targetH = targetRect.h;
  28759. var relChars = (rel || '').split('');
  28760. if (relChars[0] === 'b') {
  28761. y += targetH;
  28762. }
  28763. if (relChars[1] === 'r') {
  28764. x += targetW;
  28765. }
  28766. if (relChars[0] === 'c') {
  28767. y += round$1(targetH / 2);
  28768. }
  28769. if (relChars[1] === 'c') {
  28770. x += round$1(targetW / 2);
  28771. }
  28772. if (relChars[3] === 'b') {
  28773. y -= h;
  28774. }
  28775. if (relChars[4] === 'r') {
  28776. x -= w;
  28777. }
  28778. if (relChars[3] === 'c') {
  28779. y -= round$1(h / 2);
  28780. }
  28781. if (relChars[4] === 'c') {
  28782. x -= round$1(w / 2);
  28783. }
  28784. return create$7(x, y, w, h);
  28785. };
  28786. var findBestRelativePosition = function (rect, targetRect, constrainRect, rels) {
  28787. var pos, i;
  28788. for (i = 0; i < rels.length; i++) {
  28789. pos = relativePosition(rect, targetRect, rels[i]);
  28790. 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) {
  28791. return rels[i];
  28792. }
  28793. }
  28794. return null;
  28795. };
  28796. var inflate = function (rect, w, h) {
  28797. return create$7(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2);
  28798. };
  28799. var intersect = function (rect, cropRect) {
  28800. var x1 = max(rect.x, cropRect.x);
  28801. var y1 = max(rect.y, cropRect.y);
  28802. var x2 = min(rect.x + rect.w, cropRect.x + cropRect.w);
  28803. var y2 = min(rect.y + rect.h, cropRect.y + cropRect.h);
  28804. if (x2 - x1 < 0 || y2 - y1 < 0) {
  28805. return null;
  28806. }
  28807. return create$7(x1, y1, x2 - x1, y2 - y1);
  28808. };
  28809. var clamp$1 = function (rect, clampRect, fixedSize) {
  28810. var x1 = rect.x;
  28811. var y1 = rect.y;
  28812. var x2 = rect.x + rect.w;
  28813. var y2 = rect.y + rect.h;
  28814. var cx2 = clampRect.x + clampRect.w;
  28815. var cy2 = clampRect.y + clampRect.h;
  28816. var underflowX1 = max(0, clampRect.x - x1);
  28817. var underflowY1 = max(0, clampRect.y - y1);
  28818. var overflowX2 = max(0, x2 - cx2);
  28819. var overflowY2 = max(0, y2 - cy2);
  28820. x1 += underflowX1;
  28821. y1 += underflowY1;
  28822. if (fixedSize) {
  28823. x2 += underflowX1;
  28824. y2 += underflowY1;
  28825. x1 -= overflowX2;
  28826. y1 -= overflowY2;
  28827. }
  28828. x2 -= overflowX2;
  28829. y2 -= overflowY2;
  28830. return create$7(x1, y1, x2 - x1, y2 - y1);
  28831. };
  28832. var create$7 = function (x, y, w, h) {
  28833. return {
  28834. x: x,
  28835. y: y,
  28836. w: w,
  28837. h: h
  28838. };
  28839. };
  28840. var fromClientRect = function (clientRect) {
  28841. return create$7(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
  28842. };
  28843. var Rect = {
  28844. inflate: inflate,
  28845. relativePosition: relativePosition,
  28846. findBestRelativePosition: findBestRelativePosition,
  28847. intersect: intersect,
  28848. clamp: clamp$1,
  28849. create: create$7,
  28850. fromClientRect: fromClientRect
  28851. };
  28852. var awaiter = function (resolveCb, rejectCb, timeout) {
  28853. if (timeout === void 0) {
  28854. timeout = 1000;
  28855. }
  28856. var done = false;
  28857. var timer = null;
  28858. var complete = function (completer) {
  28859. return function () {
  28860. var args = [];
  28861. for (var _i = 0; _i < arguments.length; _i++) {
  28862. args[_i] = arguments[_i];
  28863. }
  28864. if (!done) {
  28865. done = true;
  28866. if (timer !== null) {
  28867. clearTimeout(timer);
  28868. timer = null;
  28869. }
  28870. completer.apply(null, args);
  28871. }
  28872. };
  28873. };
  28874. var resolve = complete(resolveCb);
  28875. var reject = complete(rejectCb);
  28876. var start = function () {
  28877. var args = [];
  28878. for (var _i = 0; _i < arguments.length; _i++) {
  28879. args[_i] = arguments[_i];
  28880. }
  28881. if (!done && timer === null) {
  28882. timer = setTimeout(function () {
  28883. return reject.apply(null, args);
  28884. }, timeout);
  28885. }
  28886. };
  28887. return {
  28888. start: start,
  28889. resolve: resolve,
  28890. reject: reject
  28891. };
  28892. };
  28893. var create$8 = function () {
  28894. var tasks = {};
  28895. var resultFns = {};
  28896. var load = function (id, url) {
  28897. var loadErrMsg = 'Script at URL "' + url + '" failed to load';
  28898. var runErrMsg = 'Script at URL "' + url + '" did not call `tinymce.Resource.add(\'' + id + '\', data)` within 1 second';
  28899. if (tasks[id] !== undefined) {
  28900. return tasks[id];
  28901. } else {
  28902. var task = new promiseObj(function (resolve, reject) {
  28903. var waiter = awaiter(resolve, reject);
  28904. resultFns[id] = waiter.resolve;
  28905. ScriptLoader.ScriptLoader.loadScript(url, function () {
  28906. return waiter.start(runErrMsg);
  28907. }, function () {
  28908. return waiter.reject(loadErrMsg);
  28909. });
  28910. });
  28911. tasks[id] = task;
  28912. return task;
  28913. }
  28914. };
  28915. var add = function (id, data) {
  28916. if (resultFns[id] !== undefined) {
  28917. resultFns[id](data);
  28918. delete resultFns[id];
  28919. }
  28920. tasks[id] = promiseObj.resolve(data);
  28921. };
  28922. return {
  28923. load: load,
  28924. add: add
  28925. };
  28926. };
  28927. var Resource = create$8();
  28928. var each$k = Tools.each, extend$5 = Tools.extend;
  28929. var extendClass, initializing;
  28930. var Class = function () {
  28931. };
  28932. Class.extend = extendClass = function (props) {
  28933. var self = this;
  28934. var _super = self.prototype;
  28935. var Class = function () {
  28936. var i, mixins, mixin;
  28937. var self = this;
  28938. if (!initializing) {
  28939. if (self.init) {
  28940. self.init.apply(self, arguments);
  28941. }
  28942. mixins = self.Mixins;
  28943. if (mixins) {
  28944. i = mixins.length;
  28945. while (i--) {
  28946. mixin = mixins[i];
  28947. if (mixin.init) {
  28948. mixin.init.apply(self, arguments);
  28949. }
  28950. }
  28951. }
  28952. }
  28953. };
  28954. var dummy = function () {
  28955. return this;
  28956. };
  28957. var createMethod = function (name, fn) {
  28958. return function () {
  28959. var self = this;
  28960. var tmp = self._super;
  28961. self._super = _super[name];
  28962. var ret = fn.apply(self, arguments);
  28963. self._super = tmp;
  28964. return ret;
  28965. };
  28966. };
  28967. initializing = true;
  28968. var prototype = new self();
  28969. initializing = false;
  28970. if (props.Mixins) {
  28971. each$k(props.Mixins, function (mixin) {
  28972. for (var name_1 in mixin) {
  28973. if (name_1 !== 'init') {
  28974. props[name_1] = mixin[name_1];
  28975. }
  28976. }
  28977. });
  28978. if (_super.Mixins) {
  28979. props.Mixins = _super.Mixins.concat(props.Mixins);
  28980. }
  28981. }
  28982. if (props.Methods) {
  28983. each$k(props.Methods.split(','), function (name) {
  28984. props[name] = dummy;
  28985. });
  28986. }
  28987. if (props.Properties) {
  28988. each$k(props.Properties.split(','), function (name) {
  28989. var fieldName = '_' + name;
  28990. props[name] = function (value) {
  28991. var self = this;
  28992. if (value !== undefined) {
  28993. self[fieldName] = value;
  28994. return self;
  28995. }
  28996. return self[fieldName];
  28997. };
  28998. });
  28999. }
  29000. if (props.Statics) {
  29001. each$k(props.Statics, function (func, name) {
  29002. Class[name] = func;
  29003. });
  29004. }
  29005. if (props.Defaults && _super.Defaults) {
  29006. props.Defaults = extend$5({}, _super.Defaults, props.Defaults);
  29007. }
  29008. each$1(props, function (member, name) {
  29009. if (typeof member === 'function' && _super[name]) {
  29010. prototype[name] = createMethod(name, member);
  29011. } else {
  29012. prototype[name] = member;
  29013. }
  29014. });
  29015. Class.prototype = prototype;
  29016. Class.constructor = Class;
  29017. Class.extend = extendClass;
  29018. return Class;
  29019. };
  29020. var min$1 = Math.min, max$1 = Math.max, round$2 = Math.round;
  29021. var Color = function (value) {
  29022. var self = {};
  29023. var r = 0, g = 0, b = 0;
  29024. var rgb2hsv = function (r, g, b) {
  29025. var h, s, v;
  29026. h = 0;
  29027. s = 0;
  29028. v = 0;
  29029. r = r / 255;
  29030. g = g / 255;
  29031. b = b / 255;
  29032. var minRGB = min$1(r, min$1(g, b));
  29033. var maxRGB = max$1(r, max$1(g, b));
  29034. if (minRGB === maxRGB) {
  29035. v = minRGB;
  29036. return {
  29037. h: 0,
  29038. s: 0,
  29039. v: v * 100
  29040. };
  29041. }
  29042. var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  29043. h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  29044. h = 60 * (h - d / (maxRGB - minRGB));
  29045. s = (maxRGB - minRGB) / maxRGB;
  29046. v = maxRGB;
  29047. return {
  29048. h: round$2(h),
  29049. s: round$2(s * 100),
  29050. v: round$2(v * 100)
  29051. };
  29052. };
  29053. var hsvToRgb = function (hue, saturation, brightness) {
  29054. hue = (parseInt(hue, 10) || 0) % 360;
  29055. saturation = parseInt(saturation, 10) / 100;
  29056. brightness = parseInt(brightness, 10) / 100;
  29057. saturation = max$1(0, min$1(saturation, 1));
  29058. brightness = max$1(0, min$1(brightness, 1));
  29059. if (saturation === 0) {
  29060. r = g = b = round$2(255 * brightness);
  29061. return;
  29062. }
  29063. var side = hue / 60;
  29064. var chroma = brightness * saturation;
  29065. var x = chroma * (1 - Math.abs(side % 2 - 1));
  29066. var match = brightness - chroma;
  29067. switch (Math.floor(side)) {
  29068. case 0:
  29069. r = chroma;
  29070. g = x;
  29071. b = 0;
  29072. break;
  29073. case 1:
  29074. r = x;
  29075. g = chroma;
  29076. b = 0;
  29077. break;
  29078. case 2:
  29079. r = 0;
  29080. g = chroma;
  29081. b = x;
  29082. break;
  29083. case 3:
  29084. r = 0;
  29085. g = x;
  29086. b = chroma;
  29087. break;
  29088. case 4:
  29089. r = x;
  29090. g = 0;
  29091. b = chroma;
  29092. break;
  29093. case 5:
  29094. r = chroma;
  29095. g = 0;
  29096. b = x;
  29097. break;
  29098. default:
  29099. r = g = b = 0;
  29100. }
  29101. r = round$2(255 * (r + match));
  29102. g = round$2(255 * (g + match));
  29103. b = round$2(255 * (b + match));
  29104. };
  29105. var toHex = function () {
  29106. var hex = function (val) {
  29107. val = parseInt(val, 10).toString(16);
  29108. return val.length > 1 ? val : '0' + val;
  29109. };
  29110. return '#' + hex(r) + hex(g) + hex(b);
  29111. };
  29112. var toRgb = function () {
  29113. return {
  29114. r: r,
  29115. g: g,
  29116. b: b
  29117. };
  29118. };
  29119. var toHsv = function () {
  29120. return rgb2hsv(r, g, b);
  29121. };
  29122. var parse = function (value) {
  29123. var matches;
  29124. if (typeof value === 'object') {
  29125. if ('r' in value) {
  29126. r = value.r;
  29127. g = value.g;
  29128. b = value.b;
  29129. } else if ('v' in value) {
  29130. hsvToRgb(value.h, value.s, value.v);
  29131. }
  29132. } else {
  29133. if (matches = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)[^\)]*\)/gi.exec(value)) {
  29134. r = parseInt(matches[1], 10);
  29135. g = parseInt(matches[2], 10);
  29136. b = parseInt(matches[3], 10);
  29137. } else if (matches = /#([0-F]{2})([0-F]{2})([0-F]{2})/gi.exec(value)) {
  29138. r = parseInt(matches[1], 16);
  29139. g = parseInt(matches[2], 16);
  29140. b = parseInt(matches[3], 16);
  29141. } else if (matches = /#([0-F])([0-F])([0-F])/gi.exec(value)) {
  29142. r = parseInt(matches[1] + matches[1], 16);
  29143. g = parseInt(matches[2] + matches[2], 16);
  29144. b = parseInt(matches[3] + matches[3], 16);
  29145. }
  29146. }
  29147. r = r < 0 ? 0 : r > 255 ? 255 : r;
  29148. g = g < 0 ? 0 : g > 255 ? 255 : g;
  29149. b = b < 0 ? 0 : b > 255 ? 255 : b;
  29150. return self;
  29151. };
  29152. if (value) {
  29153. parse(value);
  29154. }
  29155. self.toRgb = toRgb;
  29156. self.toHsv = toHsv;
  29157. self.toHex = toHex;
  29158. self.parse = parse;
  29159. return self;
  29160. };
  29161. var serialize = function (obj) {
  29162. var data = JSON.stringify(obj);
  29163. if (!isString(data)) {
  29164. return data;
  29165. }
  29166. return data.replace(/[\u0080-\uFFFF]/g, function (match) {
  29167. var hexCode = match.charCodeAt(0).toString(16);
  29168. return '\\u' + '0000'.substring(hexCode.length) + hexCode;
  29169. });
  29170. };
  29171. var JSONUtils = {
  29172. serialize: serialize,
  29173. parse: function (text) {
  29174. try {
  29175. return JSON.parse(text);
  29176. } catch (ex) {
  29177. }
  29178. }
  29179. };
  29180. var JSONP = {
  29181. callbacks: {},
  29182. count: 0,
  29183. send: function (settings) {
  29184. var self = this, dom = DOMUtils$1.DOM, count = settings.count !== undefined ? settings.count : self.count;
  29185. var id = 'tinymce_jsonp_' + count;
  29186. self.callbacks[count] = function (json) {
  29187. dom.remove(id);
  29188. delete self.callbacks[count];
  29189. settings.callback(json);
  29190. };
  29191. dom.add(dom.doc.body, 'script', {
  29192. id: id,
  29193. src: settings.url,
  29194. type: 'text/javascript'
  29195. });
  29196. self.count++;
  29197. }
  29198. };
  29199. var XHR = __assign(__assign({}, Observable), {
  29200. send: function (settings) {
  29201. var xhr, count = 0;
  29202. var ready = function () {
  29203. if (!settings.async || xhr.readyState === 4 || count++ > 10000) {
  29204. if (settings.success && count < 10000 && xhr.status === 200) {
  29205. settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings);
  29206. } else if (settings.error) {
  29207. settings.error.call(settings.error_scope, count > 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings);
  29208. }
  29209. xhr = null;
  29210. } else {
  29211. Delay.setTimeout(ready, 10);
  29212. }
  29213. };
  29214. settings.scope = settings.scope || this;
  29215. settings.success_scope = settings.success_scope || settings.scope;
  29216. settings.error_scope = settings.error_scope || settings.scope;
  29217. settings.async = settings.async !== false;
  29218. settings.data = settings.data || '';
  29219. XHR.fire('beforeInitialize', { settings: settings });
  29220. xhr = new XMLHttpRequest();
  29221. if (xhr.overrideMimeType) {
  29222. xhr.overrideMimeType(settings.content_type);
  29223. }
  29224. xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async);
  29225. if (settings.crossDomain) {
  29226. xhr.withCredentials = true;
  29227. }
  29228. if (settings.content_type) {
  29229. xhr.setRequestHeader('Content-Type', settings.content_type);
  29230. }
  29231. if (settings.requestheaders) {
  29232. Tools.each(settings.requestheaders, function (header) {
  29233. xhr.setRequestHeader(header.key, header.value);
  29234. });
  29235. }
  29236. xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  29237. xhr = XHR.fire('beforeSend', {
  29238. xhr: xhr,
  29239. settings: settings
  29240. }).xhr;
  29241. xhr.send(settings.data);
  29242. if (!settings.async) {
  29243. return ready();
  29244. }
  29245. Delay.setTimeout(ready, 10);
  29246. }
  29247. });
  29248. var extend$6 = Tools.extend;
  29249. var JSONRequest = function () {
  29250. function JSONRequest(settings) {
  29251. this.settings = extend$6({}, settings);
  29252. this.count = 0;
  29253. }
  29254. JSONRequest.sendRPC = function (o) {
  29255. return new JSONRequest().send(o);
  29256. };
  29257. JSONRequest.prototype.send = function (args) {
  29258. var ecb = args.error, scb = args.success;
  29259. var xhrArgs = extend$6(this.settings, args);
  29260. xhrArgs.success = function (c, x) {
  29261. c = JSONUtils.parse(c);
  29262. if (typeof c === 'undefined') {
  29263. c = { error: 'JSON Parse error.' };
  29264. }
  29265. if (c.error) {
  29266. ecb.call(xhrArgs.error_scope || xhrArgs.scope, c.error, x);
  29267. } else {
  29268. scb.call(xhrArgs.success_scope || xhrArgs.scope, c.result);
  29269. }
  29270. };
  29271. xhrArgs.error = function (ty, x) {
  29272. if (ecb) {
  29273. ecb.call(xhrArgs.error_scope || xhrArgs.scope, ty, x);
  29274. }
  29275. };
  29276. xhrArgs.data = JSONUtils.serialize({
  29277. id: args.id || 'c' + this.count++,
  29278. method: args.method,
  29279. params: args.params
  29280. });
  29281. xhrArgs.content_type = 'application/json';
  29282. XHR.send(xhrArgs);
  29283. };
  29284. return JSONRequest;
  29285. }();
  29286. var create$9 = function () {
  29287. return function () {
  29288. var data = {};
  29289. var keys = [];
  29290. var storage = {
  29291. getItem: function (key) {
  29292. var item = data[key];
  29293. return item ? item : null;
  29294. },
  29295. setItem: function (key, value) {
  29296. keys.push(key);
  29297. data[key] = String(value);
  29298. },
  29299. key: function (index) {
  29300. return keys[index];
  29301. },
  29302. removeItem: function (key) {
  29303. keys = keys.filter(function (k) {
  29304. return k === key;
  29305. });
  29306. delete data[key];
  29307. },
  29308. clear: function () {
  29309. keys = [];
  29310. data = {};
  29311. },
  29312. length: 0
  29313. };
  29314. Object.defineProperty(storage, 'length', {
  29315. get: function () {
  29316. return keys.length;
  29317. },
  29318. configurable: false,
  29319. enumerable: false
  29320. });
  29321. return storage;
  29322. }();
  29323. };
  29324. var localStorage;
  29325. try {
  29326. var test = '__storage_test__';
  29327. localStorage = window.localStorage;
  29328. localStorage.setItem(test, test);
  29329. localStorage.removeItem(test);
  29330. } catch (e) {
  29331. localStorage = create$9();
  29332. }
  29333. var LocalStorage = localStorage;
  29334. var publicApi = {
  29335. geom: { Rect: Rect },
  29336. util: {
  29337. Promise: promiseObj,
  29338. Delay: Delay,
  29339. Tools: Tools,
  29340. VK: VK,
  29341. URI: URI,
  29342. Class: Class,
  29343. EventDispatcher: EventDispatcher,
  29344. Observable: Observable,
  29345. I18n: I18n,
  29346. XHR: XHR,
  29347. JSON: JSONUtils,
  29348. JSONRequest: JSONRequest,
  29349. JSONP: JSONP,
  29350. LocalStorage: LocalStorage,
  29351. Color: Color
  29352. },
  29353. dom: {
  29354. EventUtils: EventUtils,
  29355. Sizzle: Sizzle,
  29356. DomQuery: DomQuery,
  29357. TreeWalker: DomTreeWalker,
  29358. TextSeeker: TextSeeker,
  29359. DOMUtils: DOMUtils$1,
  29360. ScriptLoader: ScriptLoader,
  29361. RangeUtils: RangeUtils$1,
  29362. Serializer: DomSerializer,
  29363. StyleSheetLoader: StyleSheetLoader,
  29364. ControlSelection: ControlSelection,
  29365. BookmarkManager: BookmarkManager$1,
  29366. Selection: EditorSelection,
  29367. Event: EventUtils.Event
  29368. },
  29369. html: {
  29370. Styles: Styles,
  29371. Entities: Entities,
  29372. Node: AstNode,
  29373. Schema: Schema,
  29374. SaxParser: SaxParser$1,
  29375. DomParser: DomParser,
  29376. Writer: Writer,
  29377. Serializer: HtmlSerializer
  29378. },
  29379. Env: Env,
  29380. AddOnManager: AddOnManager$1,
  29381. Annotator: Annotator,
  29382. Formatter: Formatter,
  29383. UndoManager: UndoManager,
  29384. EditorCommands: EditorCommands,
  29385. WindowManager: WindowManager,
  29386. NotificationManager: NotificationManager,
  29387. EditorObservable: EditorObservable,
  29388. Shortcuts: Shortcuts,
  29389. Editor: Editor,
  29390. FocusManager: FocusManager,
  29391. EditorManager: EditorManager,
  29392. DOM: DOMUtils$1.DOM,
  29393. ScriptLoader: ScriptLoader.ScriptLoader,
  29394. PluginManager: PluginManager,
  29395. ThemeManager: ThemeManager,
  29396. IconManager: IconManager,
  29397. Resource: Resource,
  29398. trim: Tools.trim,
  29399. isArray: Tools.isArray,
  29400. is: Tools.is,
  29401. toArray: Tools.toArray,
  29402. makeMap: Tools.makeMap,
  29403. each: Tools.each,
  29404. map: Tools.map,
  29405. grep: Tools.grep,
  29406. inArray: Tools.inArray,
  29407. extend: Tools.extend,
  29408. create: Tools.create,
  29409. walk: Tools.walk,
  29410. createNS: Tools.createNS,
  29411. resolve: Tools.resolve,
  29412. explode: Tools.explode,
  29413. _addCacheSuffix: Tools._addCacheSuffix,
  29414. isOpera: Env.opera,
  29415. isWebKit: Env.webkit,
  29416. isIE: Env.ie,
  29417. isGecko: Env.gecko,
  29418. isMac: Env.mac
  29419. };
  29420. var tinymce = Tools.extend(EditorManager, publicApi);
  29421. var exportToModuleLoaders = function (tinymce) {
  29422. if (typeof module === 'object') {
  29423. try {
  29424. module.exports = tinymce;
  29425. } catch (_) {
  29426. }
  29427. }
  29428. };
  29429. var exportToWindowGlobal = function (tinymce) {
  29430. window.tinymce = tinymce;
  29431. window.tinyMCE = tinymce;
  29432. };
  29433. exportToWindowGlobal(tinymce);
  29434. exportToModuleLoaders(tinymce);
  29435. }());