tinymce.js 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049
  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.10.2 (2021-11-17)
  8. */
  9. (function () {
  10. 'use strict';
  11. var typeOf$1 = 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$1 = 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$2(function (x, y) {
  44. return eqa.eq(f(x), f(y));
  45. });
  46. };
  47. var eq$2 = function (f) {
  48. return { eq: f };
  49. };
  50. var tripleEq = eq$2(function (x, y) {
  51. return x === y;
  52. });
  53. var eqString = tripleEq;
  54. var eqArray = function (eqa) {
  55. return eq$2(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$1(xs, compareFn);
  71. });
  72. };
  73. var eqRecord = function (eqa) {
  74. return eq$2(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$2(function (x, y) {
  91. if (x === y) {
  92. return true;
  93. }
  94. var tx = typeOf$1(x);
  95. var ty = typeOf$1(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 typeOf = function (x) {
  109. var t = typeof x;
  110. if (x === null) {
  111. return 'null';
  112. } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  113. return 'array';
  114. } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  115. return 'string';
  116. } else {
  117. return t;
  118. }
  119. };
  120. var isType$1 = function (type) {
  121. return function (value) {
  122. return typeOf(value) === type;
  123. };
  124. };
  125. var isSimpleType = function (type) {
  126. return function (value) {
  127. return typeof value === type;
  128. };
  129. };
  130. var eq$1 = function (t) {
  131. return function (a) {
  132. return t === a;
  133. };
  134. };
  135. var isString$1 = isType$1('string');
  136. var isObject = isType$1('object');
  137. var isArray$1 = isType$1('array');
  138. var isNull = eq$1(null);
  139. var isBoolean = isSimpleType('boolean');
  140. var isUndefined = eq$1(undefined);
  141. var isNullable = function (a) {
  142. return a === null || a === undefined;
  143. };
  144. var isNonNullable = function (a) {
  145. return !isNullable(a);
  146. };
  147. var isFunction = isSimpleType('function');
  148. var isNumber = isSimpleType('number');
  149. var noop = function () {
  150. };
  151. var compose = function (fa, fb) {
  152. return function () {
  153. var args = [];
  154. for (var _i = 0; _i < arguments.length; _i++) {
  155. args[_i] = arguments[_i];
  156. }
  157. return fa(fb.apply(null, args));
  158. };
  159. };
  160. var compose1 = function (fbc, fab) {
  161. return function (a) {
  162. return fbc(fab(a));
  163. };
  164. };
  165. var constant = function (value) {
  166. return function () {
  167. return value;
  168. };
  169. };
  170. var identity = function (x) {
  171. return x;
  172. };
  173. var tripleEquals = function (a, b) {
  174. return a === b;
  175. };
  176. function curry(fn) {
  177. var initialArgs = [];
  178. for (var _i = 1; _i < arguments.length; _i++) {
  179. initialArgs[_i - 1] = arguments[_i];
  180. }
  181. return function () {
  182. var restArgs = [];
  183. for (var _i = 0; _i < arguments.length; _i++) {
  184. restArgs[_i] = arguments[_i];
  185. }
  186. var all = initialArgs.concat(restArgs);
  187. return fn.apply(null, all);
  188. };
  189. }
  190. var not = function (f) {
  191. return function (t) {
  192. return !f(t);
  193. };
  194. };
  195. var die = function (msg) {
  196. return function () {
  197. throw new Error(msg);
  198. };
  199. };
  200. var apply = function (f) {
  201. return f();
  202. };
  203. var call = function (f) {
  204. f();
  205. };
  206. var never = constant(false);
  207. var always = constant(true);
  208. var none = function () {
  209. return NONE;
  210. };
  211. var NONE = function () {
  212. var call = function (thunk) {
  213. return thunk();
  214. };
  215. var id = identity;
  216. var me = {
  217. fold: function (n, _s) {
  218. return n();
  219. },
  220. isSome: never,
  221. isNone: always,
  222. getOr: id,
  223. getOrThunk: call,
  224. getOrDie: function (msg) {
  225. throw new Error(msg || 'error: getOrDie called on none.');
  226. },
  227. getOrNull: constant(null),
  228. getOrUndefined: constant(undefined),
  229. or: id,
  230. orThunk: call,
  231. map: none,
  232. each: noop,
  233. bind: none,
  234. exists: never,
  235. forall: always,
  236. filter: function () {
  237. return none();
  238. },
  239. toArray: function () {
  240. return [];
  241. },
  242. toString: constant('none()')
  243. };
  244. return me;
  245. }();
  246. var some = function (a) {
  247. var constant_a = constant(a);
  248. var self = function () {
  249. return me;
  250. };
  251. var bind = function (f) {
  252. return f(a);
  253. };
  254. var me = {
  255. fold: function (n, s) {
  256. return s(a);
  257. },
  258. isSome: always,
  259. isNone: never,
  260. getOr: constant_a,
  261. getOrThunk: constant_a,
  262. getOrDie: constant_a,
  263. getOrNull: constant_a,
  264. getOrUndefined: constant_a,
  265. or: self,
  266. orThunk: self,
  267. map: function (f) {
  268. return some(f(a));
  269. },
  270. each: function (f) {
  271. f(a);
  272. },
  273. bind: bind,
  274. exists: bind,
  275. forall: bind,
  276. filter: function (f) {
  277. return f(a) ? me : NONE;
  278. },
  279. toArray: function () {
  280. return [a];
  281. },
  282. toString: function () {
  283. return 'some(' + a + ')';
  284. }
  285. };
  286. return me;
  287. };
  288. var from$1 = function (value) {
  289. return value === null || value === undefined ? NONE : some(value);
  290. };
  291. var Optional = {
  292. some: some,
  293. none: none,
  294. from: from$1
  295. };
  296. var nativeSlice = Array.prototype.slice;
  297. var nativeIndexOf = Array.prototype.indexOf;
  298. var nativePush = Array.prototype.push;
  299. var rawIndexOf = function (ts, t) {
  300. return nativeIndexOf.call(ts, t);
  301. };
  302. var indexOf$2 = function (xs, x) {
  303. var r = rawIndexOf(xs, x);
  304. return r === -1 ? Optional.none() : Optional.some(r);
  305. };
  306. var contains$3 = function (xs, x) {
  307. return rawIndexOf(xs, x) > -1;
  308. };
  309. var exists = function (xs, pred) {
  310. for (var i = 0, len = xs.length; i < len; i++) {
  311. var x = xs[i];
  312. if (pred(x, i)) {
  313. return true;
  314. }
  315. }
  316. return false;
  317. };
  318. var map$3 = function (xs, f) {
  319. var len = xs.length;
  320. var r = new Array(len);
  321. for (var i = 0; i < len; i++) {
  322. var x = xs[i];
  323. r[i] = f(x, i);
  324. }
  325. return r;
  326. };
  327. var each$k = function (xs, f) {
  328. for (var i = 0, len = xs.length; i < len; i++) {
  329. var x = xs[i];
  330. f(x, i);
  331. }
  332. };
  333. var eachr = function (xs, f) {
  334. for (var i = xs.length - 1; i >= 0; i--) {
  335. var x = xs[i];
  336. f(x, i);
  337. }
  338. };
  339. var partition = function (xs, pred) {
  340. var pass = [];
  341. var fail = [];
  342. for (var i = 0, len = xs.length; i < len; i++) {
  343. var x = xs[i];
  344. var arr = pred(x, i) ? pass : fail;
  345. arr.push(x);
  346. }
  347. return {
  348. pass: pass,
  349. fail: fail
  350. };
  351. };
  352. var filter$4 = function (xs, pred) {
  353. var r = [];
  354. for (var i = 0, len = xs.length; i < len; i++) {
  355. var x = xs[i];
  356. if (pred(x, i)) {
  357. r.push(x);
  358. }
  359. }
  360. return r;
  361. };
  362. var foldr = function (xs, f, acc) {
  363. eachr(xs, function (x, i) {
  364. acc = f(acc, x, i);
  365. });
  366. return acc;
  367. };
  368. var foldl = function (xs, f, acc) {
  369. each$k(xs, function (x, i) {
  370. acc = f(acc, x, i);
  371. });
  372. return acc;
  373. };
  374. var findUntil$1 = function (xs, pred, until) {
  375. for (var i = 0, len = xs.length; i < len; i++) {
  376. var x = xs[i];
  377. if (pred(x, i)) {
  378. return Optional.some(x);
  379. } else if (until(x, i)) {
  380. break;
  381. }
  382. }
  383. return Optional.none();
  384. };
  385. var find$3 = function (xs, pred) {
  386. return findUntil$1(xs, pred, never);
  387. };
  388. var findIndex$2 = function (xs, pred) {
  389. for (var i = 0, len = xs.length; i < len; i++) {
  390. var x = xs[i];
  391. if (pred(x, i)) {
  392. return Optional.some(i);
  393. }
  394. }
  395. return Optional.none();
  396. };
  397. var flatten = function (xs) {
  398. var r = [];
  399. for (var i = 0, len = xs.length; i < len; ++i) {
  400. if (!isArray$1(xs[i])) {
  401. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  402. }
  403. nativePush.apply(r, xs[i]);
  404. }
  405. return r;
  406. };
  407. var bind = function (xs, f) {
  408. return flatten(map$3(xs, f));
  409. };
  410. var forall = function (xs, pred) {
  411. for (var i = 0, len = xs.length; i < len; ++i) {
  412. var x = xs[i];
  413. if (pred(x, i) !== true) {
  414. return false;
  415. }
  416. }
  417. return true;
  418. };
  419. var reverse = function (xs) {
  420. var r = nativeSlice.call(xs, 0);
  421. r.reverse();
  422. return r;
  423. };
  424. var difference = function (a1, a2) {
  425. return filter$4(a1, function (x) {
  426. return !contains$3(a2, x);
  427. });
  428. };
  429. var mapToObject = function (xs, f) {
  430. var r = {};
  431. for (var i = 0, len = xs.length; i < len; i++) {
  432. var x = xs[i];
  433. r[String(x)] = f(x, i);
  434. }
  435. return r;
  436. };
  437. var sort = function (xs, comparator) {
  438. var copy = nativeSlice.call(xs, 0);
  439. copy.sort(comparator);
  440. return copy;
  441. };
  442. var get$a = function (xs, i) {
  443. return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
  444. };
  445. var head = function (xs) {
  446. return get$a(xs, 0);
  447. };
  448. var last$2 = function (xs) {
  449. return get$a(xs, xs.length - 1);
  450. };
  451. var from = isFunction(Array.from) ? Array.from : function (x) {
  452. return nativeSlice.call(x);
  453. };
  454. var findMap = function (arr, f) {
  455. for (var i = 0; i < arr.length; i++) {
  456. var r = f(arr[i], i);
  457. if (r.isSome()) {
  458. return r;
  459. }
  460. }
  461. return Optional.none();
  462. };
  463. var keys = Object.keys;
  464. var hasOwnProperty$1 = Object.hasOwnProperty;
  465. var each$j = function (obj, f) {
  466. var props = keys(obj);
  467. for (var k = 0, len = props.length; k < len; k++) {
  468. var i = props[k];
  469. var x = obj[i];
  470. f(x, i);
  471. }
  472. };
  473. var map$2 = function (obj, f) {
  474. return tupleMap(obj, function (x, i) {
  475. return {
  476. k: i,
  477. v: f(x, i)
  478. };
  479. });
  480. };
  481. var tupleMap = function (obj, f) {
  482. var r = {};
  483. each$j(obj, function (x, i) {
  484. var tuple = f(x, i);
  485. r[tuple.k] = tuple.v;
  486. });
  487. return r;
  488. };
  489. var objAcc = function (r) {
  490. return function (x, i) {
  491. r[i] = x;
  492. };
  493. };
  494. var internalFilter = function (obj, pred, onTrue, onFalse) {
  495. var r = {};
  496. each$j(obj, function (x, i) {
  497. (pred(x, i) ? onTrue : onFalse)(x, i);
  498. });
  499. return r;
  500. };
  501. var bifilter = function (obj, pred) {
  502. var t = {};
  503. var f = {};
  504. internalFilter(obj, pred, objAcc(t), objAcc(f));
  505. return {
  506. t: t,
  507. f: f
  508. };
  509. };
  510. var filter$3 = function (obj, pred) {
  511. var t = {};
  512. internalFilter(obj, pred, objAcc(t), noop);
  513. return t;
  514. };
  515. var mapToArray = function (obj, f) {
  516. var r = [];
  517. each$j(obj, function (value, name) {
  518. r.push(f(value, name));
  519. });
  520. return r;
  521. };
  522. var values = function (obj) {
  523. return mapToArray(obj, identity);
  524. };
  525. var get$9 = function (obj, key) {
  526. return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
  527. };
  528. var has$2 = function (obj, key) {
  529. return hasOwnProperty$1.call(obj, key);
  530. };
  531. var hasNonNullableKey = function (obj, key) {
  532. return has$2(obj, key) && obj[key] !== undefined && obj[key] !== null;
  533. };
  534. var equal$1 = function (a1, a2, eq) {
  535. if (eq === void 0) {
  536. eq = eqAny;
  537. }
  538. return eqRecord(eq).eq(a1, a2);
  539. };
  540. var isArray = Array.isArray;
  541. var toArray$1 = function (obj) {
  542. if (!isArray(obj)) {
  543. var array = [];
  544. for (var i = 0, l = obj.length; i < l; i++) {
  545. array[i] = obj[i];
  546. }
  547. return array;
  548. } else {
  549. return obj;
  550. }
  551. };
  552. var each$i = function (o, cb, s) {
  553. var n, l;
  554. if (!o) {
  555. return false;
  556. }
  557. s = s || o;
  558. if (o.length !== undefined) {
  559. for (n = 0, l = o.length; n < l; n++) {
  560. if (cb.call(s, o[n], n, o) === false) {
  561. return false;
  562. }
  563. }
  564. } else {
  565. for (n in o) {
  566. if (has$2(o, n)) {
  567. if (cb.call(s, o[n], n, o) === false) {
  568. return false;
  569. }
  570. }
  571. }
  572. }
  573. return true;
  574. };
  575. var map$1 = function (array, callback) {
  576. var out = [];
  577. each$i(array, function (item, index) {
  578. out.push(callback(item, index, array));
  579. });
  580. return out;
  581. };
  582. var filter$2 = function (a, f) {
  583. var o = [];
  584. each$i(a, function (v, index) {
  585. if (!f || f(v, index, a)) {
  586. o.push(v);
  587. }
  588. });
  589. return o;
  590. };
  591. var indexOf$1 = function (a, v) {
  592. if (a) {
  593. for (var i = 0, l = a.length; i < l; i++) {
  594. if (a[i] === v) {
  595. return i;
  596. }
  597. }
  598. }
  599. return -1;
  600. };
  601. var reduce = function (collection, iteratee, accumulator, thisArg) {
  602. var acc = isUndefined(accumulator) ? collection[0] : accumulator;
  603. for (var i = 0; i < collection.length; i++) {
  604. acc = iteratee.call(thisArg, acc, collection[i], i);
  605. }
  606. return acc;
  607. };
  608. var findIndex$1 = function (array, predicate, thisArg) {
  609. var i, l;
  610. for (i = 0, l = array.length; i < l; i++) {
  611. if (predicate.call(thisArg, array[i], i, array)) {
  612. return i;
  613. }
  614. }
  615. return -1;
  616. };
  617. var last$1 = function (collection) {
  618. return collection[collection.length - 1];
  619. };
  620. var __assign = function () {
  621. __assign = Object.assign || function __assign(t) {
  622. for (var s, i = 1, n = arguments.length; i < n; i++) {
  623. s = arguments[i];
  624. for (var p in s)
  625. if (Object.prototype.hasOwnProperty.call(s, p))
  626. t[p] = s[p];
  627. }
  628. return t;
  629. };
  630. return __assign.apply(this, arguments);
  631. };
  632. function __rest(s, e) {
  633. var t = {};
  634. for (var p in s)
  635. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  636. t[p] = s[p];
  637. if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  638. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  639. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  640. t[p[i]] = s[p[i]];
  641. }
  642. return t;
  643. }
  644. function __spreadArray(to, from, pack) {
  645. if (pack || arguments.length === 2)
  646. for (var i = 0, l = from.length, ar; i < l; i++) {
  647. if (ar || !(i in from)) {
  648. if (!ar)
  649. ar = Array.prototype.slice.call(from, 0, i);
  650. ar[i] = from[i];
  651. }
  652. }
  653. return to.concat(ar || Array.prototype.slice.call(from));
  654. }
  655. var cached = function (f) {
  656. var called = false;
  657. var r;
  658. return function () {
  659. var args = [];
  660. for (var _i = 0; _i < arguments.length; _i++) {
  661. args[_i] = arguments[_i];
  662. }
  663. if (!called) {
  664. called = true;
  665. r = f.apply(null, args);
  666. }
  667. return r;
  668. };
  669. };
  670. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  671. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  672. var isiPhone = os.isiOS() && !isiPad;
  673. var isMobile = os.isiOS() || os.isAndroid();
  674. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  675. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  676. var isPhone = isiPhone || isMobile && !isTablet;
  677. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  678. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  679. return {
  680. isiPad: constant(isiPad),
  681. isiPhone: constant(isiPhone),
  682. isTablet: constant(isTablet),
  683. isPhone: constant(isPhone),
  684. isTouch: constant(isTouch),
  685. isAndroid: os.isAndroid,
  686. isiOS: os.isiOS,
  687. isWebView: constant(iOSwebview),
  688. isDesktop: constant(isDesktop)
  689. };
  690. };
  691. var firstMatch = function (regexes, s) {
  692. for (var i = 0; i < regexes.length; i++) {
  693. var x = regexes[i];
  694. if (x.test(s)) {
  695. return x;
  696. }
  697. }
  698. return undefined;
  699. };
  700. var find$2 = function (regexes, agent) {
  701. var r = firstMatch(regexes, agent);
  702. if (!r) {
  703. return {
  704. major: 0,
  705. minor: 0
  706. };
  707. }
  708. var group = function (i) {
  709. return Number(agent.replace(r, '$' + i));
  710. };
  711. return nu$4(group(1), group(2));
  712. };
  713. var detect$3 = function (versionRegexes, agent) {
  714. var cleanedAgent = String(agent).toLowerCase();
  715. if (versionRegexes.length === 0) {
  716. return unknown$2();
  717. }
  718. return find$2(versionRegexes, cleanedAgent);
  719. };
  720. var unknown$2 = function () {
  721. return nu$4(0, 0);
  722. };
  723. var nu$4 = function (major, minor) {
  724. return {
  725. major: major,
  726. minor: minor
  727. };
  728. };
  729. var Version = {
  730. nu: nu$4,
  731. detect: detect$3,
  732. unknown: unknown$2
  733. };
  734. var detectBrowser$1 = function (browsers, userAgentData) {
  735. return findMap(userAgentData.brands, function (uaBrand) {
  736. var lcBrand = uaBrand.brand.toLowerCase();
  737. return find$3(browsers, function (browser) {
  738. var _a;
  739. return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
  740. }).map(function (info) {
  741. return {
  742. current: info.name,
  743. version: Version.nu(parseInt(uaBrand.version, 10), 0)
  744. };
  745. });
  746. });
  747. };
  748. var detect$2 = function (candidates, userAgent) {
  749. var agent = String(userAgent).toLowerCase();
  750. return find$3(candidates, function (candidate) {
  751. return candidate.search(agent);
  752. });
  753. };
  754. var detectBrowser = function (browsers, userAgent) {
  755. return detect$2(browsers, userAgent).map(function (browser) {
  756. var version = Version.detect(browser.versionRegexes, userAgent);
  757. return {
  758. current: browser.name,
  759. version: version
  760. };
  761. });
  762. };
  763. var detectOs = function (oses, userAgent) {
  764. return detect$2(oses, userAgent).map(function (os) {
  765. var version = Version.detect(os.versionRegexes, userAgent);
  766. return {
  767. current: os.name,
  768. version: version
  769. };
  770. });
  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$2 = 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$4 = blank(/^\s+|\s+$/g);
  793. var lTrim = blank(/^\s+/g);
  794. var rTrim = blank(/\s+$/g);
  795. var isNotEmpty = function (s) {
  796. return s.length > 0;
  797. };
  798. var isEmpty$3 = function (s) {
  799. return !isNotEmpty(s);
  800. };
  801. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  802. var checkContains = function (target) {
  803. return function (uastring) {
  804. return contains$2(uastring, target);
  805. };
  806. };
  807. var browsers = [
  808. {
  809. name: 'Edge',
  810. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  811. search: function (uastring) {
  812. return contains$2(uastring, 'edge/') && contains$2(uastring, 'chrome') && contains$2(uastring, 'safari') && contains$2(uastring, 'applewebkit');
  813. }
  814. },
  815. {
  816. name: 'Chrome',
  817. brand: 'Chromium',
  818. versionRegexes: [
  819. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  820. normalVersionRegex
  821. ],
  822. search: function (uastring) {
  823. return contains$2(uastring, 'chrome') && !contains$2(uastring, 'chromeframe');
  824. }
  825. },
  826. {
  827. name: 'IE',
  828. versionRegexes: [
  829. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  830. /.*?rv:([0-9]+)\.([0-9]+).*/
  831. ],
  832. search: function (uastring) {
  833. return contains$2(uastring, 'msie') || contains$2(uastring, 'trident');
  834. }
  835. },
  836. {
  837. name: 'Opera',
  838. versionRegexes: [
  839. normalVersionRegex,
  840. /.*?opera\/([0-9]+)\.([0-9]+).*/
  841. ],
  842. search: checkContains('opera')
  843. },
  844. {
  845. name: 'Firefox',
  846. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  847. search: checkContains('firefox')
  848. },
  849. {
  850. name: 'Safari',
  851. versionRegexes: [
  852. normalVersionRegex,
  853. /.*?cpu os ([0-9]+)_([0-9]+).*/
  854. ],
  855. search: function (uastring) {
  856. return (contains$2(uastring, 'safari') || contains$2(uastring, 'mobile/')) && contains$2(uastring, 'applewebkit');
  857. }
  858. }
  859. ];
  860. var oses = [
  861. {
  862. name: 'Windows',
  863. search: checkContains('win'),
  864. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  865. },
  866. {
  867. name: 'iOS',
  868. search: function (uastring) {
  869. return contains$2(uastring, 'iphone') || contains$2(uastring, 'ipad');
  870. },
  871. versionRegexes: [
  872. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  873. /.*cpu os ([0-9]+)_([0-9]+).*/,
  874. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  875. ]
  876. },
  877. {
  878. name: 'Android',
  879. search: checkContains('android'),
  880. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  881. },
  882. {
  883. name: 'OSX',
  884. search: checkContains('mac os x'),
  885. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  886. },
  887. {
  888. name: 'Linux',
  889. search: checkContains('linux'),
  890. versionRegexes: []
  891. },
  892. {
  893. name: 'Solaris',
  894. search: checkContains('sunos'),
  895. versionRegexes: []
  896. },
  897. {
  898. name: 'FreeBSD',
  899. search: checkContains('freebsd'),
  900. versionRegexes: []
  901. },
  902. {
  903. name: 'ChromeOS',
  904. search: checkContains('cros'),
  905. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  906. }
  907. ];
  908. var PlatformInfo = {
  909. browsers: constant(browsers),
  910. oses: constant(oses)
  911. };
  912. var edge = 'Edge';
  913. var chrome = 'Chrome';
  914. var ie$1 = 'IE';
  915. var opera = 'Opera';
  916. var firefox = 'Firefox';
  917. var safari = 'Safari';
  918. var unknown$1 = function () {
  919. return nu$3({
  920. current: undefined,
  921. version: Version.unknown()
  922. });
  923. };
  924. var nu$3 = function (info) {
  925. var current = info.current;
  926. var version = info.version;
  927. var isBrowser = function (name) {
  928. return function () {
  929. return current === name;
  930. };
  931. };
  932. return {
  933. current: current,
  934. version: version,
  935. isEdge: isBrowser(edge),
  936. isChrome: isBrowser(chrome),
  937. isIE: isBrowser(ie$1),
  938. isOpera: isBrowser(opera),
  939. isFirefox: isBrowser(firefox),
  940. isSafari: isBrowser(safari)
  941. };
  942. };
  943. var Browser = {
  944. unknown: unknown$1,
  945. nu: nu$3,
  946. edge: constant(edge),
  947. chrome: constant(chrome),
  948. ie: constant(ie$1),
  949. opera: constant(opera),
  950. firefox: constant(firefox),
  951. safari: constant(safari)
  952. };
  953. var windows = 'Windows';
  954. var ios = 'iOS';
  955. var android = 'Android';
  956. var linux = 'Linux';
  957. var osx = 'OSX';
  958. var solaris = 'Solaris';
  959. var freebsd = 'FreeBSD';
  960. var chromeos = 'ChromeOS';
  961. var unknown = function () {
  962. return nu$2({
  963. current: undefined,
  964. version: Version.unknown()
  965. });
  966. };
  967. var nu$2 = function (info) {
  968. var current = info.current;
  969. var version = info.version;
  970. var isOS = function (name) {
  971. return function () {
  972. return current === name;
  973. };
  974. };
  975. return {
  976. current: current,
  977. version: version,
  978. isWindows: isOS(windows),
  979. isiOS: isOS(ios),
  980. isAndroid: isOS(android),
  981. isOSX: isOS(osx),
  982. isLinux: isOS(linux),
  983. isSolaris: isOS(solaris),
  984. isFreeBSD: isOS(freebsd),
  985. isChromeOS: isOS(chromeos)
  986. };
  987. };
  988. var OperatingSystem = {
  989. unknown: unknown,
  990. nu: nu$2,
  991. windows: constant(windows),
  992. ios: constant(ios),
  993. android: constant(android),
  994. linux: constant(linux),
  995. osx: constant(osx),
  996. solaris: constant(solaris),
  997. freebsd: constant(freebsd),
  998. chromeos: constant(chromeos)
  999. };
  1000. var detect$1 = function (userAgent, userAgentDataOpt, mediaMatch) {
  1001. var browsers = PlatformInfo.browsers();
  1002. var oses = PlatformInfo.oses();
  1003. var browser = userAgentDataOpt.bind(function (userAgentData) {
  1004. return detectBrowser$1(browsers, userAgentData);
  1005. }).orThunk(function () {
  1006. return detectBrowser(browsers, userAgent);
  1007. }).fold(Browser.unknown, Browser.nu);
  1008. var os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  1009. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  1010. return {
  1011. browser: browser,
  1012. os: os,
  1013. deviceType: deviceType
  1014. };
  1015. };
  1016. var PlatformDetection = { detect: detect$1 };
  1017. var mediaMatch = function (query) {
  1018. return window.matchMedia(query).matches;
  1019. };
  1020. var platform$2 = cached(function () {
  1021. return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
  1022. });
  1023. var detect = function () {
  1024. return platform$2();
  1025. };
  1026. var userAgent = navigator.userAgent;
  1027. var platform$1 = detect();
  1028. var browser$4 = platform$1.browser;
  1029. var os = platform$1.os;
  1030. var deviceType = platform$1.deviceType;
  1031. var webkit = /WebKit/.test(userAgent) && !browser$4.isEdge();
  1032. var fileApi = 'FormData' in window && 'FileReader' in window && 'URL' in window && !!URL.createObjectURL;
  1033. var windowsPhone = userAgent.indexOf('Windows Phone') !== -1;
  1034. var Env = {
  1035. opera: browser$4.isOpera(),
  1036. webkit: webkit,
  1037. ie: browser$4.isIE() || browser$4.isEdge() ? browser$4.version.major : false,
  1038. gecko: browser$4.isFirefox(),
  1039. mac: os.isOSX() || os.isiOS(),
  1040. iOS: deviceType.isiPad() || deviceType.isiPhone(),
  1041. android: os.isAndroid(),
  1042. contentEditable: true,
  1043. transparentSrc: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
  1044. caretAfter: true,
  1045. range: window.getSelection && 'Range' in window,
  1046. documentMode: browser$4.isIE() ? document.documentMode || 7 : 10,
  1047. fileApi: fileApi,
  1048. ceFalse: true,
  1049. cacheSuffix: null,
  1050. container: null,
  1051. experimentalShadowDom: false,
  1052. canHaveCSP: !browser$4.isIE(),
  1053. desktop: deviceType.isDesktop(),
  1054. windowsPhone: windowsPhone,
  1055. browser: {
  1056. current: browser$4.current,
  1057. version: browser$4.version,
  1058. isChrome: browser$4.isChrome,
  1059. isEdge: browser$4.isEdge,
  1060. isFirefox: browser$4.isFirefox,
  1061. isIE: browser$4.isIE,
  1062. isOpera: browser$4.isOpera,
  1063. isSafari: browser$4.isSafari
  1064. },
  1065. os: {
  1066. current: os.current,
  1067. version: os.version,
  1068. isAndroid: os.isAndroid,
  1069. isChromeOS: os.isChromeOS,
  1070. isFreeBSD: os.isFreeBSD,
  1071. isiOS: os.isiOS,
  1072. isLinux: os.isLinux,
  1073. isOSX: os.isOSX,
  1074. isSolaris: os.isSolaris,
  1075. isWindows: os.isWindows
  1076. },
  1077. deviceType: {
  1078. isDesktop: deviceType.isDesktop,
  1079. isiPad: deviceType.isiPad,
  1080. isiPhone: deviceType.isiPhone,
  1081. isPhone: deviceType.isPhone,
  1082. isTablet: deviceType.isTablet,
  1083. isTouch: deviceType.isTouch,
  1084. isWebView: deviceType.isWebView
  1085. }
  1086. };
  1087. var whiteSpaceRegExp$2 = /^\s*|\s*$/g;
  1088. var trim$3 = function (str) {
  1089. return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp$2, '');
  1090. };
  1091. var is$3 = function (obj, type) {
  1092. if (!type) {
  1093. return obj !== undefined;
  1094. }
  1095. if (type === 'array' && isArray(obj)) {
  1096. return true;
  1097. }
  1098. return typeof obj === type;
  1099. };
  1100. var makeMap$4 = function (items, delim, map) {
  1101. var i;
  1102. items = items || [];
  1103. delim = delim || ',';
  1104. if (typeof items === 'string') {
  1105. items = items.split(delim);
  1106. }
  1107. map = map || {};
  1108. i = items.length;
  1109. while (i--) {
  1110. map[items[i]] = {};
  1111. }
  1112. return map;
  1113. };
  1114. var hasOwnProperty = has$2;
  1115. var create$9 = function (s, p, root) {
  1116. var self = this;
  1117. var sp, scn, c, de = 0;
  1118. s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
  1119. var cn = s[3].match(/(^|\.)(\w+)$/i)[2];
  1120. var ns = self.createNS(s[3].replace(/\.\w+$/, ''), root);
  1121. if (ns[cn]) {
  1122. return;
  1123. }
  1124. if (s[2] === 'static') {
  1125. ns[cn] = p;
  1126. if (this.onCreate) {
  1127. this.onCreate(s[2], s[3], ns[cn]);
  1128. }
  1129. return;
  1130. }
  1131. if (!p[cn]) {
  1132. p[cn] = function () {
  1133. };
  1134. de = 1;
  1135. }
  1136. ns[cn] = p[cn];
  1137. self.extend(ns[cn].prototype, p);
  1138. if (s[5]) {
  1139. sp = self.resolve(s[5]).prototype;
  1140. scn = s[5].match(/\.(\w+)$/i)[1];
  1141. c = ns[cn];
  1142. if (de) {
  1143. ns[cn] = function () {
  1144. return sp[scn].apply(this, arguments);
  1145. };
  1146. } else {
  1147. ns[cn] = function () {
  1148. this.parent = sp[scn];
  1149. return c.apply(this, arguments);
  1150. };
  1151. }
  1152. ns[cn].prototype[cn] = ns[cn];
  1153. self.each(sp, function (f, n) {
  1154. ns[cn].prototype[n] = sp[n];
  1155. });
  1156. self.each(p, function (f, n) {
  1157. if (sp[n]) {
  1158. ns[cn].prototype[n] = function () {
  1159. this.parent = sp[n];
  1160. return f.apply(this, arguments);
  1161. };
  1162. } else {
  1163. if (n !== cn) {
  1164. ns[cn].prototype[n] = f;
  1165. }
  1166. }
  1167. });
  1168. }
  1169. self.each(p.static, function (f, n) {
  1170. ns[cn][n] = f;
  1171. });
  1172. };
  1173. var extend$6 = function (obj) {
  1174. var exts = [];
  1175. for (var _i = 1; _i < arguments.length; _i++) {
  1176. exts[_i - 1] = arguments[_i];
  1177. }
  1178. for (var i = 0; i < exts.length; i++) {
  1179. var ext = exts[i];
  1180. for (var name_1 in ext) {
  1181. if (has$2(ext, name_1)) {
  1182. var value = ext[name_1];
  1183. if (value !== undefined) {
  1184. obj[name_1] = value;
  1185. }
  1186. }
  1187. }
  1188. }
  1189. return obj;
  1190. };
  1191. var walk$3 = function (o, f, n, s) {
  1192. s = s || this;
  1193. if (o) {
  1194. if (n) {
  1195. o = o[n];
  1196. }
  1197. each$i(o, function (o, i) {
  1198. if (f.call(s, o, i, n) === false) {
  1199. return false;
  1200. }
  1201. walk$3(o, f, n, s);
  1202. });
  1203. }
  1204. };
  1205. var createNS = function (n, o) {
  1206. var i, v;
  1207. o = o || window;
  1208. n = n.split('.');
  1209. for (i = 0; i < n.length; i++) {
  1210. v = n[i];
  1211. if (!o[v]) {
  1212. o[v] = {};
  1213. }
  1214. o = o[v];
  1215. }
  1216. return o;
  1217. };
  1218. var resolve$3 = function (n, o) {
  1219. var i, l;
  1220. o = o || window;
  1221. n = n.split('.');
  1222. for (i = 0, l = n.length; i < l; i++) {
  1223. o = o[n[i]];
  1224. if (!o) {
  1225. break;
  1226. }
  1227. }
  1228. return o;
  1229. };
  1230. var explode$4 = function (s, d) {
  1231. if (!s || is$3(s, 'array')) {
  1232. return s;
  1233. }
  1234. return map$1(s.split(d || ','), trim$3);
  1235. };
  1236. var _addCacheSuffix = function (url) {
  1237. var cacheSuffix = Env.cacheSuffix;
  1238. if (cacheSuffix) {
  1239. url += (url.indexOf('?') === -1 ? '?' : '&') + cacheSuffix;
  1240. }
  1241. return url;
  1242. };
  1243. var Tools = {
  1244. trim: trim$3,
  1245. isArray: isArray,
  1246. is: is$3,
  1247. toArray: toArray$1,
  1248. makeMap: makeMap$4,
  1249. each: each$i,
  1250. map: map$1,
  1251. grep: filter$2,
  1252. inArray: indexOf$1,
  1253. hasOwn: hasOwnProperty,
  1254. extend: extend$6,
  1255. create: create$9,
  1256. walk: walk$3,
  1257. createNS: createNS,
  1258. resolve: resolve$3,
  1259. explode: explode$4,
  1260. _addCacheSuffix: _addCacheSuffix
  1261. };
  1262. var fromHtml$1 = function (html, scope) {
  1263. var doc = scope || document;
  1264. var div = doc.createElement('div');
  1265. div.innerHTML = html;
  1266. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  1267. console.error('HTML does not have a single root node', html);
  1268. throw new Error('HTML must have a single root node');
  1269. }
  1270. return fromDom$2(div.childNodes[0]);
  1271. };
  1272. var fromTag = function (tag, scope) {
  1273. var doc = scope || document;
  1274. var node = doc.createElement(tag);
  1275. return fromDom$2(node);
  1276. };
  1277. var fromText = function (text, scope) {
  1278. var doc = scope || document;
  1279. var node = doc.createTextNode(text);
  1280. return fromDom$2(node);
  1281. };
  1282. var fromDom$2 = function (node) {
  1283. if (node === null || node === undefined) {
  1284. throw new Error('Node cannot be null or undefined');
  1285. }
  1286. return { dom: node };
  1287. };
  1288. var fromPoint$1 = function (docElm, x, y) {
  1289. return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom$2);
  1290. };
  1291. var SugarElement = {
  1292. fromHtml: fromHtml$1,
  1293. fromTag: fromTag,
  1294. fromText: fromText,
  1295. fromDom: fromDom$2,
  1296. fromPoint: fromPoint$1
  1297. };
  1298. var toArray = function (target, f) {
  1299. var r = [];
  1300. var recurse = function (e) {
  1301. r.push(e);
  1302. return f(e);
  1303. };
  1304. var cur = f(target);
  1305. do {
  1306. cur = cur.bind(recurse);
  1307. } while (cur.isSome());
  1308. return r;
  1309. };
  1310. var compareDocumentPosition = function (a, b, match) {
  1311. return (a.compareDocumentPosition(b) & match) !== 0;
  1312. };
  1313. var documentPositionContainedBy = function (a, b) {
  1314. return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
  1315. };
  1316. var COMMENT = 8;
  1317. var DOCUMENT = 9;
  1318. var DOCUMENT_FRAGMENT = 11;
  1319. var ELEMENT = 1;
  1320. var TEXT = 3;
  1321. var is$2 = function (element, selector) {
  1322. var dom = element.dom;
  1323. if (dom.nodeType !== ELEMENT) {
  1324. return false;
  1325. } else {
  1326. var elem = dom;
  1327. if (elem.matches !== undefined) {
  1328. return elem.matches(selector);
  1329. } else if (elem.msMatchesSelector !== undefined) {
  1330. return elem.msMatchesSelector(selector);
  1331. } else if (elem.webkitMatchesSelector !== undefined) {
  1332. return elem.webkitMatchesSelector(selector);
  1333. } else if (elem.mozMatchesSelector !== undefined) {
  1334. return elem.mozMatchesSelector(selector);
  1335. } else {
  1336. throw new Error('Browser lacks native selectors');
  1337. }
  1338. }
  1339. };
  1340. var bypassSelector = function (dom) {
  1341. return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  1342. };
  1343. var all = function (selector, scope) {
  1344. var base = scope === undefined ? document : scope.dom;
  1345. return bypassSelector(base) ? [] : map$3(base.querySelectorAll(selector), SugarElement.fromDom);
  1346. };
  1347. var one = function (selector, scope) {
  1348. var base = scope === undefined ? document : scope.dom;
  1349. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  1350. };
  1351. var eq = function (e1, e2) {
  1352. return e1.dom === e2.dom;
  1353. };
  1354. var regularContains = function (e1, e2) {
  1355. var d1 = e1.dom;
  1356. var d2 = e2.dom;
  1357. return d1 === d2 ? false : d1.contains(d2);
  1358. };
  1359. var ieContains = function (e1, e2) {
  1360. return documentPositionContainedBy(e1.dom, e2.dom);
  1361. };
  1362. var contains$1 = function (e1, e2) {
  1363. return detect().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
  1364. };
  1365. typeof window !== 'undefined' ? window : Function('return this;')();
  1366. var name = function (element) {
  1367. var r = element.dom.nodeName;
  1368. return r.toLowerCase();
  1369. };
  1370. var type = function (element) {
  1371. return element.dom.nodeType;
  1372. };
  1373. var isType = function (t) {
  1374. return function (element) {
  1375. return type(element) === t;
  1376. };
  1377. };
  1378. var isComment$1 = function (element) {
  1379. return type(element) === COMMENT || name(element) === '#comment';
  1380. };
  1381. var isElement$6 = isType(ELEMENT);
  1382. var isText$8 = isType(TEXT);
  1383. var isDocument$2 = isType(DOCUMENT);
  1384. var isDocumentFragment$1 = isType(DOCUMENT_FRAGMENT);
  1385. var isTag = function (tag) {
  1386. return function (e) {
  1387. return isElement$6(e) && name(e) === tag;
  1388. };
  1389. };
  1390. var owner$1 = function (element) {
  1391. return SugarElement.fromDom(element.dom.ownerDocument);
  1392. };
  1393. var documentOrOwner = function (dos) {
  1394. return isDocument$2(dos) ? dos : owner$1(dos);
  1395. };
  1396. var documentElement = function (element) {
  1397. return SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
  1398. };
  1399. var defaultView = function (element) {
  1400. return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  1401. };
  1402. var parent = function (element) {
  1403. return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  1404. };
  1405. var parents$1 = function (element, isRoot) {
  1406. var stop = isFunction(isRoot) ? isRoot : never;
  1407. var dom = element.dom;
  1408. var ret = [];
  1409. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  1410. var rawParent = dom.parentNode;
  1411. var p = SugarElement.fromDom(rawParent);
  1412. ret.push(p);
  1413. if (stop(p) === true) {
  1414. break;
  1415. } else {
  1416. dom = rawParent;
  1417. }
  1418. }
  1419. return ret;
  1420. };
  1421. var siblings = function (element) {
  1422. var filterSelf = function (elements) {
  1423. return filter$4(elements, function (x) {
  1424. return !eq(element, x);
  1425. });
  1426. };
  1427. return parent(element).map(children).map(filterSelf).getOr([]);
  1428. };
  1429. var prevSibling = function (element) {
  1430. return Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
  1431. };
  1432. var nextSibling = function (element) {
  1433. return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  1434. };
  1435. var prevSiblings = function (element) {
  1436. return reverse(toArray(element, prevSibling));
  1437. };
  1438. var nextSiblings = function (element) {
  1439. return toArray(element, nextSibling);
  1440. };
  1441. var children = function (element) {
  1442. return map$3(element.dom.childNodes, SugarElement.fromDom);
  1443. };
  1444. var child$1 = function (element, index) {
  1445. var cs = element.dom.childNodes;
  1446. return Optional.from(cs[index]).map(SugarElement.fromDom);
  1447. };
  1448. var firstChild = function (element) {
  1449. return child$1(element, 0);
  1450. };
  1451. var lastChild = function (element) {
  1452. return child$1(element, element.dom.childNodes.length - 1);
  1453. };
  1454. var childNodesCount = function (element) {
  1455. return element.dom.childNodes.length;
  1456. };
  1457. var getHead = function (doc) {
  1458. var b = doc.dom.head;
  1459. if (b === null || b === undefined) {
  1460. throw new Error('Head is not available yet');
  1461. }
  1462. return SugarElement.fromDom(b);
  1463. };
  1464. var isShadowRoot = function (dos) {
  1465. return isDocumentFragment$1(dos) && isNonNullable(dos.dom.host);
  1466. };
  1467. var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  1468. var isSupported$1 = constant(supported);
  1469. var getRootNode = supported ? function (e) {
  1470. return SugarElement.fromDom(e.dom.getRootNode());
  1471. } : documentOrOwner;
  1472. var getStyleContainer = function (dos) {
  1473. return isShadowRoot(dos) ? dos : getHead(documentOrOwner(dos));
  1474. };
  1475. var getShadowRoot = function (e) {
  1476. var r = getRootNode(e);
  1477. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  1478. };
  1479. var getShadowHost = function (e) {
  1480. return SugarElement.fromDom(e.dom.host);
  1481. };
  1482. var getOriginalEventTarget = function (event) {
  1483. if (isSupported$1() && isNonNullable(event.target)) {
  1484. var el = SugarElement.fromDom(event.target);
  1485. if (isElement$6(el) && isOpenShadowHost(el)) {
  1486. if (event.composed && event.composedPath) {
  1487. var composedPath = event.composedPath();
  1488. if (composedPath) {
  1489. return head(composedPath);
  1490. }
  1491. }
  1492. }
  1493. }
  1494. return Optional.from(event.target);
  1495. };
  1496. var isOpenShadowHost = function (element) {
  1497. return isNonNullable(element.dom.shadowRoot);
  1498. };
  1499. var before$4 = function (marker, element) {
  1500. var parent$1 = parent(marker);
  1501. parent$1.each(function (v) {
  1502. v.dom.insertBefore(element.dom, marker.dom);
  1503. });
  1504. };
  1505. var after$3 = function (marker, element) {
  1506. var sibling = nextSibling(marker);
  1507. sibling.fold(function () {
  1508. var parent$1 = parent(marker);
  1509. parent$1.each(function (v) {
  1510. append$1(v, element);
  1511. });
  1512. }, function (v) {
  1513. before$4(v, element);
  1514. });
  1515. };
  1516. var prepend = function (parent, element) {
  1517. var firstChild$1 = firstChild(parent);
  1518. firstChild$1.fold(function () {
  1519. append$1(parent, element);
  1520. }, function (v) {
  1521. parent.dom.insertBefore(element.dom, v.dom);
  1522. });
  1523. };
  1524. var append$1 = function (parent, element) {
  1525. parent.dom.appendChild(element.dom);
  1526. };
  1527. var wrap$3 = function (element, wrapper) {
  1528. before$4(element, wrapper);
  1529. append$1(wrapper, element);
  1530. };
  1531. var before$3 = function (marker, elements) {
  1532. each$k(elements, function (x) {
  1533. before$4(marker, x);
  1534. });
  1535. };
  1536. var append = function (parent, elements) {
  1537. each$k(elements, function (x) {
  1538. append$1(parent, x);
  1539. });
  1540. };
  1541. var empty = function (element) {
  1542. element.dom.textContent = '';
  1543. each$k(children(element), function (rogue) {
  1544. remove$7(rogue);
  1545. });
  1546. };
  1547. var remove$7 = function (element) {
  1548. var dom = element.dom;
  1549. if (dom.parentNode !== null) {
  1550. dom.parentNode.removeChild(dom);
  1551. }
  1552. };
  1553. var unwrap = function (wrapper) {
  1554. var children$1 = children(wrapper);
  1555. if (children$1.length > 0) {
  1556. before$3(wrapper, children$1);
  1557. }
  1558. remove$7(wrapper);
  1559. };
  1560. var inBody = function (element) {
  1561. var dom = isText$8(element) ? element.dom.parentNode : element.dom;
  1562. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1563. return false;
  1564. }
  1565. var doc = dom.ownerDocument;
  1566. return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  1567. return doc.body.contains(dom);
  1568. }, compose1(inBody, getShadowHost));
  1569. };
  1570. var r = function (left, top) {
  1571. var translate = function (x, y) {
  1572. return r(left + x, top + y);
  1573. };
  1574. return {
  1575. left: left,
  1576. top: top,
  1577. translate: translate
  1578. };
  1579. };
  1580. var SugarPosition = r;
  1581. var boxPosition = function (dom) {
  1582. var box = dom.getBoundingClientRect();
  1583. return SugarPosition(box.left, box.top);
  1584. };
  1585. var firstDefinedOrZero = function (a, b) {
  1586. if (a !== undefined) {
  1587. return a;
  1588. } else {
  1589. return b !== undefined ? b : 0;
  1590. }
  1591. };
  1592. var absolute = function (element) {
  1593. var doc = element.dom.ownerDocument;
  1594. var body = doc.body;
  1595. var win = doc.defaultView;
  1596. var html = doc.documentElement;
  1597. if (body === element.dom) {
  1598. return SugarPosition(body.offsetLeft, body.offsetTop);
  1599. }
  1600. var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
  1601. var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
  1602. var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  1603. var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  1604. return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  1605. };
  1606. var viewport = function (element) {
  1607. var dom = element.dom;
  1608. var doc = dom.ownerDocument;
  1609. var body = doc.body;
  1610. if (body === dom) {
  1611. return SugarPosition(body.offsetLeft, body.offsetTop);
  1612. }
  1613. if (!inBody(element)) {
  1614. return SugarPosition(0, 0);
  1615. }
  1616. return boxPosition(dom);
  1617. };
  1618. var get$8 = function (_DOC) {
  1619. var doc = _DOC !== undefined ? _DOC.dom : document;
  1620. var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  1621. var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  1622. return SugarPosition(x, y);
  1623. };
  1624. var to = function (x, y, _DOC) {
  1625. var doc = _DOC !== undefined ? _DOC.dom : document;
  1626. var win = doc.defaultView;
  1627. if (win) {
  1628. win.scrollTo(x, y);
  1629. }
  1630. };
  1631. var intoView = function (element, alignToTop) {
  1632. var isSafari = detect().browser.isSafari();
  1633. if (isSafari && isFunction(element.dom.scrollIntoViewIfNeeded)) {
  1634. element.dom.scrollIntoViewIfNeeded(false);
  1635. } else {
  1636. element.dom.scrollIntoView(alignToTop);
  1637. }
  1638. };
  1639. var get$7 = function (_win) {
  1640. var win = _win === undefined ? window : _win;
  1641. if (detect().browser.isFirefox()) {
  1642. return Optional.none();
  1643. } else {
  1644. return Optional.from(win['visualViewport']);
  1645. }
  1646. };
  1647. var bounds = function (x, y, width, height) {
  1648. return {
  1649. x: x,
  1650. y: y,
  1651. width: width,
  1652. height: height,
  1653. right: x + width,
  1654. bottom: y + height
  1655. };
  1656. };
  1657. var getBounds = function (_win) {
  1658. var win = _win === undefined ? window : _win;
  1659. var doc = win.document;
  1660. var scroll = get$8(SugarElement.fromDom(doc));
  1661. return get$7(win).fold(function () {
  1662. var html = win.document.documentElement;
  1663. var width = html.clientWidth;
  1664. var height = html.clientHeight;
  1665. return bounds(scroll.left, scroll.top, width, height);
  1666. }, function (visualViewport) {
  1667. return bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
  1668. });
  1669. };
  1670. var isNodeType = function (type) {
  1671. return function (node) {
  1672. return !!node && node.nodeType === type;
  1673. };
  1674. };
  1675. var isRestrictedNode = function (node) {
  1676. return !!node && !Object.getPrototypeOf(node);
  1677. };
  1678. var isElement$5 = isNodeType(1);
  1679. var matchNodeNames = function (names) {
  1680. var lowercasedNames = names.map(function (s) {
  1681. return s.toLowerCase();
  1682. });
  1683. return function (node) {
  1684. if (node && node.nodeName) {
  1685. var nodeName = node.nodeName.toLowerCase();
  1686. return contains$3(lowercasedNames, nodeName);
  1687. }
  1688. return false;
  1689. };
  1690. };
  1691. var matchStyleValues = function (name, values) {
  1692. var items = values.toLowerCase().split(' ');
  1693. return function (node) {
  1694. if (isElement$5(node)) {
  1695. for (var i = 0; i < items.length; i++) {
  1696. var computed = node.ownerDocument.defaultView.getComputedStyle(node, null);
  1697. var cssValue = computed ? computed.getPropertyValue(name) : null;
  1698. if (cssValue === items[i]) {
  1699. return true;
  1700. }
  1701. }
  1702. }
  1703. return false;
  1704. };
  1705. };
  1706. var hasAttribute = function (attrName) {
  1707. return function (node) {
  1708. return isElement$5(node) && node.hasAttribute(attrName);
  1709. };
  1710. };
  1711. var hasAttributeValue = function (attrName, attrValue) {
  1712. return function (node) {
  1713. return isElement$5(node) && node.getAttribute(attrName) === attrValue;
  1714. };
  1715. };
  1716. var isBogus$2 = function (node) {
  1717. return isElement$5(node) && node.hasAttribute('data-mce-bogus');
  1718. };
  1719. var isBogusAll$1 = function (node) {
  1720. return isElement$5(node) && node.getAttribute('data-mce-bogus') === 'all';
  1721. };
  1722. var isTable$3 = function (node) {
  1723. return isElement$5(node) && node.tagName === 'TABLE';
  1724. };
  1725. var hasContentEditableState = function (value) {
  1726. return function (node) {
  1727. if (isElement$5(node)) {
  1728. if (node.contentEditable === value) {
  1729. return true;
  1730. }
  1731. if (node.getAttribute('data-mce-contenteditable') === value) {
  1732. return true;
  1733. }
  1734. }
  1735. return false;
  1736. };
  1737. };
  1738. var isTextareaOrInput = matchNodeNames([
  1739. 'textarea',
  1740. 'input'
  1741. ]);
  1742. var isText$7 = isNodeType(3);
  1743. var isComment = isNodeType(8);
  1744. var isDocument$1 = isNodeType(9);
  1745. var isDocumentFragment = isNodeType(11);
  1746. var isBr$5 = matchNodeNames(['br']);
  1747. var isImg = matchNodeNames(['img']);
  1748. var isContentEditableTrue$4 = hasContentEditableState('true');
  1749. var isContentEditableFalse$b = hasContentEditableState('false');
  1750. var isTableCell$5 = matchNodeNames([
  1751. 'td',
  1752. 'th'
  1753. ]);
  1754. var isMedia$2 = matchNodeNames([
  1755. 'video',
  1756. 'audio',
  1757. 'object',
  1758. 'embed'
  1759. ]);
  1760. var is$1 = function (lhs, rhs, comparator) {
  1761. if (comparator === void 0) {
  1762. comparator = tripleEquals;
  1763. }
  1764. return lhs.exists(function (left) {
  1765. return comparator(left, rhs);
  1766. });
  1767. };
  1768. var cat = function (arr) {
  1769. var r = [];
  1770. var push = function (x) {
  1771. r.push(x);
  1772. };
  1773. for (var i = 0; i < arr.length; i++) {
  1774. arr[i].each(push);
  1775. }
  1776. return r;
  1777. };
  1778. var lift2 = function (oa, ob, f) {
  1779. return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  1780. };
  1781. var lift3 = function (oa, ob, oc, f) {
  1782. return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
  1783. };
  1784. var someIf = function (b, a) {
  1785. return b ? Optional.some(a) : Optional.none();
  1786. };
  1787. var isSupported = function (dom) {
  1788. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  1789. };
  1790. var rawSet = function (dom, key, value) {
  1791. if (isString$1(value) || isBoolean(value) || isNumber(value)) {
  1792. dom.setAttribute(key, value + '');
  1793. } else {
  1794. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1795. throw new Error('Attribute value was not simple');
  1796. }
  1797. };
  1798. var set$1 = function (element, key, value) {
  1799. rawSet(element.dom, key, value);
  1800. };
  1801. var setAll$1 = function (element, attrs) {
  1802. var dom = element.dom;
  1803. each$j(attrs, function (v, k) {
  1804. rawSet(dom, k, v);
  1805. });
  1806. };
  1807. var get$6 = function (element, key) {
  1808. var v = element.dom.getAttribute(key);
  1809. return v === null ? undefined : v;
  1810. };
  1811. var getOpt = function (element, key) {
  1812. return Optional.from(get$6(element, key));
  1813. };
  1814. var has$1 = function (element, key) {
  1815. var dom = element.dom;
  1816. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  1817. };
  1818. var remove$6 = function (element, key) {
  1819. element.dom.removeAttribute(key);
  1820. };
  1821. var clone$3 = function (element) {
  1822. return foldl(element.dom.attributes, function (acc, attr) {
  1823. acc[attr.name] = attr.value;
  1824. return acc;
  1825. }, {});
  1826. };
  1827. var internalSet = function (dom, property, value) {
  1828. if (!isString$1(value)) {
  1829. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  1830. throw new Error('CSS value must be a string: ' + value);
  1831. }
  1832. if (isSupported(dom)) {
  1833. dom.style.setProperty(property, value);
  1834. }
  1835. };
  1836. var setAll = function (element, css) {
  1837. var dom = element.dom;
  1838. each$j(css, function (v, k) {
  1839. internalSet(dom, k, v);
  1840. });
  1841. };
  1842. var get$5 = function (element, property) {
  1843. var dom = element.dom;
  1844. var styles = window.getComputedStyle(dom);
  1845. var r = styles.getPropertyValue(property);
  1846. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  1847. };
  1848. var getUnsafeProperty = function (dom, property) {
  1849. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  1850. };
  1851. var getRaw = function (element, property) {
  1852. var dom = element.dom;
  1853. var raw = getUnsafeProperty(dom, property);
  1854. return Optional.from(raw).filter(function (r) {
  1855. return r.length > 0;
  1856. });
  1857. };
  1858. var getAllRaw = function (element) {
  1859. var css = {};
  1860. var dom = element.dom;
  1861. if (isSupported(dom)) {
  1862. for (var i = 0; i < dom.style.length; i++) {
  1863. var ruleName = dom.style.item(i);
  1864. css[ruleName] = dom.style[ruleName];
  1865. }
  1866. }
  1867. return css;
  1868. };
  1869. var reflow = function (e) {
  1870. return e.dom.offsetWidth;
  1871. };
  1872. var browser$3 = detect().browser;
  1873. var firstElement = function (nodes) {
  1874. return find$3(nodes, isElement$6);
  1875. };
  1876. var getTableCaptionDeltaY = function (elm) {
  1877. if (browser$3.isFirefox() && name(elm) === 'table') {
  1878. return firstElement(children(elm)).filter(function (elm) {
  1879. return name(elm) === 'caption';
  1880. }).bind(function (caption) {
  1881. return firstElement(nextSiblings(caption)).map(function (body) {
  1882. var bodyTop = body.dom.offsetTop;
  1883. var captionTop = caption.dom.offsetTop;
  1884. var captionHeight = caption.dom.offsetHeight;
  1885. return bodyTop <= captionTop ? -captionHeight : 0;
  1886. });
  1887. }).getOr(0);
  1888. } else {
  1889. return 0;
  1890. }
  1891. };
  1892. var hasChild = function (elm, child) {
  1893. return elm.children && contains$3(elm.children, child);
  1894. };
  1895. var getPos = function (body, elm, rootElm) {
  1896. var x = 0, y = 0;
  1897. var doc = body.ownerDocument;
  1898. rootElm = rootElm ? rootElm : body;
  1899. if (elm) {
  1900. if (rootElm === body && elm.getBoundingClientRect && get$5(SugarElement.fromDom(body), 'position') === 'static') {
  1901. var pos = elm.getBoundingClientRect();
  1902. x = pos.left + (doc.documentElement.scrollLeft || body.scrollLeft) - doc.documentElement.clientLeft;
  1903. y = pos.top + (doc.documentElement.scrollTop || body.scrollTop) - doc.documentElement.clientTop;
  1904. return {
  1905. x: x,
  1906. y: y
  1907. };
  1908. }
  1909. var offsetParent = elm;
  1910. while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  1911. var castOffsetParent = offsetParent;
  1912. x += castOffsetParent.offsetLeft || 0;
  1913. y += castOffsetParent.offsetTop || 0;
  1914. offsetParent = castOffsetParent.offsetParent;
  1915. }
  1916. offsetParent = elm.parentNode;
  1917. while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  1918. x -= offsetParent.scrollLeft || 0;
  1919. y -= offsetParent.scrollTop || 0;
  1920. offsetParent = offsetParent.parentNode;
  1921. }
  1922. y += getTableCaptionDeltaY(SugarElement.fromDom(elm));
  1923. }
  1924. return {
  1925. x: x,
  1926. y: y
  1927. };
  1928. };
  1929. var exports$1 = {}, module$1 = { exports: exports$1 };
  1930. (function (define, exports, module, require) {
  1931. (function (global, factory) {
  1932. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.EphoxContactWrapper = factory());
  1933. }(this, function () {
  1934. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  1935. var promise = { exports: {} };
  1936. (function (module) {
  1937. (function (root) {
  1938. var setTimeoutFunc = setTimeout;
  1939. function noop() {
  1940. }
  1941. function bind(fn, thisArg) {
  1942. return function () {
  1943. fn.apply(thisArg, arguments);
  1944. };
  1945. }
  1946. function Promise(fn) {
  1947. if (typeof this !== 'object')
  1948. throw new TypeError('Promises must be constructed via new');
  1949. if (typeof fn !== 'function')
  1950. throw new TypeError('not a function');
  1951. this._state = 0;
  1952. this._handled = false;
  1953. this._value = undefined;
  1954. this._deferreds = [];
  1955. doResolve(fn, this);
  1956. }
  1957. function handle(self, deferred) {
  1958. while (self._state === 3) {
  1959. self = self._value;
  1960. }
  1961. if (self._state === 0) {
  1962. self._deferreds.push(deferred);
  1963. return;
  1964. }
  1965. self._handled = true;
  1966. Promise._immediateFn(function () {
  1967. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  1968. if (cb === null) {
  1969. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  1970. return;
  1971. }
  1972. var ret;
  1973. try {
  1974. ret = cb(self._value);
  1975. } catch (e) {
  1976. reject(deferred.promise, e);
  1977. return;
  1978. }
  1979. resolve(deferred.promise, ret);
  1980. });
  1981. }
  1982. function resolve(self, newValue) {
  1983. try {
  1984. if (newValue === self)
  1985. throw new TypeError('A promise cannot be resolved with itself.');
  1986. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  1987. var then = newValue.then;
  1988. if (newValue instanceof Promise) {
  1989. self._state = 3;
  1990. self._value = newValue;
  1991. finale(self);
  1992. return;
  1993. } else if (typeof then === 'function') {
  1994. doResolve(bind(then, newValue), self);
  1995. return;
  1996. }
  1997. }
  1998. self._state = 1;
  1999. self._value = newValue;
  2000. finale(self);
  2001. } catch (e) {
  2002. reject(self, e);
  2003. }
  2004. }
  2005. function reject(self, newValue) {
  2006. self._state = 2;
  2007. self._value = newValue;
  2008. finale(self);
  2009. }
  2010. function finale(self) {
  2011. if (self._state === 2 && self._deferreds.length === 0) {
  2012. Promise._immediateFn(function () {
  2013. if (!self._handled) {
  2014. Promise._unhandledRejectionFn(self._value);
  2015. }
  2016. });
  2017. }
  2018. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  2019. handle(self, self._deferreds[i]);
  2020. }
  2021. self._deferreds = null;
  2022. }
  2023. function Handler(onFulfilled, onRejected, promise) {
  2024. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  2025. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  2026. this.promise = promise;
  2027. }
  2028. function doResolve(fn, self) {
  2029. var done = false;
  2030. try {
  2031. fn(function (value) {
  2032. if (done)
  2033. return;
  2034. done = true;
  2035. resolve(self, value);
  2036. }, function (reason) {
  2037. if (done)
  2038. return;
  2039. done = true;
  2040. reject(self, reason);
  2041. });
  2042. } catch (ex) {
  2043. if (done)
  2044. return;
  2045. done = true;
  2046. reject(self, ex);
  2047. }
  2048. }
  2049. Promise.prototype['catch'] = function (onRejected) {
  2050. return this.then(null, onRejected);
  2051. };
  2052. Promise.prototype.then = function (onFulfilled, onRejected) {
  2053. var prom = new this.constructor(noop);
  2054. handle(this, new Handler(onFulfilled, onRejected, prom));
  2055. return prom;
  2056. };
  2057. Promise.all = function (arr) {
  2058. var args = Array.prototype.slice.call(arr);
  2059. return new Promise(function (resolve, reject) {
  2060. if (args.length === 0)
  2061. return resolve([]);
  2062. var remaining = args.length;
  2063. function res(i, val) {
  2064. try {
  2065. if (val && (typeof val === 'object' || typeof val === 'function')) {
  2066. var then = val.then;
  2067. if (typeof then === 'function') {
  2068. then.call(val, function (val) {
  2069. res(i, val);
  2070. }, reject);
  2071. return;
  2072. }
  2073. }
  2074. args[i] = val;
  2075. if (--remaining === 0) {
  2076. resolve(args);
  2077. }
  2078. } catch (ex) {
  2079. reject(ex);
  2080. }
  2081. }
  2082. for (var i = 0; i < args.length; i++) {
  2083. res(i, args[i]);
  2084. }
  2085. });
  2086. };
  2087. Promise.resolve = function (value) {
  2088. if (value && typeof value === 'object' && value.constructor === Promise) {
  2089. return value;
  2090. }
  2091. return new Promise(function (resolve) {
  2092. resolve(value);
  2093. });
  2094. };
  2095. Promise.reject = function (value) {
  2096. return new Promise(function (resolve, reject) {
  2097. reject(value);
  2098. });
  2099. };
  2100. Promise.race = function (values) {
  2101. return new Promise(function (resolve, reject) {
  2102. for (var i = 0, len = values.length; i < len; i++) {
  2103. values[i].then(resolve, reject);
  2104. }
  2105. });
  2106. };
  2107. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  2108. setImmediate(fn);
  2109. } : function (fn) {
  2110. setTimeoutFunc(fn, 0);
  2111. };
  2112. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  2113. if (typeof console !== 'undefined' && console) {
  2114. console.warn('Possible Unhandled Promise Rejection:', err);
  2115. }
  2116. };
  2117. Promise._setImmediateFn = function _setImmediateFn(fn) {
  2118. Promise._immediateFn = fn;
  2119. };
  2120. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  2121. Promise._unhandledRejectionFn = fn;
  2122. };
  2123. if (module.exports) {
  2124. module.exports = Promise;
  2125. } else if (!root.Promise) {
  2126. root.Promise = Promise;
  2127. }
  2128. }(commonjsGlobal));
  2129. }(promise));
  2130. var promisePolyfill = promise.exports;
  2131. var Global = function () {
  2132. if (typeof window !== 'undefined') {
  2133. return window;
  2134. } else {
  2135. return Function('return this;')();
  2136. }
  2137. }();
  2138. var promisePolyfill_1 = { boltExport: Global.Promise || promisePolyfill };
  2139. return promisePolyfill_1;
  2140. }));
  2141. }(undefined, exports$1, module$1));
  2142. var Promise$1 = module$1.exports.boltExport;
  2143. var nu$1 = function (baseFn) {
  2144. var data = Optional.none();
  2145. var callbacks = [];
  2146. var map = function (f) {
  2147. return nu$1(function (nCallback) {
  2148. get(function (data) {
  2149. nCallback(f(data));
  2150. });
  2151. });
  2152. };
  2153. var get = function (nCallback) {
  2154. if (isReady()) {
  2155. call(nCallback);
  2156. } else {
  2157. callbacks.push(nCallback);
  2158. }
  2159. };
  2160. var set = function (x) {
  2161. if (!isReady()) {
  2162. data = Optional.some(x);
  2163. run(callbacks);
  2164. callbacks = [];
  2165. }
  2166. };
  2167. var isReady = function () {
  2168. return data.isSome();
  2169. };
  2170. var run = function (cbs) {
  2171. each$k(cbs, call);
  2172. };
  2173. var call = function (cb) {
  2174. data.each(function (x) {
  2175. setTimeout(function () {
  2176. cb(x);
  2177. }, 0);
  2178. });
  2179. };
  2180. baseFn(set);
  2181. return {
  2182. get: get,
  2183. map: map,
  2184. isReady: isReady
  2185. };
  2186. };
  2187. var pure$1 = function (a) {
  2188. return nu$1(function (callback) {
  2189. callback(a);
  2190. });
  2191. };
  2192. var LazyValue = {
  2193. nu: nu$1,
  2194. pure: pure$1
  2195. };
  2196. var errorReporter = function (err) {
  2197. setTimeout(function () {
  2198. throw err;
  2199. }, 0);
  2200. };
  2201. var make = function (run) {
  2202. var get = function (callback) {
  2203. run().then(callback, errorReporter);
  2204. };
  2205. var map = function (fab) {
  2206. return make(function () {
  2207. return run().then(fab);
  2208. });
  2209. };
  2210. var bind = function (aFutureB) {
  2211. return make(function () {
  2212. return run().then(function (v) {
  2213. return aFutureB(v).toPromise();
  2214. });
  2215. });
  2216. };
  2217. var anonBind = function (futureB) {
  2218. return make(function () {
  2219. return run().then(function () {
  2220. return futureB.toPromise();
  2221. });
  2222. });
  2223. };
  2224. var toLazy = function () {
  2225. return LazyValue.nu(get);
  2226. };
  2227. var toCached = function () {
  2228. var cache = null;
  2229. return make(function () {
  2230. if (cache === null) {
  2231. cache = run();
  2232. }
  2233. return cache;
  2234. });
  2235. };
  2236. var toPromise = run;
  2237. return {
  2238. map: map,
  2239. bind: bind,
  2240. anonBind: anonBind,
  2241. toLazy: toLazy,
  2242. toCached: toCached,
  2243. toPromise: toPromise,
  2244. get: get
  2245. };
  2246. };
  2247. var nu = function (baseFn) {
  2248. return make(function () {
  2249. return new Promise$1(baseFn);
  2250. });
  2251. };
  2252. var pure = function (a) {
  2253. return make(function () {
  2254. return Promise$1.resolve(a);
  2255. });
  2256. };
  2257. var Future = {
  2258. nu: nu,
  2259. pure: pure
  2260. };
  2261. var par$1 = function (asyncValues, nu) {
  2262. return nu(function (callback) {
  2263. var r = [];
  2264. var count = 0;
  2265. var cb = function (i) {
  2266. return function (value) {
  2267. r[i] = value;
  2268. count++;
  2269. if (count >= asyncValues.length) {
  2270. callback(r);
  2271. }
  2272. };
  2273. };
  2274. if (asyncValues.length === 0) {
  2275. callback([]);
  2276. } else {
  2277. each$k(asyncValues, function (asyncValue, i) {
  2278. asyncValue.get(cb(i));
  2279. });
  2280. }
  2281. });
  2282. };
  2283. var par = function (futures) {
  2284. return par$1(futures, Future.nu);
  2285. };
  2286. var value$1 = function (o) {
  2287. var or = function (_opt) {
  2288. return value$1(o);
  2289. };
  2290. var orThunk = function (_f) {
  2291. return value$1(o);
  2292. };
  2293. var map = function (f) {
  2294. return value$1(f(o));
  2295. };
  2296. var mapError = function (_f) {
  2297. return value$1(o);
  2298. };
  2299. var each = function (f) {
  2300. f(o);
  2301. };
  2302. var bind = function (f) {
  2303. return f(o);
  2304. };
  2305. var fold = function (_, onValue) {
  2306. return onValue(o);
  2307. };
  2308. var exists = function (f) {
  2309. return f(o);
  2310. };
  2311. var forall = function (f) {
  2312. return f(o);
  2313. };
  2314. var toOptional = function () {
  2315. return Optional.some(o);
  2316. };
  2317. return {
  2318. isValue: always,
  2319. isError: never,
  2320. getOr: constant(o),
  2321. getOrThunk: constant(o),
  2322. getOrDie: constant(o),
  2323. or: or,
  2324. orThunk: orThunk,
  2325. fold: fold,
  2326. map: map,
  2327. mapError: mapError,
  2328. each: each,
  2329. bind: bind,
  2330. exists: exists,
  2331. forall: forall,
  2332. toOptional: toOptional
  2333. };
  2334. };
  2335. var error = function (message) {
  2336. var getOrThunk = function (f) {
  2337. return f();
  2338. };
  2339. var getOrDie = function () {
  2340. return die(String(message))();
  2341. };
  2342. var or = identity;
  2343. var orThunk = function (f) {
  2344. return f();
  2345. };
  2346. var map = function (_f) {
  2347. return error(message);
  2348. };
  2349. var mapError = function (f) {
  2350. return error(f(message));
  2351. };
  2352. var bind = function (_f) {
  2353. return error(message);
  2354. };
  2355. var fold = function (onError, _) {
  2356. return onError(message);
  2357. };
  2358. return {
  2359. isValue: never,
  2360. isError: always,
  2361. getOr: identity,
  2362. getOrThunk: getOrThunk,
  2363. getOrDie: getOrDie,
  2364. or: or,
  2365. orThunk: orThunk,
  2366. fold: fold,
  2367. map: map,
  2368. mapError: mapError,
  2369. each: noop,
  2370. bind: bind,
  2371. exists: never,
  2372. forall: always,
  2373. toOptional: Optional.none
  2374. };
  2375. };
  2376. var fromOption = function (opt, err) {
  2377. return opt.fold(function () {
  2378. return error(err);
  2379. }, value$1);
  2380. };
  2381. var Result = {
  2382. value: value$1,
  2383. error: error,
  2384. fromOption: fromOption
  2385. };
  2386. var generate$1 = function (cases) {
  2387. if (!isArray$1(cases)) {
  2388. throw new Error('cases must be an array');
  2389. }
  2390. if (cases.length === 0) {
  2391. throw new Error('there must be at least one case');
  2392. }
  2393. var constructors = [];
  2394. var adt = {};
  2395. each$k(cases, function (acase, count) {
  2396. var keys$1 = keys(acase);
  2397. if (keys$1.length !== 1) {
  2398. throw new Error('one and only one name per case');
  2399. }
  2400. var key = keys$1[0];
  2401. var value = acase[key];
  2402. if (adt[key] !== undefined) {
  2403. throw new Error('duplicate key detected:' + key);
  2404. } else if (key === 'cata') {
  2405. throw new Error('cannot have a case named cata (sorry)');
  2406. } else if (!isArray$1(value)) {
  2407. throw new Error('case arguments must be an array');
  2408. }
  2409. constructors.push(key);
  2410. adt[key] = function () {
  2411. var args = [];
  2412. for (var _i = 0; _i < arguments.length; _i++) {
  2413. args[_i] = arguments[_i];
  2414. }
  2415. var argLength = args.length;
  2416. if (argLength !== value.length) {
  2417. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  2418. }
  2419. var match = function (branches) {
  2420. var branchKeys = keys(branches);
  2421. if (constructors.length !== branchKeys.length) {
  2422. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  2423. }
  2424. var allReqd = forall(constructors, function (reqKey) {
  2425. return contains$3(branchKeys, reqKey);
  2426. });
  2427. if (!allReqd) {
  2428. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  2429. }
  2430. return branches[key].apply(null, args);
  2431. };
  2432. return {
  2433. fold: function () {
  2434. var foldArgs = [];
  2435. for (var _i = 0; _i < arguments.length; _i++) {
  2436. foldArgs[_i] = arguments[_i];
  2437. }
  2438. if (foldArgs.length !== cases.length) {
  2439. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  2440. }
  2441. var target = foldArgs[count];
  2442. return target.apply(null, args);
  2443. },
  2444. match: match,
  2445. log: function (label) {
  2446. console.log(label, {
  2447. constructors: constructors,
  2448. constructor: key,
  2449. params: args
  2450. });
  2451. }
  2452. };
  2453. };
  2454. });
  2455. return adt;
  2456. };
  2457. var Adt = { generate: generate$1 };
  2458. Adt.generate([
  2459. {
  2460. bothErrors: [
  2461. 'error1',
  2462. 'error2'
  2463. ]
  2464. },
  2465. {
  2466. firstError: [
  2467. 'error1',
  2468. 'value2'
  2469. ]
  2470. },
  2471. {
  2472. secondError: [
  2473. 'value1',
  2474. 'error2'
  2475. ]
  2476. },
  2477. {
  2478. bothValues: [
  2479. 'value1',
  2480. 'value2'
  2481. ]
  2482. }
  2483. ]);
  2484. var unite = function (result) {
  2485. return result.fold(identity, identity);
  2486. };
  2487. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  2488. if (is(scope, a)) {
  2489. return Optional.some(scope);
  2490. } else if (isFunction(isRoot) && isRoot(scope)) {
  2491. return Optional.none();
  2492. } else {
  2493. return ancestor(scope, a, isRoot);
  2494. }
  2495. }
  2496. var ancestor$3 = function (scope, predicate, isRoot) {
  2497. var element = scope.dom;
  2498. var stop = isFunction(isRoot) ? isRoot : never;
  2499. while (element.parentNode) {
  2500. element = element.parentNode;
  2501. var el = SugarElement.fromDom(element);
  2502. if (predicate(el)) {
  2503. return Optional.some(el);
  2504. } else if (stop(el)) {
  2505. break;
  2506. }
  2507. }
  2508. return Optional.none();
  2509. };
  2510. var closest$3 = function (scope, predicate, isRoot) {
  2511. var is = function (s, test) {
  2512. return test(s);
  2513. };
  2514. return ClosestOrAncestor(is, ancestor$3, scope, predicate, isRoot);
  2515. };
  2516. var sibling$2 = function (scope, predicate) {
  2517. var element = scope.dom;
  2518. if (!element.parentNode) {
  2519. return Optional.none();
  2520. }
  2521. return child(SugarElement.fromDom(element.parentNode), function (x) {
  2522. return !eq(scope, x) && predicate(x);
  2523. });
  2524. };
  2525. var child = function (scope, predicate) {
  2526. var pred = function (node) {
  2527. return predicate(SugarElement.fromDom(node));
  2528. };
  2529. var result = find$3(scope.dom.childNodes, pred);
  2530. return result.map(SugarElement.fromDom);
  2531. };
  2532. var ancestor$2 = function (scope, selector, isRoot) {
  2533. return ancestor$3(scope, function (e) {
  2534. return is$2(e, selector);
  2535. }, isRoot);
  2536. };
  2537. var descendant = function (scope, selector) {
  2538. return one(selector, scope);
  2539. };
  2540. var closest$2 = function (scope, selector, isRoot) {
  2541. var is = function (element, selector) {
  2542. return is$2(element, selector);
  2543. };
  2544. return ClosestOrAncestor(is, ancestor$2, scope, selector, isRoot);
  2545. };
  2546. var promiseObj = window.Promise ? window.Promise : Promise$1;
  2547. var requestAnimationFramePromise;
  2548. var requestAnimationFrame = function (callback, element) {
  2549. var requestAnimationFrameFunc = window.requestAnimationFrame;
  2550. var vendors = [
  2551. 'ms',
  2552. 'moz',
  2553. 'webkit'
  2554. ];
  2555. var featurefill = function (cb) {
  2556. window.setTimeout(cb, 0);
  2557. };
  2558. for (var i = 0; i < vendors.length && !requestAnimationFrameFunc; i++) {
  2559. requestAnimationFrameFunc = window[vendors[i] + 'RequestAnimationFrame'];
  2560. }
  2561. if (!requestAnimationFrameFunc) {
  2562. requestAnimationFrameFunc = featurefill;
  2563. }
  2564. requestAnimationFrameFunc(callback, element);
  2565. };
  2566. var wrappedSetTimeout = function (callback, time) {
  2567. if (typeof time !== 'number') {
  2568. time = 0;
  2569. }
  2570. return setTimeout(callback, time);
  2571. };
  2572. var wrappedSetInterval = function (callback, time) {
  2573. if (typeof time !== 'number') {
  2574. time = 1;
  2575. }
  2576. return setInterval(callback, time);
  2577. };
  2578. var wrappedClearTimeout = function (id) {
  2579. return clearTimeout(id);
  2580. };
  2581. var wrappedClearInterval = function (id) {
  2582. return clearInterval(id);
  2583. };
  2584. var debounce = function (callback, time) {
  2585. var timer;
  2586. var func = function () {
  2587. var args = [];
  2588. for (var _i = 0; _i < arguments.length; _i++) {
  2589. args[_i] = arguments[_i];
  2590. }
  2591. clearTimeout(timer);
  2592. timer = wrappedSetTimeout(function () {
  2593. callback.apply(this, args);
  2594. }, time);
  2595. };
  2596. func.stop = function () {
  2597. clearTimeout(timer);
  2598. };
  2599. return func;
  2600. };
  2601. var Delay = {
  2602. requestAnimationFrame: function (callback, element) {
  2603. if (requestAnimationFramePromise) {
  2604. requestAnimationFramePromise.then(callback);
  2605. return;
  2606. }
  2607. requestAnimationFramePromise = new promiseObj(function (resolve) {
  2608. if (!element) {
  2609. element = document.body;
  2610. }
  2611. requestAnimationFrame(resolve, element);
  2612. }).then(callback);
  2613. },
  2614. setTimeout: wrappedSetTimeout,
  2615. setInterval: wrappedSetInterval,
  2616. setEditorTimeout: function (editor, callback, time) {
  2617. return wrappedSetTimeout(function () {
  2618. if (!editor.removed) {
  2619. callback();
  2620. }
  2621. }, time);
  2622. },
  2623. setEditorInterval: function (editor, callback, time) {
  2624. var timer = wrappedSetInterval(function () {
  2625. if (!editor.removed) {
  2626. callback();
  2627. } else {
  2628. clearInterval(timer);
  2629. }
  2630. }, time);
  2631. return timer;
  2632. },
  2633. debounce: debounce,
  2634. throttle: debounce,
  2635. clearInterval: wrappedClearInterval,
  2636. clearTimeout: wrappedClearTimeout
  2637. };
  2638. var StyleSheetLoader = function (documentOrShadowRoot, settings) {
  2639. if (settings === void 0) {
  2640. settings = {};
  2641. }
  2642. var idCount = 0;
  2643. var loadedStates = {};
  2644. var edos = SugarElement.fromDom(documentOrShadowRoot);
  2645. var doc = documentOrOwner(edos);
  2646. var maxLoadTime = settings.maxLoadTime || 5000;
  2647. var _setReferrerPolicy = function (referrerPolicy) {
  2648. settings.referrerPolicy = referrerPolicy;
  2649. };
  2650. var addStyle = function (element) {
  2651. append$1(getStyleContainer(edos), element);
  2652. };
  2653. var removeStyle = function (id) {
  2654. var styleContainer = getStyleContainer(edos);
  2655. descendant(styleContainer, '#' + id).each(remove$7);
  2656. };
  2657. var getOrCreateState = function (url) {
  2658. return get$9(loadedStates, url).getOrThunk(function () {
  2659. return {
  2660. id: 'mce-u' + idCount++,
  2661. passed: [],
  2662. failed: [],
  2663. count: 0
  2664. };
  2665. });
  2666. };
  2667. var load = function (url, success, failure) {
  2668. var link;
  2669. var urlWithSuffix = Tools._addCacheSuffix(url);
  2670. var state = getOrCreateState(urlWithSuffix);
  2671. loadedStates[urlWithSuffix] = state;
  2672. state.count++;
  2673. var resolve = function (callbacks, status) {
  2674. var i = callbacks.length;
  2675. while (i--) {
  2676. callbacks[i]();
  2677. }
  2678. state.status = status;
  2679. state.passed = [];
  2680. state.failed = [];
  2681. if (link) {
  2682. link.onload = null;
  2683. link.onerror = null;
  2684. link = null;
  2685. }
  2686. };
  2687. var passed = function () {
  2688. return resolve(state.passed, 2);
  2689. };
  2690. var failed = function () {
  2691. return resolve(state.failed, 3);
  2692. };
  2693. var wait = function (testCallback, waitCallback) {
  2694. if (!testCallback()) {
  2695. if (Date.now() - startTime < maxLoadTime) {
  2696. Delay.setTimeout(waitCallback);
  2697. } else {
  2698. failed();
  2699. }
  2700. }
  2701. };
  2702. var waitForWebKitLinkLoaded = function () {
  2703. wait(function () {
  2704. var styleSheets = documentOrShadowRoot.styleSheets;
  2705. var i = styleSheets.length;
  2706. while (i--) {
  2707. var styleSheet = styleSheets[i];
  2708. var owner = styleSheet.ownerNode;
  2709. if (owner && owner.id === link.id) {
  2710. passed();
  2711. return true;
  2712. }
  2713. }
  2714. return false;
  2715. }, waitForWebKitLinkLoaded);
  2716. };
  2717. if (success) {
  2718. state.passed.push(success);
  2719. }
  2720. if (failure) {
  2721. state.failed.push(failure);
  2722. }
  2723. if (state.status === 1) {
  2724. return;
  2725. }
  2726. if (state.status === 2) {
  2727. passed();
  2728. return;
  2729. }
  2730. if (state.status === 3) {
  2731. failed();
  2732. return;
  2733. }
  2734. state.status = 1;
  2735. var linkElem = SugarElement.fromTag('link', doc.dom);
  2736. setAll$1(linkElem, {
  2737. rel: 'stylesheet',
  2738. type: 'text/css',
  2739. id: state.id
  2740. });
  2741. var startTime = Date.now();
  2742. if (settings.contentCssCors) {
  2743. set$1(linkElem, 'crossOrigin', 'anonymous');
  2744. }
  2745. if (settings.referrerPolicy) {
  2746. set$1(linkElem, 'referrerpolicy', settings.referrerPolicy);
  2747. }
  2748. link = linkElem.dom;
  2749. link.onload = waitForWebKitLinkLoaded;
  2750. link.onerror = failed;
  2751. addStyle(linkElem);
  2752. set$1(linkElem, 'href', urlWithSuffix);
  2753. };
  2754. var loadF = function (url) {
  2755. return Future.nu(function (resolve) {
  2756. load(url, compose(resolve, constant(Result.value(url))), compose(resolve, constant(Result.error(url))));
  2757. });
  2758. };
  2759. var loadAll = function (urls, success, failure) {
  2760. par(map$3(urls, loadF)).get(function (result) {
  2761. var parts = partition(result, function (r) {
  2762. return r.isValue();
  2763. });
  2764. if (parts.fail.length > 0) {
  2765. failure(parts.fail.map(unite));
  2766. } else {
  2767. success(parts.pass.map(unite));
  2768. }
  2769. });
  2770. };
  2771. var unload = function (url) {
  2772. var urlWithSuffix = Tools._addCacheSuffix(url);
  2773. get$9(loadedStates, urlWithSuffix).each(function (state) {
  2774. var count = --state.count;
  2775. if (count === 0) {
  2776. delete loadedStates[urlWithSuffix];
  2777. removeStyle(state.id);
  2778. }
  2779. });
  2780. };
  2781. var unloadAll = function (urls) {
  2782. each$k(urls, function (url) {
  2783. unload(url);
  2784. });
  2785. };
  2786. return {
  2787. load: load,
  2788. loadAll: loadAll,
  2789. unload: unload,
  2790. unloadAll: unloadAll,
  2791. _setReferrerPolicy: _setReferrerPolicy
  2792. };
  2793. };
  2794. var create$8 = function () {
  2795. var map = new WeakMap();
  2796. var forElement = function (referenceElement, settings) {
  2797. var root = getRootNode(referenceElement);
  2798. var rootDom = root.dom;
  2799. return Optional.from(map.get(rootDom)).getOrThunk(function () {
  2800. var sl = StyleSheetLoader(rootDom, settings);
  2801. map.set(rootDom, sl);
  2802. return sl;
  2803. });
  2804. };
  2805. return { forElement: forElement };
  2806. };
  2807. var instance = create$8();
  2808. var DomTreeWalker = function () {
  2809. function DomTreeWalker(startNode, rootNode) {
  2810. this.node = startNode;
  2811. this.rootNode = rootNode;
  2812. this.current = this.current.bind(this);
  2813. this.next = this.next.bind(this);
  2814. this.prev = this.prev.bind(this);
  2815. this.prev2 = this.prev2.bind(this);
  2816. }
  2817. DomTreeWalker.prototype.current = function () {
  2818. return this.node;
  2819. };
  2820. DomTreeWalker.prototype.next = function (shallow) {
  2821. this.node = this.findSibling(this.node, 'firstChild', 'nextSibling', shallow);
  2822. return this.node;
  2823. };
  2824. DomTreeWalker.prototype.prev = function (shallow) {
  2825. this.node = this.findSibling(this.node, 'lastChild', 'previousSibling', shallow);
  2826. return this.node;
  2827. };
  2828. DomTreeWalker.prototype.prev2 = function (shallow) {
  2829. this.node = this.findPreviousNode(this.node, 'lastChild', 'previousSibling', shallow);
  2830. return this.node;
  2831. };
  2832. DomTreeWalker.prototype.findSibling = function (node, startName, siblingName, shallow) {
  2833. var sibling, parent;
  2834. if (node) {
  2835. if (!shallow && node[startName]) {
  2836. return node[startName];
  2837. }
  2838. if (node !== this.rootNode) {
  2839. sibling = node[siblingName];
  2840. if (sibling) {
  2841. return sibling;
  2842. }
  2843. for (parent = node.parentNode; parent && parent !== this.rootNode; parent = parent.parentNode) {
  2844. sibling = parent[siblingName];
  2845. if (sibling) {
  2846. return sibling;
  2847. }
  2848. }
  2849. }
  2850. }
  2851. };
  2852. DomTreeWalker.prototype.findPreviousNode = function (node, startName, siblingName, shallow) {
  2853. var sibling, parent, child;
  2854. if (node) {
  2855. sibling = node[siblingName];
  2856. if (this.rootNode && sibling === this.rootNode) {
  2857. return;
  2858. }
  2859. if (sibling) {
  2860. if (!shallow) {
  2861. for (child = sibling[startName]; child; child = child[startName]) {
  2862. if (!child[startName]) {
  2863. return child;
  2864. }
  2865. }
  2866. }
  2867. return sibling;
  2868. }
  2869. parent = node.parentNode;
  2870. if (parent && parent !== this.rootNode) {
  2871. return parent;
  2872. }
  2873. }
  2874. };
  2875. return DomTreeWalker;
  2876. }();
  2877. var blocks = [
  2878. 'article',
  2879. 'aside',
  2880. 'details',
  2881. 'div',
  2882. 'dt',
  2883. 'figcaption',
  2884. 'footer',
  2885. 'form',
  2886. 'fieldset',
  2887. 'header',
  2888. 'hgroup',
  2889. 'html',
  2890. 'main',
  2891. 'nav',
  2892. 'section',
  2893. 'summary',
  2894. 'body',
  2895. 'p',
  2896. 'dl',
  2897. 'multicol',
  2898. 'dd',
  2899. 'figure',
  2900. 'address',
  2901. 'center',
  2902. 'blockquote',
  2903. 'h1',
  2904. 'h2',
  2905. 'h3',
  2906. 'h4',
  2907. 'h5',
  2908. 'h6',
  2909. 'listing',
  2910. 'xmp',
  2911. 'pre',
  2912. 'plaintext',
  2913. 'menu',
  2914. 'dir',
  2915. 'ul',
  2916. 'ol',
  2917. 'li',
  2918. 'hr',
  2919. 'table',
  2920. 'tbody',
  2921. 'thead',
  2922. 'tfoot',
  2923. 'th',
  2924. 'tr',
  2925. 'td',
  2926. 'caption'
  2927. ];
  2928. var tableCells = [
  2929. 'td',
  2930. 'th'
  2931. ];
  2932. var tableSections = [
  2933. 'thead',
  2934. 'tbody',
  2935. 'tfoot'
  2936. ];
  2937. var textBlocks = [
  2938. 'h1',
  2939. 'h2',
  2940. 'h3',
  2941. 'h4',
  2942. 'h5',
  2943. 'h6',
  2944. 'p',
  2945. 'div',
  2946. 'address',
  2947. 'pre',
  2948. 'form',
  2949. 'blockquote',
  2950. 'center',
  2951. 'dir',
  2952. 'fieldset',
  2953. 'header',
  2954. 'footer',
  2955. 'article',
  2956. 'section',
  2957. 'hgroup',
  2958. 'aside',
  2959. 'nav',
  2960. 'figure'
  2961. ];
  2962. var headings = [
  2963. 'h1',
  2964. 'h2',
  2965. 'h3',
  2966. 'h4',
  2967. 'h5',
  2968. 'h6'
  2969. ];
  2970. var listItems$1 = [
  2971. 'li',
  2972. 'dd',
  2973. 'dt'
  2974. ];
  2975. var lists = [
  2976. 'ul',
  2977. 'ol',
  2978. 'dl'
  2979. ];
  2980. var wsElements = [
  2981. 'pre',
  2982. 'script',
  2983. 'textarea',
  2984. 'style'
  2985. ];
  2986. var lazyLookup = function (items) {
  2987. var lookup;
  2988. return function (node) {
  2989. lookup = lookup ? lookup : mapToObject(items, always);
  2990. return has$2(lookup, name(node));
  2991. };
  2992. };
  2993. var isHeading = lazyLookup(headings);
  2994. var isBlock$2 = lazyLookup(blocks);
  2995. var isTable$2 = function (node) {
  2996. return name(node) === 'table';
  2997. };
  2998. var isInline$1 = function (node) {
  2999. return isElement$6(node) && !isBlock$2(node);
  3000. };
  3001. var isBr$4 = function (node) {
  3002. return isElement$6(node) && name(node) === 'br';
  3003. };
  3004. var isTextBlock$2 = lazyLookup(textBlocks);
  3005. var isList = lazyLookup(lists);
  3006. var isListItem = lazyLookup(listItems$1);
  3007. var isTableSection = lazyLookup(tableSections);
  3008. var isTableCell$4 = lazyLookup(tableCells);
  3009. var isWsPreserveElement = lazyLookup(wsElements);
  3010. var ancestor$1 = function (scope, selector, isRoot) {
  3011. return ancestor$2(scope, selector, isRoot).isSome();
  3012. };
  3013. var zeroWidth = '\uFEFF';
  3014. var nbsp = '\xA0';
  3015. var isZwsp$1 = function (char) {
  3016. return char === zeroWidth;
  3017. };
  3018. var removeZwsp = function (s) {
  3019. return s.replace(/\uFEFF/g, '');
  3020. };
  3021. var ZWSP$1 = zeroWidth;
  3022. var isZwsp = isZwsp$1;
  3023. var trim$2 = removeZwsp;
  3024. var isElement$4 = isElement$5;
  3025. var isText$6 = isText$7;
  3026. var isCaretContainerBlock$1 = function (node) {
  3027. if (isText$6(node)) {
  3028. node = node.parentNode;
  3029. }
  3030. return isElement$4(node) && node.hasAttribute('data-mce-caret');
  3031. };
  3032. var isCaretContainerInline = function (node) {
  3033. return isText$6(node) && isZwsp(node.data);
  3034. };
  3035. var isCaretContainer$2 = function (node) {
  3036. return isCaretContainerBlock$1(node) || isCaretContainerInline(node);
  3037. };
  3038. var hasContent = function (node) {
  3039. return node.firstChild !== node.lastChild || !isBr$5(node.firstChild);
  3040. };
  3041. var insertInline$1 = function (node, before) {
  3042. var doc = node.ownerDocument;
  3043. var textNode = doc.createTextNode(ZWSP$1);
  3044. var parentNode = node.parentNode;
  3045. if (!before) {
  3046. var sibling = node.nextSibling;
  3047. if (isText$6(sibling)) {
  3048. if (isCaretContainer$2(sibling)) {
  3049. return sibling;
  3050. }
  3051. if (startsWithCaretContainer$1(sibling)) {
  3052. sibling.splitText(1);
  3053. return sibling;
  3054. }
  3055. }
  3056. if (node.nextSibling) {
  3057. parentNode.insertBefore(textNode, node.nextSibling);
  3058. } else {
  3059. parentNode.appendChild(textNode);
  3060. }
  3061. } else {
  3062. var sibling = node.previousSibling;
  3063. if (isText$6(sibling)) {
  3064. if (isCaretContainer$2(sibling)) {
  3065. return sibling;
  3066. }
  3067. if (endsWithCaretContainer$1(sibling)) {
  3068. return sibling.splitText(sibling.data.length - 1);
  3069. }
  3070. }
  3071. parentNode.insertBefore(textNode, node);
  3072. }
  3073. return textNode;
  3074. };
  3075. var isBeforeInline = function (pos) {
  3076. var container = pos.container();
  3077. if (!isText$7(container)) {
  3078. return false;
  3079. }
  3080. return container.data.charAt(pos.offset()) === ZWSP$1 || pos.isAtStart() && isCaretContainerInline(container.previousSibling);
  3081. };
  3082. var isAfterInline = function (pos) {
  3083. var container = pos.container();
  3084. if (!isText$7(container)) {
  3085. return false;
  3086. }
  3087. return container.data.charAt(pos.offset() - 1) === ZWSP$1 || pos.isAtEnd() && isCaretContainerInline(container.nextSibling);
  3088. };
  3089. var createBogusBr = function () {
  3090. var br = document.createElement('br');
  3091. br.setAttribute('data-mce-bogus', '1');
  3092. return br;
  3093. };
  3094. var insertBlock$1 = function (blockName, node, before) {
  3095. var doc = node.ownerDocument;
  3096. var blockNode = doc.createElement(blockName);
  3097. blockNode.setAttribute('data-mce-caret', before ? 'before' : 'after');
  3098. blockNode.setAttribute('data-mce-bogus', 'all');
  3099. blockNode.appendChild(createBogusBr());
  3100. var parentNode = node.parentNode;
  3101. if (!before) {
  3102. if (node.nextSibling) {
  3103. parentNode.insertBefore(blockNode, node.nextSibling);
  3104. } else {
  3105. parentNode.appendChild(blockNode);
  3106. }
  3107. } else {
  3108. parentNode.insertBefore(blockNode, node);
  3109. }
  3110. return blockNode;
  3111. };
  3112. var startsWithCaretContainer$1 = function (node) {
  3113. return isText$6(node) && node.data[0] === ZWSP$1;
  3114. };
  3115. var endsWithCaretContainer$1 = function (node) {
  3116. return isText$6(node) && node.data[node.data.length - 1] === ZWSP$1;
  3117. };
  3118. var trimBogusBr = function (elm) {
  3119. var brs = elm.getElementsByTagName('br');
  3120. var lastBr = brs[brs.length - 1];
  3121. if (isBogus$2(lastBr)) {
  3122. lastBr.parentNode.removeChild(lastBr);
  3123. }
  3124. };
  3125. var showCaretContainerBlock = function (caretContainer) {
  3126. if (caretContainer && caretContainer.hasAttribute('data-mce-caret')) {
  3127. trimBogusBr(caretContainer);
  3128. caretContainer.removeAttribute('data-mce-caret');
  3129. caretContainer.removeAttribute('data-mce-bogus');
  3130. caretContainer.removeAttribute('style');
  3131. caretContainer.removeAttribute('_moz_abspos');
  3132. return caretContainer;
  3133. }
  3134. return null;
  3135. };
  3136. var isRangeInCaretContainerBlock = function (range) {
  3137. return isCaretContainerBlock$1(range.startContainer);
  3138. };
  3139. var isContentEditableTrue$3 = isContentEditableTrue$4;
  3140. var isContentEditableFalse$a = isContentEditableFalse$b;
  3141. var isBr$3 = isBr$5;
  3142. var isText$5 = isText$7;
  3143. var isInvalidTextElement = matchNodeNames([
  3144. 'script',
  3145. 'style',
  3146. 'textarea'
  3147. ]);
  3148. var isAtomicInline = matchNodeNames([
  3149. 'img',
  3150. 'input',
  3151. 'textarea',
  3152. 'hr',
  3153. 'iframe',
  3154. 'video',
  3155. 'audio',
  3156. 'object',
  3157. 'embed'
  3158. ]);
  3159. var isTable$1 = matchNodeNames(['table']);
  3160. var isCaretContainer$1 = isCaretContainer$2;
  3161. var isCaretCandidate$3 = function (node) {
  3162. if (isCaretContainer$1(node)) {
  3163. return false;
  3164. }
  3165. if (isText$5(node)) {
  3166. return !isInvalidTextElement(node.parentNode);
  3167. }
  3168. return isAtomicInline(node) || isBr$3(node) || isTable$1(node) || isNonUiContentEditableFalse(node);
  3169. };
  3170. var isUnselectable = function (node) {
  3171. return isElement$5(node) && node.getAttribute('unselectable') === 'true';
  3172. };
  3173. var isNonUiContentEditableFalse = function (node) {
  3174. return isUnselectable(node) === false && isContentEditableFalse$a(node);
  3175. };
  3176. var isInEditable = function (node, root) {
  3177. for (node = node.parentNode; node && node !== root; node = node.parentNode) {
  3178. if (isNonUiContentEditableFalse(node)) {
  3179. return false;
  3180. }
  3181. if (isContentEditableTrue$3(node)) {
  3182. return true;
  3183. }
  3184. }
  3185. return true;
  3186. };
  3187. var isAtomicContentEditableFalse = function (node) {
  3188. if (!isNonUiContentEditableFalse(node)) {
  3189. return false;
  3190. }
  3191. return foldl(from(node.getElementsByTagName('*')), function (result, elm) {
  3192. return result || isContentEditableTrue$3(elm);
  3193. }, false) !== true;
  3194. };
  3195. var isAtomic$1 = function (node) {
  3196. return isAtomicInline(node) || isAtomicContentEditableFalse(node);
  3197. };
  3198. var isEditableCaretCandidate$1 = function (node, root) {
  3199. return isCaretCandidate$3(node) && isInEditable(node, root);
  3200. };
  3201. var whiteSpaceRegExp$1 = /^[ \t\r\n]*$/;
  3202. var isWhitespaceText = function (text) {
  3203. return whiteSpaceRegExp$1.test(text);
  3204. };
  3205. var hasWhitespacePreserveParent = function (node, rootNode) {
  3206. var rootElement = SugarElement.fromDom(rootNode);
  3207. var startNode = SugarElement.fromDom(node);
  3208. return ancestor$1(startNode, 'pre,code', curry(eq, rootElement));
  3209. };
  3210. var isWhitespace = function (node, rootNode) {
  3211. return isText$7(node) && isWhitespaceText(node.data) && hasWhitespacePreserveParent(node, rootNode) === false;
  3212. };
  3213. var isNamedAnchor = function (node) {
  3214. return isElement$5(node) && node.nodeName === 'A' && !node.hasAttribute('href') && (node.hasAttribute('name') || node.hasAttribute('id'));
  3215. };
  3216. var isContent$1 = function (node, rootNode) {
  3217. return isCaretCandidate$3(node) && isWhitespace(node, rootNode) === false || isNamedAnchor(node) || isBookmark(node);
  3218. };
  3219. var isBookmark = hasAttribute('data-mce-bookmark');
  3220. var isBogus$1 = hasAttribute('data-mce-bogus');
  3221. var isBogusAll = hasAttributeValue('data-mce-bogus', 'all');
  3222. var isEmptyNode = function (targetNode, skipBogus) {
  3223. var brCount = 0;
  3224. if (isContent$1(targetNode, targetNode)) {
  3225. return false;
  3226. } else {
  3227. var node = targetNode.firstChild;
  3228. if (!node) {
  3229. return true;
  3230. }
  3231. var walker = new DomTreeWalker(node, targetNode);
  3232. do {
  3233. if (skipBogus) {
  3234. if (isBogusAll(node)) {
  3235. node = walker.next(true);
  3236. continue;
  3237. }
  3238. if (isBogus$1(node)) {
  3239. node = walker.next();
  3240. continue;
  3241. }
  3242. }
  3243. if (isBr$5(node)) {
  3244. brCount++;
  3245. node = walker.next();
  3246. continue;
  3247. }
  3248. if (isContent$1(node, targetNode)) {
  3249. return false;
  3250. }
  3251. node = walker.next();
  3252. } while (node);
  3253. return brCount <= 1;
  3254. }
  3255. };
  3256. var isEmpty$2 = function (elm, skipBogus) {
  3257. if (skipBogus === void 0) {
  3258. skipBogus = true;
  3259. }
  3260. return isEmptyNode(elm.dom, skipBogus);
  3261. };
  3262. var isSpan = function (node) {
  3263. return node.nodeName.toLowerCase() === 'span';
  3264. };
  3265. var isInlineContent = function (node, root) {
  3266. return isNonNullable(node) && (isContent$1(node, root) || isInline$1(SugarElement.fromDom(node)));
  3267. };
  3268. var surroundedByInlineContent = function (node, root) {
  3269. var prev = new DomTreeWalker(node, root).prev(false);
  3270. var next = new DomTreeWalker(node, root).next(false);
  3271. var prevIsInline = isUndefined(prev) || isInlineContent(prev, root);
  3272. var nextIsInline = isUndefined(next) || isInlineContent(next, root);
  3273. return prevIsInline && nextIsInline;
  3274. };
  3275. var isBookmarkNode$2 = function (node) {
  3276. return isSpan(node) && node.getAttribute('data-mce-type') === 'bookmark';
  3277. };
  3278. var isKeepTextNode = function (node, root) {
  3279. return isText$7(node) && node.data.length > 0 && surroundedByInlineContent(node, root);
  3280. };
  3281. var isKeepElement = function (node) {
  3282. return isElement$5(node) ? node.childNodes.length > 0 : false;
  3283. };
  3284. var isDocument = function (node) {
  3285. return isDocumentFragment(node) || isDocument$1(node);
  3286. };
  3287. var trimNode = function (dom, node, root) {
  3288. var rootNode = root || node;
  3289. if (isElement$5(node) && isBookmarkNode$2(node)) {
  3290. return node;
  3291. }
  3292. var children = node.childNodes;
  3293. for (var i = children.length - 1; i >= 0; i--) {
  3294. trimNode(dom, children[i], rootNode);
  3295. }
  3296. if (isElement$5(node)) {
  3297. var currentChildren = node.childNodes;
  3298. if (currentChildren.length === 1 && isBookmarkNode$2(currentChildren[0])) {
  3299. node.parentNode.insertBefore(currentChildren[0], node);
  3300. }
  3301. }
  3302. if (!isDocument(node) && !isContent$1(node, rootNode) && !isKeepElement(node) && !isKeepTextNode(node, rootNode)) {
  3303. dom.remove(node);
  3304. }
  3305. return node;
  3306. };
  3307. var makeMap$3 = Tools.makeMap;
  3308. var attrsCharsRegExp = /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  3309. var textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  3310. var rawCharsRegExp = /[<>&\"\']/g;
  3311. var entityRegExp = /&#([a-z0-9]+);?|&([a-z0-9]+);/gi;
  3312. var asciiMap = {
  3313. 128: '\u20AC',
  3314. 130: '\u201A',
  3315. 131: '\u0192',
  3316. 132: '\u201E',
  3317. 133: '\u2026',
  3318. 134: '\u2020',
  3319. 135: '\u2021',
  3320. 136: '\u02c6',
  3321. 137: '\u2030',
  3322. 138: '\u0160',
  3323. 139: '\u2039',
  3324. 140: '\u0152',
  3325. 142: '\u017d',
  3326. 145: '\u2018',
  3327. 146: '\u2019',
  3328. 147: '\u201C',
  3329. 148: '\u201D',
  3330. 149: '\u2022',
  3331. 150: '\u2013',
  3332. 151: '\u2014',
  3333. 152: '\u02DC',
  3334. 153: '\u2122',
  3335. 154: '\u0161',
  3336. 155: '\u203A',
  3337. 156: '\u0153',
  3338. 158: '\u017e',
  3339. 159: '\u0178'
  3340. };
  3341. var baseEntities = {
  3342. '"': '&quot;',
  3343. '\'': '&#39;',
  3344. '<': '&lt;',
  3345. '>': '&gt;',
  3346. '&': '&amp;',
  3347. '`': '&#96;'
  3348. };
  3349. var reverseEntities = {
  3350. '&lt;': '<',
  3351. '&gt;': '>',
  3352. '&amp;': '&',
  3353. '&quot;': '"',
  3354. '&apos;': '\''
  3355. };
  3356. var nativeDecode = function (text) {
  3357. var elm = SugarElement.fromTag('div').dom;
  3358. elm.innerHTML = text;
  3359. return elm.textContent || elm.innerText || text;
  3360. };
  3361. var buildEntitiesLookup = function (items, radix) {
  3362. var i, chr, entity;
  3363. var lookup = {};
  3364. if (items) {
  3365. items = items.split(',');
  3366. radix = radix || 10;
  3367. for (i = 0; i < items.length; i += 2) {
  3368. chr = String.fromCharCode(parseInt(items[i], radix));
  3369. if (!baseEntities[chr]) {
  3370. entity = '&' + items[i + 1] + ';';
  3371. lookup[chr] = entity;
  3372. lookup[entity] = chr;
  3373. }
  3374. }
  3375. return lookup;
  3376. }
  3377. };
  3378. 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);
  3379. var encodeRaw = function (text, attr) {
  3380. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3381. return baseEntities[chr] || chr;
  3382. });
  3383. };
  3384. var encodeAllRaw = function (text) {
  3385. return ('' + text).replace(rawCharsRegExp, function (chr) {
  3386. return baseEntities[chr] || chr;
  3387. });
  3388. };
  3389. var encodeNumeric = function (text, attr) {
  3390. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3391. if (chr.length > 1) {
  3392. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  3393. }
  3394. return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
  3395. });
  3396. };
  3397. var encodeNamed = function (text, attr, entities) {
  3398. entities = entities || namedEntities;
  3399. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3400. return baseEntities[chr] || entities[chr] || chr;
  3401. });
  3402. };
  3403. var getEncodeFunc = function (name, entities) {
  3404. var entitiesMap = buildEntitiesLookup(entities) || namedEntities;
  3405. var encodeNamedAndNumeric = function (text, attr) {
  3406. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3407. if (baseEntities[chr] !== undefined) {
  3408. return baseEntities[chr];
  3409. }
  3410. if (entitiesMap[chr] !== undefined) {
  3411. return entitiesMap[chr];
  3412. }
  3413. if (chr.length > 1) {
  3414. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  3415. }
  3416. return '&#' + chr.charCodeAt(0) + ';';
  3417. });
  3418. };
  3419. var encodeCustomNamed = function (text, attr) {
  3420. return encodeNamed(text, attr, entitiesMap);
  3421. };
  3422. var nameMap = makeMap$3(name.replace(/\+/g, ','));
  3423. if (nameMap.named && nameMap.numeric) {
  3424. return encodeNamedAndNumeric;
  3425. }
  3426. if (nameMap.named) {
  3427. if (entities) {
  3428. return encodeCustomNamed;
  3429. }
  3430. return encodeNamed;
  3431. }
  3432. if (nameMap.numeric) {
  3433. return encodeNumeric;
  3434. }
  3435. return encodeRaw;
  3436. };
  3437. var decode = function (text) {
  3438. return text.replace(entityRegExp, function (all, numeric) {
  3439. if (numeric) {
  3440. if (numeric.charAt(0).toLowerCase() === 'x') {
  3441. numeric = parseInt(numeric.substr(1), 16);
  3442. } else {
  3443. numeric = parseInt(numeric, 10);
  3444. }
  3445. if (numeric > 65535) {
  3446. numeric -= 65536;
  3447. return String.fromCharCode(55296 + (numeric >> 10), 56320 + (numeric & 1023));
  3448. }
  3449. return asciiMap[numeric] || String.fromCharCode(numeric);
  3450. }
  3451. return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
  3452. });
  3453. };
  3454. var Entities = {
  3455. encodeRaw: encodeRaw,
  3456. encodeAllRaw: encodeAllRaw,
  3457. encodeNumeric: encodeNumeric,
  3458. encodeNamed: encodeNamed,
  3459. getEncodeFunc: getEncodeFunc,
  3460. decode: decode
  3461. };
  3462. var mapCache = {}, dummyObj = {};
  3463. var makeMap$2 = Tools.makeMap, each$h = Tools.each, extend$5 = Tools.extend, explode$3 = Tools.explode, inArray$2 = Tools.inArray;
  3464. var split$1 = function (items, delim) {
  3465. items = Tools.trim(items);
  3466. return items ? items.split(delim || ' ') : [];
  3467. };
  3468. var compileSchema = function (type) {
  3469. var schema = {};
  3470. var globalAttributes, blockContent;
  3471. var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
  3472. var add = function (name, attributes, children) {
  3473. var ni, attributesOrder, element;
  3474. var arrayToMap = function (array, obj) {
  3475. var map = {};
  3476. var i, l;
  3477. for (i = 0, l = array.length; i < l; i++) {
  3478. map[array[i]] = obj || {};
  3479. }
  3480. return map;
  3481. };
  3482. children = children || [];
  3483. attributes = attributes || '';
  3484. if (typeof children === 'string') {
  3485. children = split$1(children);
  3486. }
  3487. var names = split$1(name);
  3488. ni = names.length;
  3489. while (ni--) {
  3490. attributesOrder = split$1([
  3491. globalAttributes,
  3492. attributes
  3493. ].join(' '));
  3494. element = {
  3495. attributes: arrayToMap(attributesOrder),
  3496. attributesOrder: attributesOrder,
  3497. children: arrayToMap(children, dummyObj)
  3498. };
  3499. schema[names[ni]] = element;
  3500. }
  3501. };
  3502. var addAttrs = function (name, attributes) {
  3503. var ni, schemaItem, i, l;
  3504. var names = split$1(name);
  3505. ni = names.length;
  3506. var attrs = split$1(attributes);
  3507. while (ni--) {
  3508. schemaItem = schema[names[ni]];
  3509. for (i = 0, l = attrs.length; i < l; i++) {
  3510. schemaItem.attributes[attrs[i]] = {};
  3511. schemaItem.attributesOrder.push(attrs[i]);
  3512. }
  3513. }
  3514. };
  3515. if (mapCache[type]) {
  3516. return mapCache[type];
  3517. }
  3518. globalAttributes = 'id accesskey class dir lang style tabindex title role';
  3519. blockContent = 'address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul';
  3520. 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';
  3521. if (type !== 'html4') {
  3522. globalAttributes += ' contenteditable contextmenu draggable dropzone ' + 'hidden spellcheck translate';
  3523. blockContent += ' article aside details dialog figure main header footer hgroup section nav';
  3524. phrasingContent += ' audio canvas command datalist mark meter output picture ' + 'progress time wbr video ruby bdi keygen';
  3525. }
  3526. if (type !== 'html5-strict') {
  3527. globalAttributes += ' xml:lang';
  3528. html4PhrasingContent = 'acronym applet basefont big font strike tt';
  3529. phrasingContent = [
  3530. phrasingContent,
  3531. html4PhrasingContent
  3532. ].join(' ');
  3533. each$h(split$1(html4PhrasingContent), function (name) {
  3534. add(name, '', phrasingContent);
  3535. });
  3536. html4BlockContent = 'center dir isindex noframes';
  3537. blockContent = [
  3538. blockContent,
  3539. html4BlockContent
  3540. ].join(' ');
  3541. flowContent = [
  3542. blockContent,
  3543. phrasingContent
  3544. ].join(' ');
  3545. each$h(split$1(html4BlockContent), function (name) {
  3546. add(name, '', flowContent);
  3547. });
  3548. }
  3549. flowContent = flowContent || [
  3550. blockContent,
  3551. phrasingContent
  3552. ].join(' ');
  3553. add('html', 'manifest', 'head body');
  3554. add('head', '', 'base command link meta noscript script style title');
  3555. add('title hr noscript br');
  3556. add('base', 'href target');
  3557. add('link', 'href rel media hreflang type sizes hreflang');
  3558. add('meta', 'name http-equiv content charset');
  3559. add('style', 'media type scoped');
  3560. add('script', 'src async defer type charset');
  3561. add('body', 'onafterprint onbeforeprint onbeforeunload onblur onerror onfocus ' + 'onhashchange onload onmessage onoffline ononline onpagehide onpageshow ' + 'onpopstate onresize onscroll onstorage onunload', flowContent);
  3562. add('address dt dd div caption', '', flowContent);
  3563. 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);
  3564. add('blockquote', 'cite', flowContent);
  3565. add('ol', 'reversed start type', 'li');
  3566. add('ul', '', 'li');
  3567. add('li', 'value', flowContent);
  3568. add('dl', '', 'dt dd');
  3569. add('a', 'href target rel media hreflang type', phrasingContent);
  3570. add('q', 'cite', phrasingContent);
  3571. add('ins del', 'cite datetime', flowContent);
  3572. add('img', 'src sizes srcset alt usemap ismap width height');
  3573. add('iframe', 'src name width height', flowContent);
  3574. add('embed', 'src type width height');
  3575. add('object', 'data type typemustmatch name usemap form width height', [
  3576. flowContent,
  3577. 'param'
  3578. ].join(' '));
  3579. add('param', 'name value');
  3580. add('map', 'name', [
  3581. flowContent,
  3582. 'area'
  3583. ].join(' '));
  3584. add('area', 'alt coords shape href target rel media hreflang type');
  3585. add('table', 'border', 'caption colgroup thead tfoot tbody tr' + (type === 'html4' ? ' col' : ''));
  3586. add('colgroup', 'span', 'col');
  3587. add('col', 'span');
  3588. add('tbody thead tfoot', '', 'tr');
  3589. add('tr', '', 'td th');
  3590. add('td', 'colspan rowspan headers', flowContent);
  3591. add('th', 'colspan rowspan headers scope abbr', flowContent);
  3592. add('form', 'accept-charset action autocomplete enctype method name novalidate target', flowContent);
  3593. add('fieldset', 'disabled form name', [
  3594. flowContent,
  3595. 'legend'
  3596. ].join(' '));
  3597. add('label', 'form for', phrasingContent);
  3598. 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');
  3599. add('button', 'disabled form formaction formenctype formmethod formnovalidate formtarget name type value', type === 'html4' ? flowContent : phrasingContent);
  3600. add('select', 'disabled form multiple name required size', 'option optgroup');
  3601. add('optgroup', 'disabled label', 'option');
  3602. add('option', 'disabled label selected value');
  3603. add('textarea', 'cols dirname disabled form maxlength name readonly required rows wrap');
  3604. add('menu', 'type label', [
  3605. flowContent,
  3606. 'li'
  3607. ].join(' '));
  3608. add('noscript', '', flowContent);
  3609. if (type !== 'html4') {
  3610. add('wbr');
  3611. add('ruby', '', [
  3612. phrasingContent,
  3613. 'rt rp'
  3614. ].join(' '));
  3615. add('figcaption', '', flowContent);
  3616. add('mark rt rp summary bdi', '', phrasingContent);
  3617. add('canvas', 'width height', flowContent);
  3618. add('video', 'src crossorigin poster preload autoplay mediagroup loop ' + 'muted controls width height buffered', [
  3619. flowContent,
  3620. 'track source'
  3621. ].join(' '));
  3622. add('audio', 'src crossorigin preload autoplay mediagroup loop muted controls ' + 'buffered volume', [
  3623. flowContent,
  3624. 'track source'
  3625. ].join(' '));
  3626. add('picture', '', 'img source');
  3627. add('source', 'src srcset type media sizes');
  3628. add('track', 'kind src srclang label default');
  3629. add('datalist', '', [
  3630. phrasingContent,
  3631. 'option'
  3632. ].join(' '));
  3633. add('article section nav aside main header footer', '', flowContent);
  3634. add('hgroup', '', 'h1 h2 h3 h4 h5 h6');
  3635. add('figure', '', [
  3636. flowContent,
  3637. 'figcaption'
  3638. ].join(' '));
  3639. add('time', 'datetime', phrasingContent);
  3640. add('dialog', 'open', flowContent);
  3641. add('command', 'type label icon disabled checked radiogroup command');
  3642. add('output', 'for form name', phrasingContent);
  3643. add('progress', 'value max', phrasingContent);
  3644. add('meter', 'value min max low high optimum', phrasingContent);
  3645. add('details', 'open', [
  3646. flowContent,
  3647. 'summary'
  3648. ].join(' '));
  3649. add('keygen', 'autofocus challenge disabled form keytype name');
  3650. }
  3651. if (type !== 'html5-strict') {
  3652. addAttrs('script', 'language xml:space');
  3653. addAttrs('style', 'xml:space');
  3654. addAttrs('object', 'declare classid code codebase codetype archive standby align border hspace vspace');
  3655. addAttrs('embed', 'align name hspace vspace');
  3656. addAttrs('param', 'valuetype type');
  3657. addAttrs('a', 'charset name rev shape coords');
  3658. addAttrs('br', 'clear');
  3659. addAttrs('applet', 'codebase archive code object alt name width height align hspace vspace');
  3660. addAttrs('img', 'name longdesc align border hspace vspace');
  3661. addAttrs('iframe', 'longdesc frameborder marginwidth marginheight scrolling align');
  3662. addAttrs('font basefont', 'size color face');
  3663. addAttrs('input', 'usemap align');
  3664. addAttrs('select');
  3665. addAttrs('textarea');
  3666. addAttrs('h1 h2 h3 h4 h5 h6 div p legend caption', 'align');
  3667. addAttrs('ul', 'type compact');
  3668. addAttrs('li', 'type');
  3669. addAttrs('ol dl menu dir', 'compact');
  3670. addAttrs('pre', 'width xml:space');
  3671. addAttrs('hr', 'align noshade size width');
  3672. addAttrs('isindex', 'prompt');
  3673. addAttrs('table', 'summary width frame rules cellspacing cellpadding align bgcolor');
  3674. addAttrs('col', 'width align char charoff valign');
  3675. addAttrs('colgroup', 'width align char charoff valign');
  3676. addAttrs('thead', 'align char charoff valign');
  3677. addAttrs('tr', 'align char charoff valign bgcolor');
  3678. addAttrs('th', 'axis align char charoff valign nowrap bgcolor width height');
  3679. addAttrs('form', 'accept');
  3680. addAttrs('td', 'abbr axis scope align char charoff valign nowrap bgcolor width height');
  3681. addAttrs('tfoot', 'align char charoff valign');
  3682. addAttrs('tbody', 'align char charoff valign');
  3683. addAttrs('area', 'nohref');
  3684. addAttrs('body', 'background bgcolor text link vlink alink');
  3685. }
  3686. if (type !== 'html4') {
  3687. addAttrs('input button select textarea', 'autofocus');
  3688. addAttrs('input textarea', 'placeholder');
  3689. addAttrs('a', 'download');
  3690. addAttrs('link script img', 'crossorigin');
  3691. addAttrs('img', 'loading');
  3692. addAttrs('iframe', 'sandbox seamless allowfullscreen loading');
  3693. }
  3694. each$h(split$1('a form meter progress dfn'), function (name) {
  3695. if (schema[name]) {
  3696. delete schema[name].children[name];
  3697. }
  3698. });
  3699. delete schema.caption.children.table;
  3700. delete schema.script;
  3701. mapCache[type] = schema;
  3702. return schema;
  3703. };
  3704. var compileElementMap = function (value, mode) {
  3705. var styles;
  3706. if (value) {
  3707. styles = {};
  3708. if (typeof value === 'string') {
  3709. value = { '*': value };
  3710. }
  3711. each$h(value, function (value, key) {
  3712. styles[key] = styles[key.toUpperCase()] = mode === 'map' ? makeMap$2(value, /[, ]/) : explode$3(value, /[, ]/);
  3713. });
  3714. }
  3715. return styles;
  3716. };
  3717. var Schema = function (settings) {
  3718. var elements = {};
  3719. var children = {};
  3720. var patternElements = [];
  3721. var customElementsMap = {}, specialElements = {};
  3722. var createLookupTable = function (option, defaultValue, extendWith) {
  3723. var value = settings[option];
  3724. if (!value) {
  3725. value = mapCache[option];
  3726. if (!value) {
  3727. value = makeMap$2(defaultValue, ' ', makeMap$2(defaultValue.toUpperCase(), ' '));
  3728. value = extend$5(value, extendWith);
  3729. mapCache[option] = value;
  3730. }
  3731. } else {
  3732. value = makeMap$2(value, /[, ]/, makeMap$2(value.toUpperCase(), /[, ]/));
  3733. }
  3734. return value;
  3735. };
  3736. settings = settings || {};
  3737. var schemaItems = compileSchema(settings.schema);
  3738. if (settings.verify_html === false) {
  3739. settings.valid_elements = '*[*]';
  3740. }
  3741. var validStyles = compileElementMap(settings.valid_styles);
  3742. var invalidStyles = compileElementMap(settings.invalid_styles, 'map');
  3743. var validClasses = compileElementMap(settings.valid_classes, 'map');
  3744. var whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object code');
  3745. var selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
  3746. var shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link ' + 'meta param embed source wbr track');
  3747. var boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + 'noshade nowrap readonly selected autoplay loop controls');
  3748. var nonEmptyOrMoveCaretBeforeOnEnter = 'td th iframe video audio object script code';
  3749. var nonEmptyElementsMap = createLookupTable('non_empty_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' pre', shortEndedElementsMap);
  3750. var moveCaretBeforeOnEnterElementsMap = createLookupTable('move_caret_before_on_enter_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' table', shortEndedElementsMap);
  3751. 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');
  3752. 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);
  3753. var textInlineElementsMap = createLookupTable('text_inline_elements', 'span strong b em i font strike u var cite ' + 'dfn code mark q sup sub samp');
  3754. each$h((settings.special || 'script noscript iframe noframes noembed title style textarea xmp').split(' '), function (name) {
  3755. specialElements[name] = new RegExp('</' + name + '[^>]*>', 'gi');
  3756. });
  3757. var patternToRegExp = function (str) {
  3758. return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
  3759. };
  3760. var addValidElements = function (validElements) {
  3761. var ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, value;
  3762. var elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/, attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/;
  3763. if (validElements) {
  3764. var validElementsArr = split$1(validElements, ',');
  3765. if (elements['@']) {
  3766. globalAttributes = elements['@'].attributes;
  3767. globalAttributesOrder = elements['@'].attributesOrder;
  3768. }
  3769. for (ei = 0, el = validElementsArr.length; ei < el; ei++) {
  3770. matches = elementRuleRegExp.exec(validElementsArr[ei]);
  3771. if (matches) {
  3772. prefix = matches[1];
  3773. elementName = matches[2];
  3774. outputName = matches[3];
  3775. attrData = matches[5];
  3776. attributes = {};
  3777. attributesOrder = [];
  3778. element = {
  3779. attributes: attributes,
  3780. attributesOrder: attributesOrder
  3781. };
  3782. if (prefix === '#') {
  3783. element.paddEmpty = true;
  3784. }
  3785. if (prefix === '-') {
  3786. element.removeEmpty = true;
  3787. }
  3788. if (matches[4] === '!') {
  3789. element.removeEmptyAttrs = true;
  3790. }
  3791. if (globalAttributes) {
  3792. each$j(globalAttributes, function (value, key) {
  3793. attributes[key] = value;
  3794. });
  3795. attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
  3796. }
  3797. if (attrData) {
  3798. attrData = split$1(attrData, '|');
  3799. for (ai = 0, al = attrData.length; ai < al; ai++) {
  3800. matches = attrRuleRegExp.exec(attrData[ai]);
  3801. if (matches) {
  3802. attr = {};
  3803. attrType = matches[1];
  3804. attrName = matches[2].replace(/[\\:]:/g, ':');
  3805. prefix = matches[3];
  3806. value = matches[4];
  3807. if (attrType === '!') {
  3808. element.attributesRequired = element.attributesRequired || [];
  3809. element.attributesRequired.push(attrName);
  3810. attr.required = true;
  3811. }
  3812. if (attrType === '-') {
  3813. delete attributes[attrName];
  3814. attributesOrder.splice(inArray$2(attributesOrder, attrName), 1);
  3815. continue;
  3816. }
  3817. if (prefix) {
  3818. if (prefix === '=') {
  3819. element.attributesDefault = element.attributesDefault || [];
  3820. element.attributesDefault.push({
  3821. name: attrName,
  3822. value: value
  3823. });
  3824. attr.defaultValue = value;
  3825. }
  3826. if (prefix === ':') {
  3827. element.attributesForced = element.attributesForced || [];
  3828. element.attributesForced.push({
  3829. name: attrName,
  3830. value: value
  3831. });
  3832. attr.forcedValue = value;
  3833. }
  3834. if (prefix === '<') {
  3835. attr.validValues = makeMap$2(value, '?');
  3836. }
  3837. }
  3838. if (hasPatternsRegExp.test(attrName)) {
  3839. element.attributePatterns = element.attributePatterns || [];
  3840. attr.pattern = patternToRegExp(attrName);
  3841. element.attributePatterns.push(attr);
  3842. } else {
  3843. if (!attributes[attrName]) {
  3844. attributesOrder.push(attrName);
  3845. }
  3846. attributes[attrName] = attr;
  3847. }
  3848. }
  3849. }
  3850. }
  3851. if (!globalAttributes && elementName === '@') {
  3852. globalAttributes = attributes;
  3853. globalAttributesOrder = attributesOrder;
  3854. }
  3855. if (outputName) {
  3856. element.outputName = elementName;
  3857. elements[outputName] = element;
  3858. }
  3859. if (hasPatternsRegExp.test(elementName)) {
  3860. element.pattern = patternToRegExp(elementName);
  3861. patternElements.push(element);
  3862. } else {
  3863. elements[elementName] = element;
  3864. }
  3865. }
  3866. }
  3867. }
  3868. };
  3869. var setValidElements = function (validElements) {
  3870. elements = {};
  3871. patternElements = [];
  3872. addValidElements(validElements);
  3873. each$h(schemaItems, function (element, name) {
  3874. children[name] = element.children;
  3875. });
  3876. };
  3877. var addCustomElements = function (customElements) {
  3878. var customElementRegExp = /^(~)?(.+)$/;
  3879. if (customElements) {
  3880. mapCache.text_block_elements = mapCache.block_elements = null;
  3881. each$h(split$1(customElements, ','), function (rule) {
  3882. var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2];
  3883. children[name] = children[cloneName];
  3884. customElementsMap[name] = cloneName;
  3885. if (!inline) {
  3886. blockElementsMap[name.toUpperCase()] = {};
  3887. blockElementsMap[name] = {};
  3888. }
  3889. if (!elements[name]) {
  3890. var customRule = elements[cloneName];
  3891. customRule = extend$5({}, customRule);
  3892. delete customRule.removeEmptyAttrs;
  3893. delete customRule.removeEmpty;
  3894. elements[name] = customRule;
  3895. }
  3896. each$h(children, function (element, elmName) {
  3897. if (element[cloneName]) {
  3898. children[elmName] = element = extend$5({}, children[elmName]);
  3899. element[name] = element[cloneName];
  3900. }
  3901. });
  3902. });
  3903. }
  3904. };
  3905. var addValidChildren = function (validChildren) {
  3906. 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]+)\[([^\]]+)]$/;
  3907. mapCache[settings.schema] = null;
  3908. if (validChildren) {
  3909. each$h(split$1(validChildren, ','), function (rule) {
  3910. var matches = childRuleRegExp.exec(rule);
  3911. var parent, prefix;
  3912. if (matches) {
  3913. prefix = matches[1];
  3914. if (prefix) {
  3915. parent = children[matches[2]];
  3916. } else {
  3917. parent = children[matches[2]] = { '#comment': {} };
  3918. }
  3919. parent = children[matches[2]];
  3920. each$h(split$1(matches[3], '|'), function (child) {
  3921. if (prefix === '-') {
  3922. delete parent[child];
  3923. } else {
  3924. parent[child] = {};
  3925. }
  3926. });
  3927. }
  3928. });
  3929. }
  3930. };
  3931. var getElementRule = function (name) {
  3932. var element = elements[name], i;
  3933. if (element) {
  3934. return element;
  3935. }
  3936. i = patternElements.length;
  3937. while (i--) {
  3938. element = patternElements[i];
  3939. if (element.pattern.test(name)) {
  3940. return element;
  3941. }
  3942. }
  3943. };
  3944. if (!settings.valid_elements) {
  3945. each$h(schemaItems, function (element, name) {
  3946. elements[name] = {
  3947. attributes: element.attributes,
  3948. attributesOrder: element.attributesOrder
  3949. };
  3950. children[name] = element.children;
  3951. });
  3952. if (settings.schema !== 'html5') {
  3953. each$h(split$1('strong/b em/i'), function (item) {
  3954. var items = split$1(item, '/');
  3955. elements[items[1]].outputName = items[0];
  3956. });
  3957. }
  3958. each$h(split$1('ol ul sub sup blockquote span font a table tbody strong em b i'), function (name) {
  3959. if (elements[name]) {
  3960. elements[name].removeEmpty = true;
  3961. }
  3962. });
  3963. each$h(split$1('p h1 h2 h3 h4 h5 h6 th td pre div address caption li'), function (name) {
  3964. elements[name].paddEmpty = true;
  3965. });
  3966. each$h(split$1('span'), function (name) {
  3967. elements[name].removeEmptyAttrs = true;
  3968. });
  3969. } else {
  3970. setValidElements(settings.valid_elements);
  3971. }
  3972. addCustomElements(settings.custom_elements);
  3973. addValidChildren(settings.valid_children);
  3974. addValidElements(settings.extended_valid_elements);
  3975. addValidChildren('+ol[ul|ol],+ul[ul|ol]');
  3976. each$h({
  3977. dd: 'dl',
  3978. dt: 'dl',
  3979. li: 'ul ol',
  3980. td: 'tr',
  3981. th: 'tr',
  3982. tr: 'tbody thead tfoot',
  3983. tbody: 'table',
  3984. thead: 'table',
  3985. tfoot: 'table',
  3986. legend: 'fieldset',
  3987. area: 'map',
  3988. param: 'video audio object'
  3989. }, function (parents, item) {
  3990. if (elements[item]) {
  3991. elements[item].parentsRequired = split$1(parents);
  3992. }
  3993. });
  3994. if (settings.invalid_elements) {
  3995. each$h(explode$3(settings.invalid_elements), function (item) {
  3996. if (elements[item]) {
  3997. delete elements[item];
  3998. }
  3999. });
  4000. }
  4001. if (!getElementRule('span')) {
  4002. addValidElements('span[!data-mce-type|*]');
  4003. }
  4004. var getValidStyles = constant(validStyles);
  4005. var getInvalidStyles = constant(invalidStyles);
  4006. var getValidClasses = constant(validClasses);
  4007. var getBoolAttrs = constant(boolAttrMap);
  4008. var getBlockElements = constant(blockElementsMap);
  4009. var getTextBlockElements = constant(textBlockElementsMap);
  4010. var getTextInlineElements = constant(textInlineElementsMap);
  4011. var getShortEndedElements = constant(shortEndedElementsMap);
  4012. var getSelfClosingElements = constant(selfClosingElementsMap);
  4013. var getNonEmptyElements = constant(nonEmptyElementsMap);
  4014. var getMoveCaretBeforeOnEnterElements = constant(moveCaretBeforeOnEnterElementsMap);
  4015. var getWhiteSpaceElements = constant(whiteSpaceElementsMap);
  4016. var getSpecialElements = constant(specialElements);
  4017. var isValidChild = function (name, child) {
  4018. var parent = children[name.toLowerCase()];
  4019. return !!(parent && parent[child.toLowerCase()]);
  4020. };
  4021. var isValid = function (name, attr) {
  4022. var attrPatterns, i;
  4023. var rule = getElementRule(name);
  4024. if (rule) {
  4025. if (attr) {
  4026. if (rule.attributes[attr]) {
  4027. return true;
  4028. }
  4029. attrPatterns = rule.attributePatterns;
  4030. if (attrPatterns) {
  4031. i = attrPatterns.length;
  4032. while (i--) {
  4033. if (attrPatterns[i].pattern.test(name)) {
  4034. return true;
  4035. }
  4036. }
  4037. }
  4038. } else {
  4039. return true;
  4040. }
  4041. }
  4042. return false;
  4043. };
  4044. var getCustomElements = constant(customElementsMap);
  4045. return {
  4046. children: children,
  4047. elements: elements,
  4048. getValidStyles: getValidStyles,
  4049. getValidClasses: getValidClasses,
  4050. getBlockElements: getBlockElements,
  4051. getInvalidStyles: getInvalidStyles,
  4052. getShortEndedElements: getShortEndedElements,
  4053. getTextBlockElements: getTextBlockElements,
  4054. getTextInlineElements: getTextInlineElements,
  4055. getBoolAttrs: getBoolAttrs,
  4056. getElementRule: getElementRule,
  4057. getSelfClosingElements: getSelfClosingElements,
  4058. getNonEmptyElements: getNonEmptyElements,
  4059. getMoveCaretBeforeOnEnterElements: getMoveCaretBeforeOnEnterElements,
  4060. getWhiteSpaceElements: getWhiteSpaceElements,
  4061. getSpecialElements: getSpecialElements,
  4062. isValidChild: isValidChild,
  4063. isValid: isValid,
  4064. getCustomElements: getCustomElements,
  4065. addValidElements: addValidElements,
  4066. setValidElements: setValidElements,
  4067. addCustomElements: addCustomElements,
  4068. addValidChildren: addValidChildren
  4069. };
  4070. };
  4071. var toHex = function (match, r, g, b) {
  4072. var hex = function (val) {
  4073. val = parseInt(val, 10).toString(16);
  4074. return val.length > 1 ? val : '0' + val;
  4075. };
  4076. return '#' + hex(r) + hex(g) + hex(b);
  4077. };
  4078. var Styles = function (settings, schema) {
  4079. var _this = this;
  4080. var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
  4081. var urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
  4082. var styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
  4083. var trimRightRegExp = /\s+$/;
  4084. var i;
  4085. var encodingLookup = {};
  4086. var validStyles;
  4087. var invalidStyles;
  4088. var invisibleChar = zeroWidth;
  4089. settings = settings || {};
  4090. if (schema) {
  4091. validStyles = schema.getValidStyles();
  4092. invalidStyles = schema.getInvalidStyles();
  4093. }
  4094. var encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' ');
  4095. for (i = 0; i < encodingItems.length; i++) {
  4096. encodingLookup[encodingItems[i]] = invisibleChar + i;
  4097. encodingLookup[invisibleChar + i] = encodingItems[i];
  4098. }
  4099. return {
  4100. toHex: function (color) {
  4101. return color.replace(rgbRegExp, toHex);
  4102. },
  4103. parse: function (css) {
  4104. var styles = {};
  4105. var matches, name, value, isEncoded;
  4106. var urlConverter = settings.url_converter;
  4107. var urlConverterScope = settings.url_converter_scope || _this;
  4108. var compress = function (prefix, suffix, noJoin) {
  4109. var top = styles[prefix + '-top' + suffix];
  4110. if (!top) {
  4111. return;
  4112. }
  4113. var right = styles[prefix + '-right' + suffix];
  4114. if (!right) {
  4115. return;
  4116. }
  4117. var bottom = styles[prefix + '-bottom' + suffix];
  4118. if (!bottom) {
  4119. return;
  4120. }
  4121. var left = styles[prefix + '-left' + suffix];
  4122. if (!left) {
  4123. return;
  4124. }
  4125. var box = [
  4126. top,
  4127. right,
  4128. bottom,
  4129. left
  4130. ];
  4131. i = box.length - 1;
  4132. while (i--) {
  4133. if (box[i] !== box[i + 1]) {
  4134. break;
  4135. }
  4136. }
  4137. if (i > -1 && noJoin) {
  4138. return;
  4139. }
  4140. styles[prefix + suffix] = i === -1 ? box[0] : box.join(' ');
  4141. delete styles[prefix + '-top' + suffix];
  4142. delete styles[prefix + '-right' + suffix];
  4143. delete styles[prefix + '-bottom' + suffix];
  4144. delete styles[prefix + '-left' + suffix];
  4145. };
  4146. var canCompress = function (key) {
  4147. var value = styles[key], i;
  4148. if (!value) {
  4149. return;
  4150. }
  4151. value = value.split(' ');
  4152. i = value.length;
  4153. while (i--) {
  4154. if (value[i] !== value[0]) {
  4155. return false;
  4156. }
  4157. }
  4158. styles[key] = value[0];
  4159. return true;
  4160. };
  4161. var compress2 = function (target, a, b, c) {
  4162. if (!canCompress(a)) {
  4163. return;
  4164. }
  4165. if (!canCompress(b)) {
  4166. return;
  4167. }
  4168. if (!canCompress(c)) {
  4169. return;
  4170. }
  4171. styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
  4172. delete styles[a];
  4173. delete styles[b];
  4174. delete styles[c];
  4175. };
  4176. var encode = function (str) {
  4177. isEncoded = true;
  4178. return encodingLookup[str];
  4179. };
  4180. var decode = function (str, keepSlashes) {
  4181. if (isEncoded) {
  4182. str = str.replace(/\uFEFF[0-9]/g, function (str) {
  4183. return encodingLookup[str];
  4184. });
  4185. }
  4186. if (!keepSlashes) {
  4187. str = str.replace(/\\([\'\";:])/g, '$1');
  4188. }
  4189. return str;
  4190. };
  4191. var decodeSingleHexSequence = function (escSeq) {
  4192. return String.fromCharCode(parseInt(escSeq.slice(1), 16));
  4193. };
  4194. var decodeHexSequences = function (value) {
  4195. return value.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
  4196. };
  4197. var processUrl = function (match, url, url2, url3, str, str2) {
  4198. str = str || str2;
  4199. if (str) {
  4200. str = decode(str);
  4201. return '\'' + str.replace(/\'/g, '\\\'') + '\'';
  4202. }
  4203. url = decode(url || url2 || url3);
  4204. if (!settings.allow_script_urls) {
  4205. var scriptUrl = url.replace(/[\s\r\n]+/g, '');
  4206. if (/(java|vb)script:/i.test(scriptUrl)) {
  4207. return '';
  4208. }
  4209. if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
  4210. return '';
  4211. }
  4212. }
  4213. if (urlConverter) {
  4214. url = urlConverter.call(urlConverterScope, url, 'style');
  4215. }
  4216. return 'url(\'' + url.replace(/\'/g, '\\\'') + '\')';
  4217. };
  4218. if (css) {
  4219. css = css.replace(/[\u0000-\u001F]/g, '');
  4220. css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function (str) {
  4221. return str.replace(/[;:]/g, encode);
  4222. });
  4223. while (matches = styleRegExp.exec(css)) {
  4224. styleRegExp.lastIndex = matches.index + matches[0].length;
  4225. name = matches[1].replace(trimRightRegExp, '').toLowerCase();
  4226. value = matches[2].replace(trimRightRegExp, '');
  4227. if (name && value) {
  4228. name = decodeHexSequences(name);
  4229. value = decodeHexSequences(value);
  4230. if (name.indexOf(invisibleChar) !== -1 || name.indexOf('"') !== -1) {
  4231. continue;
  4232. }
  4233. if (!settings.allow_script_urls && (name === 'behavior' || /expression\s*\(|\/\*|\*\//.test(value))) {
  4234. continue;
  4235. }
  4236. if (name === 'font-weight' && value === '700') {
  4237. value = 'bold';
  4238. } else if (name === 'color' || name === 'background-color') {
  4239. value = value.toLowerCase();
  4240. }
  4241. value = value.replace(rgbRegExp, toHex);
  4242. value = value.replace(urlOrStrRegExp, processUrl);
  4243. styles[name] = isEncoded ? decode(value, true) : value;
  4244. }
  4245. }
  4246. compress('border', '', true);
  4247. compress('border', '-width');
  4248. compress('border', '-color');
  4249. compress('border', '-style');
  4250. compress('padding', '');
  4251. compress('margin', '');
  4252. compress2('border', 'border-width', 'border-style', 'border-color');
  4253. if (styles.border === 'medium none') {
  4254. delete styles.border;
  4255. }
  4256. if (styles['border-image'] === 'none') {
  4257. delete styles['border-image'];
  4258. }
  4259. }
  4260. return styles;
  4261. },
  4262. serialize: function (styles, elementName) {
  4263. var css = '';
  4264. var serializeStyles = function (name) {
  4265. var value;
  4266. var styleList = validStyles[name];
  4267. if (styleList) {
  4268. for (var i_1 = 0, l = styleList.length; i_1 < l; i_1++) {
  4269. name = styleList[i_1];
  4270. value = styles[name];
  4271. if (value) {
  4272. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4273. }
  4274. }
  4275. }
  4276. };
  4277. var isValid = function (name, elementName) {
  4278. var styleMap = invalidStyles['*'];
  4279. if (styleMap && styleMap[name]) {
  4280. return false;
  4281. }
  4282. styleMap = invalidStyles[elementName];
  4283. return !(styleMap && styleMap[name]);
  4284. };
  4285. if (elementName && validStyles) {
  4286. serializeStyles('*');
  4287. serializeStyles(elementName);
  4288. } else {
  4289. each$j(styles, function (value, name) {
  4290. if (value && (!invalidStyles || isValid(name, elementName))) {
  4291. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4292. }
  4293. });
  4294. }
  4295. return css;
  4296. }
  4297. };
  4298. };
  4299. var deprecated = {
  4300. keyLocation: true,
  4301. layerX: true,
  4302. layerY: true,
  4303. returnValue: true,
  4304. webkitMovementX: true,
  4305. webkitMovementY: true,
  4306. keyIdentifier: true,
  4307. mozPressure: true
  4308. };
  4309. var isNativeEvent = function (event) {
  4310. return event instanceof Event || isFunction(event.initEvent);
  4311. };
  4312. var hasIsDefaultPrevented = function (event) {
  4313. return event.isDefaultPrevented === always || event.isDefaultPrevented === never;
  4314. };
  4315. var needsNormalizing = function (event) {
  4316. return isNullable(event.preventDefault) || isNativeEvent(event);
  4317. };
  4318. var clone$2 = function (originalEvent, data) {
  4319. var event = data !== null && data !== void 0 ? data : {};
  4320. for (var name_1 in originalEvent) {
  4321. if (!has$2(deprecated, name_1)) {
  4322. event[name_1] = originalEvent[name_1];
  4323. }
  4324. }
  4325. if (isNonNullable(event.composedPath)) {
  4326. event.composedPath = function () {
  4327. return originalEvent.composedPath();
  4328. };
  4329. }
  4330. return event;
  4331. };
  4332. var normalize$3 = function (type, originalEvent, fallbackTarget, data) {
  4333. var _a;
  4334. var event = clone$2(originalEvent, data);
  4335. event.type = type;
  4336. if (isNullable(event.target)) {
  4337. event.target = (_a = event.srcElement) !== null && _a !== void 0 ? _a : fallbackTarget;
  4338. }
  4339. if (needsNormalizing(originalEvent)) {
  4340. event.preventDefault = function () {
  4341. event.defaultPrevented = true;
  4342. event.isDefaultPrevented = always;
  4343. if (isFunction(originalEvent.preventDefault)) {
  4344. originalEvent.preventDefault();
  4345. } else if (isNativeEvent(originalEvent)) {
  4346. originalEvent.returnValue = false;
  4347. }
  4348. };
  4349. event.stopPropagation = function () {
  4350. event.cancelBubble = true;
  4351. event.isPropagationStopped = always;
  4352. if (isFunction(originalEvent.stopPropagation)) {
  4353. originalEvent.stopPropagation();
  4354. } else if (isNativeEvent(originalEvent)) {
  4355. originalEvent.cancelBubble = true;
  4356. }
  4357. };
  4358. event.stopImmediatePropagation = function () {
  4359. event.isImmediatePropagationStopped = always;
  4360. event.stopPropagation();
  4361. };
  4362. if (!hasIsDefaultPrevented(event)) {
  4363. event.isDefaultPrevented = event.defaultPrevented === true ? always : never;
  4364. event.isPropagationStopped = event.cancelBubble === true ? always : never;
  4365. event.isImmediatePropagationStopped = never;
  4366. }
  4367. }
  4368. return event;
  4369. };
  4370. var eventExpandoPrefix = 'mce-data-';
  4371. var mouseEventRe = /^(?:mouse|contextmenu)|click/;
  4372. var addEvent = function (target, name, callback, capture) {
  4373. if (target.addEventListener) {
  4374. target.addEventListener(name, callback, capture || false);
  4375. } else if (target.attachEvent) {
  4376. target.attachEvent('on' + name, callback);
  4377. }
  4378. };
  4379. var removeEvent = function (target, name, callback, capture) {
  4380. if (target.removeEventListener) {
  4381. target.removeEventListener(name, callback, capture || false);
  4382. } else if (target.detachEvent) {
  4383. target.detachEvent('on' + name, callback);
  4384. }
  4385. };
  4386. var isMouseEvent = function (event) {
  4387. return isNonNullable(event) && mouseEventRe.test(event.type);
  4388. };
  4389. var fix = function (originalEvent, data) {
  4390. var event = normalize$3(originalEvent.type, originalEvent, document, data);
  4391. if (isMouseEvent(originalEvent) && isUndefined(originalEvent.pageX) && !isUndefined(originalEvent.clientX)) {
  4392. var eventDoc = event.target.ownerDocument || document;
  4393. var doc = eventDoc.documentElement;
  4394. var body = eventDoc.body;
  4395. var mouseEvent = event;
  4396. mouseEvent.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  4397. mouseEvent.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  4398. }
  4399. if (isUndefined(event.metaKey)) {
  4400. event.metaKey = false;
  4401. }
  4402. return event;
  4403. };
  4404. var bindOnReady = function (win, callback, eventUtils) {
  4405. var doc = win.document, event = { type: 'ready' };
  4406. if (eventUtils.domLoaded) {
  4407. callback(event);
  4408. return;
  4409. }
  4410. var isDocReady = function () {
  4411. return doc.readyState === 'complete' || doc.readyState === 'interactive' && doc.body;
  4412. };
  4413. var readyHandler = function () {
  4414. removeEvent(win, 'DOMContentLoaded', readyHandler);
  4415. removeEvent(win, 'load', readyHandler);
  4416. if (!eventUtils.domLoaded) {
  4417. eventUtils.domLoaded = true;
  4418. callback(event);
  4419. }
  4420. win = null;
  4421. };
  4422. if (isDocReady()) {
  4423. readyHandler();
  4424. } else {
  4425. addEvent(win, 'DOMContentLoaded', readyHandler);
  4426. }
  4427. if (!eventUtils.domLoaded) {
  4428. addEvent(win, 'load', readyHandler);
  4429. }
  4430. };
  4431. var EventUtils = function () {
  4432. function EventUtils() {
  4433. this.domLoaded = false;
  4434. this.events = {};
  4435. this.count = 1;
  4436. this.expando = eventExpandoPrefix + (+new Date()).toString(32);
  4437. this.hasMouseEnterLeave = 'onmouseenter' in document.documentElement;
  4438. this.hasFocusIn = 'onfocusin' in document.documentElement;
  4439. this.count = 1;
  4440. }
  4441. EventUtils.prototype.bind = function (target, names, callback, scope) {
  4442. var self = this;
  4443. var id, callbackList, i, name, fakeName, nativeHandler, capture;
  4444. var win = window;
  4445. var defaultNativeHandler = function (evt) {
  4446. self.executeHandlers(fix(evt || win.event), id);
  4447. };
  4448. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4449. return;
  4450. }
  4451. if (!target[self.expando]) {
  4452. id = self.count++;
  4453. target[self.expando] = id;
  4454. self.events[id] = {};
  4455. } else {
  4456. id = target[self.expando];
  4457. }
  4458. scope = scope || target;
  4459. var namesList = names.split(' ');
  4460. i = namesList.length;
  4461. while (i--) {
  4462. name = namesList[i];
  4463. nativeHandler = defaultNativeHandler;
  4464. fakeName = capture = false;
  4465. if (name === 'DOMContentLoaded') {
  4466. name = 'ready';
  4467. }
  4468. if (self.domLoaded && name === 'ready' && target.readyState === 'complete') {
  4469. callback.call(scope, fix({ type: name }));
  4470. continue;
  4471. }
  4472. if (!self.hasMouseEnterLeave) {
  4473. fakeName = self.mouseEnterLeave[name];
  4474. if (fakeName) {
  4475. nativeHandler = function (evt) {
  4476. var current = evt.currentTarget;
  4477. var related = evt.relatedTarget;
  4478. if (related && current.contains) {
  4479. related = current.contains(related);
  4480. } else {
  4481. while (related && related !== current) {
  4482. related = related.parentNode;
  4483. }
  4484. }
  4485. if (!related) {
  4486. evt = fix(evt || win.event);
  4487. evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
  4488. evt.target = current;
  4489. self.executeHandlers(evt, id);
  4490. }
  4491. };
  4492. }
  4493. }
  4494. if (!self.hasFocusIn && (name === 'focusin' || name === 'focusout')) {
  4495. capture = true;
  4496. fakeName = name === 'focusin' ? 'focus' : 'blur';
  4497. nativeHandler = function (evt) {
  4498. evt = fix(evt || win.event);
  4499. evt.type = evt.type === 'focus' ? 'focusin' : 'focusout';
  4500. self.executeHandlers(evt, id);
  4501. };
  4502. }
  4503. callbackList = self.events[id][name];
  4504. if (!callbackList) {
  4505. self.events[id][name] = callbackList = [{
  4506. func: callback,
  4507. scope: scope
  4508. }];
  4509. callbackList.fakeName = fakeName;
  4510. callbackList.capture = capture;
  4511. callbackList.nativeHandler = nativeHandler;
  4512. if (name === 'ready') {
  4513. bindOnReady(target, nativeHandler, self);
  4514. } else {
  4515. addEvent(target, fakeName || name, nativeHandler, capture);
  4516. }
  4517. } else {
  4518. if (name === 'ready' && self.domLoaded) {
  4519. callback(fix({ type: name }));
  4520. } else {
  4521. callbackList.push({
  4522. func: callback,
  4523. scope: scope
  4524. });
  4525. }
  4526. }
  4527. }
  4528. target = callbackList = null;
  4529. return callback;
  4530. };
  4531. EventUtils.prototype.unbind = function (target, names, callback) {
  4532. var callbackList, i, ci, name, eventMap;
  4533. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4534. return this;
  4535. }
  4536. var id = target[this.expando];
  4537. if (id) {
  4538. eventMap = this.events[id];
  4539. if (names) {
  4540. var namesList = names.split(' ');
  4541. i = namesList.length;
  4542. while (i--) {
  4543. name = namesList[i];
  4544. callbackList = eventMap[name];
  4545. if (callbackList) {
  4546. if (callback) {
  4547. ci = callbackList.length;
  4548. while (ci--) {
  4549. if (callbackList[ci].func === callback) {
  4550. var nativeHandler = callbackList.nativeHandler;
  4551. var fakeName = callbackList.fakeName, capture = callbackList.capture;
  4552. callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
  4553. callbackList.nativeHandler = nativeHandler;
  4554. callbackList.fakeName = fakeName;
  4555. callbackList.capture = capture;
  4556. eventMap[name] = callbackList;
  4557. }
  4558. }
  4559. }
  4560. if (!callback || callbackList.length === 0) {
  4561. delete eventMap[name];
  4562. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  4563. }
  4564. }
  4565. }
  4566. } else {
  4567. each$j(eventMap, function (callbackList, name) {
  4568. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  4569. });
  4570. eventMap = {};
  4571. }
  4572. for (name in eventMap) {
  4573. if (has$2(eventMap, name)) {
  4574. return this;
  4575. }
  4576. }
  4577. delete this.events[id];
  4578. try {
  4579. delete target[this.expando];
  4580. } catch (ex) {
  4581. target[this.expando] = null;
  4582. }
  4583. }
  4584. return this;
  4585. };
  4586. EventUtils.prototype.fire = function (target, name, args) {
  4587. var id;
  4588. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4589. return this;
  4590. }
  4591. var event = fix({
  4592. type: name,
  4593. target: target
  4594. }, args);
  4595. do {
  4596. id = target[this.expando];
  4597. if (id) {
  4598. this.executeHandlers(event, id);
  4599. }
  4600. target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
  4601. } while (target && !event.isPropagationStopped());
  4602. return this;
  4603. };
  4604. EventUtils.prototype.clean = function (target) {
  4605. var i, children;
  4606. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4607. return this;
  4608. }
  4609. if (target[this.expando]) {
  4610. this.unbind(target);
  4611. }
  4612. if (!target.getElementsByTagName) {
  4613. target = target.document;
  4614. }
  4615. if (target && target.getElementsByTagName) {
  4616. this.unbind(target);
  4617. children = target.getElementsByTagName('*');
  4618. i = children.length;
  4619. while (i--) {
  4620. target = children[i];
  4621. if (target[this.expando]) {
  4622. this.unbind(target);
  4623. }
  4624. }
  4625. }
  4626. return this;
  4627. };
  4628. EventUtils.prototype.destroy = function () {
  4629. this.events = {};
  4630. };
  4631. EventUtils.prototype.cancel = function (e) {
  4632. if (e) {
  4633. e.preventDefault();
  4634. e.stopImmediatePropagation();
  4635. }
  4636. return false;
  4637. };
  4638. EventUtils.prototype.executeHandlers = function (evt, id) {
  4639. var container = this.events[id];
  4640. var callbackList = container && container[evt.type];
  4641. if (callbackList) {
  4642. for (var i = 0, l = callbackList.length; i < l; i++) {
  4643. var callback = callbackList[i];
  4644. if (callback && callback.func.call(callback.scope, evt) === false) {
  4645. evt.preventDefault();
  4646. }
  4647. if (evt.isImmediatePropagationStopped()) {
  4648. return;
  4649. }
  4650. }
  4651. }
  4652. };
  4653. EventUtils.Event = new EventUtils();
  4654. return EventUtils;
  4655. }();
  4656. var support, Expr, getText, isXML, tokenize, compile, select$1, outermostContext, sortInput, hasDuplicate, setDocument, document$1, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, expando = 'sizzle' + -new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function (a, b) {
  4657. if (a === b) {
  4658. hasDuplicate = true;
  4659. }
  4660. return 0;
  4661. }, strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, hasOwn = {}.hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push$1 = arr.push, slice$1 = arr.slice, indexOf = arr.indexOf || function (elem) {
  4662. var i = 0, len = this.length;
  4663. for (; i < len; i++) {
  4664. if (this[i] === elem) {
  4665. return i;
  4666. }
  4667. }
  4668. return -1;
  4669. }, 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 = {
  4670. ID: new RegExp('^#(' + identifier + ')'),
  4671. CLASS: new RegExp('^\\.(' + identifier + ')'),
  4672. TAG: new RegExp('^(' + identifier + '|[*])'),
  4673. ATTR: new RegExp('^' + attributes),
  4674. PSEUDO: new RegExp('^' + pseudos),
  4675. CHILD: new RegExp('^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(' + whitespace + '*(even|odd|(([+-]|)(\\d*)n|)' + whitespace + '*(?:([+-]|)' + whitespace + '*(\\d+)|))' + whitespace + '*\\)|)', 'i'),
  4676. bool: new RegExp('^(?:' + booleans + ')$', 'i'),
  4677. needsContext: new RegExp('^' + whitespace + '*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(' + whitespace + '*((?:-\\d)?\\d*)' + whitespace + '*\\)|)(?=[^-]|$)', 'i')
  4678. }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, rquickExpr$1 = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, runescape = new RegExp('\\\\([\\da-f]{1,6}' + whitespace + '?|(' + whitespace + ')|.)', 'ig'), funescape = function (_, escaped, escapedWhitespace) {
  4679. var high = '0x' + escaped - 65536;
  4680. return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320);
  4681. };
  4682. try {
  4683. push$1.apply(arr = slice$1.call(preferredDoc.childNodes), preferredDoc.childNodes);
  4684. arr[preferredDoc.childNodes.length].nodeType;
  4685. } catch (e) {
  4686. push$1 = {
  4687. apply: arr.length ? function (target, els) {
  4688. push_native.apply(target, slice$1.call(els));
  4689. } : function (target, els) {
  4690. var j = target.length, i = 0;
  4691. while (target[j++] = els[i++]) {
  4692. }
  4693. target.length = j - 1;
  4694. }
  4695. };
  4696. }
  4697. var Sizzle = function (selector, context, results, seed) {
  4698. var match, elem, m, nodeType, i, groups, old, nid, newContext, newSelector;
  4699. if ((context ? context.ownerDocument || context : preferredDoc) !== document$1) {
  4700. setDocument(context);
  4701. }
  4702. context = context || document$1;
  4703. results = results || [];
  4704. if (!selector || typeof selector !== 'string') {
  4705. return results;
  4706. }
  4707. if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) {
  4708. return [];
  4709. }
  4710. if (documentIsHTML && !seed) {
  4711. if (match = rquickExpr$1.exec(selector)) {
  4712. if (m = match[1]) {
  4713. if (nodeType === 9) {
  4714. elem = context.getElementById(m);
  4715. if (elem && elem.parentNode) {
  4716. if (elem.id === m) {
  4717. results.push(elem);
  4718. return results;
  4719. }
  4720. } else {
  4721. return results;
  4722. }
  4723. } else {
  4724. if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains(context, elem) && elem.id === m) {
  4725. results.push(elem);
  4726. return results;
  4727. }
  4728. }
  4729. } else if (match[2]) {
  4730. push$1.apply(results, context.getElementsByTagName(selector));
  4731. return results;
  4732. } else if ((m = match[3]) && support.getElementsByClassName) {
  4733. push$1.apply(results, context.getElementsByClassName(m));
  4734. return results;
  4735. }
  4736. }
  4737. if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
  4738. nid = old = expando;
  4739. newContext = context;
  4740. newSelector = nodeType === 9 && selector;
  4741. if (nodeType === 1 && context.nodeName.toLowerCase() !== 'object') {
  4742. groups = tokenize(selector);
  4743. if (old = context.getAttribute('id')) {
  4744. nid = old.replace(rescape, '\\$&');
  4745. } else {
  4746. context.setAttribute('id', nid);
  4747. }
  4748. nid = '[id=\'' + nid + '\'] ';
  4749. i = groups.length;
  4750. while (i--) {
  4751. groups[i] = nid + toSelector(groups[i]);
  4752. }
  4753. newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
  4754. newSelector = groups.join(',');
  4755. }
  4756. if (newSelector) {
  4757. try {
  4758. push$1.apply(results, newContext.querySelectorAll(newSelector));
  4759. return results;
  4760. } catch (qsaError) {
  4761. } finally {
  4762. if (!old) {
  4763. context.removeAttribute('id');
  4764. }
  4765. }
  4766. }
  4767. }
  4768. }
  4769. return select$1(selector.replace(rtrim, '$1'), context, results, seed);
  4770. };
  4771. function createCache() {
  4772. var keys = [];
  4773. function cache(key, value) {
  4774. if (keys.push(key + ' ') > Expr.cacheLength) {
  4775. delete cache[keys.shift()];
  4776. }
  4777. return cache[key + ' '] = value;
  4778. }
  4779. return cache;
  4780. }
  4781. function markFunction(fn) {
  4782. fn[expando] = true;
  4783. return fn;
  4784. }
  4785. function siblingCheck(a, b) {
  4786. var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && (~b.sourceIndex || MAX_NEGATIVE) - (~a.sourceIndex || MAX_NEGATIVE);
  4787. if (diff) {
  4788. return diff;
  4789. }
  4790. if (cur) {
  4791. while (cur = cur.nextSibling) {
  4792. if (cur === b) {
  4793. return -1;
  4794. }
  4795. }
  4796. }
  4797. return a ? 1 : -1;
  4798. }
  4799. function createInputPseudo(type) {
  4800. return function (elem) {
  4801. var name = elem.nodeName.toLowerCase();
  4802. return name === 'input' && elem.type === type;
  4803. };
  4804. }
  4805. function createButtonPseudo(type) {
  4806. return function (elem) {
  4807. var name = elem.nodeName.toLowerCase();
  4808. return (name === 'input' || name === 'button') && elem.type === type;
  4809. };
  4810. }
  4811. function createPositionalPseudo(fn) {
  4812. return markFunction(function (argument) {
  4813. argument = +argument;
  4814. return markFunction(function (seed, matches) {
  4815. var j, matchIndexes = fn([], seed.length, argument), i = matchIndexes.length;
  4816. while (i--) {
  4817. if (seed[j = matchIndexes[i]]) {
  4818. seed[j] = !(matches[j] = seed[j]);
  4819. }
  4820. }
  4821. });
  4822. });
  4823. }
  4824. function testContext(context) {
  4825. return context && typeof context.getElementsByTagName !== strundefined && context;
  4826. }
  4827. support = Sizzle.support = {};
  4828. isXML = Sizzle.isXML = function (elem) {
  4829. var documentElement = elem && (elem.ownerDocument || elem).documentElement;
  4830. return documentElement ? documentElement.nodeName !== 'HTML' : false;
  4831. };
  4832. setDocument = Sizzle.setDocument = function (node) {
  4833. var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView;
  4834. function getTop(win) {
  4835. try {
  4836. return win.top;
  4837. } catch (ex) {
  4838. }
  4839. return null;
  4840. }
  4841. if (doc === document$1 || doc.nodeType !== 9 || !doc.documentElement) {
  4842. return document$1;
  4843. }
  4844. document$1 = doc;
  4845. docElem = doc.documentElement;
  4846. documentIsHTML = !isXML(doc);
  4847. if (parent && parent !== getTop(parent)) {
  4848. if (parent.addEventListener) {
  4849. parent.addEventListener('unload', function () {
  4850. setDocument();
  4851. }, false);
  4852. } else if (parent.attachEvent) {
  4853. parent.attachEvent('onunload', function () {
  4854. setDocument();
  4855. });
  4856. }
  4857. }
  4858. support.attributes = true;
  4859. support.getElementsByTagName = true;
  4860. support.getElementsByClassName = rnative.test(doc.getElementsByClassName);
  4861. support.getById = true;
  4862. Expr.find.ID = function (id, context) {
  4863. if (typeof context.getElementById !== strundefined && documentIsHTML) {
  4864. var m = context.getElementById(id);
  4865. return m && m.parentNode ? [m] : [];
  4866. }
  4867. };
  4868. Expr.filter.ID = function (id) {
  4869. var attrId = id.replace(runescape, funescape);
  4870. return function (elem) {
  4871. return elem.getAttribute('id') === attrId;
  4872. };
  4873. };
  4874. Expr.find.TAG = support.getElementsByTagName ? function (tag, context) {
  4875. if (typeof context.getElementsByTagName !== strundefined) {
  4876. return context.getElementsByTagName(tag);
  4877. }
  4878. } : function (tag, context) {
  4879. var elem, tmp = [], i = 0, results = context.getElementsByTagName(tag);
  4880. if (tag === '*') {
  4881. while (elem = results[i++]) {
  4882. if (elem.nodeType === 1) {
  4883. tmp.push(elem);
  4884. }
  4885. }
  4886. return tmp;
  4887. }
  4888. return results;
  4889. };
  4890. Expr.find.CLASS = support.getElementsByClassName && function (className, context) {
  4891. if (documentIsHTML) {
  4892. return context.getElementsByClassName(className);
  4893. }
  4894. };
  4895. rbuggyMatches = [];
  4896. rbuggyQSA = [];
  4897. support.disconnectedMatch = true;
  4898. rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join('|'));
  4899. rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join('|'));
  4900. hasCompare = rnative.test(docElem.compareDocumentPosition);
  4901. contains = hasCompare || rnative.test(docElem.contains) ? function (a, b) {
  4902. var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode;
  4903. return a === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
  4904. } : function (a, b) {
  4905. if (b) {
  4906. while (b = b.parentNode) {
  4907. if (b === a) {
  4908. return true;
  4909. }
  4910. }
  4911. }
  4912. return false;
  4913. };
  4914. sortOrder = hasCompare ? function (a, b) {
  4915. if (a === b) {
  4916. hasDuplicate = true;
  4917. return 0;
  4918. }
  4919. var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
  4920. if (compare) {
  4921. return compare;
  4922. }
  4923. compare = (a.ownerDocument || a) === (b.ownerDocument || b) ? a.compareDocumentPosition(b) : 1;
  4924. if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {
  4925. if (a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a)) {
  4926. return -1;
  4927. }
  4928. if (b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b)) {
  4929. return 1;
  4930. }
  4931. return sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
  4932. }
  4933. return compare & 4 ? -1 : 1;
  4934. } : function (a, b) {
  4935. if (a === b) {
  4936. hasDuplicate = true;
  4937. return 0;
  4938. }
  4939. var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [a], bp = [b];
  4940. if (!aup || !bup) {
  4941. return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
  4942. } else if (aup === bup) {
  4943. return siblingCheck(a, b);
  4944. }
  4945. cur = a;
  4946. while (cur = cur.parentNode) {
  4947. ap.unshift(cur);
  4948. }
  4949. cur = b;
  4950. while (cur = cur.parentNode) {
  4951. bp.unshift(cur);
  4952. }
  4953. while (ap[i] === bp[i]) {
  4954. i++;
  4955. }
  4956. return i ? siblingCheck(ap[i], bp[i]) : ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0;
  4957. };
  4958. return doc;
  4959. };
  4960. Sizzle.matches = function (expr, elements) {
  4961. return Sizzle(expr, null, null, elements);
  4962. };
  4963. Sizzle.matchesSelector = function (elem, expr) {
  4964. if ((elem.ownerDocument || elem) !== document$1) {
  4965. setDocument(elem);
  4966. }
  4967. expr = expr.replace(rattributeQuotes, '=\'$1\']');
  4968. if (support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
  4969. try {
  4970. var ret = matches.call(elem, expr);
  4971. if (ret || support.disconnectedMatch || elem.document && elem.document.nodeType !== 11) {
  4972. return ret;
  4973. }
  4974. } catch (e) {
  4975. }
  4976. }
  4977. return Sizzle(expr, document$1, null, [elem]).length > 0;
  4978. };
  4979. Sizzle.contains = function (context, elem) {
  4980. if ((context.ownerDocument || context) !== document$1) {
  4981. setDocument(context);
  4982. }
  4983. return contains(context, elem);
  4984. };
  4985. Sizzle.attr = function (elem, name) {
  4986. if ((elem.ownerDocument || elem) !== document$1) {
  4987. setDocument(elem);
  4988. }
  4989. var fn = Expr.attrHandle[name.toLowerCase()], val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;
  4990. return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
  4991. };
  4992. Sizzle.error = function (msg) {
  4993. throw new Error('Syntax error, unrecognized expression: ' + msg);
  4994. };
  4995. Sizzle.uniqueSort = function (results) {
  4996. var elem, duplicates = [], j = 0, i = 0;
  4997. hasDuplicate = !support.detectDuplicates;
  4998. sortInput = !support.sortStable && results.slice(0);
  4999. results.sort(sortOrder);
  5000. if (hasDuplicate) {
  5001. while (elem = results[i++]) {
  5002. if (elem === results[i]) {
  5003. j = duplicates.push(i);
  5004. }
  5005. }
  5006. while (j--) {
  5007. results.splice(duplicates[j], 1);
  5008. }
  5009. }
  5010. sortInput = null;
  5011. return results;
  5012. };
  5013. getText = Sizzle.getText = function (elem) {
  5014. var node, ret = '', i = 0, nodeType = elem.nodeType;
  5015. if (!nodeType) {
  5016. while (node = elem[i++]) {
  5017. ret += getText(node);
  5018. }
  5019. } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
  5020. if (typeof elem.textContent === 'string') {
  5021. return elem.textContent;
  5022. } else {
  5023. for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5024. ret += getText(elem);
  5025. }
  5026. }
  5027. } else if (nodeType === 3 || nodeType === 4) {
  5028. return elem.nodeValue;
  5029. }
  5030. return ret;
  5031. };
  5032. Expr = Sizzle.selectors = {
  5033. cacheLength: 50,
  5034. createPseudo: markFunction,
  5035. match: matchExpr,
  5036. attrHandle: {},
  5037. find: {},
  5038. relative: {
  5039. '>': {
  5040. dir: 'parentNode',
  5041. first: true
  5042. },
  5043. ' ': { dir: 'parentNode' },
  5044. '+': {
  5045. dir: 'previousSibling',
  5046. first: true
  5047. },
  5048. '~': { dir: 'previousSibling' }
  5049. },
  5050. preFilter: {
  5051. ATTR: function (match) {
  5052. match[1] = match[1].replace(runescape, funescape);
  5053. match[3] = (match[3] || match[4] || match[5] || '').replace(runescape, funescape);
  5054. if (match[2] === '~=') {
  5055. match[3] = ' ' + match[3] + ' ';
  5056. }
  5057. return match.slice(0, 4);
  5058. },
  5059. CHILD: function (match) {
  5060. match[1] = match[1].toLowerCase();
  5061. if (match[1].slice(0, 3) === 'nth') {
  5062. if (!match[3]) {
  5063. Sizzle.error(match[0]);
  5064. }
  5065. match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === 'even' || match[3] === 'odd'));
  5066. match[5] = +(match[7] + match[8] || match[3] === 'odd');
  5067. } else if (match[3]) {
  5068. Sizzle.error(match[0]);
  5069. }
  5070. return match;
  5071. },
  5072. PSEUDO: function (match) {
  5073. var excess, unquoted = !match[6] && match[2];
  5074. if (matchExpr.CHILD.test(match[0])) {
  5075. return null;
  5076. }
  5077. if (match[3]) {
  5078. match[2] = match[4] || match[5] || '';
  5079. } else if (unquoted && rpseudo.test(unquoted) && (excess = tokenize(unquoted, true)) && (excess = unquoted.indexOf(')', unquoted.length - excess) - unquoted.length)) {
  5080. match[0] = match[0].slice(0, excess);
  5081. match[2] = unquoted.slice(0, excess);
  5082. }
  5083. return match.slice(0, 3);
  5084. }
  5085. },
  5086. filter: {
  5087. TAG: function (nodeNameSelector) {
  5088. var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
  5089. return nodeNameSelector === '*' ? function () {
  5090. return true;
  5091. } : function (elem) {
  5092. return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
  5093. };
  5094. },
  5095. CLASS: function (className) {
  5096. var pattern = classCache[className + ' '];
  5097. return pattern || (pattern = new RegExp('(^|' + whitespace + ')' + className + '(' + whitespace + '|$)')) && classCache(className, function (elem) {
  5098. return pattern.test(typeof elem.className === 'string' && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute('class') || '');
  5099. });
  5100. },
  5101. ATTR: function (name, operator, check) {
  5102. return function (elem) {
  5103. var result = Sizzle.attr(elem, name);
  5104. if (result == null) {
  5105. return operator === '!=';
  5106. }
  5107. if (!operator) {
  5108. return true;
  5109. }
  5110. result += '';
  5111. 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;
  5112. };
  5113. },
  5114. CHILD: function (type, what, argument, first, last) {
  5115. var simple = type.slice(0, 3) !== 'nth', forward = type.slice(-4) !== 'last', ofType = what === 'of-type';
  5116. return first === 1 && last === 0 ? function (elem) {
  5117. return !!elem.parentNode;
  5118. } : function (elem, context, xml) {
  5119. var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? 'nextSibling' : 'previousSibling', parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType;
  5120. if (parent) {
  5121. if (simple) {
  5122. while (dir) {
  5123. node = elem;
  5124. while (node = node[dir]) {
  5125. if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
  5126. return false;
  5127. }
  5128. }
  5129. start = dir = type === 'only' && !start && 'nextSibling';
  5130. }
  5131. return true;
  5132. }
  5133. start = [forward ? parent.firstChild : parent.lastChild];
  5134. if (forward && useCache) {
  5135. outerCache = parent[expando] || (parent[expando] = {});
  5136. cache = outerCache[type] || [];
  5137. nodeIndex = cache[0] === dirruns && cache[1];
  5138. diff = cache[0] === dirruns && cache[2];
  5139. node = nodeIndex && parent.childNodes[nodeIndex];
  5140. while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5141. if (node.nodeType === 1 && ++diff && node === elem) {
  5142. outerCache[type] = [
  5143. dirruns,
  5144. nodeIndex,
  5145. diff
  5146. ];
  5147. break;
  5148. }
  5149. }
  5150. } else if (useCache && (cache = (elem[expando] || (elem[expando] = {}))[type]) && cache[0] === dirruns) {
  5151. diff = cache[1];
  5152. } else {
  5153. while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5154. if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) {
  5155. if (useCache) {
  5156. (node[expando] || (node[expando] = {}))[type] = [
  5157. dirruns,
  5158. diff
  5159. ];
  5160. }
  5161. if (node === elem) {
  5162. break;
  5163. }
  5164. }
  5165. }
  5166. }
  5167. diff -= last;
  5168. return diff === first || diff % first === 0 && diff / first >= 0;
  5169. }
  5170. };
  5171. },
  5172. PSEUDO: function (pseudo, argument) {
  5173. var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error('unsupported pseudo: ' + pseudo);
  5174. if (fn[expando]) {
  5175. return fn(argument);
  5176. }
  5177. if (fn.length > 1) {
  5178. args = [
  5179. pseudo,
  5180. pseudo,
  5181. '',
  5182. argument
  5183. ];
  5184. return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) {
  5185. var idx, matched = fn(seed, argument), i = matched.length;
  5186. while (i--) {
  5187. idx = indexOf.call(seed, matched[i]);
  5188. seed[idx] = !(matches[idx] = matched[i]);
  5189. }
  5190. }) : function (elem) {
  5191. return fn(elem, 0, args);
  5192. };
  5193. }
  5194. return fn;
  5195. }
  5196. },
  5197. pseudos: {
  5198. not: markFunction(function (selector) {
  5199. var input = [], results = [], matcher = compile(selector.replace(rtrim, '$1'));
  5200. return matcher[expando] ? markFunction(function (seed, matches, context, xml) {
  5201. var elem, unmatched = matcher(seed, null, xml, []), i = seed.length;
  5202. while (i--) {
  5203. if (elem = unmatched[i]) {
  5204. seed[i] = !(matches[i] = elem);
  5205. }
  5206. }
  5207. }) : function (elem, context, xml) {
  5208. input[0] = elem;
  5209. matcher(input, null, xml, results);
  5210. input[0] = null;
  5211. return !results.pop();
  5212. };
  5213. }),
  5214. has: markFunction(function (selector) {
  5215. return function (elem) {
  5216. return Sizzle(selector, elem).length > 0;
  5217. };
  5218. }),
  5219. contains: markFunction(function (text) {
  5220. text = text.replace(runescape, funescape);
  5221. return function (elem) {
  5222. return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1;
  5223. };
  5224. }),
  5225. lang: markFunction(function (lang) {
  5226. if (!ridentifier.test(lang || '')) {
  5227. Sizzle.error('unsupported lang: ' + lang);
  5228. }
  5229. lang = lang.replace(runescape, funescape).toLowerCase();
  5230. return function (elem) {
  5231. var elemLang;
  5232. do {
  5233. if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute('xml:lang') || elem.getAttribute('lang')) {
  5234. elemLang = elemLang.toLowerCase();
  5235. return elemLang === lang || elemLang.indexOf(lang + '-') === 0;
  5236. }
  5237. } while ((elem = elem.parentNode) && elem.nodeType === 1);
  5238. return false;
  5239. };
  5240. }),
  5241. target: function (elem) {
  5242. var hash = window.location && window.location.hash;
  5243. return hash && hash.slice(1) === elem.id;
  5244. },
  5245. root: function (elem) {
  5246. return elem === docElem;
  5247. },
  5248. focus: function (elem) {
  5249. return elem === document$1.activeElement && (!document$1.hasFocus || document$1.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
  5250. },
  5251. enabled: function (elem) {
  5252. return elem.disabled === false;
  5253. },
  5254. disabled: function (elem) {
  5255. return elem.disabled === true;
  5256. },
  5257. checked: function (elem) {
  5258. var nodeName = elem.nodeName.toLowerCase();
  5259. return nodeName === 'input' && !!elem.checked || nodeName === 'option' && !!elem.selected;
  5260. },
  5261. selected: function (elem) {
  5262. if (elem.parentNode) {
  5263. elem.parentNode.selectedIndex;
  5264. }
  5265. return elem.selected === true;
  5266. },
  5267. empty: function (elem) {
  5268. for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5269. if (elem.nodeType < 6) {
  5270. return false;
  5271. }
  5272. }
  5273. return true;
  5274. },
  5275. parent: function (elem) {
  5276. return !Expr.pseudos.empty(elem);
  5277. },
  5278. header: function (elem) {
  5279. return rheader.test(elem.nodeName);
  5280. },
  5281. input: function (elem) {
  5282. return rinputs.test(elem.nodeName);
  5283. },
  5284. button: function (elem) {
  5285. var name = elem.nodeName.toLowerCase();
  5286. return name === 'input' && elem.type === 'button' || name === 'button';
  5287. },
  5288. text: function (elem) {
  5289. var attr;
  5290. return elem.nodeName.toLowerCase() === 'input' && elem.type === 'text' && ((attr = elem.getAttribute('type')) == null || attr.toLowerCase() === 'text');
  5291. },
  5292. first: createPositionalPseudo(function () {
  5293. return [0];
  5294. }),
  5295. last: createPositionalPseudo(function (matchIndexes, length) {
  5296. return [length - 1];
  5297. }),
  5298. eq: createPositionalPseudo(function (matchIndexes, length, argument) {
  5299. return [argument < 0 ? argument + length : argument];
  5300. }),
  5301. even: createPositionalPseudo(function (matchIndexes, length) {
  5302. var i = 0;
  5303. for (; i < length; i += 2) {
  5304. matchIndexes.push(i);
  5305. }
  5306. return matchIndexes;
  5307. }),
  5308. odd: createPositionalPseudo(function (matchIndexes, length) {
  5309. var i = 1;
  5310. for (; i < length; i += 2) {
  5311. matchIndexes.push(i);
  5312. }
  5313. return matchIndexes;
  5314. }),
  5315. lt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5316. var i = argument < 0 ? argument + length : argument;
  5317. for (; --i >= 0;) {
  5318. matchIndexes.push(i);
  5319. }
  5320. return matchIndexes;
  5321. }),
  5322. gt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5323. var i = argument < 0 ? argument + length : argument;
  5324. for (; ++i < length;) {
  5325. matchIndexes.push(i);
  5326. }
  5327. return matchIndexes;
  5328. })
  5329. }
  5330. };
  5331. Expr.pseudos.nth = Expr.pseudos.eq;
  5332. each$k([
  5333. 'radio',
  5334. 'checkbox',
  5335. 'file',
  5336. 'password',
  5337. 'image'
  5338. ], function (i) {
  5339. Expr.pseudos[i] = createInputPseudo(i);
  5340. });
  5341. each$k([
  5342. 'submit',
  5343. 'reset'
  5344. ], function (i) {
  5345. Expr.pseudos[i] = createButtonPseudo(i);
  5346. });
  5347. function setFilters() {
  5348. }
  5349. setFilters.prototype = Expr.filters = Expr.pseudos;
  5350. Expr.setFilters = new setFilters();
  5351. tokenize = Sizzle.tokenize = function (selector, parseOnly) {
  5352. var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + ' '];
  5353. if (cached) {
  5354. return parseOnly ? 0 : cached.slice(0);
  5355. }
  5356. soFar = selector;
  5357. groups = [];
  5358. preFilters = Expr.preFilter;
  5359. while (soFar) {
  5360. if (!matched || (match = rcomma.exec(soFar))) {
  5361. if (match) {
  5362. soFar = soFar.slice(match[0].length) || soFar;
  5363. }
  5364. groups.push(tokens = []);
  5365. }
  5366. matched = false;
  5367. if (match = rcombinators.exec(soFar)) {
  5368. matched = match.shift();
  5369. tokens.push({
  5370. value: matched,
  5371. type: match[0].replace(rtrim, ' ')
  5372. });
  5373. soFar = soFar.slice(matched.length);
  5374. }
  5375. for (type in Expr.filter) {
  5376. if (!Expr.filter.hasOwnProperty(type)) {
  5377. continue;
  5378. }
  5379. if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) {
  5380. matched = match.shift();
  5381. tokens.push({
  5382. value: matched,
  5383. type: type,
  5384. matches: match
  5385. });
  5386. soFar = soFar.slice(matched.length);
  5387. }
  5388. }
  5389. if (!matched) {
  5390. break;
  5391. }
  5392. }
  5393. return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : tokenCache(selector, groups).slice(0);
  5394. };
  5395. function toSelector(tokens) {
  5396. var i = 0, len = tokens.length, selector = '';
  5397. for (; i < len; i++) {
  5398. selector += tokens[i].value;
  5399. }
  5400. return selector;
  5401. }
  5402. function addCombinator(matcher, combinator, base) {
  5403. var dir = combinator.dir, checkNonElements = base && dir === 'parentNode', doneName = done++;
  5404. return combinator.first ? function (elem, context, xml) {
  5405. while (elem = elem[dir]) {
  5406. if (elem.nodeType === 1 || checkNonElements) {
  5407. return matcher(elem, context, xml);
  5408. }
  5409. }
  5410. } : function (elem, context, xml) {
  5411. var oldCache, outerCache, newCache = [
  5412. dirruns,
  5413. doneName
  5414. ];
  5415. if (xml) {
  5416. while (elem = elem[dir]) {
  5417. if (elem.nodeType === 1 || checkNonElements) {
  5418. if (matcher(elem, context, xml)) {
  5419. return true;
  5420. }
  5421. }
  5422. }
  5423. } else {
  5424. while (elem = elem[dir]) {
  5425. if (elem.nodeType === 1 || checkNonElements) {
  5426. outerCache = elem[expando] || (elem[expando] = {});
  5427. if ((oldCache = outerCache[dir]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
  5428. return newCache[2] = oldCache[2];
  5429. } else {
  5430. outerCache[dir] = newCache;
  5431. if (newCache[2] = matcher(elem, context, xml)) {
  5432. return true;
  5433. }
  5434. }
  5435. }
  5436. }
  5437. }
  5438. };
  5439. }
  5440. function elementMatcher(matchers) {
  5441. return matchers.length > 1 ? function (elem, context, xml) {
  5442. var i = matchers.length;
  5443. while (i--) {
  5444. if (!matchers[i](elem, context, xml)) {
  5445. return false;
  5446. }
  5447. }
  5448. return true;
  5449. } : matchers[0];
  5450. }
  5451. function multipleContexts(selector, contexts, results) {
  5452. var i = 0, len = contexts.length;
  5453. for (; i < len; i++) {
  5454. Sizzle(selector, contexts[i], results);
  5455. }
  5456. return results;
  5457. }
  5458. function condense(unmatched, map, filter, context, xml) {
  5459. var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null;
  5460. for (; i < len; i++) {
  5461. if (elem = unmatched[i]) {
  5462. if (!filter || filter(elem, context, xml)) {
  5463. newUnmatched.push(elem);
  5464. if (mapped) {
  5465. map.push(i);
  5466. }
  5467. }
  5468. }
  5469. }
  5470. return newUnmatched;
  5471. }
  5472. function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
  5473. if (postFilter && !postFilter[expando]) {
  5474. postFilter = setMatcher(postFilter);
  5475. }
  5476. if (postFinder && !postFinder[expando]) {
  5477. postFinder = setMatcher(postFinder, postSelector);
  5478. }
  5479. return markFunction(function (seed, results, context, xml) {
  5480. 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;
  5481. if (matcher) {
  5482. matcher(matcherIn, matcherOut, context, xml);
  5483. }
  5484. if (postFilter) {
  5485. temp = condense(matcherOut, postMap);
  5486. postFilter(temp, [], context, xml);
  5487. i = temp.length;
  5488. while (i--) {
  5489. if (elem = temp[i]) {
  5490. matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
  5491. }
  5492. }
  5493. }
  5494. if (seed) {
  5495. if (postFinder || preFilter) {
  5496. if (postFinder) {
  5497. temp = [];
  5498. i = matcherOut.length;
  5499. while (i--) {
  5500. if (elem = matcherOut[i]) {
  5501. temp.push(matcherIn[i] = elem);
  5502. }
  5503. }
  5504. postFinder(null, matcherOut = [], temp, xml);
  5505. }
  5506. i = matcherOut.length;
  5507. while (i--) {
  5508. if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf.call(seed, elem) : preMap[i]) > -1) {
  5509. seed[temp] = !(results[temp] = elem);
  5510. }
  5511. }
  5512. }
  5513. } else {
  5514. matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
  5515. if (postFinder) {
  5516. postFinder(null, results, matcherOut, xml);
  5517. } else {
  5518. push$1.apply(results, matcherOut);
  5519. }
  5520. }
  5521. });
  5522. }
  5523. function matcherFromTokens(tokens) {
  5524. 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) {
  5525. return elem === checkContext;
  5526. }, implicitRelative, true), matchAnyContext = addCombinator(function (elem) {
  5527. return indexOf.call(checkContext, elem) > -1;
  5528. }, implicitRelative, true), matchers = [function (elem, context, xml) {
  5529. var ret = !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
  5530. checkContext = null;
  5531. return ret;
  5532. }];
  5533. for (; i < len; i++) {
  5534. if (matcher = Expr.relative[tokens[i].type]) {
  5535. matchers = [addCombinator(elementMatcher(matchers), matcher)];
  5536. } else {
  5537. matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);
  5538. if (matcher[expando]) {
  5539. j = ++i;
  5540. for (; j < len; j++) {
  5541. if (Expr.relative[tokens[j].type]) {
  5542. break;
  5543. }
  5544. }
  5545. 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));
  5546. }
  5547. matchers.push(matcher);
  5548. }
  5549. }
  5550. return elementMatcher(matchers);
  5551. }
  5552. function matcherFromGroupMatchers(elementMatchers, setMatchers) {
  5553. var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function (seed, context, xml, results, outermost) {
  5554. 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;
  5555. if (outermost) {
  5556. outermostContext = context !== document$1 && context;
  5557. }
  5558. for (; i !== len && (elem = elems[i]) != null; i++) {
  5559. if (byElement && elem) {
  5560. j = 0;
  5561. while (matcher = elementMatchers[j++]) {
  5562. if (matcher(elem, context, xml)) {
  5563. results.push(elem);
  5564. break;
  5565. }
  5566. }
  5567. if (outermost) {
  5568. dirruns = dirrunsUnique;
  5569. }
  5570. }
  5571. if (bySet) {
  5572. if (elem = !matcher && elem) {
  5573. matchedCount--;
  5574. }
  5575. if (seed) {
  5576. unmatched.push(elem);
  5577. }
  5578. }
  5579. }
  5580. matchedCount += i;
  5581. if (bySet && i !== matchedCount) {
  5582. j = 0;
  5583. while (matcher = setMatchers[j++]) {
  5584. matcher(unmatched, setMatched, context, xml);
  5585. }
  5586. if (seed) {
  5587. if (matchedCount > 0) {
  5588. while (i--) {
  5589. if (!(unmatched[i] || setMatched[i])) {
  5590. setMatched[i] = pop.call(results);
  5591. }
  5592. }
  5593. }
  5594. setMatched = condense(setMatched);
  5595. }
  5596. push$1.apply(results, setMatched);
  5597. if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
  5598. Sizzle.uniqueSort(results);
  5599. }
  5600. }
  5601. if (outermost) {
  5602. dirruns = dirrunsUnique;
  5603. outermostContext = contextBackup;
  5604. }
  5605. return unmatched;
  5606. };
  5607. return bySet ? markFunction(superMatcher) : superMatcher;
  5608. }
  5609. compile = Sizzle.compile = function (selector, match) {
  5610. var i, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + ' '];
  5611. if (!cached) {
  5612. if (!match) {
  5613. match = tokenize(selector);
  5614. }
  5615. i = match.length;
  5616. while (i--) {
  5617. cached = matcherFromTokens(match[i]);
  5618. if (cached[expando]) {
  5619. setMatchers.push(cached);
  5620. } else {
  5621. elementMatchers.push(cached);
  5622. }
  5623. }
  5624. cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
  5625. cached.selector = selector;
  5626. }
  5627. return cached;
  5628. };
  5629. select$1 = Sizzle.select = function (selector, context, results, seed) {
  5630. var i, tokens, token, type, find, compiled = typeof selector === 'function' && selector, match = !seed && tokenize(selector = compiled.selector || selector);
  5631. results = results || [];
  5632. if (match.length === 1) {
  5633. tokens = match[0] = match[0].slice(0);
  5634. if (tokens.length > 2 && (token = tokens[0]).type === 'ID' && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
  5635. context = (Expr.find.ID(token.matches[0].replace(runescape, funescape), context) || [])[0];
  5636. if (!context) {
  5637. return results;
  5638. } else if (compiled) {
  5639. context = context.parentNode;
  5640. }
  5641. selector = selector.slice(tokens.shift().value.length);
  5642. }
  5643. i = matchExpr.needsContext.test(selector) ? 0 : tokens.length;
  5644. while (i--) {
  5645. token = tokens[i];
  5646. if (Expr.relative[type = token.type]) {
  5647. break;
  5648. }
  5649. if (find = Expr.find[type]) {
  5650. if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {
  5651. tokens.splice(i, 1);
  5652. selector = seed.length && toSelector(tokens);
  5653. if (!selector) {
  5654. push$1.apply(results, seed);
  5655. return results;
  5656. }
  5657. break;
  5658. }
  5659. }
  5660. }
  5661. }
  5662. (compiled || compile(selector, match))(seed, context, !documentIsHTML, results, rsibling.test(selector) && testContext(context.parentNode) || context);
  5663. return results;
  5664. };
  5665. support.sortStable = expando.split('').sort(sortOrder).join('') === expando;
  5666. support.detectDuplicates = !!hasDuplicate;
  5667. setDocument();
  5668. support.sortDetached = true;
  5669. var doc = document;
  5670. var push = Array.prototype.push;
  5671. var slice = Array.prototype.slice;
  5672. var rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
  5673. var Event$1 = EventUtils.Event;
  5674. var skipUniques = Tools.makeMap('children,contents,next,prev');
  5675. var isDefined = function (obj) {
  5676. return typeof obj !== 'undefined';
  5677. };
  5678. var isString = function (obj) {
  5679. return typeof obj === 'string';
  5680. };
  5681. var isWindow = function (obj) {
  5682. return obj && obj === obj.window;
  5683. };
  5684. var createFragment$1 = function (html, fragDoc) {
  5685. fragDoc = fragDoc || doc;
  5686. var container = fragDoc.createElement('div');
  5687. var frag = fragDoc.createDocumentFragment();
  5688. container.innerHTML = html;
  5689. var node;
  5690. while (node = container.firstChild) {
  5691. frag.appendChild(node);
  5692. }
  5693. return frag;
  5694. };
  5695. var domManipulate = function (targetNodes, sourceItem, callback, reverse) {
  5696. var i;
  5697. if (isString(sourceItem)) {
  5698. sourceItem = createFragment$1(sourceItem, getElementDocument(targetNodes[0]));
  5699. } else if (sourceItem.length && !sourceItem.nodeType) {
  5700. sourceItem = DomQuery.makeArray(sourceItem);
  5701. if (reverse) {
  5702. for (i = sourceItem.length - 1; i >= 0; i--) {
  5703. domManipulate(targetNodes, sourceItem[i], callback, reverse);
  5704. }
  5705. } else {
  5706. for (i = 0; i < sourceItem.length; i++) {
  5707. domManipulate(targetNodes, sourceItem[i], callback, reverse);
  5708. }
  5709. }
  5710. return targetNodes;
  5711. }
  5712. if (sourceItem.nodeType) {
  5713. i = targetNodes.length;
  5714. while (i--) {
  5715. callback.call(targetNodes[i], sourceItem);
  5716. }
  5717. }
  5718. return targetNodes;
  5719. };
  5720. var hasClass = function (node, className) {
  5721. return node && className && (' ' + node.className + ' ').indexOf(' ' + className + ' ') !== -1;
  5722. };
  5723. var wrap$2 = function (elements, wrapper, all) {
  5724. var lastParent, newWrapper;
  5725. wrapper = DomQuery(wrapper)[0];
  5726. elements.each(function () {
  5727. var self = this;
  5728. if (!all || lastParent !== self.parentNode) {
  5729. lastParent = self.parentNode;
  5730. newWrapper = wrapper.cloneNode(false);
  5731. self.parentNode.insertBefore(newWrapper, self);
  5732. newWrapper.appendChild(self);
  5733. } else {
  5734. newWrapper.appendChild(self);
  5735. }
  5736. });
  5737. return elements;
  5738. };
  5739. var numericCssMap = Tools.makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom', ' ');
  5740. var booleanMap = Tools.makeMap('checked compact declare defer disabled ismap multiple nohref noshade nowrap readonly selected', ' ');
  5741. var propFix = {
  5742. for: 'htmlFor',
  5743. class: 'className',
  5744. readonly: 'readOnly'
  5745. };
  5746. var cssFix = { float: 'cssFloat' };
  5747. var attrHooks = {}, cssHooks = {};
  5748. var DomQueryConstructor = function (selector, context) {
  5749. return new DomQuery.fn.init(selector, context);
  5750. };
  5751. var inArray$1 = function (item, array) {
  5752. var i;
  5753. if (array.indexOf) {
  5754. return array.indexOf(item);
  5755. }
  5756. i = array.length;
  5757. while (i--) {
  5758. if (array[i] === item) {
  5759. return i;
  5760. }
  5761. }
  5762. return -1;
  5763. };
  5764. var whiteSpaceRegExp = /^\s*|\s*$/g;
  5765. var trim$1 = function (str) {
  5766. return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp, '');
  5767. };
  5768. var each$g = function (obj, callback) {
  5769. var length, key, i, value;
  5770. if (obj) {
  5771. length = obj.length;
  5772. if (length === undefined) {
  5773. for (key in obj) {
  5774. if (obj.hasOwnProperty(key)) {
  5775. value = obj[key];
  5776. if (callback.call(value, key, value) === false) {
  5777. break;
  5778. }
  5779. }
  5780. }
  5781. } else {
  5782. for (i = 0; i < length; i++) {
  5783. value = obj[i];
  5784. if (callback.call(value, i, value) === false) {
  5785. break;
  5786. }
  5787. }
  5788. }
  5789. }
  5790. return obj;
  5791. };
  5792. var grep$2 = function (array, callback) {
  5793. var out = [];
  5794. each$g(array, function (i, item) {
  5795. if (callback(item, i)) {
  5796. out.push(item);
  5797. }
  5798. });
  5799. return out;
  5800. };
  5801. var getElementDocument = function (element) {
  5802. if (!element) {
  5803. return doc;
  5804. }
  5805. if (element.nodeType === 9) {
  5806. return element;
  5807. }
  5808. return element.ownerDocument;
  5809. };
  5810. DomQueryConstructor.fn = DomQueryConstructor.prototype = {
  5811. constructor: DomQueryConstructor,
  5812. selector: '',
  5813. context: null,
  5814. length: 0,
  5815. init: function (selector, context) {
  5816. var self = this;
  5817. var match, node;
  5818. if (!selector) {
  5819. return self;
  5820. }
  5821. if (selector.nodeType) {
  5822. self.context = self[0] = selector;
  5823. self.length = 1;
  5824. return self;
  5825. }
  5826. if (context && context.nodeType) {
  5827. self.context = context;
  5828. } else {
  5829. if (context) {
  5830. return DomQuery(selector).attr(context);
  5831. }
  5832. self.context = context = document;
  5833. }
  5834. if (isString(selector)) {
  5835. self.selector = selector;
  5836. if (selector.charAt(0) === '<' && selector.charAt(selector.length - 1) === '>' && selector.length >= 3) {
  5837. match = [
  5838. null,
  5839. selector,
  5840. null
  5841. ];
  5842. } else {
  5843. match = rquickExpr.exec(selector);
  5844. }
  5845. if (match) {
  5846. if (match[1]) {
  5847. node = createFragment$1(selector, getElementDocument(context)).firstChild;
  5848. while (node) {
  5849. push.call(self, node);
  5850. node = node.nextSibling;
  5851. }
  5852. } else {
  5853. node = getElementDocument(context).getElementById(match[2]);
  5854. if (!node) {
  5855. return self;
  5856. }
  5857. if (node.id !== match[2]) {
  5858. return self.find(selector);
  5859. }
  5860. self.length = 1;
  5861. self[0] = node;
  5862. }
  5863. } else {
  5864. return DomQuery(context).find(selector);
  5865. }
  5866. } else {
  5867. this.add(selector, false);
  5868. }
  5869. return self;
  5870. },
  5871. toArray: function () {
  5872. return Tools.toArray(this);
  5873. },
  5874. add: function (items, sort) {
  5875. var self = this;
  5876. var nodes, i;
  5877. if (isString(items)) {
  5878. return self.add(DomQuery(items));
  5879. }
  5880. if (sort !== false) {
  5881. nodes = DomQuery.unique(self.toArray().concat(DomQuery.makeArray(items)));
  5882. self.length = nodes.length;
  5883. for (i = 0; i < nodes.length; i++) {
  5884. self[i] = nodes[i];
  5885. }
  5886. } else {
  5887. push.apply(self, DomQuery.makeArray(items));
  5888. }
  5889. return self;
  5890. },
  5891. attr: function (name, value) {
  5892. var self = this;
  5893. var hook;
  5894. if (typeof name === 'object') {
  5895. each$g(name, function (name, value) {
  5896. self.attr(name, value);
  5897. });
  5898. } else if (isDefined(value)) {
  5899. this.each(function () {
  5900. var hook;
  5901. if (this.nodeType === 1) {
  5902. hook = attrHooks[name];
  5903. if (hook && hook.set) {
  5904. hook.set(this, value);
  5905. return;
  5906. }
  5907. if (value === null) {
  5908. this.removeAttribute(name, 2);
  5909. } else {
  5910. this.setAttribute(name, value, 2);
  5911. }
  5912. }
  5913. });
  5914. } else {
  5915. if (self[0] && self[0].nodeType === 1) {
  5916. hook = attrHooks[name];
  5917. if (hook && hook.get) {
  5918. return hook.get(self[0], name);
  5919. }
  5920. if (booleanMap[name]) {
  5921. return self.prop(name) ? name : undefined;
  5922. }
  5923. value = self[0].getAttribute(name, 2);
  5924. if (value === null) {
  5925. value = undefined;
  5926. }
  5927. }
  5928. return value;
  5929. }
  5930. return self;
  5931. },
  5932. removeAttr: function (name) {
  5933. return this.attr(name, null);
  5934. },
  5935. prop: function (name, value) {
  5936. var self = this;
  5937. name = propFix[name] || name;
  5938. if (typeof name === 'object') {
  5939. each$g(name, function (name, value) {
  5940. self.prop(name, value);
  5941. });
  5942. } else if (isDefined(value)) {
  5943. this.each(function () {
  5944. if (this.nodeType === 1) {
  5945. this[name] = value;
  5946. }
  5947. });
  5948. } else {
  5949. if (self[0] && self[0].nodeType && name in self[0]) {
  5950. return self[0][name];
  5951. }
  5952. return value;
  5953. }
  5954. return self;
  5955. },
  5956. css: function (name, value) {
  5957. var self = this;
  5958. var elm, hook;
  5959. var camel = function (name) {
  5960. return name.replace(/-(\D)/g, function (a, b) {
  5961. return b.toUpperCase();
  5962. });
  5963. };
  5964. var dashed = function (name) {
  5965. return name.replace(/[A-Z]/g, function (a) {
  5966. return '-' + a;
  5967. });
  5968. };
  5969. if (typeof name === 'object') {
  5970. each$g(name, function (name, value) {
  5971. self.css(name, value);
  5972. });
  5973. } else {
  5974. if (isDefined(value)) {
  5975. name = camel(name);
  5976. if (typeof value === 'number' && !numericCssMap[name]) {
  5977. value = value.toString() + 'px';
  5978. }
  5979. self.each(function () {
  5980. var style = this.style;
  5981. hook = cssHooks[name];
  5982. if (hook && hook.set) {
  5983. hook.set(this, value);
  5984. return;
  5985. }
  5986. try {
  5987. this.style[cssFix[name] || name] = value;
  5988. } catch (ex) {
  5989. }
  5990. if (value === null || value === '') {
  5991. if (style.removeProperty) {
  5992. style.removeProperty(dashed(name));
  5993. } else {
  5994. style.removeAttribute(name);
  5995. }
  5996. }
  5997. });
  5998. } else {
  5999. elm = self[0];
  6000. hook = cssHooks[name];
  6001. if (hook && hook.get) {
  6002. return hook.get(elm);
  6003. }
  6004. if (elm.ownerDocument.defaultView) {
  6005. try {
  6006. return elm.ownerDocument.defaultView.getComputedStyle(elm, null).getPropertyValue(dashed(name));
  6007. } catch (ex) {
  6008. return undefined;
  6009. }
  6010. } else if (elm.currentStyle) {
  6011. return elm.currentStyle[camel(name)];
  6012. } else {
  6013. return '';
  6014. }
  6015. }
  6016. }
  6017. return self;
  6018. },
  6019. remove: function () {
  6020. var self = this;
  6021. var node, i = this.length;
  6022. while (i--) {
  6023. node = self[i];
  6024. Event$1.clean(node);
  6025. if (node.parentNode) {
  6026. node.parentNode.removeChild(node);
  6027. }
  6028. }
  6029. return this;
  6030. },
  6031. empty: function () {
  6032. var self = this;
  6033. var node, i = this.length;
  6034. while (i--) {
  6035. node = self[i];
  6036. while (node.firstChild) {
  6037. node.removeChild(node.firstChild);
  6038. }
  6039. }
  6040. return this;
  6041. },
  6042. html: function (value) {
  6043. var self = this;
  6044. var i;
  6045. if (isDefined(value)) {
  6046. i = self.length;
  6047. try {
  6048. while (i--) {
  6049. self[i].innerHTML = value;
  6050. }
  6051. } catch (ex) {
  6052. DomQuery(self[i]).empty().append(value);
  6053. }
  6054. return self;
  6055. }
  6056. return self[0] ? self[0].innerHTML : '';
  6057. },
  6058. text: function (value) {
  6059. var self = this;
  6060. var i;
  6061. if (isDefined(value)) {
  6062. i = self.length;
  6063. while (i--) {
  6064. if ('innerText' in self[i]) {
  6065. self[i].innerText = value;
  6066. } else {
  6067. self[0].textContent = value;
  6068. }
  6069. }
  6070. return self;
  6071. }
  6072. return self[0] ? self[0].innerText || self[0].textContent : '';
  6073. },
  6074. append: function () {
  6075. return domManipulate(this, arguments, function (node) {
  6076. if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6077. this.appendChild(node);
  6078. }
  6079. });
  6080. },
  6081. prepend: function () {
  6082. return domManipulate(this, arguments, function (node) {
  6083. if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6084. this.insertBefore(node, this.firstChild);
  6085. }
  6086. }, true);
  6087. },
  6088. before: function () {
  6089. var self = this;
  6090. if (self[0] && self[0].parentNode) {
  6091. return domManipulate(self, arguments, function (node) {
  6092. this.parentNode.insertBefore(node, this);
  6093. });
  6094. }
  6095. return self;
  6096. },
  6097. after: function () {
  6098. var self = this;
  6099. if (self[0] && self[0].parentNode) {
  6100. return domManipulate(self, arguments, function (node) {
  6101. this.parentNode.insertBefore(node, this.nextSibling);
  6102. }, true);
  6103. }
  6104. return self;
  6105. },
  6106. appendTo: function (val) {
  6107. DomQuery(val).append(this);
  6108. return this;
  6109. },
  6110. prependTo: function (val) {
  6111. DomQuery(val).prepend(this);
  6112. return this;
  6113. },
  6114. replaceWith: function (content) {
  6115. return this.before(content).remove();
  6116. },
  6117. wrap: function (content) {
  6118. return wrap$2(this, content);
  6119. },
  6120. wrapAll: function (content) {
  6121. return wrap$2(this, content, true);
  6122. },
  6123. wrapInner: function (content) {
  6124. this.each(function () {
  6125. DomQuery(this).contents().wrapAll(content);
  6126. });
  6127. return this;
  6128. },
  6129. unwrap: function () {
  6130. return this.parent().each(function () {
  6131. DomQuery(this).replaceWith(this.childNodes);
  6132. });
  6133. },
  6134. clone: function () {
  6135. var result = [];
  6136. this.each(function () {
  6137. result.push(this.cloneNode(true));
  6138. });
  6139. return DomQuery(result);
  6140. },
  6141. addClass: function (className) {
  6142. return this.toggleClass(className, true);
  6143. },
  6144. removeClass: function (className) {
  6145. return this.toggleClass(className, false);
  6146. },
  6147. toggleClass: function (className, state) {
  6148. var self = this;
  6149. if (typeof className !== 'string') {
  6150. return self;
  6151. }
  6152. if (className.indexOf(' ') !== -1) {
  6153. each$g(className.split(' '), function () {
  6154. self.toggleClass(this, state);
  6155. });
  6156. } else {
  6157. self.each(function (index, node) {
  6158. var classState = hasClass(node, className);
  6159. if (classState !== state) {
  6160. var existingClassName = node.className;
  6161. if (classState) {
  6162. node.className = trim$1((' ' + existingClassName + ' ').replace(' ' + className + ' ', ' '));
  6163. } else {
  6164. node.className += existingClassName ? ' ' + className : className;
  6165. }
  6166. }
  6167. });
  6168. }
  6169. return self;
  6170. },
  6171. hasClass: function (className) {
  6172. return hasClass(this[0], className);
  6173. },
  6174. each: function (callback) {
  6175. return each$g(this, callback);
  6176. },
  6177. on: function (name, callback) {
  6178. return this.each(function () {
  6179. Event$1.bind(this, name, callback);
  6180. });
  6181. },
  6182. off: function (name, callback) {
  6183. return this.each(function () {
  6184. Event$1.unbind(this, name, callback);
  6185. });
  6186. },
  6187. trigger: function (name) {
  6188. return this.each(function () {
  6189. if (typeof name === 'object') {
  6190. Event$1.fire(this, name.type, name);
  6191. } else {
  6192. Event$1.fire(this, name);
  6193. }
  6194. });
  6195. },
  6196. show: function () {
  6197. return this.css('display', '');
  6198. },
  6199. hide: function () {
  6200. return this.css('display', 'none');
  6201. },
  6202. slice: function () {
  6203. return DomQuery(slice.apply(this, arguments));
  6204. },
  6205. eq: function (index) {
  6206. return index === -1 ? this.slice(index) : this.slice(index, +index + 1);
  6207. },
  6208. first: function () {
  6209. return this.eq(0);
  6210. },
  6211. last: function () {
  6212. return this.eq(-1);
  6213. },
  6214. find: function (selector) {
  6215. var i, l;
  6216. var ret = [];
  6217. for (i = 0, l = this.length; i < l; i++) {
  6218. DomQuery.find(selector, this[i], ret);
  6219. }
  6220. return DomQuery(ret);
  6221. },
  6222. filter: function (selector) {
  6223. if (typeof selector === 'function') {
  6224. return DomQuery(grep$2(this.toArray(), function (item, i) {
  6225. return selector(i, item);
  6226. }));
  6227. }
  6228. return DomQuery(DomQuery.filter(selector, this.toArray()));
  6229. },
  6230. closest: function (selector) {
  6231. var result = [];
  6232. if (selector instanceof DomQuery) {
  6233. selector = selector[0];
  6234. }
  6235. this.each(function (i, node) {
  6236. while (node) {
  6237. if (typeof selector === 'string' && DomQuery(node).is(selector)) {
  6238. result.push(node);
  6239. break;
  6240. } else if (node === selector) {
  6241. result.push(node);
  6242. break;
  6243. }
  6244. node = node.parentNode;
  6245. }
  6246. });
  6247. return DomQuery(result);
  6248. },
  6249. offset: function (offset) {
  6250. var elm, doc, docElm;
  6251. var x = 0, y = 0, pos;
  6252. if (!offset) {
  6253. elm = this[0];
  6254. if (elm) {
  6255. doc = elm.ownerDocument;
  6256. docElm = doc.documentElement;
  6257. if (elm.getBoundingClientRect) {
  6258. pos = elm.getBoundingClientRect();
  6259. x = pos.left + (docElm.scrollLeft || doc.body.scrollLeft) - docElm.clientLeft;
  6260. y = pos.top + (docElm.scrollTop || doc.body.scrollTop) - docElm.clientTop;
  6261. }
  6262. }
  6263. return {
  6264. left: x,
  6265. top: y
  6266. };
  6267. }
  6268. return this.css(offset);
  6269. },
  6270. push: push,
  6271. sort: Array.prototype.sort,
  6272. splice: Array.prototype.splice
  6273. };
  6274. Tools.extend(DomQueryConstructor, {
  6275. extend: Tools.extend,
  6276. makeArray: function (object) {
  6277. if (isWindow(object) || object.nodeType) {
  6278. return [object];
  6279. }
  6280. return Tools.toArray(object);
  6281. },
  6282. inArray: inArray$1,
  6283. isArray: Tools.isArray,
  6284. each: each$g,
  6285. trim: trim$1,
  6286. grep: grep$2,
  6287. find: Sizzle,
  6288. expr: Sizzle.selectors,
  6289. unique: Sizzle.uniqueSort,
  6290. text: Sizzle.getText,
  6291. contains: Sizzle.contains,
  6292. filter: function (expr, elems, not) {
  6293. var i = elems.length;
  6294. if (not) {
  6295. expr = ':not(' + expr + ')';
  6296. }
  6297. while (i--) {
  6298. if (elems[i].nodeType !== 1) {
  6299. elems.splice(i, 1);
  6300. }
  6301. }
  6302. if (elems.length === 1) {
  6303. elems = DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [];
  6304. } else {
  6305. elems = DomQuery.find.matches(expr, elems);
  6306. }
  6307. return elems;
  6308. }
  6309. });
  6310. var dir = function (el, prop, until) {
  6311. var matched = [];
  6312. var cur = el[prop];
  6313. if (typeof until !== 'string' && until instanceof DomQuery) {
  6314. until = until[0];
  6315. }
  6316. while (cur && cur.nodeType !== 9) {
  6317. if (until !== undefined) {
  6318. if (cur === until) {
  6319. break;
  6320. }
  6321. if (typeof until === 'string' && DomQuery(cur).is(until)) {
  6322. break;
  6323. }
  6324. }
  6325. if (cur.nodeType === 1) {
  6326. matched.push(cur);
  6327. }
  6328. cur = cur[prop];
  6329. }
  6330. return matched;
  6331. };
  6332. var sibling$1 = function (node, siblingName, nodeType, until) {
  6333. var result = [];
  6334. if (until instanceof DomQuery) {
  6335. until = until[0];
  6336. }
  6337. for (; node; node = node[siblingName]) {
  6338. if (nodeType && node.nodeType !== nodeType) {
  6339. continue;
  6340. }
  6341. if (until !== undefined) {
  6342. if (node === until) {
  6343. break;
  6344. }
  6345. if (typeof until === 'string' && DomQuery(node).is(until)) {
  6346. break;
  6347. }
  6348. }
  6349. result.push(node);
  6350. }
  6351. return result;
  6352. };
  6353. var firstSibling = function (node, siblingName, nodeType) {
  6354. for (node = node[siblingName]; node; node = node[siblingName]) {
  6355. if (node.nodeType === nodeType) {
  6356. return node;
  6357. }
  6358. }
  6359. return null;
  6360. };
  6361. each$g({
  6362. parent: function (node) {
  6363. var parent = node.parentNode;
  6364. return parent && parent.nodeType !== 11 ? parent : null;
  6365. },
  6366. parents: function (node) {
  6367. return dir(node, 'parentNode');
  6368. },
  6369. next: function (node) {
  6370. return firstSibling(node, 'nextSibling', 1);
  6371. },
  6372. prev: function (node) {
  6373. return firstSibling(node, 'previousSibling', 1);
  6374. },
  6375. children: function (node) {
  6376. return sibling$1(node.firstChild, 'nextSibling', 1);
  6377. },
  6378. contents: function (node) {
  6379. return Tools.toArray((node.nodeName === 'iframe' ? node.contentDocument || node.contentWindow.document : node).childNodes);
  6380. }
  6381. }, function (name, fn) {
  6382. DomQueryConstructor.fn[name] = function (selector) {
  6383. var self = this;
  6384. var result = [];
  6385. self.each(function () {
  6386. var nodes = fn.call(result, this, selector, result);
  6387. if (nodes) {
  6388. if (DomQuery.isArray(nodes)) {
  6389. result.push.apply(result, nodes);
  6390. } else {
  6391. result.push(nodes);
  6392. }
  6393. }
  6394. });
  6395. if (this.length > 1) {
  6396. if (!skipUniques[name]) {
  6397. result = DomQuery.unique(result);
  6398. }
  6399. if (name.indexOf('parents') === 0) {
  6400. result = result.reverse();
  6401. }
  6402. }
  6403. var wrappedResult = DomQuery(result);
  6404. if (selector) {
  6405. return wrappedResult.filter(selector);
  6406. }
  6407. return wrappedResult;
  6408. };
  6409. });
  6410. each$g({
  6411. parentsUntil: function (node, until) {
  6412. return dir(node, 'parentNode', until);
  6413. },
  6414. nextUntil: function (node, until) {
  6415. return sibling$1(node, 'nextSibling', 1, until).slice(1);
  6416. },
  6417. prevUntil: function (node, until) {
  6418. return sibling$1(node, 'previousSibling', 1, until).slice(1);
  6419. }
  6420. }, function (name, fn) {
  6421. DomQueryConstructor.fn[name] = function (selector, filter) {
  6422. var self = this;
  6423. var result = [];
  6424. self.each(function () {
  6425. var nodes = fn.call(result, this, selector, result);
  6426. if (nodes) {
  6427. if (DomQuery.isArray(nodes)) {
  6428. result.push.apply(result, nodes);
  6429. } else {
  6430. result.push(nodes);
  6431. }
  6432. }
  6433. });
  6434. if (this.length > 1) {
  6435. result = DomQuery.unique(result);
  6436. if (name.indexOf('parents') === 0 || name === 'prevUntil') {
  6437. result = result.reverse();
  6438. }
  6439. }
  6440. var wrappedResult = DomQuery(result);
  6441. if (filter) {
  6442. return wrappedResult.filter(filter);
  6443. }
  6444. return wrappedResult;
  6445. };
  6446. });
  6447. DomQueryConstructor.fn.is = function (selector) {
  6448. return !!selector && this.filter(selector).length > 0;
  6449. };
  6450. DomQueryConstructor.fn.init.prototype = DomQueryConstructor.fn;
  6451. DomQueryConstructor.overrideDefaults = function (callback) {
  6452. var defaults;
  6453. var sub = function (selector, context) {
  6454. defaults = defaults || callback();
  6455. if (arguments.length === 0) {
  6456. selector = defaults.element;
  6457. }
  6458. if (!context) {
  6459. context = defaults.context;
  6460. }
  6461. return new sub.fn.init(selector, context);
  6462. };
  6463. DomQuery.extend(sub, this);
  6464. return sub;
  6465. };
  6466. DomQueryConstructor.attrHooks = attrHooks;
  6467. DomQueryConstructor.cssHooks = cssHooks;
  6468. var DomQuery = DomQueryConstructor;
  6469. var each$f = Tools.each;
  6470. var grep$1 = Tools.grep;
  6471. var isIE = Env.ie;
  6472. var simpleSelectorRe = /^([a-z0-9],?)+$/i;
  6473. var setupAttrHooks = function (styles, settings, getContext) {
  6474. var keepValues = settings.keep_values;
  6475. var keepUrlHook = {
  6476. set: function ($elm, value, name) {
  6477. if (settings.url_converter && value !== null) {
  6478. value = settings.url_converter.call(settings.url_converter_scope || getContext(), value, name, $elm[0]);
  6479. }
  6480. $elm.attr('data-mce-' + name, value).attr(name, value);
  6481. },
  6482. get: function ($elm, name) {
  6483. return $elm.attr('data-mce-' + name) || $elm.attr(name);
  6484. }
  6485. };
  6486. var attrHooks = {
  6487. style: {
  6488. set: function ($elm, value) {
  6489. if (value !== null && typeof value === 'object') {
  6490. $elm.css(value);
  6491. return;
  6492. }
  6493. if (keepValues) {
  6494. $elm.attr('data-mce-style', value);
  6495. }
  6496. if (value !== null && typeof value === 'string') {
  6497. $elm.removeAttr('style');
  6498. $elm.css(styles.parse(value));
  6499. } else {
  6500. $elm.attr('style', value);
  6501. }
  6502. },
  6503. get: function ($elm) {
  6504. var value = $elm.attr('data-mce-style') || $elm.attr('style');
  6505. value = styles.serialize(styles.parse(value), $elm[0].nodeName);
  6506. return value;
  6507. }
  6508. }
  6509. };
  6510. if (keepValues) {
  6511. attrHooks.href = attrHooks.src = keepUrlHook;
  6512. }
  6513. return attrHooks;
  6514. };
  6515. var updateInternalStyleAttr = function (styles, $elm) {
  6516. var rawValue = $elm.attr('style');
  6517. var value = styles.serialize(styles.parse(rawValue), $elm[0].nodeName);
  6518. if (!value) {
  6519. value = null;
  6520. }
  6521. $elm.attr('data-mce-style', value);
  6522. };
  6523. var findNodeIndex = function (node, normalized) {
  6524. var idx = 0, lastNodeType, nodeType;
  6525. if (node) {
  6526. for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
  6527. nodeType = node.nodeType;
  6528. if (normalized && nodeType === 3) {
  6529. if (nodeType === lastNodeType || !node.nodeValue.length) {
  6530. continue;
  6531. }
  6532. }
  6533. idx++;
  6534. lastNodeType = nodeType;
  6535. }
  6536. }
  6537. return idx;
  6538. };
  6539. var DOMUtils = function (doc, settings) {
  6540. if (settings === void 0) {
  6541. settings = {};
  6542. }
  6543. var addedStyles = {};
  6544. var win = window;
  6545. var files = {};
  6546. var counter = 0;
  6547. var stdMode = true;
  6548. var boxModel = true;
  6549. var styleSheetLoader = instance.forElement(SugarElement.fromDom(doc), {
  6550. contentCssCors: settings.contentCssCors,
  6551. referrerPolicy: settings.referrerPolicy
  6552. });
  6553. var boundEvents = [];
  6554. var schema = settings.schema ? settings.schema : Schema({});
  6555. var styles = Styles({
  6556. url_converter: settings.url_converter,
  6557. url_converter_scope: settings.url_converter_scope
  6558. }, settings.schema);
  6559. var events = settings.ownEvents ? new EventUtils() : EventUtils.Event;
  6560. var blockElementsMap = schema.getBlockElements();
  6561. var $ = DomQuery.overrideDefaults(function () {
  6562. return {
  6563. context: doc,
  6564. element: self.getRoot()
  6565. };
  6566. });
  6567. var isBlock = function (node) {
  6568. if (typeof node === 'string') {
  6569. return !!blockElementsMap[node];
  6570. } else if (node) {
  6571. var type = node.nodeType;
  6572. if (type) {
  6573. return !!(type === 1 && blockElementsMap[node.nodeName]);
  6574. }
  6575. }
  6576. return false;
  6577. };
  6578. var get = function (elm) {
  6579. return elm && doc && isString$1(elm) ? doc.getElementById(elm) : elm;
  6580. };
  6581. var $$ = function (elm) {
  6582. return $(typeof elm === 'string' ? get(elm) : elm);
  6583. };
  6584. var getAttrib = function (elm, name, defaultVal) {
  6585. var hook, value;
  6586. var $elm = $$(elm);
  6587. if ($elm.length) {
  6588. hook = attrHooks[name];
  6589. if (hook && hook.get) {
  6590. value = hook.get($elm, name);
  6591. } else {
  6592. value = $elm.attr(name);
  6593. }
  6594. }
  6595. if (typeof value === 'undefined') {
  6596. value = defaultVal || '';
  6597. }
  6598. return value;
  6599. };
  6600. var getAttribs = function (elm) {
  6601. var node = get(elm);
  6602. if (!node) {
  6603. return [];
  6604. }
  6605. return node.attributes;
  6606. };
  6607. var setAttrib = function (elm, name, value) {
  6608. if (value === '') {
  6609. value = null;
  6610. }
  6611. var $elm = $$(elm);
  6612. var originalValue = $elm.attr(name);
  6613. if (!$elm.length) {
  6614. return;
  6615. }
  6616. var hook = attrHooks[name];
  6617. if (hook && hook.set) {
  6618. hook.set($elm, value, name);
  6619. } else {
  6620. $elm.attr(name, value);
  6621. }
  6622. if (originalValue !== value && settings.onSetAttrib) {
  6623. settings.onSetAttrib({
  6624. attrElm: $elm,
  6625. attrName: name,
  6626. attrValue: value
  6627. });
  6628. }
  6629. };
  6630. var clone = function (node, deep) {
  6631. if (!isIE || node.nodeType !== 1 || deep) {
  6632. return node.cloneNode(deep);
  6633. } else {
  6634. var clone_1 = doc.createElement(node.nodeName);
  6635. each$f(getAttribs(node), function (attr) {
  6636. setAttrib(clone_1, attr.nodeName, getAttrib(node, attr.nodeName));
  6637. });
  6638. return clone_1;
  6639. }
  6640. };
  6641. var getRoot = function () {
  6642. return settings.root_element || doc.body;
  6643. };
  6644. var getViewPort = function (argWin) {
  6645. var vp = getBounds(argWin);
  6646. return {
  6647. x: vp.x,
  6648. y: vp.y,
  6649. w: vp.width,
  6650. h: vp.height
  6651. };
  6652. };
  6653. var getPos$1 = function (elm, rootElm) {
  6654. return getPos(doc.body, get(elm), rootElm);
  6655. };
  6656. var setStyle = function (elm, name, value) {
  6657. var $elm = isString$1(name) ? $$(elm).css(name, value) : $$(elm).css(name);
  6658. if (settings.update_styles) {
  6659. updateInternalStyleAttr(styles, $elm);
  6660. }
  6661. };
  6662. var setStyles = function (elm, stylesArg) {
  6663. var $elm = $$(elm).css(stylesArg);
  6664. if (settings.update_styles) {
  6665. updateInternalStyleAttr(styles, $elm);
  6666. }
  6667. };
  6668. var getStyle = function (elm, name, computed) {
  6669. var $elm = $$(elm);
  6670. if (computed) {
  6671. return $elm.css(name);
  6672. }
  6673. name = name.replace(/-(\D)/g, function (a, b) {
  6674. return b.toUpperCase();
  6675. });
  6676. if (name === 'float') {
  6677. name = Env.browser.isIE() ? 'styleFloat' : 'cssFloat';
  6678. }
  6679. return $elm[0] && $elm[0].style ? $elm[0].style[name] : undefined;
  6680. };
  6681. var getSize = function (elm) {
  6682. var w, h;
  6683. elm = get(elm);
  6684. w = getStyle(elm, 'width');
  6685. h = getStyle(elm, 'height');
  6686. if (w.indexOf('px') === -1) {
  6687. w = 0;
  6688. }
  6689. if (h.indexOf('px') === -1) {
  6690. h = 0;
  6691. }
  6692. return {
  6693. w: parseInt(w, 10) || elm.offsetWidth || elm.clientWidth,
  6694. h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight
  6695. };
  6696. };
  6697. var getRect = function (elm) {
  6698. elm = get(elm);
  6699. var pos = getPos$1(elm);
  6700. var size = getSize(elm);
  6701. return {
  6702. x: pos.x,
  6703. y: pos.y,
  6704. w: size.w,
  6705. h: size.h
  6706. };
  6707. };
  6708. var is = function (elm, selector) {
  6709. var i;
  6710. if (!elm) {
  6711. return false;
  6712. }
  6713. if (!Array.isArray(elm)) {
  6714. if (selector === '*') {
  6715. return elm.nodeType === 1;
  6716. }
  6717. if (simpleSelectorRe.test(selector)) {
  6718. var selectors = selector.toLowerCase().split(/,/);
  6719. var elmName = elm.nodeName.toLowerCase();
  6720. for (i = selectors.length - 1; i >= 0; i--) {
  6721. if (selectors[i] === elmName) {
  6722. return true;
  6723. }
  6724. }
  6725. return false;
  6726. }
  6727. if (elm.nodeType && elm.nodeType !== 1) {
  6728. return false;
  6729. }
  6730. }
  6731. var elms = !Array.isArray(elm) ? [elm] : elm;
  6732. return Sizzle(selector, elms[0].ownerDocument || elms[0], null, elms).length > 0;
  6733. };
  6734. var getParents = function (elm, selector, root, collect) {
  6735. var result = [];
  6736. var selectorVal;
  6737. var node = get(elm);
  6738. collect = collect === undefined;
  6739. root = root || (getRoot().nodeName !== 'BODY' ? getRoot().parentNode : null);
  6740. if (Tools.is(selector, 'string')) {
  6741. selectorVal = selector;
  6742. if (selector === '*') {
  6743. selector = function (node) {
  6744. return node.nodeType === 1;
  6745. };
  6746. } else {
  6747. selector = function (node) {
  6748. return is(node, selectorVal);
  6749. };
  6750. }
  6751. }
  6752. while (node) {
  6753. if (node === root || isNullable(node.nodeType) || isDocument$1(node) || isDocumentFragment(node)) {
  6754. break;
  6755. }
  6756. if (!selector || typeof selector === 'function' && selector(node)) {
  6757. if (collect) {
  6758. result.push(node);
  6759. } else {
  6760. return [node];
  6761. }
  6762. }
  6763. node = node.parentNode;
  6764. }
  6765. return collect ? result : null;
  6766. };
  6767. var getParent = function (node, selector, root) {
  6768. var parents = getParents(node, selector, root, false);
  6769. return parents && parents.length > 0 ? parents[0] : null;
  6770. };
  6771. var _findSib = function (node, selector, name) {
  6772. var func = selector;
  6773. if (node) {
  6774. if (typeof selector === 'string') {
  6775. func = function (node) {
  6776. return is(node, selector);
  6777. };
  6778. }
  6779. for (node = node[name]; node; node = node[name]) {
  6780. if (typeof func === 'function' && func(node)) {
  6781. return node;
  6782. }
  6783. }
  6784. }
  6785. return null;
  6786. };
  6787. var getNext = function (node, selector) {
  6788. return _findSib(node, selector, 'nextSibling');
  6789. };
  6790. var getPrev = function (node, selector) {
  6791. return _findSib(node, selector, 'previousSibling');
  6792. };
  6793. var select = function (selector, scope) {
  6794. return Sizzle(selector, get(scope) || settings.root_element || doc, []);
  6795. };
  6796. var run = function (elm, func, scope) {
  6797. var result;
  6798. var node = typeof elm === 'string' ? get(elm) : elm;
  6799. if (!node) {
  6800. return false;
  6801. }
  6802. if (Tools.isArray(node) && (node.length || node.length === 0)) {
  6803. result = [];
  6804. each$f(node, function (elm, i) {
  6805. if (elm) {
  6806. result.push(func.call(scope, typeof elm === 'string' ? get(elm) : elm, i));
  6807. }
  6808. });
  6809. return result;
  6810. }
  6811. var context = scope ? scope : this;
  6812. return func.call(context, node);
  6813. };
  6814. var setAttribs = function (elm, attrs) {
  6815. $$(elm).each(function (i, node) {
  6816. each$f(attrs, function (value, name) {
  6817. setAttrib(node, name, value);
  6818. });
  6819. });
  6820. };
  6821. var setHTML = function (elm, html) {
  6822. var $elm = $$(elm);
  6823. if (isIE) {
  6824. $elm.each(function (i, target) {
  6825. if (target.canHaveHTML === false) {
  6826. return;
  6827. }
  6828. while (target.firstChild) {
  6829. target.removeChild(target.firstChild);
  6830. }
  6831. try {
  6832. target.innerHTML = '<br>' + html;
  6833. target.removeChild(target.firstChild);
  6834. } catch (ex) {
  6835. DomQuery('<div></div>').html('<br>' + html).contents().slice(1).appendTo(target);
  6836. }
  6837. return html;
  6838. });
  6839. } else {
  6840. $elm.html(html);
  6841. }
  6842. };
  6843. var add = function (parentElm, name, attrs, html, create) {
  6844. return run(parentElm, function (parentElm) {
  6845. var newElm = typeof name === 'string' ? doc.createElement(name) : name;
  6846. setAttribs(newElm, attrs);
  6847. if (html) {
  6848. if (typeof html !== 'string' && html.nodeType) {
  6849. newElm.appendChild(html);
  6850. } else if (typeof html === 'string') {
  6851. setHTML(newElm, html);
  6852. }
  6853. }
  6854. return !create ? parentElm.appendChild(newElm) : newElm;
  6855. });
  6856. };
  6857. var create = function (name, attrs, html) {
  6858. return add(doc.createElement(name), name, attrs, html, true);
  6859. };
  6860. var decode = Entities.decode;
  6861. var encode = Entities.encodeAllRaw;
  6862. var createHTML = function (name, attrs, html) {
  6863. var outHtml = '', key;
  6864. outHtml += '<' + name;
  6865. for (key in attrs) {
  6866. if (hasNonNullableKey(attrs, key)) {
  6867. outHtml += ' ' + key + '="' + encode(attrs[key]) + '"';
  6868. }
  6869. }
  6870. if (typeof html !== 'undefined') {
  6871. return outHtml + '>' + html + '</' + name + '>';
  6872. }
  6873. return outHtml + ' />';
  6874. };
  6875. var createFragment = function (html) {
  6876. var node;
  6877. var container = doc.createElement('div');
  6878. var frag = doc.createDocumentFragment();
  6879. frag.appendChild(container);
  6880. if (html) {
  6881. container.innerHTML = html;
  6882. }
  6883. while (node = container.firstChild) {
  6884. frag.appendChild(node);
  6885. }
  6886. frag.removeChild(container);
  6887. return frag;
  6888. };
  6889. var remove = function (node, keepChildren) {
  6890. var $node = $$(node);
  6891. if (keepChildren) {
  6892. $node.each(function () {
  6893. var child;
  6894. while (child = this.firstChild) {
  6895. if (child.nodeType === 3 && child.data.length === 0) {
  6896. this.removeChild(child);
  6897. } else {
  6898. this.parentNode.insertBefore(child, this);
  6899. }
  6900. }
  6901. }).remove();
  6902. } else {
  6903. $node.remove();
  6904. }
  6905. return $node.length > 1 ? $node.toArray() : $node[0];
  6906. };
  6907. var removeAllAttribs = function (e) {
  6908. return run(e, function (e) {
  6909. var i;
  6910. var attrs = e.attributes;
  6911. for (i = attrs.length - 1; i >= 0; i--) {
  6912. e.removeAttributeNode(attrs.item(i));
  6913. }
  6914. });
  6915. };
  6916. var parseStyle = function (cssText) {
  6917. return styles.parse(cssText);
  6918. };
  6919. var serializeStyle = function (stylesArg, name) {
  6920. return styles.serialize(stylesArg, name);
  6921. };
  6922. var addStyle = function (cssText) {
  6923. var head, styleElm;
  6924. if (self !== DOMUtils.DOM && doc === document) {
  6925. if (addedStyles[cssText]) {
  6926. return;
  6927. }
  6928. addedStyles[cssText] = true;
  6929. }
  6930. styleElm = doc.getElementById('mceDefaultStyles');
  6931. if (!styleElm) {
  6932. styleElm = doc.createElement('style');
  6933. styleElm.id = 'mceDefaultStyles';
  6934. styleElm.type = 'text/css';
  6935. head = doc.getElementsByTagName('head')[0];
  6936. if (head.firstChild) {
  6937. head.insertBefore(styleElm, head.firstChild);
  6938. } else {
  6939. head.appendChild(styleElm);
  6940. }
  6941. }
  6942. if (styleElm.styleSheet) {
  6943. styleElm.styleSheet.cssText += cssText;
  6944. } else {
  6945. styleElm.appendChild(doc.createTextNode(cssText));
  6946. }
  6947. };
  6948. var loadCSS = function (urls) {
  6949. if (!urls) {
  6950. urls = '';
  6951. }
  6952. each$k(urls.split(','), function (url) {
  6953. files[url] = true;
  6954. styleSheetLoader.load(url, noop);
  6955. });
  6956. };
  6957. var toggleClass = function (elm, cls, state) {
  6958. $$(elm).toggleClass(cls, state).each(function () {
  6959. if (this.className === '') {
  6960. DomQuery(this).attr('class', null);
  6961. }
  6962. });
  6963. };
  6964. var addClass = function (elm, cls) {
  6965. $$(elm).addClass(cls);
  6966. };
  6967. var removeClass = function (elm, cls) {
  6968. toggleClass(elm, cls, false);
  6969. };
  6970. var hasClass = function (elm, cls) {
  6971. return $$(elm).hasClass(cls);
  6972. };
  6973. var show = function (elm) {
  6974. $$(elm).show();
  6975. };
  6976. var hide = function (elm) {
  6977. $$(elm).hide();
  6978. };
  6979. var isHidden = function (elm) {
  6980. return $$(elm).css('display') === 'none';
  6981. };
  6982. var uniqueId = function (prefix) {
  6983. return (!prefix ? 'mce_' : prefix) + counter++;
  6984. };
  6985. var getOuterHTML = function (elm) {
  6986. var node = typeof elm === 'string' ? get(elm) : elm;
  6987. return isElement$5(node) ? node.outerHTML : DomQuery('<div></div>').append(DomQuery(node).clone()).html();
  6988. };
  6989. var setOuterHTML = function (elm, html) {
  6990. $$(elm).each(function () {
  6991. try {
  6992. if ('outerHTML' in this) {
  6993. this.outerHTML = html;
  6994. return;
  6995. }
  6996. } catch (ex) {
  6997. }
  6998. remove(DomQuery(this).html(html), true);
  6999. });
  7000. };
  7001. var insertAfter = function (node, reference) {
  7002. var referenceNode = get(reference);
  7003. return run(node, function (node) {
  7004. var parent = referenceNode.parentNode;
  7005. var nextSibling = referenceNode.nextSibling;
  7006. if (nextSibling) {
  7007. parent.insertBefore(node, nextSibling);
  7008. } else {
  7009. parent.appendChild(node);
  7010. }
  7011. return node;
  7012. });
  7013. };
  7014. var replace = function (newElm, oldElm, keepChildren) {
  7015. return run(oldElm, function (oldElm) {
  7016. if (Tools.is(oldElm, 'array')) {
  7017. newElm = newElm.cloneNode(true);
  7018. }
  7019. if (keepChildren) {
  7020. each$f(grep$1(oldElm.childNodes), function (node) {
  7021. newElm.appendChild(node);
  7022. });
  7023. }
  7024. return oldElm.parentNode.replaceChild(newElm, oldElm);
  7025. });
  7026. };
  7027. var rename = function (elm, name) {
  7028. var newElm;
  7029. if (elm.nodeName !== name.toUpperCase()) {
  7030. newElm = create(name);
  7031. each$f(getAttribs(elm), function (attrNode) {
  7032. setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
  7033. });
  7034. replace(newElm, elm, true);
  7035. }
  7036. return newElm || elm;
  7037. };
  7038. var findCommonAncestor = function (a, b) {
  7039. var ps = a, pe;
  7040. while (ps) {
  7041. pe = b;
  7042. while (pe && ps !== pe) {
  7043. pe = pe.parentNode;
  7044. }
  7045. if (ps === pe) {
  7046. break;
  7047. }
  7048. ps = ps.parentNode;
  7049. }
  7050. if (!ps && a.ownerDocument) {
  7051. return a.ownerDocument.documentElement;
  7052. }
  7053. return ps;
  7054. };
  7055. var toHex = function (rgbVal) {
  7056. return styles.toHex(Tools.trim(rgbVal));
  7057. };
  7058. var isNonEmptyElement = function (node) {
  7059. if (isElement$5(node)) {
  7060. var isNamedAnchor = node.nodeName.toLowerCase() === 'a' && !getAttrib(node, 'href') && getAttrib(node, 'id');
  7061. if (getAttrib(node, 'name') || getAttrib(node, 'data-mce-bookmark') || isNamedAnchor) {
  7062. return true;
  7063. }
  7064. }
  7065. return false;
  7066. };
  7067. var isEmpty = function (node, elements) {
  7068. var type, name, brCount = 0;
  7069. if (isNonEmptyElement(node)) {
  7070. return false;
  7071. }
  7072. node = node.firstChild;
  7073. if (node) {
  7074. var walker = new DomTreeWalker(node, node.parentNode);
  7075. var whitespace = schema ? schema.getWhiteSpaceElements() : {};
  7076. elements = elements || (schema ? schema.getNonEmptyElements() : null);
  7077. do {
  7078. type = node.nodeType;
  7079. if (isElement$5(node)) {
  7080. var bogusVal = node.getAttribute('data-mce-bogus');
  7081. if (bogusVal) {
  7082. node = walker.next(bogusVal === 'all');
  7083. continue;
  7084. }
  7085. name = node.nodeName.toLowerCase();
  7086. if (elements && elements[name]) {
  7087. if (name === 'br') {
  7088. brCount++;
  7089. node = walker.next();
  7090. continue;
  7091. }
  7092. return false;
  7093. }
  7094. if (isNonEmptyElement(node)) {
  7095. return false;
  7096. }
  7097. }
  7098. if (type === 8) {
  7099. return false;
  7100. }
  7101. if (type === 3 && !isWhitespaceText(node.nodeValue)) {
  7102. return false;
  7103. }
  7104. if (type === 3 && node.parentNode && whitespace[node.parentNode.nodeName] && isWhitespaceText(node.nodeValue)) {
  7105. return false;
  7106. }
  7107. node = walker.next();
  7108. } while (node);
  7109. }
  7110. return brCount <= 1;
  7111. };
  7112. var createRng = function () {
  7113. return doc.createRange();
  7114. };
  7115. var split = function (parentElm, splitElm, replacementElm) {
  7116. var range = createRng();
  7117. var beforeFragment;
  7118. var afterFragment;
  7119. var parentNode;
  7120. if (parentElm && splitElm) {
  7121. range.setStart(parentElm.parentNode, findNodeIndex(parentElm));
  7122. range.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
  7123. beforeFragment = range.extractContents();
  7124. range = createRng();
  7125. range.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
  7126. range.setEnd(parentElm.parentNode, findNodeIndex(parentElm) + 1);
  7127. afterFragment = range.extractContents();
  7128. parentNode = parentElm.parentNode;
  7129. parentNode.insertBefore(trimNode(self, beforeFragment), parentElm);
  7130. if (replacementElm) {
  7131. parentNode.insertBefore(replacementElm, parentElm);
  7132. } else {
  7133. parentNode.insertBefore(splitElm, parentElm);
  7134. }
  7135. parentNode.insertBefore(trimNode(self, afterFragment), parentElm);
  7136. remove(parentElm);
  7137. return replacementElm || splitElm;
  7138. }
  7139. };
  7140. var bind = function (target, name, func, scope) {
  7141. if (Tools.isArray(target)) {
  7142. var i = target.length;
  7143. var rv = [];
  7144. while (i--) {
  7145. rv[i] = bind(target[i], name, func, scope);
  7146. }
  7147. return rv;
  7148. }
  7149. if (settings.collect && (target === doc || target === win)) {
  7150. boundEvents.push([
  7151. target,
  7152. name,
  7153. func,
  7154. scope
  7155. ]);
  7156. }
  7157. var output = events.bind(target, name, func, scope || self);
  7158. return output;
  7159. };
  7160. var unbind = function (target, name, func) {
  7161. if (Tools.isArray(target)) {
  7162. var i = target.length;
  7163. var rv = [];
  7164. while (i--) {
  7165. rv[i] = unbind(target[i], name, func);
  7166. }
  7167. return rv;
  7168. } else {
  7169. if (boundEvents.length > 0 && (target === doc || target === win)) {
  7170. var i = boundEvents.length;
  7171. while (i--) {
  7172. var item = boundEvents[i];
  7173. if (target === item[0] && (!name || name === item[1]) && (!func || func === item[2])) {
  7174. events.unbind(item[0], item[1], item[2]);
  7175. }
  7176. }
  7177. }
  7178. return events.unbind(target, name, func);
  7179. }
  7180. };
  7181. var fire = function (target, name, evt) {
  7182. return events.fire(target, name, evt);
  7183. };
  7184. var getContentEditable = function (node) {
  7185. if (node && isElement$5(node)) {
  7186. var contentEditable = node.getAttribute('data-mce-contenteditable');
  7187. if (contentEditable && contentEditable !== 'inherit') {
  7188. return contentEditable;
  7189. }
  7190. return node.contentEditable !== 'inherit' ? node.contentEditable : null;
  7191. } else {
  7192. return null;
  7193. }
  7194. };
  7195. var getContentEditableParent = function (node) {
  7196. var root = getRoot();
  7197. var state = null;
  7198. for (; node && node !== root; node = node.parentNode) {
  7199. state = getContentEditable(node);
  7200. if (state !== null) {
  7201. break;
  7202. }
  7203. }
  7204. return state;
  7205. };
  7206. var destroy = function () {
  7207. if (boundEvents.length > 0) {
  7208. var i = boundEvents.length;
  7209. while (i--) {
  7210. var item = boundEvents[i];
  7211. events.unbind(item[0], item[1], item[2]);
  7212. }
  7213. }
  7214. each$j(files, function (_, url) {
  7215. styleSheetLoader.unload(url);
  7216. delete files[url];
  7217. });
  7218. if (Sizzle.setDocument) {
  7219. Sizzle.setDocument();
  7220. }
  7221. };
  7222. var isChildOf = function (node, parent) {
  7223. if (!isIE) {
  7224. return node === parent || parent.contains(node);
  7225. } else {
  7226. while (node) {
  7227. if (parent === node) {
  7228. return true;
  7229. }
  7230. node = node.parentNode;
  7231. }
  7232. return false;
  7233. }
  7234. };
  7235. var dumpRng = function (r) {
  7236. return 'startContainer: ' + r.startContainer.nodeName + ', startOffset: ' + r.startOffset + ', endContainer: ' + r.endContainer.nodeName + ', endOffset: ' + r.endOffset;
  7237. };
  7238. var self = {
  7239. doc: doc,
  7240. settings: settings,
  7241. win: win,
  7242. files: files,
  7243. stdMode: stdMode,
  7244. boxModel: boxModel,
  7245. styleSheetLoader: styleSheetLoader,
  7246. boundEvents: boundEvents,
  7247. styles: styles,
  7248. schema: schema,
  7249. events: events,
  7250. isBlock: isBlock,
  7251. $: $,
  7252. $$: $$,
  7253. root: null,
  7254. clone: clone,
  7255. getRoot: getRoot,
  7256. getViewPort: getViewPort,
  7257. getRect: getRect,
  7258. getSize: getSize,
  7259. getParent: getParent,
  7260. getParents: getParents,
  7261. get: get,
  7262. getNext: getNext,
  7263. getPrev: getPrev,
  7264. select: select,
  7265. is: is,
  7266. add: add,
  7267. create: create,
  7268. createHTML: createHTML,
  7269. createFragment: createFragment,
  7270. remove: remove,
  7271. setStyle: setStyle,
  7272. getStyle: getStyle,
  7273. setStyles: setStyles,
  7274. removeAllAttribs: removeAllAttribs,
  7275. setAttrib: setAttrib,
  7276. setAttribs: setAttribs,
  7277. getAttrib: getAttrib,
  7278. getPos: getPos$1,
  7279. parseStyle: parseStyle,
  7280. serializeStyle: serializeStyle,
  7281. addStyle: addStyle,
  7282. loadCSS: loadCSS,
  7283. addClass: addClass,
  7284. removeClass: removeClass,
  7285. hasClass: hasClass,
  7286. toggleClass: toggleClass,
  7287. show: show,
  7288. hide: hide,
  7289. isHidden: isHidden,
  7290. uniqueId: uniqueId,
  7291. setHTML: setHTML,
  7292. getOuterHTML: getOuterHTML,
  7293. setOuterHTML: setOuterHTML,
  7294. decode: decode,
  7295. encode: encode,
  7296. insertAfter: insertAfter,
  7297. replace: replace,
  7298. rename: rename,
  7299. findCommonAncestor: findCommonAncestor,
  7300. toHex: toHex,
  7301. run: run,
  7302. getAttribs: getAttribs,
  7303. isEmpty: isEmpty,
  7304. createRng: createRng,
  7305. nodeIndex: findNodeIndex,
  7306. split: split,
  7307. bind: bind,
  7308. unbind: unbind,
  7309. fire: fire,
  7310. getContentEditable: getContentEditable,
  7311. getContentEditableParent: getContentEditableParent,
  7312. destroy: destroy,
  7313. isChildOf: isChildOf,
  7314. dumpRng: dumpRng
  7315. };
  7316. var attrHooks = setupAttrHooks(styles, settings, constant(self));
  7317. return self;
  7318. };
  7319. DOMUtils.DOM = DOMUtils(document);
  7320. DOMUtils.nodeIndex = findNodeIndex;
  7321. var DOM$a = DOMUtils.DOM;
  7322. var each$e = Tools.each, grep = Tools.grep;
  7323. var QUEUED = 0;
  7324. var LOADING = 1;
  7325. var LOADED = 2;
  7326. var FAILED = 3;
  7327. var ScriptLoader = function () {
  7328. function ScriptLoader(settings) {
  7329. if (settings === void 0) {
  7330. settings = {};
  7331. }
  7332. this.states = {};
  7333. this.queue = [];
  7334. this.scriptLoadedCallbacks = {};
  7335. this.queueLoadedCallbacks = [];
  7336. this.loading = 0;
  7337. this.settings = settings;
  7338. }
  7339. ScriptLoader.prototype._setReferrerPolicy = function (referrerPolicy) {
  7340. this.settings.referrerPolicy = referrerPolicy;
  7341. };
  7342. ScriptLoader.prototype.loadScript = function (url, success, failure) {
  7343. var dom = DOM$a;
  7344. var elm;
  7345. var cleanup = function () {
  7346. dom.remove(id);
  7347. if (elm) {
  7348. elm.onerror = elm.onload = elm = null;
  7349. }
  7350. };
  7351. var done = function () {
  7352. cleanup();
  7353. success();
  7354. };
  7355. var error = function () {
  7356. cleanup();
  7357. if (isFunction(failure)) {
  7358. failure();
  7359. } else {
  7360. if (typeof console !== 'undefined' && console.log) {
  7361. console.log('Failed to load script: ' + url);
  7362. }
  7363. }
  7364. };
  7365. var id = dom.uniqueId();
  7366. elm = document.createElement('script');
  7367. elm.id = id;
  7368. elm.type = 'text/javascript';
  7369. elm.src = Tools._addCacheSuffix(url);
  7370. if (this.settings.referrerPolicy) {
  7371. dom.setAttrib(elm, 'referrerpolicy', this.settings.referrerPolicy);
  7372. }
  7373. elm.onload = done;
  7374. elm.onerror = error;
  7375. (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
  7376. };
  7377. ScriptLoader.prototype.isDone = function (url) {
  7378. return this.states[url] === LOADED;
  7379. };
  7380. ScriptLoader.prototype.markDone = function (url) {
  7381. this.states[url] = LOADED;
  7382. };
  7383. ScriptLoader.prototype.add = function (url, success, scope, failure) {
  7384. var state = this.states[url];
  7385. this.queue.push(url);
  7386. if (state === undefined) {
  7387. this.states[url] = QUEUED;
  7388. }
  7389. if (success) {
  7390. if (!this.scriptLoadedCallbacks[url]) {
  7391. this.scriptLoadedCallbacks[url] = [];
  7392. }
  7393. this.scriptLoadedCallbacks[url].push({
  7394. success: success,
  7395. failure: failure,
  7396. scope: scope || this
  7397. });
  7398. }
  7399. };
  7400. ScriptLoader.prototype.load = function (url, success, scope, failure) {
  7401. return this.add(url, success, scope, failure);
  7402. };
  7403. ScriptLoader.prototype.remove = function (url) {
  7404. delete this.states[url];
  7405. delete this.scriptLoadedCallbacks[url];
  7406. };
  7407. ScriptLoader.prototype.loadQueue = function (success, scope, failure) {
  7408. this.loadScripts(this.queue, success, scope, failure);
  7409. };
  7410. ScriptLoader.prototype.loadScripts = function (scripts, success, scope, failure) {
  7411. var self = this;
  7412. var failures = [];
  7413. var execCallbacks = function (name, url) {
  7414. each$e(self.scriptLoadedCallbacks[url], function (callback) {
  7415. if (isFunction(callback[name])) {
  7416. callback[name].call(callback.scope);
  7417. }
  7418. });
  7419. self.scriptLoadedCallbacks[url] = undefined;
  7420. };
  7421. self.queueLoadedCallbacks.push({
  7422. success: success,
  7423. failure: failure,
  7424. scope: scope || this
  7425. });
  7426. var loadScripts = function () {
  7427. var loadingScripts = grep(scripts);
  7428. scripts.length = 0;
  7429. each$e(loadingScripts, function (url) {
  7430. if (self.states[url] === LOADED) {
  7431. execCallbacks('success', url);
  7432. return;
  7433. }
  7434. if (self.states[url] === FAILED) {
  7435. execCallbacks('failure', url);
  7436. return;
  7437. }
  7438. if (self.states[url] !== LOADING) {
  7439. self.states[url] = LOADING;
  7440. self.loading++;
  7441. self.loadScript(url, function () {
  7442. self.states[url] = LOADED;
  7443. self.loading--;
  7444. execCallbacks('success', url);
  7445. loadScripts();
  7446. }, function () {
  7447. self.states[url] = FAILED;
  7448. self.loading--;
  7449. failures.push(url);
  7450. execCallbacks('failure', url);
  7451. loadScripts();
  7452. });
  7453. }
  7454. });
  7455. if (!self.loading) {
  7456. var notifyCallbacks = self.queueLoadedCallbacks.slice(0);
  7457. self.queueLoadedCallbacks.length = 0;
  7458. each$e(notifyCallbacks, function (callback) {
  7459. if (failures.length === 0) {
  7460. if (isFunction(callback.success)) {
  7461. callback.success.call(callback.scope);
  7462. }
  7463. } else {
  7464. if (isFunction(callback.failure)) {
  7465. callback.failure.call(callback.scope, failures);
  7466. }
  7467. }
  7468. });
  7469. }
  7470. };
  7471. loadScripts();
  7472. };
  7473. ScriptLoader.ScriptLoader = new ScriptLoader();
  7474. return ScriptLoader;
  7475. }();
  7476. var Cell = function (initial) {
  7477. var value = initial;
  7478. var get = function () {
  7479. return value;
  7480. };
  7481. var set = function (v) {
  7482. value = v;
  7483. };
  7484. return {
  7485. get: get,
  7486. set: set
  7487. };
  7488. };
  7489. var isRaw = function (str) {
  7490. return isObject(str) && has$2(str, 'raw');
  7491. };
  7492. var isTokenised = function (str) {
  7493. return isArray$1(str) && str.length > 1;
  7494. };
  7495. var data = {};
  7496. var currentCode = Cell('en');
  7497. var getLanguageData = function () {
  7498. return get$9(data, currentCode.get());
  7499. };
  7500. var getData = function () {
  7501. return map$2(data, function (value) {
  7502. return __assign({}, value);
  7503. });
  7504. };
  7505. var setCode = function (newCode) {
  7506. if (newCode) {
  7507. currentCode.set(newCode);
  7508. }
  7509. };
  7510. var getCode = function () {
  7511. return currentCode.get();
  7512. };
  7513. var add$4 = function (code, items) {
  7514. var langData = data[code];
  7515. if (!langData) {
  7516. data[code] = langData = {};
  7517. }
  7518. each$j(items, function (translation, name) {
  7519. langData[name.toLowerCase()] = translation;
  7520. });
  7521. };
  7522. var translate = function (text) {
  7523. var langData = getLanguageData().getOr({});
  7524. var toString = function (obj) {
  7525. if (isFunction(obj)) {
  7526. return Object.prototype.toString.call(obj);
  7527. }
  7528. return !isEmpty(obj) ? '' + obj : '';
  7529. };
  7530. var isEmpty = function (text) {
  7531. return text === '' || text === null || text === undefined;
  7532. };
  7533. var getLangData = function (text) {
  7534. var textstr = toString(text);
  7535. return get$9(langData, textstr.toLowerCase()).map(toString).getOr(textstr);
  7536. };
  7537. var removeContext = function (str) {
  7538. return str.replace(/{context:\w+}$/, '');
  7539. };
  7540. if (isEmpty(text)) {
  7541. return '';
  7542. }
  7543. if (isRaw(text)) {
  7544. return toString(text.raw);
  7545. }
  7546. if (isTokenised(text)) {
  7547. var values_1 = text.slice(1);
  7548. var substitued = getLangData(text[0]).replace(/\{([0-9]+)\}/g, function ($1, $2) {
  7549. return has$2(values_1, $2) ? toString(values_1[$2]) : $1;
  7550. });
  7551. return removeContext(substitued);
  7552. }
  7553. return removeContext(getLangData(text));
  7554. };
  7555. var isRtl$1 = function () {
  7556. return getLanguageData().bind(function (items) {
  7557. return get$9(items, '_dir');
  7558. }).exists(function (dir) {
  7559. return dir === 'rtl';
  7560. });
  7561. };
  7562. var hasCode = function (code) {
  7563. return has$2(data, code);
  7564. };
  7565. var I18n = {
  7566. getData: getData,
  7567. setCode: setCode,
  7568. getCode: getCode,
  7569. add: add$4,
  7570. translate: translate,
  7571. isRtl: isRtl$1,
  7572. hasCode: hasCode
  7573. };
  7574. var AddOnManager = function () {
  7575. var items = [];
  7576. var urls = {};
  7577. var lookup = {};
  7578. var _listeners = [];
  7579. var runListeners = function (name, state) {
  7580. var matchedListeners = filter$4(_listeners, function (listener) {
  7581. return listener.name === name && listener.state === state;
  7582. });
  7583. each$k(matchedListeners, function (listener) {
  7584. return listener.callback();
  7585. });
  7586. };
  7587. var get = function (name) {
  7588. if (lookup[name]) {
  7589. return lookup[name].instance;
  7590. }
  7591. return undefined;
  7592. };
  7593. var dependencies = function (name) {
  7594. var result;
  7595. if (lookup[name]) {
  7596. result = lookup[name].dependencies;
  7597. }
  7598. return result || [];
  7599. };
  7600. var requireLangPack = function (name, languages) {
  7601. if (AddOnManager.languageLoad !== false) {
  7602. waitFor(name, function () {
  7603. var language = I18n.getCode();
  7604. var wrappedLanguages = ',' + (languages || '') + ',';
  7605. if (!language || languages && wrappedLanguages.indexOf(',' + language + ',') === -1) {
  7606. return;
  7607. }
  7608. ScriptLoader.ScriptLoader.add(urls[name] + '/langs/' + language + '.js');
  7609. }, 'loaded');
  7610. }
  7611. };
  7612. var add = function (id, addOn, dependencies) {
  7613. var addOnConstructor = addOn;
  7614. items.push(addOnConstructor);
  7615. lookup[id] = {
  7616. instance: addOnConstructor,
  7617. dependencies: dependencies
  7618. };
  7619. runListeners(id, 'added');
  7620. return addOnConstructor;
  7621. };
  7622. var remove = function (name) {
  7623. delete urls[name];
  7624. delete lookup[name];
  7625. };
  7626. var createUrl = function (baseUrl, dep) {
  7627. if (typeof dep === 'object') {
  7628. return dep;
  7629. }
  7630. return typeof baseUrl === 'string' ? {
  7631. prefix: '',
  7632. resource: dep,
  7633. suffix: ''
  7634. } : {
  7635. prefix: baseUrl.prefix,
  7636. resource: dep,
  7637. suffix: baseUrl.suffix
  7638. };
  7639. };
  7640. var addComponents = function (pluginName, scripts) {
  7641. var pluginUrl = urls[pluginName];
  7642. each$k(scripts, function (script) {
  7643. ScriptLoader.ScriptLoader.add(pluginUrl + '/' + script);
  7644. });
  7645. };
  7646. var loadDependencies = function (name, addOnUrl, success, scope) {
  7647. var deps = dependencies(name);
  7648. each$k(deps, function (dep) {
  7649. var newUrl = createUrl(addOnUrl, dep);
  7650. load(newUrl.resource, newUrl, undefined, undefined);
  7651. });
  7652. if (success) {
  7653. if (scope) {
  7654. success.call(scope);
  7655. } else {
  7656. success.call(ScriptLoader);
  7657. }
  7658. }
  7659. };
  7660. var load = function (name, addOnUrl, success, scope, failure) {
  7661. if (urls[name]) {
  7662. return;
  7663. }
  7664. var urlString = typeof addOnUrl === 'string' ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
  7665. if (urlString.indexOf('/') !== 0 && urlString.indexOf('://') === -1) {
  7666. urlString = AddOnManager.baseURL + '/' + urlString;
  7667. }
  7668. urls[name] = urlString.substring(0, urlString.lastIndexOf('/'));
  7669. var done = function () {
  7670. runListeners(name, 'loaded');
  7671. loadDependencies(name, addOnUrl, success, scope);
  7672. };
  7673. if (lookup[name]) {
  7674. done();
  7675. } else {
  7676. ScriptLoader.ScriptLoader.add(urlString, done, scope, failure);
  7677. }
  7678. };
  7679. var waitFor = function (name, callback, state) {
  7680. if (state === void 0) {
  7681. state = 'added';
  7682. }
  7683. if (has$2(lookup, name) && state === 'added') {
  7684. callback();
  7685. } else if (has$2(urls, name) && state === 'loaded') {
  7686. callback();
  7687. } else {
  7688. _listeners.push({
  7689. name: name,
  7690. state: state,
  7691. callback: callback
  7692. });
  7693. }
  7694. };
  7695. return {
  7696. items: items,
  7697. urls: urls,
  7698. lookup: lookup,
  7699. _listeners: _listeners,
  7700. get: get,
  7701. dependencies: dependencies,
  7702. requireLangPack: requireLangPack,
  7703. add: add,
  7704. remove: remove,
  7705. createUrl: createUrl,
  7706. addComponents: addComponents,
  7707. load: load,
  7708. waitFor: waitFor
  7709. };
  7710. };
  7711. AddOnManager.languageLoad = true;
  7712. AddOnManager.baseURL = '';
  7713. AddOnManager.PluginManager = AddOnManager();
  7714. AddOnManager.ThemeManager = AddOnManager();
  7715. var singleton = function (doRevoke) {
  7716. var subject = Cell(Optional.none());
  7717. var revoke = function () {
  7718. return subject.get().each(doRevoke);
  7719. };
  7720. var clear = function () {
  7721. revoke();
  7722. subject.set(Optional.none());
  7723. };
  7724. var isSet = function () {
  7725. return subject.get().isSome();
  7726. };
  7727. var get = function () {
  7728. return subject.get();
  7729. };
  7730. var set = function (s) {
  7731. revoke();
  7732. subject.set(Optional.some(s));
  7733. };
  7734. return {
  7735. clear: clear,
  7736. isSet: isSet,
  7737. get: get,
  7738. set: set
  7739. };
  7740. };
  7741. var value = function () {
  7742. var subject = singleton(noop);
  7743. var on = function (f) {
  7744. return subject.get().each(f);
  7745. };
  7746. return __assign(__assign({}, subject), { on: on });
  7747. };
  7748. var first = function (fn, rate) {
  7749. var timer = null;
  7750. var cancel = function () {
  7751. if (!isNull(timer)) {
  7752. clearTimeout(timer);
  7753. timer = null;
  7754. }
  7755. };
  7756. var throttle = function () {
  7757. var args = [];
  7758. for (var _i = 0; _i < arguments.length; _i++) {
  7759. args[_i] = arguments[_i];
  7760. }
  7761. if (isNull(timer)) {
  7762. timer = setTimeout(function () {
  7763. timer = null;
  7764. fn.apply(null, args);
  7765. }, rate);
  7766. }
  7767. };
  7768. return {
  7769. cancel: cancel,
  7770. throttle: throttle
  7771. };
  7772. };
  7773. var last = function (fn, rate) {
  7774. var timer = null;
  7775. var cancel = function () {
  7776. if (!isNull(timer)) {
  7777. clearTimeout(timer);
  7778. timer = null;
  7779. }
  7780. };
  7781. var throttle = function () {
  7782. var args = [];
  7783. for (var _i = 0; _i < arguments.length; _i++) {
  7784. args[_i] = arguments[_i];
  7785. }
  7786. cancel();
  7787. timer = setTimeout(function () {
  7788. timer = null;
  7789. fn.apply(null, args);
  7790. }, rate);
  7791. };
  7792. return {
  7793. cancel: cancel,
  7794. throttle: throttle
  7795. };
  7796. };
  7797. var read$4 = function (element, attr) {
  7798. var value = get$6(element, attr);
  7799. return value === undefined || value === '' ? [] : value.split(' ');
  7800. };
  7801. var add$3 = function (element, attr, id) {
  7802. var old = read$4(element, attr);
  7803. var nu = old.concat([id]);
  7804. set$1(element, attr, nu.join(' '));
  7805. return true;
  7806. };
  7807. var remove$5 = function (element, attr, id) {
  7808. var nu = filter$4(read$4(element, attr), function (v) {
  7809. return v !== id;
  7810. });
  7811. if (nu.length > 0) {
  7812. set$1(element, attr, nu.join(' '));
  7813. } else {
  7814. remove$6(element, attr);
  7815. }
  7816. return false;
  7817. };
  7818. var supports = function (element) {
  7819. return element.dom.classList !== undefined;
  7820. };
  7821. var get$4 = function (element) {
  7822. return read$4(element, 'class');
  7823. };
  7824. var add$2 = function (element, clazz) {
  7825. return add$3(element, 'class', clazz);
  7826. };
  7827. var remove$4 = function (element, clazz) {
  7828. return remove$5(element, 'class', clazz);
  7829. };
  7830. var add$1 = function (element, clazz) {
  7831. if (supports(element)) {
  7832. element.dom.classList.add(clazz);
  7833. } else {
  7834. add$2(element, clazz);
  7835. }
  7836. };
  7837. var cleanClass = function (element) {
  7838. var classList = supports(element) ? element.dom.classList : get$4(element);
  7839. if (classList.length === 0) {
  7840. remove$6(element, 'class');
  7841. }
  7842. };
  7843. var remove$3 = function (element, clazz) {
  7844. if (supports(element)) {
  7845. var classList = element.dom.classList;
  7846. classList.remove(clazz);
  7847. } else {
  7848. remove$4(element, clazz);
  7849. }
  7850. cleanClass(element);
  7851. };
  7852. var has = function (element, clazz) {
  7853. return supports(element) && element.dom.classList.contains(clazz);
  7854. };
  7855. var descendants$1 = function (scope, predicate) {
  7856. var result = [];
  7857. each$k(children(scope), function (x) {
  7858. if (predicate(x)) {
  7859. result = result.concat([x]);
  7860. }
  7861. result = result.concat(descendants$1(x, predicate));
  7862. });
  7863. return result;
  7864. };
  7865. var descendants = function (scope, selector) {
  7866. return all(selector, scope);
  7867. };
  7868. var annotation = constant('mce-annotation');
  7869. var dataAnnotation = constant('data-mce-annotation');
  7870. var dataAnnotationId = constant('data-mce-annotation-uid');
  7871. var identify = function (editor, annotationName) {
  7872. var rng = editor.selection.getRng();
  7873. var start = SugarElement.fromDom(rng.startContainer);
  7874. var root = SugarElement.fromDom(editor.getBody());
  7875. var selector = annotationName.fold(function () {
  7876. return '.' + annotation();
  7877. }, function (an) {
  7878. return '[' + dataAnnotation() + '="' + an + '"]';
  7879. });
  7880. var newStart = child$1(start, rng.startOffset).getOr(start);
  7881. var closest = closest$2(newStart, selector, function (n) {
  7882. return eq(n, root);
  7883. });
  7884. var getAttr = function (c, property) {
  7885. if (has$1(c, property)) {
  7886. return Optional.some(get$6(c, property));
  7887. } else {
  7888. return Optional.none();
  7889. }
  7890. };
  7891. return closest.bind(function (c) {
  7892. return getAttr(c, '' + dataAnnotationId()).bind(function (uid) {
  7893. return getAttr(c, '' + dataAnnotation()).map(function (name) {
  7894. var elements = findMarkers(editor, uid);
  7895. return {
  7896. uid: uid,
  7897. name: name,
  7898. elements: elements
  7899. };
  7900. });
  7901. });
  7902. });
  7903. };
  7904. var isAnnotation = function (elem) {
  7905. return isElement$6(elem) && has(elem, annotation());
  7906. };
  7907. var findMarkers = function (editor, uid) {
  7908. var body = SugarElement.fromDom(editor.getBody());
  7909. return descendants(body, '[' + dataAnnotationId() + '="' + uid + '"]');
  7910. };
  7911. var findAll = function (editor, name) {
  7912. var body = SugarElement.fromDom(editor.getBody());
  7913. var markers = descendants(body, '[' + dataAnnotation() + '="' + name + '"]');
  7914. var directory = {};
  7915. each$k(markers, function (m) {
  7916. var uid = get$6(m, dataAnnotationId());
  7917. var nodesAlready = get$9(directory, uid).getOr([]);
  7918. directory[uid] = nodesAlready.concat([m]);
  7919. });
  7920. return directory;
  7921. };
  7922. var setup$n = function (editor, _registry) {
  7923. var changeCallbacks = Cell({});
  7924. var initData = function () {
  7925. return {
  7926. listeners: [],
  7927. previous: value()
  7928. };
  7929. };
  7930. var withCallbacks = function (name, f) {
  7931. updateCallbacks(name, function (data) {
  7932. f(data);
  7933. return data;
  7934. });
  7935. };
  7936. var updateCallbacks = function (name, f) {
  7937. var callbackMap = changeCallbacks.get();
  7938. var data = get$9(callbackMap, name).getOrThunk(initData);
  7939. var outputData = f(data);
  7940. callbackMap[name] = outputData;
  7941. changeCallbacks.set(callbackMap);
  7942. };
  7943. var fireCallbacks = function (name, uid, elements) {
  7944. withCallbacks(name, function (data) {
  7945. each$k(data.listeners, function (f) {
  7946. return f(true, name, {
  7947. uid: uid,
  7948. nodes: map$3(elements, function (elem) {
  7949. return elem.dom;
  7950. })
  7951. });
  7952. });
  7953. });
  7954. };
  7955. var fireNoAnnotation = function (name) {
  7956. withCallbacks(name, function (data) {
  7957. each$k(data.listeners, function (f) {
  7958. return f(false, name);
  7959. });
  7960. });
  7961. };
  7962. var onNodeChange = last(function () {
  7963. var callbackMap = changeCallbacks.get();
  7964. var annotations = sort(keys(callbackMap));
  7965. each$k(annotations, function (name) {
  7966. updateCallbacks(name, function (data) {
  7967. var prev = data.previous.get();
  7968. identify(editor, Optional.some(name)).fold(function () {
  7969. if (prev.isSome()) {
  7970. fireNoAnnotation(name);
  7971. data.previous.clear();
  7972. }
  7973. }, function (_a) {
  7974. var uid = _a.uid, name = _a.name, elements = _a.elements;
  7975. if (!is$1(prev, uid)) {
  7976. fireCallbacks(name, uid, elements);
  7977. data.previous.set(uid);
  7978. }
  7979. });
  7980. return {
  7981. previous: data.previous,
  7982. listeners: data.listeners
  7983. };
  7984. });
  7985. });
  7986. }, 30);
  7987. editor.on('remove', function () {
  7988. onNodeChange.cancel();
  7989. });
  7990. editor.on('NodeChange', function () {
  7991. onNodeChange.throttle();
  7992. });
  7993. var addListener = function (name, f) {
  7994. updateCallbacks(name, function (data) {
  7995. return {
  7996. previous: data.previous,
  7997. listeners: data.listeners.concat([f])
  7998. };
  7999. });
  8000. };
  8001. return { addListener: addListener };
  8002. };
  8003. var setup$m = function (editor, registry) {
  8004. var identifyParserNode = function (span) {
  8005. return Optional.from(span.attr(dataAnnotation())).bind(registry.lookup);
  8006. };
  8007. editor.on('init', function () {
  8008. editor.serializer.addNodeFilter('span', function (spans) {
  8009. each$k(spans, function (span) {
  8010. identifyParserNode(span).each(function (settings) {
  8011. if (settings.persistent === false) {
  8012. span.unwrap();
  8013. }
  8014. });
  8015. });
  8016. });
  8017. });
  8018. };
  8019. var create$7 = function () {
  8020. var annotations = {};
  8021. var register = function (name, settings) {
  8022. annotations[name] = {
  8023. name: name,
  8024. settings: settings
  8025. };
  8026. };
  8027. var lookup = function (name) {
  8028. return get$9(annotations, name).map(function (a) {
  8029. return a.settings;
  8030. });
  8031. };
  8032. return {
  8033. register: register,
  8034. lookup: lookup
  8035. };
  8036. };
  8037. var unique = 0;
  8038. var generate = function (prefix) {
  8039. var date = new Date();
  8040. var time = date.getTime();
  8041. var random = Math.floor(Math.random() * 1000000000);
  8042. unique++;
  8043. return prefix + '_' + random + unique + String(time);
  8044. };
  8045. var add = function (element, classes) {
  8046. each$k(classes, function (x) {
  8047. add$1(element, x);
  8048. });
  8049. };
  8050. var fromHtml = function (html, scope) {
  8051. var doc = scope || document;
  8052. var div = doc.createElement('div');
  8053. div.innerHTML = html;
  8054. return children(SugarElement.fromDom(div));
  8055. };
  8056. var fromDom$1 = function (nodes) {
  8057. return map$3(nodes, SugarElement.fromDom);
  8058. };
  8059. var get$3 = function (element) {
  8060. return element.dom.innerHTML;
  8061. };
  8062. var set = function (element, content) {
  8063. var owner = owner$1(element);
  8064. var docDom = owner.dom;
  8065. var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  8066. var contentElements = fromHtml(content, docDom);
  8067. append(fragment, contentElements);
  8068. empty(element);
  8069. append$1(element, fragment);
  8070. };
  8071. var clone$1 = function (original, isDeep) {
  8072. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  8073. };
  8074. var shallow = function (original) {
  8075. return clone$1(original, false);
  8076. };
  8077. var deep$1 = function (original) {
  8078. return clone$1(original, true);
  8079. };
  8080. var TextWalker = function (startNode, rootNode, isBoundary) {
  8081. if (isBoundary === void 0) {
  8082. isBoundary = never;
  8083. }
  8084. var walker = new DomTreeWalker(startNode, rootNode);
  8085. var walk = function (direction) {
  8086. var next;
  8087. do {
  8088. next = walker[direction]();
  8089. } while (next && !isText$7(next) && !isBoundary(next));
  8090. return Optional.from(next).filter(isText$7);
  8091. };
  8092. return {
  8093. current: function () {
  8094. return Optional.from(walker.current()).filter(isText$7);
  8095. },
  8096. next: function () {
  8097. return walk('next');
  8098. },
  8099. prev: function () {
  8100. return walk('prev');
  8101. },
  8102. prev2: function () {
  8103. return walk('prev2');
  8104. }
  8105. };
  8106. };
  8107. var TextSeeker = function (dom, isBoundary) {
  8108. var isBlockBoundary = isBoundary ? isBoundary : function (node) {
  8109. return dom.isBlock(node) || isBr$5(node) || isContentEditableFalse$b(node);
  8110. };
  8111. var walk = function (node, offset, walker, process) {
  8112. if (isText$7(node)) {
  8113. var newOffset = process(node, offset, node.data);
  8114. if (newOffset !== -1) {
  8115. return Optional.some({
  8116. container: node,
  8117. offset: newOffset
  8118. });
  8119. }
  8120. }
  8121. return walker().bind(function (next) {
  8122. return walk(next.container, next.offset, walker, process);
  8123. });
  8124. };
  8125. var backwards = function (node, offset, process, root) {
  8126. var walker = TextWalker(node, root, isBlockBoundary);
  8127. return walk(node, offset, function () {
  8128. return walker.prev().map(function (prev) {
  8129. return {
  8130. container: prev,
  8131. offset: prev.length
  8132. };
  8133. });
  8134. }, process).getOrNull();
  8135. };
  8136. var forwards = function (node, offset, process, root) {
  8137. var walker = TextWalker(node, root, isBlockBoundary);
  8138. return walk(node, offset, function () {
  8139. return walker.next().map(function (next) {
  8140. return {
  8141. container: next,
  8142. offset: 0
  8143. };
  8144. });
  8145. }, process).getOrNull();
  8146. };
  8147. return {
  8148. backwards: backwards,
  8149. forwards: forwards
  8150. };
  8151. };
  8152. var round$2 = Math.round;
  8153. var clone = function (rect) {
  8154. if (!rect) {
  8155. return {
  8156. left: 0,
  8157. top: 0,
  8158. bottom: 0,
  8159. right: 0,
  8160. width: 0,
  8161. height: 0
  8162. };
  8163. }
  8164. return {
  8165. left: round$2(rect.left),
  8166. top: round$2(rect.top),
  8167. bottom: round$2(rect.bottom),
  8168. right: round$2(rect.right),
  8169. width: round$2(rect.width),
  8170. height: round$2(rect.height)
  8171. };
  8172. };
  8173. var collapse = function (rect, toStart) {
  8174. rect = clone(rect);
  8175. if (toStart) {
  8176. rect.right = rect.left;
  8177. } else {
  8178. rect.left = rect.left + rect.width;
  8179. rect.right = rect.left;
  8180. }
  8181. rect.width = 0;
  8182. return rect;
  8183. };
  8184. var isEqual = function (rect1, rect2) {
  8185. return rect1.left === rect2.left && rect1.top === rect2.top && rect1.bottom === rect2.bottom && rect1.right === rect2.right;
  8186. };
  8187. var isValidOverflow = function (overflowY, rect1, rect2) {
  8188. return overflowY >= 0 && overflowY <= Math.min(rect1.height, rect2.height) / 2;
  8189. };
  8190. var isAbove$1 = function (rect1, rect2) {
  8191. var halfHeight = Math.min(rect2.height / 2, rect1.height / 2);
  8192. if (rect1.bottom - halfHeight < rect2.top) {
  8193. return true;
  8194. }
  8195. if (rect1.top > rect2.bottom) {
  8196. return false;
  8197. }
  8198. return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
  8199. };
  8200. var isBelow$1 = function (rect1, rect2) {
  8201. if (rect1.top > rect2.bottom) {
  8202. return true;
  8203. }
  8204. if (rect1.bottom < rect2.top) {
  8205. return false;
  8206. }
  8207. return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
  8208. };
  8209. var containsXY = function (rect, clientX, clientY) {
  8210. return clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
  8211. };
  8212. var clamp$2 = function (value, min, max) {
  8213. return Math.min(Math.max(value, min), max);
  8214. };
  8215. var getSelectedNode = function (range) {
  8216. var startContainer = range.startContainer, startOffset = range.startOffset;
  8217. if (startContainer.hasChildNodes() && range.endOffset === startOffset + 1) {
  8218. return startContainer.childNodes[startOffset];
  8219. }
  8220. return null;
  8221. };
  8222. var getNode$1 = function (container, offset) {
  8223. if (isElement$5(container) && container.hasChildNodes()) {
  8224. var childNodes = container.childNodes;
  8225. var safeOffset = clamp$2(offset, 0, childNodes.length - 1);
  8226. return childNodes[safeOffset];
  8227. } else {
  8228. return container;
  8229. }
  8230. };
  8231. var getNodeUnsafe = function (container, offset) {
  8232. if (offset < 0 && isElement$5(container) && container.hasChildNodes()) {
  8233. return undefined;
  8234. } else {
  8235. return getNode$1(container, offset);
  8236. }
  8237. };
  8238. 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]');
  8239. var isExtendingChar = function (ch) {
  8240. return typeof ch === 'string' && ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
  8241. };
  8242. var or = function () {
  8243. var args = [];
  8244. for (var _i = 0; _i < arguments.length; _i++) {
  8245. args[_i] = arguments[_i];
  8246. }
  8247. return function (x) {
  8248. for (var i = 0; i < args.length; i++) {
  8249. if (args[i](x)) {
  8250. return true;
  8251. }
  8252. }
  8253. return false;
  8254. };
  8255. };
  8256. var and = function () {
  8257. var args = [];
  8258. for (var _i = 0; _i < arguments.length; _i++) {
  8259. args[_i] = arguments[_i];
  8260. }
  8261. return function (x) {
  8262. for (var i = 0; i < args.length; i++) {
  8263. if (!args[i](x)) {
  8264. return false;
  8265. }
  8266. }
  8267. return true;
  8268. };
  8269. };
  8270. var isElement$3 = isElement$5;
  8271. var isCaretCandidate$2 = isCaretCandidate$3;
  8272. var isBlock$1 = matchStyleValues('display', 'block table');
  8273. var isFloated = matchStyleValues('float', 'left right');
  8274. var isValidElementCaretCandidate = and(isElement$3, isCaretCandidate$2, not(isFloated));
  8275. var isNotPre = not(matchStyleValues('white-space', 'pre pre-line pre-wrap'));
  8276. var isText$4 = isText$7;
  8277. var isBr$2 = isBr$5;
  8278. var nodeIndex$1 = DOMUtils.nodeIndex;
  8279. var resolveIndex$1 = getNodeUnsafe;
  8280. var createRange$1 = function (doc) {
  8281. return 'createRange' in doc ? doc.createRange() : DOMUtils.DOM.createRng();
  8282. };
  8283. var isWhiteSpace$1 = function (chr) {
  8284. return chr && /[\r\n\t ]/.test(chr);
  8285. };
  8286. var isRange = function (rng) {
  8287. return !!rng.setStart && !!rng.setEnd;
  8288. };
  8289. var isHiddenWhiteSpaceRange = function (range) {
  8290. var container = range.startContainer;
  8291. var offset = range.startOffset;
  8292. if (isWhiteSpace$1(range.toString()) && isNotPre(container.parentNode) && isText$7(container)) {
  8293. var text = container.data;
  8294. if (isWhiteSpace$1(text[offset - 1]) || isWhiteSpace$1(text[offset + 1])) {
  8295. return true;
  8296. }
  8297. }
  8298. return false;
  8299. };
  8300. var getBrClientRect = function (brNode) {
  8301. var doc = brNode.ownerDocument;
  8302. var rng = createRange$1(doc);
  8303. var nbsp$1 = doc.createTextNode(nbsp);
  8304. var parentNode = brNode.parentNode;
  8305. parentNode.insertBefore(nbsp$1, brNode);
  8306. rng.setStart(nbsp$1, 0);
  8307. rng.setEnd(nbsp$1, 1);
  8308. var clientRect = clone(rng.getBoundingClientRect());
  8309. parentNode.removeChild(nbsp$1);
  8310. return clientRect;
  8311. };
  8312. var getBoundingClientRectWebKitText = function (rng) {
  8313. var sc = rng.startContainer;
  8314. var ec = rng.endContainer;
  8315. var so = rng.startOffset;
  8316. var eo = rng.endOffset;
  8317. if (sc === ec && isText$7(ec) && so === 0 && eo === 1) {
  8318. var newRng = rng.cloneRange();
  8319. newRng.setEndAfter(ec);
  8320. return getBoundingClientRect$1(newRng);
  8321. } else {
  8322. return null;
  8323. }
  8324. };
  8325. var isZeroRect = function (r) {
  8326. return r.left === 0 && r.right === 0 && r.top === 0 && r.bottom === 0;
  8327. };
  8328. var getBoundingClientRect$1 = function (item) {
  8329. var clientRect;
  8330. var clientRects = item.getClientRects();
  8331. if (clientRects.length > 0) {
  8332. clientRect = clone(clientRects[0]);
  8333. } else {
  8334. clientRect = clone(item.getBoundingClientRect());
  8335. }
  8336. if (!isRange(item) && isBr$2(item) && isZeroRect(clientRect)) {
  8337. return getBrClientRect(item);
  8338. }
  8339. if (isZeroRect(clientRect) && isRange(item)) {
  8340. return getBoundingClientRectWebKitText(item);
  8341. }
  8342. return clientRect;
  8343. };
  8344. var collapseAndInflateWidth = function (clientRect, toStart) {
  8345. var newClientRect = collapse(clientRect, toStart);
  8346. newClientRect.width = 1;
  8347. newClientRect.right = newClientRect.left + 1;
  8348. return newClientRect;
  8349. };
  8350. var getCaretPositionClientRects = function (caretPosition) {
  8351. var clientRects = [];
  8352. var addUniqueAndValidRect = function (clientRect) {
  8353. if (clientRect.height === 0) {
  8354. return;
  8355. }
  8356. if (clientRects.length > 0) {
  8357. if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
  8358. return;
  8359. }
  8360. }
  8361. clientRects.push(clientRect);
  8362. };
  8363. var addCharacterOffset = function (container, offset) {
  8364. var range = createRange$1(container.ownerDocument);
  8365. if (offset < container.data.length) {
  8366. if (isExtendingChar(container.data[offset])) {
  8367. return clientRects;
  8368. }
  8369. if (isExtendingChar(container.data[offset - 1])) {
  8370. range.setStart(container, offset);
  8371. range.setEnd(container, offset + 1);
  8372. if (!isHiddenWhiteSpaceRange(range)) {
  8373. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  8374. return clientRects;
  8375. }
  8376. }
  8377. }
  8378. if (offset > 0) {
  8379. range.setStart(container, offset - 1);
  8380. range.setEnd(container, offset);
  8381. if (!isHiddenWhiteSpaceRange(range)) {
  8382. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  8383. }
  8384. }
  8385. if (offset < container.data.length) {
  8386. range.setStart(container, offset);
  8387. range.setEnd(container, offset + 1);
  8388. if (!isHiddenWhiteSpaceRange(range)) {
  8389. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), true));
  8390. }
  8391. }
  8392. };
  8393. var container = caretPosition.container();
  8394. var offset = caretPosition.offset();
  8395. if (isText$4(container)) {
  8396. addCharacterOffset(container, offset);
  8397. return clientRects;
  8398. }
  8399. if (isElement$3(container)) {
  8400. if (caretPosition.isAtEnd()) {
  8401. var node = resolveIndex$1(container, offset);
  8402. if (isText$4(node)) {
  8403. addCharacterOffset(node, node.data.length);
  8404. }
  8405. if (isValidElementCaretCandidate(node) && !isBr$2(node)) {
  8406. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  8407. }
  8408. } else {
  8409. var node = resolveIndex$1(container, offset);
  8410. if (isText$4(node)) {
  8411. addCharacterOffset(node, 0);
  8412. }
  8413. if (isValidElementCaretCandidate(node) && caretPosition.isAtEnd()) {
  8414. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  8415. return clientRects;
  8416. }
  8417. var beforeNode = resolveIndex$1(caretPosition.container(), caretPosition.offset() - 1);
  8418. if (isValidElementCaretCandidate(beforeNode) && !isBr$2(beforeNode)) {
  8419. if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
  8420. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(beforeNode), false));
  8421. }
  8422. }
  8423. if (isValidElementCaretCandidate(node)) {
  8424. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), true));
  8425. }
  8426. }
  8427. }
  8428. return clientRects;
  8429. };
  8430. var CaretPosition = function (container, offset, clientRects) {
  8431. var isAtStart = function () {
  8432. if (isText$4(container)) {
  8433. return offset === 0;
  8434. }
  8435. return offset === 0;
  8436. };
  8437. var isAtEnd = function () {
  8438. if (isText$4(container)) {
  8439. return offset >= container.data.length;
  8440. }
  8441. return offset >= container.childNodes.length;
  8442. };
  8443. var toRange = function () {
  8444. var range = createRange$1(container.ownerDocument);
  8445. range.setStart(container, offset);
  8446. range.setEnd(container, offset);
  8447. return range;
  8448. };
  8449. var getClientRects = function () {
  8450. if (!clientRects) {
  8451. clientRects = getCaretPositionClientRects(CaretPosition(container, offset));
  8452. }
  8453. return clientRects;
  8454. };
  8455. var isVisible = function () {
  8456. return getClientRects().length > 0;
  8457. };
  8458. var isEqual = function (caretPosition) {
  8459. return caretPosition && container === caretPosition.container() && offset === caretPosition.offset();
  8460. };
  8461. var getNode = function (before) {
  8462. return resolveIndex$1(container, before ? offset - 1 : offset);
  8463. };
  8464. return {
  8465. container: constant(container),
  8466. offset: constant(offset),
  8467. toRange: toRange,
  8468. getClientRects: getClientRects,
  8469. isVisible: isVisible,
  8470. isAtStart: isAtStart,
  8471. isAtEnd: isAtEnd,
  8472. isEqual: isEqual,
  8473. getNode: getNode
  8474. };
  8475. };
  8476. CaretPosition.fromRangeStart = function (range) {
  8477. return CaretPosition(range.startContainer, range.startOffset);
  8478. };
  8479. CaretPosition.fromRangeEnd = function (range) {
  8480. return CaretPosition(range.endContainer, range.endOffset);
  8481. };
  8482. CaretPosition.after = function (node) {
  8483. return CaretPosition(node.parentNode, nodeIndex$1(node) + 1);
  8484. };
  8485. CaretPosition.before = function (node) {
  8486. return CaretPosition(node.parentNode, nodeIndex$1(node));
  8487. };
  8488. CaretPosition.isAbove = function (pos1, pos2) {
  8489. return lift2(head(pos2.getClientRects()), last$2(pos1.getClientRects()), isAbove$1).getOr(false);
  8490. };
  8491. CaretPosition.isBelow = function (pos1, pos2) {
  8492. return lift2(last$2(pos2.getClientRects()), head(pos1.getClientRects()), isBelow$1).getOr(false);
  8493. };
  8494. CaretPosition.isAtStart = function (pos) {
  8495. return pos ? pos.isAtStart() : false;
  8496. };
  8497. CaretPosition.isAtEnd = function (pos) {
  8498. return pos ? pos.isAtEnd() : false;
  8499. };
  8500. CaretPosition.isTextPosition = function (pos) {
  8501. return pos ? isText$7(pos.container()) : false;
  8502. };
  8503. CaretPosition.isElementPosition = function (pos) {
  8504. return CaretPosition.isTextPosition(pos) === false;
  8505. };
  8506. var trimEmptyTextNode$1 = function (dom, node) {
  8507. if (isText$7(node) && node.data.length === 0) {
  8508. dom.remove(node);
  8509. }
  8510. };
  8511. var insertNode = function (dom, rng, node) {
  8512. rng.insertNode(node);
  8513. trimEmptyTextNode$1(dom, node.previousSibling);
  8514. trimEmptyTextNode$1(dom, node.nextSibling);
  8515. };
  8516. var insertFragment = function (dom, rng, frag) {
  8517. var firstChild = Optional.from(frag.firstChild);
  8518. var lastChild = Optional.from(frag.lastChild);
  8519. rng.insertNode(frag);
  8520. firstChild.each(function (child) {
  8521. return trimEmptyTextNode$1(dom, child.previousSibling);
  8522. });
  8523. lastChild.each(function (child) {
  8524. return trimEmptyTextNode$1(dom, child.nextSibling);
  8525. });
  8526. };
  8527. var rangeInsertNode = function (dom, rng, node) {
  8528. if (isDocumentFragment(node)) {
  8529. insertFragment(dom, rng, node);
  8530. } else {
  8531. insertNode(dom, rng, node);
  8532. }
  8533. };
  8534. var isText$3 = isText$7;
  8535. var isBogus = isBogus$2;
  8536. var nodeIndex = DOMUtils.nodeIndex;
  8537. var normalizedParent = function (node) {
  8538. var parentNode = node.parentNode;
  8539. if (isBogus(parentNode)) {
  8540. return normalizedParent(parentNode);
  8541. }
  8542. return parentNode;
  8543. };
  8544. var getChildNodes = function (node) {
  8545. if (!node) {
  8546. return [];
  8547. }
  8548. return reduce(node.childNodes, function (result, node) {
  8549. if (isBogus(node) && node.nodeName !== 'BR') {
  8550. result = result.concat(getChildNodes(node));
  8551. } else {
  8552. result.push(node);
  8553. }
  8554. return result;
  8555. }, []);
  8556. };
  8557. var normalizedTextOffset = function (node, offset) {
  8558. while (node = node.previousSibling) {
  8559. if (!isText$3(node)) {
  8560. break;
  8561. }
  8562. offset += node.data.length;
  8563. }
  8564. return offset;
  8565. };
  8566. var equal = function (a) {
  8567. return function (b) {
  8568. return a === b;
  8569. };
  8570. };
  8571. var normalizedNodeIndex = function (node) {
  8572. var nodes, index;
  8573. nodes = getChildNodes(normalizedParent(node));
  8574. index = findIndex$1(nodes, equal(node), node);
  8575. nodes = nodes.slice(0, index + 1);
  8576. var numTextFragments = reduce(nodes, function (result, node, i) {
  8577. if (isText$3(node) && isText$3(nodes[i - 1])) {
  8578. result++;
  8579. }
  8580. return result;
  8581. }, 0);
  8582. nodes = filter$2(nodes, matchNodeNames([node.nodeName]));
  8583. index = findIndex$1(nodes, equal(node), node);
  8584. return index - numTextFragments;
  8585. };
  8586. var createPathItem = function (node) {
  8587. var name;
  8588. if (isText$3(node)) {
  8589. name = 'text()';
  8590. } else {
  8591. name = node.nodeName.toLowerCase();
  8592. }
  8593. return name + '[' + normalizedNodeIndex(node) + ']';
  8594. };
  8595. var parentsUntil$1 = function (root, node, predicate) {
  8596. var parents = [];
  8597. for (node = node.parentNode; node !== root; node = node.parentNode) {
  8598. if (predicate && predicate(node)) {
  8599. break;
  8600. }
  8601. parents.push(node);
  8602. }
  8603. return parents;
  8604. };
  8605. var create$6 = function (root, caretPosition) {
  8606. var container, offset, path = [], outputOffset, childNodes, parents;
  8607. container = caretPosition.container();
  8608. offset = caretPosition.offset();
  8609. if (isText$3(container)) {
  8610. outputOffset = normalizedTextOffset(container, offset);
  8611. } else {
  8612. childNodes = container.childNodes;
  8613. if (offset >= childNodes.length) {
  8614. outputOffset = 'after';
  8615. offset = childNodes.length - 1;
  8616. } else {
  8617. outputOffset = 'before';
  8618. }
  8619. container = childNodes[offset];
  8620. }
  8621. path.push(createPathItem(container));
  8622. parents = parentsUntil$1(root, container);
  8623. parents = filter$2(parents, not(isBogus$2));
  8624. path = path.concat(map$1(parents, function (node) {
  8625. return createPathItem(node);
  8626. }));
  8627. return path.reverse().join('/') + ',' + outputOffset;
  8628. };
  8629. var resolvePathItem = function (node, name, index) {
  8630. var nodes = getChildNodes(node);
  8631. nodes = filter$2(nodes, function (node, index) {
  8632. return !isText$3(node) || !isText$3(nodes[index - 1]);
  8633. });
  8634. nodes = filter$2(nodes, matchNodeNames([name]));
  8635. return nodes[index];
  8636. };
  8637. var findTextPosition = function (container, offset) {
  8638. var node = container, targetOffset = 0, dataLen;
  8639. while (isText$3(node)) {
  8640. dataLen = node.data.length;
  8641. if (offset >= targetOffset && offset <= targetOffset + dataLen) {
  8642. container = node;
  8643. offset = offset - targetOffset;
  8644. break;
  8645. }
  8646. if (!isText$3(node.nextSibling)) {
  8647. container = node;
  8648. offset = dataLen;
  8649. break;
  8650. }
  8651. targetOffset += dataLen;
  8652. node = node.nextSibling;
  8653. }
  8654. if (isText$3(container) && offset > container.data.length) {
  8655. offset = container.data.length;
  8656. }
  8657. return CaretPosition(container, offset);
  8658. };
  8659. var resolve$2 = function (root, path) {
  8660. var offset;
  8661. if (!path) {
  8662. return null;
  8663. }
  8664. var parts = path.split(',');
  8665. var paths = parts[0].split('/');
  8666. offset = parts.length > 1 ? parts[1] : 'before';
  8667. var container = reduce(paths, function (result, value) {
  8668. var match = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value);
  8669. if (!match) {
  8670. return null;
  8671. }
  8672. if (match[1] === 'text()') {
  8673. match[1] = '#text';
  8674. }
  8675. return resolvePathItem(result, match[1], parseInt(match[2], 10));
  8676. }, root);
  8677. if (!container) {
  8678. return null;
  8679. }
  8680. if (!isText$3(container)) {
  8681. if (offset === 'after') {
  8682. offset = nodeIndex(container) + 1;
  8683. } else {
  8684. offset = nodeIndex(container);
  8685. }
  8686. return CaretPosition(container.parentNode, offset);
  8687. }
  8688. return findTextPosition(container, parseInt(offset, 10));
  8689. };
  8690. var isContentEditableFalse$9 = isContentEditableFalse$b;
  8691. var getNormalizedTextOffset = function (trim, container, offset) {
  8692. var node, trimmedOffset;
  8693. trimmedOffset = trim(container.data.slice(0, offset)).length;
  8694. for (node = container.previousSibling; node && isText$7(node); node = node.previousSibling) {
  8695. trimmedOffset += trim(node.data).length;
  8696. }
  8697. return trimmedOffset;
  8698. };
  8699. var getPoint = function (dom, trim, normalized, rng, start) {
  8700. var container = rng[start ? 'startContainer' : 'endContainer'];
  8701. var offset = rng[start ? 'startOffset' : 'endOffset'];
  8702. var point = [];
  8703. var childNodes, after = 0;
  8704. var root = dom.getRoot();
  8705. if (isText$7(container)) {
  8706. point.push(normalized ? getNormalizedTextOffset(trim, container, offset) : offset);
  8707. } else {
  8708. childNodes = container.childNodes;
  8709. if (offset >= childNodes.length && childNodes.length) {
  8710. after = 1;
  8711. offset = Math.max(0, childNodes.length - 1);
  8712. }
  8713. point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
  8714. }
  8715. for (; container && container !== root; container = container.parentNode) {
  8716. point.push(dom.nodeIndex(container, normalized));
  8717. }
  8718. return point;
  8719. };
  8720. var getLocation = function (trim, selection, normalized, rng) {
  8721. var dom = selection.dom, bookmark = {};
  8722. bookmark.start = getPoint(dom, trim, normalized, rng, true);
  8723. if (!selection.isCollapsed()) {
  8724. bookmark.end = getPoint(dom, trim, normalized, rng, false);
  8725. }
  8726. if (isRangeInCaretContainerBlock(rng)) {
  8727. bookmark.isFakeCaret = true;
  8728. }
  8729. return bookmark;
  8730. };
  8731. var findIndex = function (dom, name, element) {
  8732. var count = 0;
  8733. Tools.each(dom.select(name), function (node) {
  8734. if (node.getAttribute('data-mce-bogus') === 'all') {
  8735. return;
  8736. }
  8737. if (node === element) {
  8738. return false;
  8739. }
  8740. count++;
  8741. });
  8742. return count;
  8743. };
  8744. var moveEndPoint$1 = function (rng, start) {
  8745. var container, offset, childNodes;
  8746. var prefix = start ? 'start' : 'end';
  8747. container = rng[prefix + 'Container'];
  8748. offset = rng[prefix + 'Offset'];
  8749. if (isElement$5(container) && container.nodeName === 'TR') {
  8750. childNodes = container.childNodes;
  8751. container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
  8752. if (container) {
  8753. offset = start ? 0 : container.childNodes.length;
  8754. rng['set' + (start ? 'Start' : 'End')](container, offset);
  8755. }
  8756. }
  8757. };
  8758. var normalizeTableCellSelection = function (rng) {
  8759. moveEndPoint$1(rng, true);
  8760. moveEndPoint$1(rng, false);
  8761. return rng;
  8762. };
  8763. var findSibling = function (node, offset) {
  8764. var sibling;
  8765. if (isElement$5(node)) {
  8766. node = getNode$1(node, offset);
  8767. if (isContentEditableFalse$9(node)) {
  8768. return node;
  8769. }
  8770. }
  8771. if (isCaretContainer$2(node)) {
  8772. if (isText$7(node) && isCaretContainerBlock$1(node)) {
  8773. node = node.parentNode;
  8774. }
  8775. sibling = node.previousSibling;
  8776. if (isContentEditableFalse$9(sibling)) {
  8777. return sibling;
  8778. }
  8779. sibling = node.nextSibling;
  8780. if (isContentEditableFalse$9(sibling)) {
  8781. return sibling;
  8782. }
  8783. }
  8784. };
  8785. var findAdjacentContentEditableFalseElm = function (rng) {
  8786. return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
  8787. };
  8788. var getOffsetBookmark = function (trim, normalized, selection) {
  8789. var element = selection.getNode();
  8790. var name = element ? element.nodeName : null;
  8791. var rng = selection.getRng();
  8792. if (isContentEditableFalse$9(element) || name === 'IMG') {
  8793. return {
  8794. name: name,
  8795. index: findIndex(selection.dom, name, element)
  8796. };
  8797. }
  8798. var sibling = findAdjacentContentEditableFalseElm(rng);
  8799. if (sibling) {
  8800. name = sibling.tagName;
  8801. return {
  8802. name: name,
  8803. index: findIndex(selection.dom, name, sibling)
  8804. };
  8805. }
  8806. return getLocation(trim, selection, normalized, rng);
  8807. };
  8808. var getCaretBookmark = function (selection) {
  8809. var rng = selection.getRng();
  8810. return {
  8811. start: create$6(selection.dom.getRoot(), CaretPosition.fromRangeStart(rng)),
  8812. end: create$6(selection.dom.getRoot(), CaretPosition.fromRangeEnd(rng))
  8813. };
  8814. };
  8815. var getRangeBookmark = function (selection) {
  8816. return { rng: selection.getRng() };
  8817. };
  8818. var createBookmarkSpan = function (dom, id, filled) {
  8819. var args = {
  8820. 'data-mce-type': 'bookmark',
  8821. id: id,
  8822. 'style': 'overflow:hidden;line-height:0px'
  8823. };
  8824. return filled ? dom.create('span', args, '&#xFEFF;') : dom.create('span', args);
  8825. };
  8826. var getPersistentBookmark = function (selection, filled) {
  8827. var dom = selection.dom;
  8828. var rng = selection.getRng();
  8829. var id = dom.uniqueId();
  8830. var collapsed = selection.isCollapsed();
  8831. var element = selection.getNode();
  8832. var name = element.nodeName;
  8833. if (name === 'IMG') {
  8834. return {
  8835. name: name,
  8836. index: findIndex(dom, name, element)
  8837. };
  8838. }
  8839. var rng2 = normalizeTableCellSelection(rng.cloneRange());
  8840. if (!collapsed) {
  8841. rng2.collapse(false);
  8842. var endBookmarkNode = createBookmarkSpan(dom, id + '_end', filled);
  8843. rangeInsertNode(dom, rng2, endBookmarkNode);
  8844. }
  8845. rng = normalizeTableCellSelection(rng);
  8846. rng.collapse(true);
  8847. var startBookmarkNode = createBookmarkSpan(dom, id + '_start', filled);
  8848. rangeInsertNode(dom, rng, startBookmarkNode);
  8849. selection.moveToBookmark({
  8850. id: id,
  8851. keep: true
  8852. });
  8853. return { id: id };
  8854. };
  8855. var getBookmark$2 = function (selection, type, normalized) {
  8856. if (type === 2) {
  8857. return getOffsetBookmark(trim$2, normalized, selection);
  8858. } else if (type === 3) {
  8859. return getCaretBookmark(selection);
  8860. } else if (type) {
  8861. return getRangeBookmark(selection);
  8862. } else {
  8863. return getPersistentBookmark(selection, false);
  8864. }
  8865. };
  8866. var getUndoBookmark = curry(getOffsetBookmark, identity, true);
  8867. var DOM$9 = DOMUtils.DOM;
  8868. var defaultPreviewStyles = 'font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow';
  8869. var getBodySetting = function (editor, name, defaultValue) {
  8870. var value = editor.getParam(name, defaultValue);
  8871. if (value.indexOf('=') !== -1) {
  8872. var bodyObj = editor.getParam(name, '', 'hash');
  8873. return get$9(bodyObj, editor.id).getOr(defaultValue);
  8874. } else {
  8875. return value;
  8876. }
  8877. };
  8878. var getIframeAttrs = function (editor) {
  8879. return editor.getParam('iframe_attrs', {});
  8880. };
  8881. var getDocType = function (editor) {
  8882. return editor.getParam('doctype', '<!DOCTYPE html>');
  8883. };
  8884. var getDocumentBaseUrl = function (editor) {
  8885. return editor.getParam('document_base_url', '');
  8886. };
  8887. var getBodyId = function (editor) {
  8888. return getBodySetting(editor, 'body_id', 'tinymce');
  8889. };
  8890. var getBodyClass = function (editor) {
  8891. return getBodySetting(editor, 'body_class', '');
  8892. };
  8893. var getContentSecurityPolicy = function (editor) {
  8894. return editor.getParam('content_security_policy', '');
  8895. };
  8896. var shouldPutBrInPre$1 = function (editor) {
  8897. return editor.getParam('br_in_pre', true);
  8898. };
  8899. var getForcedRootBlock = function (editor) {
  8900. if (editor.getParam('force_p_newlines', false)) {
  8901. return 'p';
  8902. }
  8903. var block = editor.getParam('forced_root_block', 'p');
  8904. if (block === false) {
  8905. return '';
  8906. } else if (block === true) {
  8907. return 'p';
  8908. } else {
  8909. return block;
  8910. }
  8911. };
  8912. var getForcedRootBlockAttrs = function (editor) {
  8913. return editor.getParam('forced_root_block_attrs', {});
  8914. };
  8915. var getBrNewLineSelector = function (editor) {
  8916. return editor.getParam('br_newline_selector', '.mce-toc h2,figcaption,caption');
  8917. };
  8918. var getNoNewLineSelector = function (editor) {
  8919. return editor.getParam('no_newline_selector', '');
  8920. };
  8921. var shouldKeepStyles = function (editor) {
  8922. return editor.getParam('keep_styles', true);
  8923. };
  8924. var shouldEndContainerOnEmptyBlock = function (editor) {
  8925. return editor.getParam('end_container_on_empty_block', false);
  8926. };
  8927. var getFontStyleValues = function (editor) {
  8928. return Tools.explode(editor.getParam('font_size_style_values', 'xx-small,x-small,small,medium,large,x-large,xx-large'));
  8929. };
  8930. var getFontSizeClasses = function (editor) {
  8931. return Tools.explode(editor.getParam('font_size_classes', ''));
  8932. };
  8933. var getImagesDataImgFilter = function (editor) {
  8934. return editor.getParam('images_dataimg_filter', always, 'function');
  8935. };
  8936. var isAutomaticUploadsEnabled = function (editor) {
  8937. return editor.getParam('automatic_uploads', true, 'boolean');
  8938. };
  8939. var shouldReuseFileName = function (editor) {
  8940. return editor.getParam('images_reuse_filename', false, 'boolean');
  8941. };
  8942. var shouldReplaceBlobUris = function (editor) {
  8943. return editor.getParam('images_replace_blob_uris', true, 'boolean');
  8944. };
  8945. var getIconPackName = function (editor) {
  8946. return editor.getParam('icons', '', 'string');
  8947. };
  8948. var getIconsUrl = function (editor) {
  8949. return editor.getParam('icons_url', '', 'string');
  8950. };
  8951. var getImageUploadUrl = function (editor) {
  8952. return editor.getParam('images_upload_url', '', 'string');
  8953. };
  8954. var getImageUploadBasePath = function (editor) {
  8955. return editor.getParam('images_upload_base_path', '', 'string');
  8956. };
  8957. var getImagesUploadCredentials = function (editor) {
  8958. return editor.getParam('images_upload_credentials', false, 'boolean');
  8959. };
  8960. var getImagesUploadHandler = function (editor) {
  8961. return editor.getParam('images_upload_handler', null, 'function');
  8962. };
  8963. var shouldUseContentCssCors = function (editor) {
  8964. return editor.getParam('content_css_cors', false, 'boolean');
  8965. };
  8966. var getReferrerPolicy = function (editor) {
  8967. return editor.getParam('referrer_policy', '', 'string');
  8968. };
  8969. var getLanguageCode = function (editor) {
  8970. return editor.getParam('language', 'en', 'string');
  8971. };
  8972. var getLanguageUrl = function (editor) {
  8973. return editor.getParam('language_url', '', 'string');
  8974. };
  8975. var shouldIndentUseMargin = function (editor) {
  8976. return editor.getParam('indent_use_margin', false);
  8977. };
  8978. var getIndentation = function (editor) {
  8979. return editor.getParam('indentation', '40px', 'string');
  8980. };
  8981. var getContentCss = function (editor) {
  8982. var contentCss = editor.getParam('content_css');
  8983. if (isString$1(contentCss)) {
  8984. return map$3(contentCss.split(','), trim$4);
  8985. } else if (isArray$1(contentCss)) {
  8986. return contentCss;
  8987. } else if (contentCss === false || editor.inline) {
  8988. return [];
  8989. } else {
  8990. return ['default'];
  8991. }
  8992. };
  8993. var getFontCss = function (editor) {
  8994. var fontCss = editor.getParam('font_css', []);
  8995. return isArray$1(fontCss) ? fontCss : map$3(fontCss.split(','), trim$4);
  8996. };
  8997. var getDirectionality = function (editor) {
  8998. return editor.getParam('directionality', I18n.isRtl() ? 'rtl' : undefined);
  8999. };
  9000. var getInlineBoundarySelector = function (editor) {
  9001. return editor.getParam('inline_boundaries_selector', 'a[href],code,.mce-annotation', 'string');
  9002. };
  9003. var getObjectResizing = function (editor) {
  9004. var selector = editor.getParam('object_resizing');
  9005. if (selector === false || Env.iOS) {
  9006. return false;
  9007. } else {
  9008. return isString$1(selector) ? selector : 'table,img,figure.image,div,video,iframe';
  9009. }
  9010. };
  9011. var getResizeImgProportional = function (editor) {
  9012. return editor.getParam('resize_img_proportional', true, 'boolean');
  9013. };
  9014. var getPlaceholder = function (editor) {
  9015. return editor.getParam('placeholder', DOM$9.getAttrib(editor.getElement(), 'placeholder'), 'string');
  9016. };
  9017. var getEventRoot = function (editor) {
  9018. return editor.getParam('event_root');
  9019. };
  9020. var getServiceMessage = function (editor) {
  9021. return editor.getParam('service_message');
  9022. };
  9023. var getTheme = function (editor) {
  9024. return editor.getParam('theme');
  9025. };
  9026. var shouldValidate = function (editor) {
  9027. return editor.getParam('validate');
  9028. };
  9029. var isInlineBoundariesEnabled = function (editor) {
  9030. return editor.getParam('inline_boundaries') !== false;
  9031. };
  9032. var getFormats = function (editor) {
  9033. return editor.getParam('formats');
  9034. };
  9035. var getPreviewStyles = function (editor) {
  9036. var style = editor.getParam('preview_styles', defaultPreviewStyles);
  9037. if (isString$1(style)) {
  9038. return style;
  9039. } else {
  9040. return '';
  9041. }
  9042. };
  9043. var canFormatEmptyLines = function (editor) {
  9044. return editor.getParam('format_empty_lines', false, 'boolean');
  9045. };
  9046. var getCustomUiSelector = function (editor) {
  9047. return editor.getParam('custom_ui_selector', '', 'string');
  9048. };
  9049. var getThemeUrl = function (editor) {
  9050. return editor.getParam('theme_url');
  9051. };
  9052. var isInline = function (editor) {
  9053. return editor.getParam('inline');
  9054. };
  9055. var hasHiddenInput = function (editor) {
  9056. return editor.getParam('hidden_input');
  9057. };
  9058. var shouldPatchSubmit = function (editor) {
  9059. return editor.getParam('submit_patch');
  9060. };
  9061. var isEncodingXml = function (editor) {
  9062. return editor.getParam('encoding') === 'xml';
  9063. };
  9064. var shouldAddFormSubmitTrigger = function (editor) {
  9065. return editor.getParam('add_form_submit_trigger');
  9066. };
  9067. var shouldAddUnloadTrigger = function (editor) {
  9068. return editor.getParam('add_unload_trigger');
  9069. };
  9070. var hasForcedRootBlock = function (editor) {
  9071. return getForcedRootBlock(editor) !== '';
  9072. };
  9073. var getCustomUndoRedoLevels = function (editor) {
  9074. return editor.getParam('custom_undo_redo_levels', 0, 'number');
  9075. };
  9076. var shouldDisableNodeChange = function (editor) {
  9077. return editor.getParam('disable_nodechange');
  9078. };
  9079. var isReadOnly$1 = function (editor) {
  9080. return editor.getParam('readonly');
  9081. };
  9082. var hasContentCssCors = function (editor) {
  9083. return editor.getParam('content_css_cors');
  9084. };
  9085. var getPlugins = function (editor) {
  9086. return editor.getParam('plugins', '', 'string');
  9087. };
  9088. var getExternalPlugins$1 = function (editor) {
  9089. return editor.getParam('external_plugins');
  9090. };
  9091. var shouldBlockUnsupportedDrop = function (editor) {
  9092. return editor.getParam('block_unsupported_drop', true, 'boolean');
  9093. };
  9094. var isVisualAidsEnabled = function (editor) {
  9095. return editor.getParam('visual', true, 'boolean');
  9096. };
  9097. var getVisualAidsTableClass = function (editor) {
  9098. return editor.getParam('visual_table_class', 'mce-item-table', 'string');
  9099. };
  9100. var getVisualAidsAnchorClass = function (editor) {
  9101. return editor.getParam('visual_anchor_class', 'mce-item-anchor', 'string');
  9102. };
  9103. var getIframeAriaText = function (editor) {
  9104. return editor.getParam('iframe_aria_text', 'Rich Text Area. Press ALT-0 for help.', 'string');
  9105. };
  9106. var isElement$2 = isElement$5;
  9107. var isText$2 = isText$7;
  9108. var removeNode$1 = function (node) {
  9109. var parentNode = node.parentNode;
  9110. if (parentNode) {
  9111. parentNode.removeChild(node);
  9112. }
  9113. };
  9114. var trimCount = function (text) {
  9115. var trimmedText = trim$2(text);
  9116. return {
  9117. count: text.length - trimmedText.length,
  9118. text: trimmedText
  9119. };
  9120. };
  9121. var deleteZwspChars = function (caretContainer) {
  9122. var idx;
  9123. while ((idx = caretContainer.data.lastIndexOf(ZWSP$1)) !== -1) {
  9124. caretContainer.deleteData(idx, 1);
  9125. }
  9126. };
  9127. var removeUnchanged = function (caretContainer, pos) {
  9128. remove$2(caretContainer);
  9129. return pos;
  9130. };
  9131. var removeTextAndReposition = function (caretContainer, pos) {
  9132. var before = trimCount(caretContainer.data.substr(0, pos.offset()));
  9133. var after = trimCount(caretContainer.data.substr(pos.offset()));
  9134. var text = before.text + after.text;
  9135. if (text.length > 0) {
  9136. deleteZwspChars(caretContainer);
  9137. return CaretPosition(caretContainer, pos.offset() - before.count);
  9138. } else {
  9139. return pos;
  9140. }
  9141. };
  9142. var removeElementAndReposition = function (caretContainer, pos) {
  9143. var parentNode = pos.container();
  9144. var newPosition = indexOf$2(from(parentNode.childNodes), caretContainer).map(function (index) {
  9145. return index < pos.offset() ? CaretPosition(parentNode, pos.offset() - 1) : pos;
  9146. }).getOr(pos);
  9147. remove$2(caretContainer);
  9148. return newPosition;
  9149. };
  9150. var removeTextCaretContainer = function (caretContainer, pos) {
  9151. return isText$2(caretContainer) && pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9152. };
  9153. var removeElementCaretContainer = function (caretContainer, pos) {
  9154. return pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9155. };
  9156. var removeAndReposition = function (container, pos) {
  9157. return CaretPosition.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
  9158. };
  9159. var remove$2 = function (caretContainerNode) {
  9160. if (isElement$2(caretContainerNode) && isCaretContainer$2(caretContainerNode)) {
  9161. if (hasContent(caretContainerNode)) {
  9162. caretContainerNode.removeAttribute('data-mce-caret');
  9163. } else {
  9164. removeNode$1(caretContainerNode);
  9165. }
  9166. }
  9167. if (isText$2(caretContainerNode)) {
  9168. deleteZwspChars(caretContainerNode);
  9169. if (caretContainerNode.data.length === 0) {
  9170. removeNode$1(caretContainerNode);
  9171. }
  9172. }
  9173. };
  9174. var browser$2 = detect().browser;
  9175. var isContentEditableFalse$8 = isContentEditableFalse$b;
  9176. var isMedia$1 = isMedia$2;
  9177. var isTableCell$3 = isTableCell$5;
  9178. var inlineFakeCaretSelector = '*[contentEditable=false],video,audio,embed,object';
  9179. var getAbsoluteClientRect = function (root, element, before) {
  9180. var clientRect = collapse(element.getBoundingClientRect(), before);
  9181. var scrollX;
  9182. var scrollY;
  9183. if (root.tagName === 'BODY') {
  9184. var docElm = root.ownerDocument.documentElement;
  9185. scrollX = root.scrollLeft || docElm.scrollLeft;
  9186. scrollY = root.scrollTop || docElm.scrollTop;
  9187. } else {
  9188. var rootRect = root.getBoundingClientRect();
  9189. scrollX = root.scrollLeft - rootRect.left;
  9190. scrollY = root.scrollTop - rootRect.top;
  9191. }
  9192. clientRect.left += scrollX;
  9193. clientRect.right += scrollX;
  9194. clientRect.top += scrollY;
  9195. clientRect.bottom += scrollY;
  9196. clientRect.width = 1;
  9197. var margin = element.offsetWidth - element.clientWidth;
  9198. if (margin > 0) {
  9199. if (before) {
  9200. margin *= -1;
  9201. }
  9202. clientRect.left += margin;
  9203. clientRect.right += margin;
  9204. }
  9205. return clientRect;
  9206. };
  9207. var trimInlineCaretContainers = function (root) {
  9208. var fakeCaretTargetNodes = descendants(SugarElement.fromDom(root), inlineFakeCaretSelector);
  9209. for (var i = 0; i < fakeCaretTargetNodes.length; i++) {
  9210. var node = fakeCaretTargetNodes[i].dom;
  9211. var sibling = node.previousSibling;
  9212. if (endsWithCaretContainer$1(sibling)) {
  9213. var data = sibling.data;
  9214. if (data.length === 1) {
  9215. sibling.parentNode.removeChild(sibling);
  9216. } else {
  9217. sibling.deleteData(data.length - 1, 1);
  9218. }
  9219. }
  9220. sibling = node.nextSibling;
  9221. if (startsWithCaretContainer$1(sibling)) {
  9222. var data = sibling.data;
  9223. if (data.length === 1) {
  9224. sibling.parentNode.removeChild(sibling);
  9225. } else {
  9226. sibling.deleteData(0, 1);
  9227. }
  9228. }
  9229. }
  9230. };
  9231. var FakeCaret = function (editor, root, isBlock, hasFocus) {
  9232. var lastVisualCaret = value();
  9233. var cursorInterval;
  9234. var caretContainerNode;
  9235. var rootBlock = getForcedRootBlock(editor);
  9236. var caretBlock = rootBlock.length > 0 ? rootBlock : 'p';
  9237. var show = function (before, element) {
  9238. var rng;
  9239. hide();
  9240. if (isTableCell$3(element)) {
  9241. return null;
  9242. }
  9243. if (isBlock(element)) {
  9244. caretContainerNode = insertBlock$1(caretBlock, element, before);
  9245. var clientRect = getAbsoluteClientRect(root, element, before);
  9246. DomQuery(caretContainerNode).css('top', clientRect.top);
  9247. var caret = DomQuery('<div class="mce-visual-caret" data-mce-bogus="all"></div>').css(__assign({}, clientRect)).appendTo(root)[0];
  9248. lastVisualCaret.set({
  9249. caret: caret,
  9250. element: element,
  9251. before: before
  9252. });
  9253. if (before) {
  9254. DomQuery(caret).addClass('mce-visual-caret-before');
  9255. }
  9256. startBlink();
  9257. rng = element.ownerDocument.createRange();
  9258. rng.setStart(caretContainerNode, 0);
  9259. rng.setEnd(caretContainerNode, 0);
  9260. } else {
  9261. caretContainerNode = insertInline$1(element, before);
  9262. rng = element.ownerDocument.createRange();
  9263. if (isInlineFakeCaretTarget(caretContainerNode.nextSibling)) {
  9264. rng.setStart(caretContainerNode, 0);
  9265. rng.setEnd(caretContainerNode, 0);
  9266. } else {
  9267. rng.setStart(caretContainerNode, 1);
  9268. rng.setEnd(caretContainerNode, 1);
  9269. }
  9270. return rng;
  9271. }
  9272. return rng;
  9273. };
  9274. var hide = function () {
  9275. trimInlineCaretContainers(root);
  9276. if (caretContainerNode) {
  9277. remove$2(caretContainerNode);
  9278. caretContainerNode = null;
  9279. }
  9280. lastVisualCaret.on(function (caretState) {
  9281. DomQuery(caretState.caret).remove();
  9282. lastVisualCaret.clear();
  9283. });
  9284. if (cursorInterval) {
  9285. Delay.clearInterval(cursorInterval);
  9286. cursorInterval = undefined;
  9287. }
  9288. };
  9289. var startBlink = function () {
  9290. cursorInterval = Delay.setInterval(function () {
  9291. if (hasFocus()) {
  9292. DomQuery('div.mce-visual-caret', root).toggleClass('mce-visual-caret-hidden');
  9293. } else {
  9294. DomQuery('div.mce-visual-caret', root).addClass('mce-visual-caret-hidden');
  9295. }
  9296. }, 500);
  9297. };
  9298. var reposition = function () {
  9299. lastVisualCaret.on(function (caretState) {
  9300. var clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
  9301. DomQuery(caretState.caret).css(__assign({}, clientRect));
  9302. });
  9303. };
  9304. var destroy = function () {
  9305. return Delay.clearInterval(cursorInterval);
  9306. };
  9307. var getCss = function () {
  9308. 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;' + '}';
  9309. };
  9310. return {
  9311. show: show,
  9312. hide: hide,
  9313. getCss: getCss,
  9314. reposition: reposition,
  9315. destroy: destroy
  9316. };
  9317. };
  9318. var isFakeCaretTableBrowser = function () {
  9319. return browser$2.isIE() || browser$2.isEdge() || browser$2.isFirefox();
  9320. };
  9321. var isInlineFakeCaretTarget = function (node) {
  9322. return isContentEditableFalse$8(node) || isMedia$1(node);
  9323. };
  9324. var isFakeCaretTarget = function (node) {
  9325. return isInlineFakeCaretTarget(node) || isTable$3(node) && isFakeCaretTableBrowser();
  9326. };
  9327. var isContentEditableFalse$7 = isContentEditableFalse$b;
  9328. var isMedia = isMedia$2;
  9329. var isBlockLike = matchStyleValues('display', 'block table table-cell table-caption list-item');
  9330. var isCaretContainer = isCaretContainer$2;
  9331. var isCaretContainerBlock = isCaretContainerBlock$1;
  9332. var isElement$1 = isElement$5;
  9333. var isCaretCandidate$1 = isCaretCandidate$3;
  9334. var isForwards = function (direction) {
  9335. return direction > 0;
  9336. };
  9337. var isBackwards = function (direction) {
  9338. return direction < 0;
  9339. };
  9340. var skipCaretContainers = function (walk, shallow) {
  9341. var node;
  9342. while (node = walk(shallow)) {
  9343. if (!isCaretContainerBlock(node)) {
  9344. return node;
  9345. }
  9346. }
  9347. return null;
  9348. };
  9349. var findNode$1 = function (node, direction, predicateFn, rootNode, shallow) {
  9350. var walker = new DomTreeWalker(node, rootNode);
  9351. var isCefOrCaretContainer = isContentEditableFalse$7(node) || isCaretContainerBlock(node);
  9352. if (isBackwards(direction)) {
  9353. if (isCefOrCaretContainer) {
  9354. node = skipCaretContainers(walker.prev.bind(walker), true);
  9355. if (predicateFn(node)) {
  9356. return node;
  9357. }
  9358. }
  9359. while (node = skipCaretContainers(walker.prev.bind(walker), shallow)) {
  9360. if (predicateFn(node)) {
  9361. return node;
  9362. }
  9363. }
  9364. }
  9365. if (isForwards(direction)) {
  9366. if (isCefOrCaretContainer) {
  9367. node = skipCaretContainers(walker.next.bind(walker), true);
  9368. if (predicateFn(node)) {
  9369. return node;
  9370. }
  9371. }
  9372. while (node = skipCaretContainers(walker.next.bind(walker), shallow)) {
  9373. if (predicateFn(node)) {
  9374. return node;
  9375. }
  9376. }
  9377. }
  9378. return null;
  9379. };
  9380. var getParentBlock$2 = function (node, rootNode) {
  9381. while (node && node !== rootNode) {
  9382. if (isBlockLike(node)) {
  9383. return node;
  9384. }
  9385. node = node.parentNode;
  9386. }
  9387. return null;
  9388. };
  9389. var isInSameBlock = function (caretPosition1, caretPosition2, rootNode) {
  9390. return getParentBlock$2(caretPosition1.container(), rootNode) === getParentBlock$2(caretPosition2.container(), rootNode);
  9391. };
  9392. var getChildNodeAtRelativeOffset = function (relativeOffset, caretPosition) {
  9393. if (!caretPosition) {
  9394. return null;
  9395. }
  9396. var container = caretPosition.container();
  9397. var offset = caretPosition.offset();
  9398. if (!isElement$1(container)) {
  9399. return null;
  9400. }
  9401. return container.childNodes[offset + relativeOffset];
  9402. };
  9403. var beforeAfter = function (before, node) {
  9404. var range = node.ownerDocument.createRange();
  9405. if (before) {
  9406. range.setStartBefore(node);
  9407. range.setEndBefore(node);
  9408. } else {
  9409. range.setStartAfter(node);
  9410. range.setEndAfter(node);
  9411. }
  9412. return range;
  9413. };
  9414. var isNodesInSameBlock = function (root, node1, node2) {
  9415. return getParentBlock$2(node1, root) === getParentBlock$2(node2, root);
  9416. };
  9417. var lean = function (left, root, node) {
  9418. var siblingName = left ? 'previousSibling' : 'nextSibling';
  9419. while (node && node !== root) {
  9420. var sibling = node[siblingName];
  9421. if (isCaretContainer(sibling)) {
  9422. sibling = sibling[siblingName];
  9423. }
  9424. if (isContentEditableFalse$7(sibling) || isMedia(sibling)) {
  9425. if (isNodesInSameBlock(root, sibling, node)) {
  9426. return sibling;
  9427. }
  9428. break;
  9429. }
  9430. if (isCaretCandidate$1(sibling)) {
  9431. break;
  9432. }
  9433. node = node.parentNode;
  9434. }
  9435. return null;
  9436. };
  9437. var before$2 = curry(beforeAfter, true);
  9438. var after$2 = curry(beforeAfter, false);
  9439. var normalizeRange = function (direction, root, range) {
  9440. var node;
  9441. var leanLeft = curry(lean, true, root);
  9442. var leanRight = curry(lean, false, root);
  9443. var container = range.startContainer;
  9444. var offset = range.startOffset;
  9445. if (isCaretContainerBlock$1(container)) {
  9446. if (!isElement$1(container)) {
  9447. container = container.parentNode;
  9448. }
  9449. var location_1 = container.getAttribute('data-mce-caret');
  9450. if (location_1 === 'before') {
  9451. node = container.nextSibling;
  9452. if (isFakeCaretTarget(node)) {
  9453. return before$2(node);
  9454. }
  9455. }
  9456. if (location_1 === 'after') {
  9457. node = container.previousSibling;
  9458. if (isFakeCaretTarget(node)) {
  9459. return after$2(node);
  9460. }
  9461. }
  9462. }
  9463. if (!range.collapsed) {
  9464. return range;
  9465. }
  9466. if (isText$7(container)) {
  9467. if (isCaretContainer(container)) {
  9468. if (direction === 1) {
  9469. node = leanRight(container);
  9470. if (node) {
  9471. return before$2(node);
  9472. }
  9473. node = leanLeft(container);
  9474. if (node) {
  9475. return after$2(node);
  9476. }
  9477. }
  9478. if (direction === -1) {
  9479. node = leanLeft(container);
  9480. if (node) {
  9481. return after$2(node);
  9482. }
  9483. node = leanRight(container);
  9484. if (node) {
  9485. return before$2(node);
  9486. }
  9487. }
  9488. return range;
  9489. }
  9490. if (endsWithCaretContainer$1(container) && offset >= container.data.length - 1) {
  9491. if (direction === 1) {
  9492. node = leanRight(container);
  9493. if (node) {
  9494. return before$2(node);
  9495. }
  9496. }
  9497. return range;
  9498. }
  9499. if (startsWithCaretContainer$1(container) && offset <= 1) {
  9500. if (direction === -1) {
  9501. node = leanLeft(container);
  9502. if (node) {
  9503. return after$2(node);
  9504. }
  9505. }
  9506. return range;
  9507. }
  9508. if (offset === container.data.length) {
  9509. node = leanRight(container);
  9510. if (node) {
  9511. return before$2(node);
  9512. }
  9513. return range;
  9514. }
  9515. if (offset === 0) {
  9516. node = leanLeft(container);
  9517. if (node) {
  9518. return after$2(node);
  9519. }
  9520. return range;
  9521. }
  9522. }
  9523. return range;
  9524. };
  9525. var getRelativeCefElm = function (forward, caretPosition) {
  9526. return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition)).filter(isContentEditableFalse$7);
  9527. };
  9528. var getNormalizedRangeEndPoint = function (direction, root, range) {
  9529. var normalizedRange = normalizeRange(direction, root, range);
  9530. if (direction === -1) {
  9531. return CaretPosition.fromRangeStart(normalizedRange);
  9532. }
  9533. return CaretPosition.fromRangeEnd(normalizedRange);
  9534. };
  9535. var getElementFromPosition = function (pos) {
  9536. return Optional.from(pos.getNode()).map(SugarElement.fromDom);
  9537. };
  9538. var getElementFromPrevPosition = function (pos) {
  9539. return Optional.from(pos.getNode(true)).map(SugarElement.fromDom);
  9540. };
  9541. var getVisualCaretPosition = function (walkFn, caretPosition) {
  9542. while (caretPosition = walkFn(caretPosition)) {
  9543. if (caretPosition.isVisible()) {
  9544. return caretPosition;
  9545. }
  9546. }
  9547. return caretPosition;
  9548. };
  9549. var isMoveInsideSameBlock = function (from, to) {
  9550. var inSameBlock = isInSameBlock(from, to);
  9551. if (!inSameBlock && isBr$5(from.getNode())) {
  9552. return true;
  9553. }
  9554. return inSameBlock;
  9555. };
  9556. var HDirection;
  9557. (function (HDirection) {
  9558. HDirection[HDirection['Backwards'] = -1] = 'Backwards';
  9559. HDirection[HDirection['Forwards'] = 1] = 'Forwards';
  9560. }(HDirection || (HDirection = {})));
  9561. var isContentEditableFalse$6 = isContentEditableFalse$b;
  9562. var isText$1 = isText$7;
  9563. var isElement = isElement$5;
  9564. var isBr$1 = isBr$5;
  9565. var isCaretCandidate = isCaretCandidate$3;
  9566. var isAtomic = isAtomic$1;
  9567. var isEditableCaretCandidate = isEditableCaretCandidate$1;
  9568. var getParents$3 = function (node, root) {
  9569. var parents = [];
  9570. while (node && node !== root) {
  9571. parents.push(node);
  9572. node = node.parentNode;
  9573. }
  9574. return parents;
  9575. };
  9576. var nodeAtIndex = function (container, offset) {
  9577. if (container.hasChildNodes() && offset < container.childNodes.length) {
  9578. return container.childNodes[offset];
  9579. }
  9580. return null;
  9581. };
  9582. var getCaretCandidatePosition = function (direction, node) {
  9583. if (isForwards(direction)) {
  9584. if (isCaretCandidate(node.previousSibling) && !isText$1(node.previousSibling)) {
  9585. return CaretPosition.before(node);
  9586. }
  9587. if (isText$1(node)) {
  9588. return CaretPosition(node, 0);
  9589. }
  9590. }
  9591. if (isBackwards(direction)) {
  9592. if (isCaretCandidate(node.nextSibling) && !isText$1(node.nextSibling)) {
  9593. return CaretPosition.after(node);
  9594. }
  9595. if (isText$1(node)) {
  9596. return CaretPosition(node, node.data.length);
  9597. }
  9598. }
  9599. if (isBackwards(direction)) {
  9600. if (isBr$1(node)) {
  9601. return CaretPosition.before(node);
  9602. }
  9603. return CaretPosition.after(node);
  9604. }
  9605. return CaretPosition.before(node);
  9606. };
  9607. var moveForwardFromBr = function (root, nextNode) {
  9608. var nextSibling = nextNode.nextSibling;
  9609. if (nextSibling && isCaretCandidate(nextSibling)) {
  9610. if (isText$1(nextSibling)) {
  9611. return CaretPosition(nextSibling, 0);
  9612. } else {
  9613. return CaretPosition.before(nextSibling);
  9614. }
  9615. } else {
  9616. return findCaretPosition$1(HDirection.Forwards, CaretPosition.after(nextNode), root);
  9617. }
  9618. };
  9619. var findCaretPosition$1 = function (direction, startPos, root) {
  9620. var node;
  9621. var nextNode;
  9622. var innerNode;
  9623. var caretPosition;
  9624. if (!isElement(root) || !startPos) {
  9625. return null;
  9626. }
  9627. if (startPos.isEqual(CaretPosition.after(root)) && root.lastChild) {
  9628. caretPosition = CaretPosition.after(root.lastChild);
  9629. if (isBackwards(direction) && isCaretCandidate(root.lastChild) && isElement(root.lastChild)) {
  9630. return isBr$1(root.lastChild) ? CaretPosition.before(root.lastChild) : caretPosition;
  9631. }
  9632. } else {
  9633. caretPosition = startPos;
  9634. }
  9635. var container = caretPosition.container();
  9636. var offset = caretPosition.offset();
  9637. if (isText$1(container)) {
  9638. if (isBackwards(direction) && offset > 0) {
  9639. return CaretPosition(container, --offset);
  9640. }
  9641. if (isForwards(direction) && offset < container.length) {
  9642. return CaretPosition(container, ++offset);
  9643. }
  9644. node = container;
  9645. } else {
  9646. if (isBackwards(direction) && offset > 0) {
  9647. nextNode = nodeAtIndex(container, offset - 1);
  9648. if (isCaretCandidate(nextNode)) {
  9649. if (!isAtomic(nextNode)) {
  9650. innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
  9651. if (innerNode) {
  9652. if (isText$1(innerNode)) {
  9653. return CaretPosition(innerNode, innerNode.data.length);
  9654. }
  9655. return CaretPosition.after(innerNode);
  9656. }
  9657. }
  9658. if (isText$1(nextNode)) {
  9659. return CaretPosition(nextNode, nextNode.data.length);
  9660. }
  9661. return CaretPosition.before(nextNode);
  9662. }
  9663. }
  9664. if (isForwards(direction) && offset < container.childNodes.length) {
  9665. nextNode = nodeAtIndex(container, offset);
  9666. if (isCaretCandidate(nextNode)) {
  9667. if (isBr$1(nextNode)) {
  9668. return moveForwardFromBr(root, nextNode);
  9669. }
  9670. if (!isAtomic(nextNode)) {
  9671. innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
  9672. if (innerNode) {
  9673. if (isText$1(innerNode)) {
  9674. return CaretPosition(innerNode, 0);
  9675. }
  9676. return CaretPosition.before(innerNode);
  9677. }
  9678. }
  9679. if (isText$1(nextNode)) {
  9680. return CaretPosition(nextNode, 0);
  9681. }
  9682. return CaretPosition.after(nextNode);
  9683. }
  9684. }
  9685. node = nextNode ? nextNode : caretPosition.getNode();
  9686. }
  9687. if (isForwards(direction) && caretPosition.isAtEnd() || isBackwards(direction) && caretPosition.isAtStart()) {
  9688. node = findNode$1(node, direction, always, root, true);
  9689. if (isEditableCaretCandidate(node, root)) {
  9690. return getCaretCandidatePosition(direction, node);
  9691. }
  9692. }
  9693. nextNode = findNode$1(node, direction, isEditableCaretCandidate, root);
  9694. var rootContentEditableFalseElm = last$1(filter$4(getParents$3(container, root), isContentEditableFalse$6));
  9695. if (rootContentEditableFalseElm && (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
  9696. if (isForwards(direction)) {
  9697. caretPosition = CaretPosition.after(rootContentEditableFalseElm);
  9698. } else {
  9699. caretPosition = CaretPosition.before(rootContentEditableFalseElm);
  9700. }
  9701. return caretPosition;
  9702. }
  9703. if (nextNode) {
  9704. return getCaretCandidatePosition(direction, nextNode);
  9705. }
  9706. return null;
  9707. };
  9708. var CaretWalker = function (root) {
  9709. return {
  9710. next: function (caretPosition) {
  9711. return findCaretPosition$1(HDirection.Forwards, caretPosition, root);
  9712. },
  9713. prev: function (caretPosition) {
  9714. return findCaretPosition$1(HDirection.Backwards, caretPosition, root);
  9715. }
  9716. };
  9717. };
  9718. var walkToPositionIn = function (forward, root, start) {
  9719. var position = forward ? CaretPosition.before(start) : CaretPosition.after(start);
  9720. return fromPosition(forward, root, position);
  9721. };
  9722. var afterElement = function (node) {
  9723. return isBr$5(node) ? CaretPosition.before(node) : CaretPosition.after(node);
  9724. };
  9725. var isBeforeOrStart = function (position) {
  9726. if (CaretPosition.isTextPosition(position)) {
  9727. return position.offset() === 0;
  9728. } else {
  9729. return isCaretCandidate$3(position.getNode());
  9730. }
  9731. };
  9732. var isAfterOrEnd = function (position) {
  9733. if (CaretPosition.isTextPosition(position)) {
  9734. var container = position.container();
  9735. return position.offset() === container.data.length;
  9736. } else {
  9737. return isCaretCandidate$3(position.getNode(true));
  9738. }
  9739. };
  9740. var isBeforeAfterSameElement = function (from, to) {
  9741. return !CaretPosition.isTextPosition(from) && !CaretPosition.isTextPosition(to) && from.getNode() === to.getNode(true);
  9742. };
  9743. var isAtBr = function (position) {
  9744. return !CaretPosition.isTextPosition(position) && isBr$5(position.getNode());
  9745. };
  9746. var shouldSkipPosition = function (forward, from, to) {
  9747. if (forward) {
  9748. return !isBeforeAfterSameElement(from, to) && !isAtBr(from) && isAfterOrEnd(from) && isBeforeOrStart(to);
  9749. } else {
  9750. return !isBeforeAfterSameElement(to, from) && isBeforeOrStart(from) && isAfterOrEnd(to);
  9751. }
  9752. };
  9753. var fromPosition = function (forward, root, pos) {
  9754. var walker = CaretWalker(root);
  9755. return Optional.from(forward ? walker.next(pos) : walker.prev(pos));
  9756. };
  9757. var navigate = function (forward, root, from) {
  9758. return fromPosition(forward, root, from).bind(function (to) {
  9759. if (isInSameBlock(from, to, root) && shouldSkipPosition(forward, from, to)) {
  9760. return fromPosition(forward, root, to);
  9761. } else {
  9762. return Optional.some(to);
  9763. }
  9764. });
  9765. };
  9766. var navigateIgnore = function (forward, root, from, ignoreFilter) {
  9767. return navigate(forward, root, from).bind(function (pos) {
  9768. return ignoreFilter(pos) ? navigateIgnore(forward, root, pos, ignoreFilter) : Optional.some(pos);
  9769. });
  9770. };
  9771. var positionIn = function (forward, element) {
  9772. var startNode = forward ? element.firstChild : element.lastChild;
  9773. if (isText$7(startNode)) {
  9774. return Optional.some(CaretPosition(startNode, forward ? 0 : startNode.data.length));
  9775. } else if (startNode) {
  9776. if (isCaretCandidate$3(startNode)) {
  9777. return Optional.some(forward ? CaretPosition.before(startNode) : afterElement(startNode));
  9778. } else {
  9779. return walkToPositionIn(forward, element, startNode);
  9780. }
  9781. } else {
  9782. return Optional.none();
  9783. }
  9784. };
  9785. var nextPosition = curry(fromPosition, true);
  9786. var prevPosition = curry(fromPosition, false);
  9787. var firstPositionIn = curry(positionIn, true);
  9788. var lastPositionIn = curry(positionIn, false);
  9789. var CARET_ID$1 = '_mce_caret';
  9790. var isCaretNode = function (node) {
  9791. return isElement$5(node) && node.id === CARET_ID$1;
  9792. };
  9793. var getParentCaretContainer = function (body, node) {
  9794. while (node && node !== body) {
  9795. if (node.id === CARET_ID$1) {
  9796. return node;
  9797. }
  9798. node = node.parentNode;
  9799. }
  9800. return null;
  9801. };
  9802. var isStringPathBookmark = function (bookmark) {
  9803. return isString$1(bookmark.start);
  9804. };
  9805. var isRangeBookmark = function (bookmark) {
  9806. return has$2(bookmark, 'rng');
  9807. };
  9808. var isIdBookmark = function (bookmark) {
  9809. return has$2(bookmark, 'id');
  9810. };
  9811. var isIndexBookmark = function (bookmark) {
  9812. return has$2(bookmark, 'name');
  9813. };
  9814. var isPathBookmark = function (bookmark) {
  9815. return Tools.isArray(bookmark.start);
  9816. };
  9817. var addBogus = function (dom, node) {
  9818. if (isElement$5(node) && dom.isBlock(node) && !node.innerHTML && !Env.ie) {
  9819. node.innerHTML = '<br data-mce-bogus="1" />';
  9820. }
  9821. return node;
  9822. };
  9823. var resolveCaretPositionBookmark = function (dom, bookmark) {
  9824. var pos;
  9825. var rng = dom.createRng();
  9826. pos = resolve$2(dom.getRoot(), bookmark.start);
  9827. rng.setStart(pos.container(), pos.offset());
  9828. pos = resolve$2(dom.getRoot(), bookmark.end);
  9829. rng.setEnd(pos.container(), pos.offset());
  9830. return rng;
  9831. };
  9832. var insertZwsp = function (node, rng) {
  9833. var textNode = node.ownerDocument.createTextNode(ZWSP$1);
  9834. node.appendChild(textNode);
  9835. rng.setStart(textNode, 0);
  9836. rng.setEnd(textNode, 0);
  9837. };
  9838. var isEmpty$1 = function (node) {
  9839. return node.hasChildNodes() === false;
  9840. };
  9841. var tryFindRangePosition = function (node, rng) {
  9842. return lastPositionIn(node).fold(never, function (pos) {
  9843. rng.setStart(pos.container(), pos.offset());
  9844. rng.setEnd(pos.container(), pos.offset());
  9845. return true;
  9846. });
  9847. };
  9848. var padEmptyCaretContainer = function (root, node, rng) {
  9849. if (isEmpty$1(node) && getParentCaretContainer(root, node)) {
  9850. insertZwsp(node, rng);
  9851. return true;
  9852. } else {
  9853. return false;
  9854. }
  9855. };
  9856. var setEndPoint = function (dom, start, bookmark, rng) {
  9857. var point = bookmark[start ? 'start' : 'end'];
  9858. var i, node, offset, children;
  9859. var root = dom.getRoot();
  9860. if (point) {
  9861. offset = point[0];
  9862. for (node = root, i = point.length - 1; i >= 1; i--) {
  9863. children = node.childNodes;
  9864. if (padEmptyCaretContainer(root, node, rng)) {
  9865. return true;
  9866. }
  9867. if (point[i] > children.length - 1) {
  9868. if (padEmptyCaretContainer(root, node, rng)) {
  9869. return true;
  9870. }
  9871. return tryFindRangePosition(node, rng);
  9872. }
  9873. node = children[point[i]];
  9874. }
  9875. if (node.nodeType === 3) {
  9876. offset = Math.min(point[0], node.nodeValue.length);
  9877. }
  9878. if (node.nodeType === 1) {
  9879. offset = Math.min(point[0], node.childNodes.length);
  9880. }
  9881. if (start) {
  9882. rng.setStart(node, offset);
  9883. } else {
  9884. rng.setEnd(node, offset);
  9885. }
  9886. }
  9887. return true;
  9888. };
  9889. var isValidTextNode = function (node) {
  9890. return isText$7(node) && node.data.length > 0;
  9891. };
  9892. var restoreEndPoint = function (dom, suffix, bookmark) {
  9893. var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev;
  9894. var keep = bookmark.keep;
  9895. var container, offset;
  9896. if (marker) {
  9897. node = marker.parentNode;
  9898. if (suffix === 'start') {
  9899. if (!keep) {
  9900. idx = dom.nodeIndex(marker);
  9901. } else {
  9902. if (marker.hasChildNodes()) {
  9903. node = marker.firstChild;
  9904. idx = 1;
  9905. } else if (isValidTextNode(marker.nextSibling)) {
  9906. node = marker.nextSibling;
  9907. idx = 0;
  9908. } else if (isValidTextNode(marker.previousSibling)) {
  9909. node = marker.previousSibling;
  9910. idx = marker.previousSibling.data.length;
  9911. } else {
  9912. node = marker.parentNode;
  9913. idx = dom.nodeIndex(marker) + 1;
  9914. }
  9915. }
  9916. container = node;
  9917. offset = idx;
  9918. } else {
  9919. if (!keep) {
  9920. idx = dom.nodeIndex(marker);
  9921. } else {
  9922. if (marker.hasChildNodes()) {
  9923. node = marker.firstChild;
  9924. idx = 1;
  9925. } else if (isValidTextNode(marker.previousSibling)) {
  9926. node = marker.previousSibling;
  9927. idx = marker.previousSibling.data.length;
  9928. } else {
  9929. node = marker.parentNode;
  9930. idx = dom.nodeIndex(marker);
  9931. }
  9932. }
  9933. container = node;
  9934. offset = idx;
  9935. }
  9936. if (!keep) {
  9937. prev = marker.previousSibling;
  9938. next = marker.nextSibling;
  9939. Tools.each(Tools.grep(marker.childNodes), function (node) {
  9940. if (isText$7(node)) {
  9941. node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
  9942. }
  9943. });
  9944. while (marker = dom.get(bookmark.id + '_' + suffix)) {
  9945. dom.remove(marker, true);
  9946. }
  9947. if (prev && next && prev.nodeType === next.nodeType && isText$7(prev) && !Env.opera) {
  9948. idx = prev.nodeValue.length;
  9949. prev.appendData(next.nodeValue);
  9950. dom.remove(next);
  9951. container = prev;
  9952. offset = idx;
  9953. }
  9954. }
  9955. return Optional.some(CaretPosition(container, offset));
  9956. } else {
  9957. return Optional.none();
  9958. }
  9959. };
  9960. var resolvePaths = function (dom, bookmark) {
  9961. var rng = dom.createRng();
  9962. if (setEndPoint(dom, true, bookmark, rng) && setEndPoint(dom, false, bookmark, rng)) {
  9963. return Optional.some(rng);
  9964. } else {
  9965. return Optional.none();
  9966. }
  9967. };
  9968. var resolveId = function (dom, bookmark) {
  9969. var startPos = restoreEndPoint(dom, 'start', bookmark);
  9970. var endPos = restoreEndPoint(dom, 'end', bookmark);
  9971. return lift2(startPos, endPos.or(startPos), function (spos, epos) {
  9972. var rng = dom.createRng();
  9973. rng.setStart(addBogus(dom, spos.container()), spos.offset());
  9974. rng.setEnd(addBogus(dom, epos.container()), epos.offset());
  9975. return rng;
  9976. });
  9977. };
  9978. var resolveIndex = function (dom, bookmark) {
  9979. return Optional.from(dom.select(bookmark.name)[bookmark.index]).map(function (elm) {
  9980. var rng = dom.createRng();
  9981. rng.selectNode(elm);
  9982. return rng;
  9983. });
  9984. };
  9985. var resolve$1 = function (selection, bookmark) {
  9986. var dom = selection.dom;
  9987. if (bookmark) {
  9988. if (isPathBookmark(bookmark)) {
  9989. return resolvePaths(dom, bookmark);
  9990. } else if (isStringPathBookmark(bookmark)) {
  9991. return Optional.some(resolveCaretPositionBookmark(dom, bookmark));
  9992. } else if (isIdBookmark(bookmark)) {
  9993. return resolveId(dom, bookmark);
  9994. } else if (isIndexBookmark(bookmark)) {
  9995. return resolveIndex(dom, bookmark);
  9996. } else if (isRangeBookmark(bookmark)) {
  9997. return Optional.some(bookmark.rng);
  9998. }
  9999. }
  10000. return Optional.none();
  10001. };
  10002. var getBookmark$1 = function (selection, type, normalized) {
  10003. return getBookmark$2(selection, type, normalized);
  10004. };
  10005. var moveToBookmark = function (selection, bookmark) {
  10006. resolve$1(selection, bookmark).each(function (rng) {
  10007. selection.setRng(rng);
  10008. });
  10009. };
  10010. var isBookmarkNode$1 = function (node) {
  10011. return isElement$5(node) && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
  10012. };
  10013. var is = function (expected) {
  10014. return function (actual) {
  10015. return expected === actual;
  10016. };
  10017. };
  10018. var isNbsp = is(nbsp);
  10019. var isWhiteSpace = function (chr) {
  10020. return chr !== '' && ' \f\n\r\t\x0B'.indexOf(chr) !== -1;
  10021. };
  10022. var isContent = function (chr) {
  10023. return !isWhiteSpace(chr) && !isNbsp(chr);
  10024. };
  10025. var isNode = function (node) {
  10026. return !!node.nodeType;
  10027. };
  10028. var isInlineBlock = function (node) {
  10029. return node && /^(IMG)$/.test(node.nodeName);
  10030. };
  10031. var moveStart = function (dom, selection, rng) {
  10032. var offset = rng.startOffset;
  10033. var container = rng.startContainer;
  10034. if (container === rng.endContainer) {
  10035. if (isInlineBlock(container.childNodes[offset])) {
  10036. return;
  10037. }
  10038. }
  10039. if (isElement$5(container)) {
  10040. var nodes = container.childNodes;
  10041. var walker = void 0;
  10042. if (offset < nodes.length) {
  10043. container = nodes[offset];
  10044. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10045. } else {
  10046. container = nodes[nodes.length - 1];
  10047. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10048. walker.next(true);
  10049. }
  10050. for (var node = walker.current(); node; node = walker.next()) {
  10051. if (isText$7(node) && !isWhiteSpaceNode$1(node)) {
  10052. rng.setStart(node, 0);
  10053. selection.setRng(rng);
  10054. return;
  10055. }
  10056. }
  10057. }
  10058. };
  10059. var getNonWhiteSpaceSibling = function (node, next, inc) {
  10060. if (node) {
  10061. var nextName = next ? 'nextSibling' : 'previousSibling';
  10062. for (node = inc ? node : node[nextName]; node; node = node[nextName]) {
  10063. if (isElement$5(node) || !isWhiteSpaceNode$1(node)) {
  10064. return node;
  10065. }
  10066. }
  10067. }
  10068. };
  10069. var isTextBlock$1 = function (editor, name) {
  10070. if (isNode(name)) {
  10071. name = name.nodeName;
  10072. }
  10073. return !!editor.schema.getTextBlockElements()[name.toLowerCase()];
  10074. };
  10075. var isValid = function (ed, parent, child) {
  10076. return ed.schema.isValidChild(parent, child);
  10077. };
  10078. var isWhiteSpaceNode$1 = function (node, allowSpaces) {
  10079. if (allowSpaces === void 0) {
  10080. allowSpaces = false;
  10081. }
  10082. if (isNonNullable(node) && isText$7(node)) {
  10083. var data = allowSpaces ? node.data.replace(/ /g, '\xA0') : node.data;
  10084. return isWhitespaceText(data);
  10085. } else {
  10086. return false;
  10087. }
  10088. };
  10089. var isEmptyTextNode$1 = function (node) {
  10090. return isNonNullable(node) && isText$7(node) && node.length === 0;
  10091. };
  10092. var replaceVars = function (value, vars) {
  10093. if (isFunction(value)) {
  10094. value = value(vars);
  10095. } else if (isNonNullable(vars)) {
  10096. value = value.replace(/%(\w+)/g, function (str, name) {
  10097. return vars[name] || str;
  10098. });
  10099. }
  10100. return value;
  10101. };
  10102. var isEq$5 = function (str1, str2) {
  10103. str1 = str1 || '';
  10104. str2 = str2 || '';
  10105. str1 = '' + (str1.nodeName || str1);
  10106. str2 = '' + (str2.nodeName || str2);
  10107. return str1.toLowerCase() === str2.toLowerCase();
  10108. };
  10109. var normalizeStyleValue = function (dom, value, name) {
  10110. if (name === 'color' || name === 'backgroundColor') {
  10111. value = dom.toHex(value);
  10112. }
  10113. if (name === 'fontWeight' && value === 700) {
  10114. value = 'bold';
  10115. }
  10116. if (name === 'fontFamily') {
  10117. value = value.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
  10118. }
  10119. return '' + value;
  10120. };
  10121. var getStyle = function (dom, node, name) {
  10122. return normalizeStyleValue(dom, dom.getStyle(node, name), name);
  10123. };
  10124. var getTextDecoration = function (dom, node) {
  10125. var decoration;
  10126. dom.getParent(node, function (n) {
  10127. decoration = dom.getStyle(n, 'text-decoration');
  10128. return decoration && decoration !== 'none';
  10129. });
  10130. return decoration;
  10131. };
  10132. var getParents$2 = function (dom, node, selector) {
  10133. return dom.getParents(node, selector, dom.getRoot());
  10134. };
  10135. var isVariableFormatName = function (editor, formatName) {
  10136. var hasVariableValues = function (format) {
  10137. var isVariableValue = function (val) {
  10138. return val.length > 1 && val.charAt(0) === '%';
  10139. };
  10140. return exists([
  10141. 'styles',
  10142. 'attributes'
  10143. ], function (key) {
  10144. return get$9(format, key).exists(function (field) {
  10145. var fieldValues = isArray$1(field) ? field : values(field);
  10146. return exists(fieldValues, isVariableValue);
  10147. });
  10148. });
  10149. };
  10150. return exists(editor.formatter.get(formatName), hasVariableValues);
  10151. };
  10152. var areSimilarFormats = function (editor, formatName, otherFormatName) {
  10153. var validKeys = [
  10154. 'inline',
  10155. 'block',
  10156. 'selector',
  10157. 'attributes',
  10158. 'styles',
  10159. 'classes'
  10160. ];
  10161. var filterObj = function (format) {
  10162. return filter$3(format, function (_, key) {
  10163. return exists(validKeys, function (validKey) {
  10164. return validKey === key;
  10165. });
  10166. });
  10167. };
  10168. return exists(editor.formatter.get(formatName), function (fmt1) {
  10169. var filteredFmt1 = filterObj(fmt1);
  10170. return exists(editor.formatter.get(otherFormatName), function (fmt2) {
  10171. var filteredFmt2 = filterObj(fmt2);
  10172. return equal$1(filteredFmt1, filteredFmt2);
  10173. });
  10174. });
  10175. };
  10176. var isBlockFormat = function (format) {
  10177. return hasNonNullableKey(format, 'block');
  10178. };
  10179. var isSelectorFormat = function (format) {
  10180. return hasNonNullableKey(format, 'selector');
  10181. };
  10182. var isInlineFormat = function (format) {
  10183. return hasNonNullableKey(format, 'inline');
  10184. };
  10185. var isMixedFormat = function (format) {
  10186. return isSelectorFormat(format) && isInlineFormat(format) && is$1(get$9(format, 'mixed'), true);
  10187. };
  10188. var shouldExpandToSelector = function (format) {
  10189. return isSelectorFormat(format) && format.expand !== false && !isInlineFormat(format);
  10190. };
  10191. var isBookmarkNode = isBookmarkNode$1;
  10192. var getParents$1 = getParents$2;
  10193. var isWhiteSpaceNode = isWhiteSpaceNode$1;
  10194. var isTextBlock = isTextBlock$1;
  10195. var isBogusBr = function (node) {
  10196. return isBr$5(node) && node.getAttribute('data-mce-bogus') && !node.nextSibling;
  10197. };
  10198. var findParentContentEditable = function (dom, node) {
  10199. var parent = node;
  10200. while (parent) {
  10201. if (isElement$5(parent) && dom.getContentEditable(parent)) {
  10202. return dom.getContentEditable(parent) === 'false' ? parent : node;
  10203. }
  10204. parent = parent.parentNode;
  10205. }
  10206. return node;
  10207. };
  10208. var walkText = function (start, node, offset, predicate) {
  10209. var str = node.data;
  10210. for (var i = offset; start ? i >= 0 : i < str.length; start ? i-- : i++) {
  10211. if (predicate(str.charAt(i))) {
  10212. return start ? i + 1 : i;
  10213. }
  10214. }
  10215. return -1;
  10216. };
  10217. var findSpace = function (start, node, offset) {
  10218. return walkText(start, node, offset, function (c) {
  10219. return isNbsp(c) || isWhiteSpace(c);
  10220. });
  10221. };
  10222. var findContent = function (start, node, offset) {
  10223. return walkText(start, node, offset, isContent);
  10224. };
  10225. var findWordEndPoint = function (dom, body, container, offset, start, includeTrailingSpaces) {
  10226. var lastTextNode;
  10227. var rootNode = dom.getParent(container, dom.isBlock) || body;
  10228. var walk = function (container, offset, pred) {
  10229. var textSeeker = TextSeeker(dom);
  10230. var walker = start ? textSeeker.backwards : textSeeker.forwards;
  10231. return Optional.from(walker(container, offset, function (text, textOffset) {
  10232. if (isBookmarkNode(text.parentNode)) {
  10233. return -1;
  10234. } else {
  10235. lastTextNode = text;
  10236. return pred(start, text, textOffset);
  10237. }
  10238. }, rootNode));
  10239. };
  10240. var spaceResult = walk(container, offset, findSpace);
  10241. return spaceResult.bind(function (result) {
  10242. return includeTrailingSpaces ? walk(result.container, result.offset + (start ? -1 : 0), findContent) : Optional.some(result);
  10243. }).orThunk(function () {
  10244. return lastTextNode ? Optional.some({
  10245. container: lastTextNode,
  10246. offset: start ? 0 : lastTextNode.length
  10247. }) : Optional.none();
  10248. });
  10249. };
  10250. var findSelectorEndPoint = function (dom, formatList, rng, container, siblingName) {
  10251. if (isText$7(container) && isEmpty$3(container.data) && container[siblingName]) {
  10252. container = container[siblingName];
  10253. }
  10254. var parents = getParents$1(dom, container);
  10255. for (var i = 0; i < parents.length; i++) {
  10256. for (var y = 0; y < formatList.length; y++) {
  10257. var curFormat = formatList[y];
  10258. if (isNonNullable(curFormat.collapsed) && curFormat.collapsed !== rng.collapsed) {
  10259. continue;
  10260. }
  10261. if (isSelectorFormat(curFormat) && dom.is(parents[i], curFormat.selector)) {
  10262. return parents[i];
  10263. }
  10264. }
  10265. }
  10266. return container;
  10267. };
  10268. var findBlockEndPoint = function (editor, formatList, container, siblingName) {
  10269. var node = container;
  10270. var dom = editor.dom;
  10271. var root = dom.getRoot();
  10272. var format = formatList[0];
  10273. if (isBlockFormat(format)) {
  10274. node = format.wrapper ? null : dom.getParent(container, format.block, root);
  10275. }
  10276. if (!node) {
  10277. var scopeRoot = dom.getParent(container, 'LI,TD,TH');
  10278. node = dom.getParent(isText$7(container) ? container.parentNode : container, function (node) {
  10279. return node !== root && isTextBlock(editor, node);
  10280. }, scopeRoot);
  10281. }
  10282. if (node && isBlockFormat(format) && format.wrapper) {
  10283. node = getParents$1(dom, node, 'ul,ol').reverse()[0] || node;
  10284. }
  10285. if (!node) {
  10286. node = container;
  10287. while (node[siblingName] && !dom.isBlock(node[siblingName])) {
  10288. node = node[siblingName];
  10289. if (isEq$5(node, 'br')) {
  10290. break;
  10291. }
  10292. }
  10293. }
  10294. return node || container;
  10295. };
  10296. var isAtBlockBoundary$1 = function (dom, root, container, siblingName) {
  10297. var parent = container.parentNode;
  10298. if (isNonNullable(container[siblingName])) {
  10299. return false;
  10300. } else if (parent === root || isNullable(parent) || dom.isBlock(parent)) {
  10301. return true;
  10302. } else {
  10303. return isAtBlockBoundary$1(dom, root, parent, siblingName);
  10304. }
  10305. };
  10306. var findParentContainer = function (dom, formatList, container, offset, start) {
  10307. var parent = container;
  10308. var siblingName = start ? 'previousSibling' : 'nextSibling';
  10309. var root = dom.getRoot();
  10310. if (isText$7(container) && !isWhiteSpaceNode(container)) {
  10311. if (start ? offset > 0 : offset < container.data.length) {
  10312. return container;
  10313. }
  10314. }
  10315. while (true) {
  10316. if (!formatList[0].block_expand && dom.isBlock(parent)) {
  10317. return parent;
  10318. }
  10319. for (var sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
  10320. var allowSpaces = isText$7(sibling) && !isAtBlockBoundary$1(dom, root, sibling, siblingName);
  10321. if (!isBookmarkNode(sibling) && !isBogusBr(sibling) && !isWhiteSpaceNode(sibling, allowSpaces)) {
  10322. return parent;
  10323. }
  10324. }
  10325. if (parent === root || parent.parentNode === root) {
  10326. container = parent;
  10327. break;
  10328. }
  10329. parent = parent.parentNode;
  10330. }
  10331. return container;
  10332. };
  10333. var isSelfOrParentBookmark = function (container) {
  10334. return isBookmarkNode(container.parentNode) || isBookmarkNode(container);
  10335. };
  10336. var expandRng = function (editor, rng, formatList, includeTrailingSpace) {
  10337. if (includeTrailingSpace === void 0) {
  10338. includeTrailingSpace = false;
  10339. }
  10340. var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  10341. var dom = editor.dom;
  10342. var format = formatList[0];
  10343. if (isElement$5(startContainer) && startContainer.hasChildNodes()) {
  10344. startContainer = getNode$1(startContainer, startOffset);
  10345. if (isText$7(startContainer)) {
  10346. startOffset = 0;
  10347. }
  10348. }
  10349. if (isElement$5(endContainer) && endContainer.hasChildNodes()) {
  10350. endContainer = getNode$1(endContainer, rng.collapsed ? endOffset : endOffset - 1);
  10351. if (isText$7(endContainer)) {
  10352. endOffset = endContainer.nodeValue.length;
  10353. }
  10354. }
  10355. startContainer = findParentContentEditable(dom, startContainer);
  10356. endContainer = findParentContentEditable(dom, endContainer);
  10357. if (isSelfOrParentBookmark(startContainer)) {
  10358. startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
  10359. if (rng.collapsed) {
  10360. startContainer = startContainer.previousSibling || startContainer;
  10361. } else {
  10362. startContainer = startContainer.nextSibling || startContainer;
  10363. }
  10364. if (isText$7(startContainer)) {
  10365. startOffset = rng.collapsed ? startContainer.length : 0;
  10366. }
  10367. }
  10368. if (isSelfOrParentBookmark(endContainer)) {
  10369. endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
  10370. if (rng.collapsed) {
  10371. endContainer = endContainer.nextSibling || endContainer;
  10372. } else {
  10373. endContainer = endContainer.previousSibling || endContainer;
  10374. }
  10375. if (isText$7(endContainer)) {
  10376. endOffset = rng.collapsed ? 0 : endContainer.length;
  10377. }
  10378. }
  10379. if (rng.collapsed) {
  10380. var startPoint = findWordEndPoint(dom, editor.getBody(), startContainer, startOffset, true, includeTrailingSpace);
  10381. startPoint.each(function (_a) {
  10382. var container = _a.container, offset = _a.offset;
  10383. startContainer = container;
  10384. startOffset = offset;
  10385. });
  10386. var endPoint = findWordEndPoint(dom, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
  10387. endPoint.each(function (_a) {
  10388. var container = _a.container, offset = _a.offset;
  10389. endContainer = container;
  10390. endOffset = offset;
  10391. });
  10392. }
  10393. if (isInlineFormat(format) || format.block_expand) {
  10394. if (!isInlineFormat(format) || (!isText$7(startContainer) || startOffset === 0)) {
  10395. startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  10396. }
  10397. if (!isInlineFormat(format) || (!isText$7(endContainer) || endOffset === endContainer.nodeValue.length)) {
  10398. endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  10399. }
  10400. }
  10401. if (shouldExpandToSelector(format)) {
  10402. startContainer = findSelectorEndPoint(dom, formatList, rng, startContainer, 'previousSibling');
  10403. endContainer = findSelectorEndPoint(dom, formatList, rng, endContainer, 'nextSibling');
  10404. }
  10405. if (isBlockFormat(format) || isSelectorFormat(format)) {
  10406. startContainer = findBlockEndPoint(editor, formatList, startContainer, 'previousSibling');
  10407. endContainer = findBlockEndPoint(editor, formatList, endContainer, 'nextSibling');
  10408. if (isBlockFormat(format)) {
  10409. if (!dom.isBlock(startContainer)) {
  10410. startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  10411. }
  10412. if (!dom.isBlock(endContainer)) {
  10413. endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  10414. }
  10415. }
  10416. }
  10417. if (isElement$5(startContainer)) {
  10418. startOffset = dom.nodeIndex(startContainer);
  10419. startContainer = startContainer.parentNode;
  10420. }
  10421. if (isElement$5(endContainer)) {
  10422. endOffset = dom.nodeIndex(endContainer) + 1;
  10423. endContainer = endContainer.parentNode;
  10424. }
  10425. return {
  10426. startContainer: startContainer,
  10427. startOffset: startOffset,
  10428. endContainer: endContainer,
  10429. endOffset: endOffset
  10430. };
  10431. };
  10432. var walk$2 = function (dom, rng, callback) {
  10433. var startOffset = rng.startOffset;
  10434. var startContainer = getNode$1(rng.startContainer, startOffset);
  10435. var endOffset = rng.endOffset;
  10436. var endContainer = getNode$1(rng.endContainer, endOffset - 1);
  10437. var exclude = function (nodes) {
  10438. var firstNode = nodes[0];
  10439. if (isText$7(firstNode) && firstNode === startContainer && startOffset >= firstNode.data.length) {
  10440. nodes.splice(0, 1);
  10441. }
  10442. var lastNode = nodes[nodes.length - 1];
  10443. if (endOffset === 0 && nodes.length > 0 && lastNode === endContainer && isText$7(lastNode)) {
  10444. nodes.splice(nodes.length - 1, 1);
  10445. }
  10446. return nodes;
  10447. };
  10448. var collectSiblings = function (node, name, endNode) {
  10449. var siblings = [];
  10450. for (; node && node !== endNode; node = node[name]) {
  10451. siblings.push(node);
  10452. }
  10453. return siblings;
  10454. };
  10455. var findEndPoint = function (node, root) {
  10456. return dom.getParent(node, function (node) {
  10457. return node.parentNode === root;
  10458. }, root);
  10459. };
  10460. var walkBoundary = function (startNode, endNode, next) {
  10461. var siblingName = next ? 'nextSibling' : 'previousSibling';
  10462. for (var node = startNode, parent_1 = node.parentNode; node && node !== endNode; node = parent_1) {
  10463. parent_1 = node.parentNode;
  10464. var siblings_1 = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
  10465. if (siblings_1.length) {
  10466. if (!next) {
  10467. siblings_1.reverse();
  10468. }
  10469. callback(exclude(siblings_1));
  10470. }
  10471. }
  10472. };
  10473. if (startContainer === endContainer) {
  10474. return callback(exclude([startContainer]));
  10475. }
  10476. var ancestor = dom.findCommonAncestor(startContainer, endContainer);
  10477. if (dom.isChildOf(startContainer, endContainer)) {
  10478. return walkBoundary(startContainer, ancestor, true);
  10479. }
  10480. if (dom.isChildOf(endContainer, startContainer)) {
  10481. return walkBoundary(endContainer, ancestor);
  10482. }
  10483. var startPoint = findEndPoint(startContainer, ancestor) || startContainer;
  10484. var endPoint = findEndPoint(endContainer, ancestor) || endContainer;
  10485. walkBoundary(startContainer, startPoint, true);
  10486. var siblings = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint === endContainer ? endPoint.nextSibling : endPoint);
  10487. if (siblings.length) {
  10488. callback(exclude(siblings));
  10489. }
  10490. walkBoundary(endContainer, endPoint);
  10491. };
  10492. var getRanges = function (selection) {
  10493. var ranges = [];
  10494. if (selection) {
  10495. for (var i = 0; i < selection.rangeCount; i++) {
  10496. ranges.push(selection.getRangeAt(i));
  10497. }
  10498. }
  10499. return ranges;
  10500. };
  10501. var getSelectedNodes = function (ranges) {
  10502. return bind(ranges, function (range) {
  10503. var node = getSelectedNode(range);
  10504. return node ? [SugarElement.fromDom(node)] : [];
  10505. });
  10506. };
  10507. var hasMultipleRanges = function (selection) {
  10508. return getRanges(selection).length > 1;
  10509. };
  10510. var getCellsFromRanges = function (ranges) {
  10511. return filter$4(getSelectedNodes(ranges), isTableCell$4);
  10512. };
  10513. var getCellsFromElement = function (elm) {
  10514. return descendants(elm, 'td[data-mce-selected],th[data-mce-selected]');
  10515. };
  10516. var getCellsFromElementOrRanges = function (ranges, element) {
  10517. var selectedCells = getCellsFromElement(element);
  10518. return selectedCells.length > 0 ? selectedCells : getCellsFromRanges(ranges);
  10519. };
  10520. var getCellsFromEditor = function (editor) {
  10521. return getCellsFromElementOrRanges(getRanges(editor.selection.getSel()), SugarElement.fromDom(editor.getBody()));
  10522. };
  10523. var getClosestTable = function (cell, isRoot) {
  10524. return ancestor$2(cell, 'table', isRoot);
  10525. };
  10526. var getStartNode = function (rng) {
  10527. var sc = rng.startContainer, so = rng.startOffset;
  10528. if (isText$7(sc)) {
  10529. return so === 0 ? Optional.some(SugarElement.fromDom(sc)) : Optional.none();
  10530. } else {
  10531. return Optional.from(sc.childNodes[so]).map(SugarElement.fromDom);
  10532. }
  10533. };
  10534. var getEndNode = function (rng) {
  10535. var ec = rng.endContainer, eo = rng.endOffset;
  10536. if (isText$7(ec)) {
  10537. return eo === ec.data.length ? Optional.some(SugarElement.fromDom(ec)) : Optional.none();
  10538. } else {
  10539. return Optional.from(ec.childNodes[eo - 1]).map(SugarElement.fromDom);
  10540. }
  10541. };
  10542. var getFirstChildren = function (node) {
  10543. return firstChild(node).fold(constant([node]), function (child) {
  10544. return [node].concat(getFirstChildren(child));
  10545. });
  10546. };
  10547. var getLastChildren$1 = function (node) {
  10548. return lastChild(node).fold(constant([node]), function (child) {
  10549. if (name(child) === 'br') {
  10550. return prevSibling(child).map(function (sibling) {
  10551. return [node].concat(getLastChildren$1(sibling));
  10552. }).getOr([]);
  10553. } else {
  10554. return [node].concat(getLastChildren$1(child));
  10555. }
  10556. });
  10557. };
  10558. var hasAllContentsSelected = function (elm, rng) {
  10559. return lift2(getStartNode(rng), getEndNode(rng), function (startNode, endNode) {
  10560. var start = find$3(getFirstChildren(elm), curry(eq, startNode));
  10561. var end = find$3(getLastChildren$1(elm), curry(eq, endNode));
  10562. return start.isSome() && end.isSome();
  10563. }).getOr(false);
  10564. };
  10565. var moveEndPoint = function (dom, rng, node, start) {
  10566. var root = node, walker = new DomTreeWalker(node, root);
  10567. var moveCaretBeforeOnEnterElementsMap = filter$3(dom.schema.getMoveCaretBeforeOnEnterElements(), function (_, name) {
  10568. return !contains$3([
  10569. 'td',
  10570. 'th',
  10571. 'table'
  10572. ], name.toLowerCase());
  10573. });
  10574. do {
  10575. if (isText$7(node) && Tools.trim(node.nodeValue).length !== 0) {
  10576. if (start) {
  10577. rng.setStart(node, 0);
  10578. } else {
  10579. rng.setEnd(node, node.nodeValue.length);
  10580. }
  10581. return;
  10582. }
  10583. if (moveCaretBeforeOnEnterElementsMap[node.nodeName]) {
  10584. if (start) {
  10585. rng.setStartBefore(node);
  10586. } else {
  10587. if (node.nodeName === 'BR') {
  10588. rng.setEndBefore(node);
  10589. } else {
  10590. rng.setEndAfter(node);
  10591. }
  10592. }
  10593. return;
  10594. }
  10595. } while (node = start ? walker.next() : walker.prev());
  10596. if (root.nodeName === 'BODY') {
  10597. if (start) {
  10598. rng.setStart(root, 0);
  10599. } else {
  10600. rng.setEnd(root, root.childNodes.length);
  10601. }
  10602. }
  10603. };
  10604. var hasAnyRanges = function (editor) {
  10605. var sel = editor.selection.getSel();
  10606. return sel && sel.rangeCount > 0;
  10607. };
  10608. var runOnRanges = function (editor, executor) {
  10609. var fakeSelectionNodes = getCellsFromEditor(editor);
  10610. if (fakeSelectionNodes.length > 0) {
  10611. each$k(fakeSelectionNodes, function (elem) {
  10612. var node = elem.dom;
  10613. var fakeNodeRng = editor.dom.createRng();
  10614. fakeNodeRng.setStartBefore(node);
  10615. fakeNodeRng.setEndAfter(node);
  10616. executor(fakeNodeRng, true);
  10617. });
  10618. } else {
  10619. executor(editor.selection.getRng(), false);
  10620. }
  10621. };
  10622. var preserve = function (selection, fillBookmark, executor) {
  10623. var bookmark = getPersistentBookmark(selection, fillBookmark);
  10624. executor(bookmark);
  10625. selection.moveToBookmark(bookmark);
  10626. };
  10627. var NodeValue = function (is, name) {
  10628. var get = function (element) {
  10629. if (!is(element)) {
  10630. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  10631. }
  10632. return getOption(element).getOr('');
  10633. };
  10634. var getOption = function (element) {
  10635. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  10636. };
  10637. var set = function (element, value) {
  10638. if (!is(element)) {
  10639. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  10640. }
  10641. element.dom.nodeValue = value;
  10642. };
  10643. return {
  10644. get: get,
  10645. getOption: getOption,
  10646. set: set
  10647. };
  10648. };
  10649. var api$1 = NodeValue(isText$8, 'text');
  10650. var get$2 = function (element) {
  10651. return api$1.get(element);
  10652. };
  10653. var isZeroWidth = function (elem) {
  10654. return isText$8(elem) && get$2(elem) === ZWSP$1;
  10655. };
  10656. var context = function (editor, elem, wrapName, nodeName) {
  10657. return parent(elem).fold(function () {
  10658. return 'skipping';
  10659. }, function (parent) {
  10660. if (nodeName === 'br' || isZeroWidth(elem)) {
  10661. return 'valid';
  10662. } else if (isAnnotation(elem)) {
  10663. return 'existing';
  10664. } else if (isCaretNode(elem.dom)) {
  10665. return 'caret';
  10666. } else if (!isValid(editor, wrapName, nodeName) || !isValid(editor, name(parent), wrapName)) {
  10667. return 'invalid-child';
  10668. } else {
  10669. return 'valid';
  10670. }
  10671. });
  10672. };
  10673. var applyWordGrab = function (editor, rng) {
  10674. var r = expandRng(editor, rng, [{ inline: 'span' }]);
  10675. rng.setStart(r.startContainer, r.startOffset);
  10676. rng.setEnd(r.endContainer, r.endOffset);
  10677. editor.selection.setRng(rng);
  10678. };
  10679. var makeAnnotation = function (eDoc, _a, annotationName, decorate) {
  10680. var _b = _a.uid, uid = _b === void 0 ? generate('mce-annotation') : _b, data = __rest(_a, ['uid']);
  10681. var master = SugarElement.fromTag('span', eDoc);
  10682. add$1(master, annotation());
  10683. set$1(master, '' + dataAnnotationId(), uid);
  10684. set$1(master, '' + dataAnnotation(), annotationName);
  10685. var _c = decorate(uid, data), _d = _c.attributes, attributes = _d === void 0 ? {} : _d, _e = _c.classes, classes = _e === void 0 ? [] : _e;
  10686. setAll$1(master, attributes);
  10687. add(master, classes);
  10688. return master;
  10689. };
  10690. var annotate = function (editor, rng, annotationName, decorate, data) {
  10691. var newWrappers = [];
  10692. var master = makeAnnotation(editor.getDoc(), data, annotationName, decorate);
  10693. var wrapper = value();
  10694. var finishWrapper = function () {
  10695. wrapper.clear();
  10696. };
  10697. var getOrOpenWrapper = function () {
  10698. return wrapper.get().getOrThunk(function () {
  10699. var nu = shallow(master);
  10700. newWrappers.push(nu);
  10701. wrapper.set(nu);
  10702. return nu;
  10703. });
  10704. };
  10705. var processElements = function (elems) {
  10706. each$k(elems, processElement);
  10707. };
  10708. var processElement = function (elem) {
  10709. var ctx = context(editor, elem, 'span', name(elem));
  10710. switch (ctx) {
  10711. case 'invalid-child': {
  10712. finishWrapper();
  10713. var children$1 = children(elem);
  10714. processElements(children$1);
  10715. finishWrapper();
  10716. break;
  10717. }
  10718. case 'valid': {
  10719. var w = getOrOpenWrapper();
  10720. wrap$3(elem, w);
  10721. break;
  10722. }
  10723. }
  10724. };
  10725. var processNodes = function (nodes) {
  10726. var elems = map$3(nodes, SugarElement.fromDom);
  10727. processElements(elems);
  10728. };
  10729. walk$2(editor.dom, rng, function (nodes) {
  10730. finishWrapper();
  10731. processNodes(nodes);
  10732. });
  10733. return newWrappers;
  10734. };
  10735. var annotateWithBookmark = function (editor, name, settings, data) {
  10736. editor.undoManager.transact(function () {
  10737. var selection = editor.selection;
  10738. var initialRng = selection.getRng();
  10739. var hasFakeSelection = getCellsFromEditor(editor).length > 0;
  10740. if (initialRng.collapsed && !hasFakeSelection) {
  10741. applyWordGrab(editor, initialRng);
  10742. }
  10743. if (selection.getRng().collapsed && !hasFakeSelection) {
  10744. var wrapper = makeAnnotation(editor.getDoc(), data, name, settings.decorate);
  10745. set(wrapper, nbsp);
  10746. selection.getRng().insertNode(wrapper.dom);
  10747. selection.select(wrapper.dom);
  10748. } else {
  10749. preserve(selection, false, function () {
  10750. runOnRanges(editor, function (selectionRng) {
  10751. annotate(editor, selectionRng, name, settings.decorate, data);
  10752. });
  10753. });
  10754. }
  10755. });
  10756. };
  10757. var Annotator = function (editor) {
  10758. var registry = create$7();
  10759. setup$m(editor, registry);
  10760. var changes = setup$n(editor);
  10761. return {
  10762. register: function (name, settings) {
  10763. registry.register(name, settings);
  10764. },
  10765. annotate: function (name, data) {
  10766. registry.lookup(name).each(function (settings) {
  10767. annotateWithBookmark(editor, name, settings, data);
  10768. });
  10769. },
  10770. annotationChanged: function (name, callback) {
  10771. changes.addListener(name, callback);
  10772. },
  10773. remove: function (name) {
  10774. identify(editor, Optional.some(name)).each(function (_a) {
  10775. var elements = _a.elements;
  10776. each$k(elements, unwrap);
  10777. });
  10778. },
  10779. getAll: function (name) {
  10780. var directory = findAll(editor, name);
  10781. return map$2(directory, function (elems) {
  10782. return map$3(elems, function (elem) {
  10783. return elem.dom;
  10784. });
  10785. });
  10786. }
  10787. };
  10788. };
  10789. var BookmarkManager = function (selection) {
  10790. return {
  10791. getBookmark: curry(getBookmark$1, selection),
  10792. moveToBookmark: curry(moveToBookmark, selection)
  10793. };
  10794. };
  10795. BookmarkManager.isBookmarkNode = isBookmarkNode$1;
  10796. var getContentEditableRoot$1 = function (root, node) {
  10797. while (node && node !== root) {
  10798. if (isContentEditableTrue$4(node) || isContentEditableFalse$b(node)) {
  10799. return node;
  10800. }
  10801. node = node.parentNode;
  10802. }
  10803. return null;
  10804. };
  10805. var isXYWithinRange = function (clientX, clientY, range) {
  10806. if (range.collapsed) {
  10807. return false;
  10808. }
  10809. if (Env.browser.isIE() && range.startOffset === range.endOffset - 1 && range.startContainer === range.endContainer) {
  10810. var elm = range.startContainer.childNodes[range.startOffset];
  10811. if (isElement$5(elm)) {
  10812. return exists(elm.getClientRects(), function (rect) {
  10813. return containsXY(rect, clientX, clientY);
  10814. });
  10815. }
  10816. }
  10817. return exists(range.getClientRects(), function (rect) {
  10818. return containsXY(rect, clientX, clientY);
  10819. });
  10820. };
  10821. var firePreProcess = function (editor, args) {
  10822. return editor.fire('PreProcess', args);
  10823. };
  10824. var firePostProcess = function (editor, args) {
  10825. return editor.fire('PostProcess', args);
  10826. };
  10827. var fireRemove = function (editor) {
  10828. return editor.fire('remove');
  10829. };
  10830. var fireDetach = function (editor) {
  10831. return editor.fire('detach');
  10832. };
  10833. var fireSwitchMode = function (editor, mode) {
  10834. return editor.fire('SwitchMode', { mode: mode });
  10835. };
  10836. var fireObjectResizeStart = function (editor, target, width, height, origin) {
  10837. editor.fire('ObjectResizeStart', {
  10838. target: target,
  10839. width: width,
  10840. height: height,
  10841. origin: origin
  10842. });
  10843. };
  10844. var fireObjectResized = function (editor, target, width, height, origin) {
  10845. editor.fire('ObjectResized', {
  10846. target: target,
  10847. width: width,
  10848. height: height,
  10849. origin: origin
  10850. });
  10851. };
  10852. var firePreInit = function (editor) {
  10853. return editor.fire('PreInit');
  10854. };
  10855. var firePostRender = function (editor) {
  10856. return editor.fire('PostRender');
  10857. };
  10858. var fireInit = function (editor) {
  10859. return editor.fire('Init');
  10860. };
  10861. var firePlaceholderToggle = function (editor, state) {
  10862. return editor.fire('PlaceholderToggle', { state: state });
  10863. };
  10864. var fireError = function (editor, errorType, error) {
  10865. return editor.fire(errorType, error);
  10866. };
  10867. var fireFormatApply = function (editor, format, node, vars) {
  10868. return editor.fire('FormatApply', {
  10869. format: format,
  10870. node: node,
  10871. vars: vars
  10872. });
  10873. };
  10874. var fireFormatRemove = function (editor, format, node, vars) {
  10875. return editor.fire('FormatRemove', {
  10876. format: format,
  10877. node: node,
  10878. vars: vars
  10879. });
  10880. };
  10881. var VK = {
  10882. BACKSPACE: 8,
  10883. DELETE: 46,
  10884. DOWN: 40,
  10885. ENTER: 13,
  10886. ESC: 27,
  10887. LEFT: 37,
  10888. RIGHT: 39,
  10889. SPACEBAR: 32,
  10890. TAB: 9,
  10891. UP: 38,
  10892. PAGE_UP: 33,
  10893. PAGE_DOWN: 34,
  10894. END: 35,
  10895. HOME: 36,
  10896. modifierPressed: function (e) {
  10897. return e.shiftKey || e.ctrlKey || e.altKey || VK.metaKeyPressed(e);
  10898. },
  10899. metaKeyPressed: function (e) {
  10900. return Env.mac ? e.metaKey : e.ctrlKey && !e.altKey;
  10901. }
  10902. };
  10903. var isContentEditableFalse$5 = isContentEditableFalse$b;
  10904. var ControlSelection = function (selection, editor) {
  10905. var elementSelectionAttr = 'data-mce-selected';
  10906. var dom = editor.dom, each = Tools.each;
  10907. var selectedElm, selectedElmGhost, resizeHelper, selectedHandle, resizeBackdrop;
  10908. var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
  10909. var width, height;
  10910. var editableDoc = editor.getDoc(), rootDocument = document;
  10911. var abs = Math.abs, round = Math.round, rootElement = editor.getBody();
  10912. var startScrollWidth, startScrollHeight;
  10913. var resizeHandles = {
  10914. nw: [
  10915. 0,
  10916. 0,
  10917. -1,
  10918. -1
  10919. ],
  10920. ne: [
  10921. 1,
  10922. 0,
  10923. 1,
  10924. -1
  10925. ],
  10926. se: [
  10927. 1,
  10928. 1,
  10929. 1,
  10930. 1
  10931. ],
  10932. sw: [
  10933. 0,
  10934. 1,
  10935. -1,
  10936. 1
  10937. ]
  10938. };
  10939. var isImage = function (elm) {
  10940. return elm && (elm.nodeName === 'IMG' || editor.dom.is(elm, 'figure.image'));
  10941. };
  10942. var isMedia = function (elm) {
  10943. return isMedia$2(elm) || dom.hasClass(elm, 'mce-preview-object');
  10944. };
  10945. var isEventOnImageOutsideRange = function (evt, range) {
  10946. if (evt.type === 'longpress' || evt.type.indexOf('touch') === 0) {
  10947. var touch = evt.touches[0];
  10948. return isImage(evt.target) && !isXYWithinRange(touch.clientX, touch.clientY, range);
  10949. } else {
  10950. return isImage(evt.target) && !isXYWithinRange(evt.clientX, evt.clientY, range);
  10951. }
  10952. };
  10953. var contextMenuSelectImage = function (evt) {
  10954. var target = evt.target;
  10955. if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) && !evt.isDefaultPrevented()) {
  10956. editor.selection.select(target);
  10957. }
  10958. };
  10959. var getResizeTargets = function (elm) {
  10960. if (dom.is(elm, 'figure.image')) {
  10961. return [elm.querySelector('img')];
  10962. } else if (dom.hasClass(elm, 'mce-preview-object') && isNonNullable(elm.firstElementChild)) {
  10963. return [
  10964. elm,
  10965. elm.firstElementChild
  10966. ];
  10967. } else {
  10968. return [elm];
  10969. }
  10970. };
  10971. var isResizable = function (elm) {
  10972. var selector = getObjectResizing(editor);
  10973. if (!selector) {
  10974. return false;
  10975. }
  10976. if (elm.getAttribute('data-mce-resize') === 'false') {
  10977. return false;
  10978. }
  10979. if (elm === editor.getBody()) {
  10980. return false;
  10981. }
  10982. if (dom.hasClass(elm, 'mce-preview-object')) {
  10983. return is$2(SugarElement.fromDom(elm.firstElementChild), selector);
  10984. } else {
  10985. return is$2(SugarElement.fromDom(elm), selector);
  10986. }
  10987. };
  10988. var createGhostElement = function (elm) {
  10989. if (isMedia(elm)) {
  10990. return dom.create('img', { src: Env.transparentSrc });
  10991. } else {
  10992. return elm.cloneNode(true);
  10993. }
  10994. };
  10995. var setSizeProp = function (element, name, value) {
  10996. if (isNonNullable(value)) {
  10997. var targets = getResizeTargets(element);
  10998. each$k(targets, function (target) {
  10999. if (target.style[name] || !editor.schema.isValid(target.nodeName.toLowerCase(), name)) {
  11000. dom.setStyle(target, name, value);
  11001. } else {
  11002. dom.setAttrib(target, name, '' + value);
  11003. }
  11004. });
  11005. }
  11006. };
  11007. var setGhostElmSize = function (ghostElm, width, height) {
  11008. setSizeProp(ghostElm, 'width', width);
  11009. setSizeProp(ghostElm, 'height', height);
  11010. };
  11011. var resizeGhostElement = function (e) {
  11012. var deltaX, deltaY, proportional;
  11013. var resizeHelperX, resizeHelperY;
  11014. deltaX = e.screenX - startX;
  11015. deltaY = e.screenY - startY;
  11016. width = deltaX * selectedHandle[2] + startW;
  11017. height = deltaY * selectedHandle[3] + startH;
  11018. width = width < 5 ? 5 : width;
  11019. height = height < 5 ? 5 : height;
  11020. if ((isImage(selectedElm) || isMedia(selectedElm)) && getResizeImgProportional(editor) !== false) {
  11021. proportional = !VK.modifierPressed(e);
  11022. } else {
  11023. proportional = VK.modifierPressed(e);
  11024. }
  11025. if (proportional) {
  11026. if (abs(deltaX) > abs(deltaY)) {
  11027. height = round(width * ratio);
  11028. width = round(height / ratio);
  11029. } else {
  11030. width = round(height / ratio);
  11031. height = round(width * ratio);
  11032. }
  11033. }
  11034. setGhostElmSize(selectedElmGhost, width, height);
  11035. resizeHelperX = selectedHandle.startPos.x + deltaX;
  11036. resizeHelperY = selectedHandle.startPos.y + deltaY;
  11037. resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
  11038. resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
  11039. dom.setStyles(resizeHelper, {
  11040. left: resizeHelperX,
  11041. top: resizeHelperY,
  11042. display: 'block'
  11043. });
  11044. resizeHelper.innerHTML = width + ' &times; ' + height;
  11045. if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
  11046. dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
  11047. }
  11048. if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
  11049. dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
  11050. }
  11051. deltaX = rootElement.scrollWidth - startScrollWidth;
  11052. deltaY = rootElement.scrollHeight - startScrollHeight;
  11053. if (deltaX + deltaY !== 0) {
  11054. dom.setStyles(resizeHelper, {
  11055. left: resizeHelperX - deltaX,
  11056. top: resizeHelperY - deltaY
  11057. });
  11058. }
  11059. if (!resizeStarted) {
  11060. fireObjectResizeStart(editor, selectedElm, startW, startH, 'corner-' + selectedHandle.name);
  11061. resizeStarted = true;
  11062. }
  11063. };
  11064. var endGhostResize = function () {
  11065. var wasResizeStarted = resizeStarted;
  11066. resizeStarted = false;
  11067. if (wasResizeStarted) {
  11068. setSizeProp(selectedElm, 'width', width);
  11069. setSizeProp(selectedElm, 'height', height);
  11070. }
  11071. dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
  11072. dom.unbind(editableDoc, 'mouseup', endGhostResize);
  11073. if (rootDocument !== editableDoc) {
  11074. dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
  11075. dom.unbind(rootDocument, 'mouseup', endGhostResize);
  11076. }
  11077. dom.remove(selectedElmGhost);
  11078. dom.remove(resizeHelper);
  11079. dom.remove(resizeBackdrop);
  11080. showResizeRect(selectedElm);
  11081. if (wasResizeStarted) {
  11082. fireObjectResized(editor, selectedElm, width, height, 'corner-' + selectedHandle.name);
  11083. dom.setAttrib(selectedElm, 'style', dom.getAttrib(selectedElm, 'style'));
  11084. }
  11085. editor.nodeChanged();
  11086. };
  11087. var showResizeRect = function (targetElm) {
  11088. unbindResizeHandleEvents();
  11089. var position = dom.getPos(targetElm, rootElement);
  11090. var selectedElmX = position.x;
  11091. var selectedElmY = position.y;
  11092. var rect = targetElm.getBoundingClientRect();
  11093. var targetWidth = rect.width || rect.right - rect.left;
  11094. var targetHeight = rect.height || rect.bottom - rect.top;
  11095. if (selectedElm !== targetElm) {
  11096. hideResizeRect();
  11097. selectedElm = targetElm;
  11098. width = height = 0;
  11099. }
  11100. var e = editor.fire('ObjectSelected', { target: targetElm });
  11101. var selectedValue = dom.getAttrib(selectedElm, elementSelectionAttr, '1');
  11102. if (isResizable(targetElm) && !e.isDefaultPrevented()) {
  11103. each(resizeHandles, function (handle, name) {
  11104. var handleElm;
  11105. var startDrag = function (e) {
  11106. var target = getResizeTargets(selectedElm)[0];
  11107. startX = e.screenX;
  11108. startY = e.screenY;
  11109. startW = target.clientWidth;
  11110. startH = target.clientHeight;
  11111. ratio = startH / startW;
  11112. selectedHandle = handle;
  11113. selectedHandle.name = name;
  11114. selectedHandle.startPos = {
  11115. x: targetWidth * handle[0] + selectedElmX,
  11116. y: targetHeight * handle[1] + selectedElmY
  11117. };
  11118. startScrollWidth = rootElement.scrollWidth;
  11119. startScrollHeight = rootElement.scrollHeight;
  11120. resizeBackdrop = dom.add(rootElement, 'div', {
  11121. 'class': 'mce-resize-backdrop',
  11122. 'data-mce-bogus': 'all'
  11123. });
  11124. dom.setStyles(resizeBackdrop, {
  11125. position: 'fixed',
  11126. left: '0',
  11127. top: '0',
  11128. width: '100%',
  11129. height: '100%'
  11130. });
  11131. selectedElmGhost = createGhostElement(selectedElm);
  11132. dom.addClass(selectedElmGhost, 'mce-clonedresizable');
  11133. dom.setAttrib(selectedElmGhost, 'data-mce-bogus', 'all');
  11134. selectedElmGhost.contentEditable = 'false';
  11135. dom.setStyles(selectedElmGhost, {
  11136. left: selectedElmX,
  11137. top: selectedElmY,
  11138. margin: 0
  11139. });
  11140. setGhostElmSize(selectedElmGhost, targetWidth, targetHeight);
  11141. selectedElmGhost.removeAttribute(elementSelectionAttr);
  11142. rootElement.appendChild(selectedElmGhost);
  11143. dom.bind(editableDoc, 'mousemove', resizeGhostElement);
  11144. dom.bind(editableDoc, 'mouseup', endGhostResize);
  11145. if (rootDocument !== editableDoc) {
  11146. dom.bind(rootDocument, 'mousemove', resizeGhostElement);
  11147. dom.bind(rootDocument, 'mouseup', endGhostResize);
  11148. }
  11149. resizeHelper = dom.add(rootElement, 'div', {
  11150. 'class': 'mce-resize-helper',
  11151. 'data-mce-bogus': 'all'
  11152. }, startW + ' &times; ' + startH);
  11153. };
  11154. handleElm = dom.get('mceResizeHandle' + name);
  11155. if (handleElm) {
  11156. dom.remove(handleElm);
  11157. }
  11158. handleElm = dom.add(rootElement, 'div', {
  11159. 'id': 'mceResizeHandle' + name,
  11160. 'data-mce-bogus': 'all',
  11161. 'class': 'mce-resizehandle',
  11162. 'unselectable': true,
  11163. 'style': 'cursor:' + name + '-resize; margin:0; padding:0'
  11164. });
  11165. if (Env.ie === 11) {
  11166. handleElm.contentEditable = false;
  11167. }
  11168. dom.bind(handleElm, 'mousedown', function (e) {
  11169. e.stopImmediatePropagation();
  11170. e.preventDefault();
  11171. startDrag(e);
  11172. });
  11173. handle.elm = handleElm;
  11174. dom.setStyles(handleElm, {
  11175. left: targetWidth * handle[0] + selectedElmX - handleElm.offsetWidth / 2,
  11176. top: targetHeight * handle[1] + selectedElmY - handleElm.offsetHeight / 2
  11177. });
  11178. });
  11179. } else {
  11180. hideResizeRect();
  11181. }
  11182. if (!dom.getAttrib(selectedElm, elementSelectionAttr)) {
  11183. selectedElm.setAttribute(elementSelectionAttr, selectedValue);
  11184. }
  11185. };
  11186. var hideResizeRect = function () {
  11187. unbindResizeHandleEvents();
  11188. if (selectedElm) {
  11189. selectedElm.removeAttribute(elementSelectionAttr);
  11190. }
  11191. each$j(resizeHandles, function (value, name) {
  11192. var handleElm = dom.get('mceResizeHandle' + name);
  11193. if (handleElm) {
  11194. dom.unbind(handleElm);
  11195. dom.remove(handleElm);
  11196. }
  11197. });
  11198. };
  11199. var updateResizeRect = function (e) {
  11200. var startElm, controlElm;
  11201. var isChildOrEqual = function (node, parent) {
  11202. if (node) {
  11203. do {
  11204. if (node === parent) {
  11205. return true;
  11206. }
  11207. } while (node = node.parentNode);
  11208. }
  11209. };
  11210. if (resizeStarted || editor.removed) {
  11211. return;
  11212. }
  11213. each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function (img) {
  11214. img.removeAttribute(elementSelectionAttr);
  11215. });
  11216. controlElm = e.type === 'mousedown' ? e.target : selection.getNode();
  11217. controlElm = dom.$(controlElm).closest('table,img,figure.image,hr,video,span.mce-preview-object')[0];
  11218. if (isChildOrEqual(controlElm, rootElement)) {
  11219. disableGeckoResize();
  11220. startElm = selection.getStart(true);
  11221. if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
  11222. showResizeRect(controlElm);
  11223. return;
  11224. }
  11225. }
  11226. hideResizeRect();
  11227. };
  11228. var isWithinContentEditableFalse = function (elm) {
  11229. return isContentEditableFalse$5(getContentEditableRoot$1(editor.getBody(), elm));
  11230. };
  11231. var unbindResizeHandleEvents = function () {
  11232. each$j(resizeHandles, function (handle) {
  11233. if (handle.elm) {
  11234. dom.unbind(handle.elm);
  11235. delete handle.elm;
  11236. }
  11237. });
  11238. };
  11239. var disableGeckoResize = function () {
  11240. try {
  11241. editor.getDoc().execCommand('enableObjectResizing', false, 'false');
  11242. } catch (ex) {
  11243. }
  11244. };
  11245. editor.on('init', function () {
  11246. disableGeckoResize();
  11247. if (Env.browser.isIE() || Env.browser.isEdge()) {
  11248. editor.on('mousedown click', function (e) {
  11249. var target = e.target, nodeName = target.nodeName;
  11250. if (!resizeStarted && /^(TABLE|IMG|HR)$/.test(nodeName) && !isWithinContentEditableFalse(target)) {
  11251. if (e.button !== 2) {
  11252. editor.selection.select(target, nodeName === 'TABLE');
  11253. }
  11254. if (e.type === 'mousedown') {
  11255. editor.nodeChanged();
  11256. }
  11257. }
  11258. });
  11259. var handleMSControlSelect_1 = function (e) {
  11260. var delayedSelect = function (node) {
  11261. Delay.setEditorTimeout(editor, function () {
  11262. return editor.selection.select(node);
  11263. });
  11264. };
  11265. if (isWithinContentEditableFalse(e.target) || isMedia$2(e.target)) {
  11266. e.preventDefault();
  11267. delayedSelect(e.target);
  11268. return;
  11269. }
  11270. if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) {
  11271. e.preventDefault();
  11272. if (e.target.tagName === 'IMG') {
  11273. delayedSelect(e.target);
  11274. }
  11275. }
  11276. };
  11277. dom.bind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11278. editor.on('remove', function () {
  11279. return dom.unbind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11280. });
  11281. }
  11282. var throttledUpdateResizeRect = Delay.throttle(function (e) {
  11283. if (!editor.composing) {
  11284. updateResizeRect(e);
  11285. }
  11286. });
  11287. editor.on('nodechange ResizeEditor ResizeWindow ResizeContent drop FullscreenStateChanged', throttledUpdateResizeRect);
  11288. editor.on('keyup compositionend', function (e) {
  11289. if (selectedElm && selectedElm.nodeName === 'TABLE') {
  11290. throttledUpdateResizeRect(e);
  11291. }
  11292. });
  11293. editor.on('hide blur', hideResizeRect);
  11294. editor.on('contextmenu longpress', contextMenuSelectImage, true);
  11295. });
  11296. editor.on('remove', unbindResizeHandleEvents);
  11297. var destroy = function () {
  11298. selectedElm = selectedElmGhost = resizeBackdrop = null;
  11299. };
  11300. return {
  11301. isResizable: isResizable,
  11302. showResizeRect: showResizeRect,
  11303. hideResizeRect: hideResizeRect,
  11304. updateResizeRect: updateResizeRect,
  11305. destroy: destroy
  11306. };
  11307. };
  11308. var hasCeProperty = function (node) {
  11309. return isContentEditableTrue$4(node) || isContentEditableFalse$b(node);
  11310. };
  11311. var findParent$1 = function (node, rootNode, predicate) {
  11312. while (node && node !== rootNode) {
  11313. if (predicate(node)) {
  11314. return node;
  11315. }
  11316. node = node.parentNode;
  11317. }
  11318. return null;
  11319. };
  11320. var findClosestIeRange = function (clientX, clientY, doc) {
  11321. var rects;
  11322. var element = doc.elementFromPoint(clientX, clientY);
  11323. var rng = doc.body.createTextRange();
  11324. if (!element || element.tagName === 'HTML') {
  11325. element = doc.body;
  11326. }
  11327. rng.moveToElementText(element);
  11328. rects = Tools.toArray(rng.getClientRects());
  11329. rects = rects.sort(function (a, b) {
  11330. a = Math.abs(Math.max(a.top - clientY, a.bottom - clientY));
  11331. b = Math.abs(Math.max(b.top - clientY, b.bottom - clientY));
  11332. return a - b;
  11333. });
  11334. if (rects.length > 0) {
  11335. clientY = (rects[0].bottom + rects[0].top) / 2;
  11336. try {
  11337. rng.moveToPoint(clientX, clientY);
  11338. rng.collapse(true);
  11339. return rng;
  11340. } catch (ex) {
  11341. }
  11342. }
  11343. return null;
  11344. };
  11345. var moveOutOfContentEditableFalse = function (rng, rootNode) {
  11346. var parentElement = rng && rng.parentElement ? rng.parentElement() : null;
  11347. return isContentEditableFalse$b(findParent$1(parentElement, rootNode, hasCeProperty)) ? null : rng;
  11348. };
  11349. var fromPoint = function (clientX, clientY, doc) {
  11350. var rng, point;
  11351. var pointDoc = doc;
  11352. if (pointDoc.caretPositionFromPoint) {
  11353. point = pointDoc.caretPositionFromPoint(clientX, clientY);
  11354. if (point) {
  11355. rng = doc.createRange();
  11356. rng.setStart(point.offsetNode, point.offset);
  11357. rng.collapse(true);
  11358. }
  11359. } else if (pointDoc.caretRangeFromPoint) {
  11360. rng = pointDoc.caretRangeFromPoint(clientX, clientY);
  11361. } else if (pointDoc.body.createTextRange) {
  11362. rng = pointDoc.body.createTextRange();
  11363. try {
  11364. rng.moveToPoint(clientX, clientY);
  11365. rng.collapse(true);
  11366. } catch (ex) {
  11367. rng = findClosestIeRange(clientX, clientY, doc);
  11368. }
  11369. return moveOutOfContentEditableFalse(rng, doc.body);
  11370. }
  11371. return rng;
  11372. };
  11373. var isEq$4 = function (rng1, rng2) {
  11374. return rng1 && rng2 && (rng1.startContainer === rng2.startContainer && rng1.startOffset === rng2.startOffset) && (rng1.endContainer === rng2.endContainer && rng1.endOffset === rng2.endOffset);
  11375. };
  11376. var findParent = function (node, rootNode, predicate) {
  11377. while (node && node !== rootNode) {
  11378. if (predicate(node)) {
  11379. return node;
  11380. }
  11381. node = node.parentNode;
  11382. }
  11383. return null;
  11384. };
  11385. var hasParent$1 = function (node, rootNode, predicate) {
  11386. return findParent(node, rootNode, predicate) !== null;
  11387. };
  11388. var hasParentWithName = function (node, rootNode, name) {
  11389. return hasParent$1(node, rootNode, function (node) {
  11390. return node.nodeName === name;
  11391. });
  11392. };
  11393. var isTable = function (node) {
  11394. return node && node.nodeName === 'TABLE';
  11395. };
  11396. var isTableCell$2 = function (node) {
  11397. return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  11398. };
  11399. var isCeFalseCaretContainer = function (node, rootNode) {
  11400. return isCaretContainer$2(node) && hasParent$1(node, rootNode, isCaretNode) === false;
  11401. };
  11402. var hasBrBeforeAfter = function (dom, node, left) {
  11403. var walker = new DomTreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || dom.getRoot());
  11404. while (node = walker[left ? 'prev' : 'next']()) {
  11405. if (isBr$5(node)) {
  11406. return true;
  11407. }
  11408. }
  11409. };
  11410. var isPrevNode = function (node, name) {
  11411. return node.previousSibling && node.previousSibling.nodeName === name;
  11412. };
  11413. var hasContentEditableFalseParent = function (body, node) {
  11414. while (node && node !== body) {
  11415. if (isContentEditableFalse$b(node)) {
  11416. return true;
  11417. }
  11418. node = node.parentNode;
  11419. }
  11420. return false;
  11421. };
  11422. var findTextNodeRelative = function (dom, isAfterNode, collapsed, left, startNode) {
  11423. var lastInlineElement;
  11424. var body = dom.getRoot();
  11425. var node;
  11426. var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11427. var parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body;
  11428. if (left && isBr$5(startNode) && isAfterNode && dom.isEmpty(parentBlockContainer)) {
  11429. return Optional.some(CaretPosition(startNode.parentNode, dom.nodeIndex(startNode)));
  11430. }
  11431. var walker = new DomTreeWalker(startNode, parentBlockContainer);
  11432. while (node = walker[left ? 'prev' : 'next']()) {
  11433. if (dom.getContentEditableParent(node) === 'false' || isCeFalseCaretContainer(node, body)) {
  11434. return Optional.none();
  11435. }
  11436. if (isText$7(node) && node.nodeValue.length > 0) {
  11437. if (hasParentWithName(node, body, 'A') === false) {
  11438. return Optional.some(CaretPosition(node, left ? node.nodeValue.length : 0));
  11439. }
  11440. return Optional.none();
  11441. }
  11442. if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  11443. return Optional.none();
  11444. }
  11445. lastInlineElement = node;
  11446. }
  11447. if (collapsed && lastInlineElement) {
  11448. return Optional.some(CaretPosition(lastInlineElement, 0));
  11449. }
  11450. return Optional.none();
  11451. };
  11452. var normalizeEndPoint = function (dom, collapsed, start, rng) {
  11453. var container, offset;
  11454. var body = dom.getRoot();
  11455. var node;
  11456. var directionLeft, normalized = false;
  11457. container = rng[(start ? 'start' : 'end') + 'Container'];
  11458. offset = rng[(start ? 'start' : 'end') + 'Offset'];
  11459. var isAfterNode = isElement$5(container) && offset === container.childNodes.length;
  11460. var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11461. directionLeft = start;
  11462. if (isCaretContainer$2(container)) {
  11463. return Optional.none();
  11464. }
  11465. if (isElement$5(container) && offset > container.childNodes.length - 1) {
  11466. directionLeft = false;
  11467. }
  11468. if (isDocument$1(container)) {
  11469. container = body;
  11470. offset = 0;
  11471. }
  11472. if (container === body) {
  11473. if (directionLeft) {
  11474. node = container.childNodes[offset > 0 ? offset - 1 : 0];
  11475. if (node) {
  11476. if (isCaretContainer$2(node)) {
  11477. return Optional.none();
  11478. }
  11479. if (nonEmptyElementsMap[node.nodeName] || isTable(node)) {
  11480. return Optional.none();
  11481. }
  11482. }
  11483. }
  11484. if (container.hasChildNodes()) {
  11485. offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
  11486. container = container.childNodes[offset];
  11487. offset = isText$7(container) && isAfterNode ? container.data.length : 0;
  11488. if (!collapsed && container === body.lastChild && isTable(container)) {
  11489. return Optional.none();
  11490. }
  11491. if (hasContentEditableFalseParent(body, container) || isCaretContainer$2(container)) {
  11492. return Optional.none();
  11493. }
  11494. if (container.hasChildNodes() && isTable(container) === false) {
  11495. node = container;
  11496. var walker = new DomTreeWalker(container, body);
  11497. do {
  11498. if (isContentEditableFalse$b(node) || isCaretContainer$2(node)) {
  11499. normalized = false;
  11500. break;
  11501. }
  11502. if (isText$7(node) && node.nodeValue.length > 0) {
  11503. offset = directionLeft ? 0 : node.nodeValue.length;
  11504. container = node;
  11505. normalized = true;
  11506. break;
  11507. }
  11508. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCell$2(node)) {
  11509. offset = dom.nodeIndex(node);
  11510. container = node.parentNode;
  11511. if (!directionLeft) {
  11512. offset++;
  11513. }
  11514. normalized = true;
  11515. break;
  11516. }
  11517. } while (node = directionLeft ? walker.next() : walker.prev());
  11518. }
  11519. }
  11520. }
  11521. if (collapsed) {
  11522. if (isText$7(container) && offset === 0) {
  11523. findTextNodeRelative(dom, isAfterNode, collapsed, true, container).each(function (pos) {
  11524. container = pos.container();
  11525. offset = pos.offset();
  11526. normalized = true;
  11527. });
  11528. }
  11529. if (isElement$5(container)) {
  11530. node = container.childNodes[offset];
  11531. if (!node) {
  11532. node = container.childNodes[offset - 1];
  11533. }
  11534. if (node && isBr$5(node) && !isPrevNode(node, 'A') && !hasBrBeforeAfter(dom, node, false) && !hasBrBeforeAfter(dom, node, true)) {
  11535. findTextNodeRelative(dom, isAfterNode, collapsed, true, node).each(function (pos) {
  11536. container = pos.container();
  11537. offset = pos.offset();
  11538. normalized = true;
  11539. });
  11540. }
  11541. }
  11542. }
  11543. if (directionLeft && !collapsed && isText$7(container) && offset === container.nodeValue.length) {
  11544. findTextNodeRelative(dom, isAfterNode, collapsed, false, container).each(function (pos) {
  11545. container = pos.container();
  11546. offset = pos.offset();
  11547. normalized = true;
  11548. });
  11549. }
  11550. return normalized ? Optional.some(CaretPosition(container, offset)) : Optional.none();
  11551. };
  11552. var normalize$2 = function (dom, rng) {
  11553. var collapsed = rng.collapsed, normRng = rng.cloneRange();
  11554. var startPos = CaretPosition.fromRangeStart(rng);
  11555. normalizeEndPoint(dom, collapsed, true, normRng).each(function (pos) {
  11556. if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
  11557. normRng.setStart(pos.container(), pos.offset());
  11558. }
  11559. });
  11560. if (!collapsed) {
  11561. normalizeEndPoint(dom, collapsed, false, normRng).each(function (pos) {
  11562. normRng.setEnd(pos.container(), pos.offset());
  11563. });
  11564. }
  11565. if (collapsed) {
  11566. normRng.collapse(true);
  11567. }
  11568. return isEq$4(rng, normRng) ? Optional.none() : Optional.some(normRng);
  11569. };
  11570. var splitText = function (node, offset) {
  11571. return node.splitText(offset);
  11572. };
  11573. var split = function (rng) {
  11574. var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  11575. if (startContainer === endContainer && isText$7(startContainer)) {
  11576. if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  11577. endContainer = splitText(startContainer, startOffset);
  11578. startContainer = endContainer.previousSibling;
  11579. if (endOffset > startOffset) {
  11580. endOffset = endOffset - startOffset;
  11581. startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
  11582. endOffset = endContainer.nodeValue.length;
  11583. startOffset = 0;
  11584. } else {
  11585. endOffset = 0;
  11586. }
  11587. }
  11588. } else {
  11589. if (isText$7(startContainer) && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  11590. startContainer = splitText(startContainer, startOffset);
  11591. startOffset = 0;
  11592. }
  11593. if (isText$7(endContainer) && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
  11594. endContainer = splitText(endContainer, endOffset).previousSibling;
  11595. endOffset = endContainer.nodeValue.length;
  11596. }
  11597. }
  11598. return {
  11599. startContainer: startContainer,
  11600. startOffset: startOffset,
  11601. endContainer: endContainer,
  11602. endOffset: endOffset
  11603. };
  11604. };
  11605. var RangeUtils = function (dom) {
  11606. var walk = function (rng, callback) {
  11607. return walk$2(dom, rng, callback);
  11608. };
  11609. var split$1 = split;
  11610. var normalize = function (rng) {
  11611. return normalize$2(dom, rng).fold(never, function (normalizedRng) {
  11612. rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
  11613. rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
  11614. return true;
  11615. });
  11616. };
  11617. return {
  11618. walk: walk,
  11619. split: split$1,
  11620. normalize: normalize
  11621. };
  11622. };
  11623. RangeUtils.compareRanges = isEq$4;
  11624. RangeUtils.getCaretRangeFromPoint = fromPoint;
  11625. RangeUtils.getSelectedNode = getSelectedNode;
  11626. RangeUtils.getNode = getNode$1;
  11627. var Dimension = function (name, getOffset) {
  11628. var set = function (element, h) {
  11629. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  11630. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  11631. }
  11632. var dom = element.dom;
  11633. if (isSupported(dom)) {
  11634. dom.style[name] = h + 'px';
  11635. }
  11636. };
  11637. var get = function (element) {
  11638. var r = getOffset(element);
  11639. if (r <= 0 || r === null) {
  11640. var css = get$5(element, name);
  11641. return parseFloat(css) || 0;
  11642. }
  11643. return r;
  11644. };
  11645. var getOuter = get;
  11646. var aggregate = function (element, properties) {
  11647. return foldl(properties, function (acc, property) {
  11648. var val = get$5(element, property);
  11649. var value = val === undefined ? 0 : parseInt(val, 10);
  11650. return isNaN(value) ? acc : acc + value;
  11651. }, 0);
  11652. };
  11653. var max = function (element, value, properties) {
  11654. var cumulativeInclusions = aggregate(element, properties);
  11655. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  11656. return absoluteMax;
  11657. };
  11658. return {
  11659. set: set,
  11660. get: get,
  11661. getOuter: getOuter,
  11662. aggregate: aggregate,
  11663. max: max
  11664. };
  11665. };
  11666. var api = Dimension('height', function (element) {
  11667. var dom = element.dom;
  11668. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  11669. });
  11670. var get$1 = function (element) {
  11671. return api.get(element);
  11672. };
  11673. var walkUp = function (navigation, doc) {
  11674. var frame = navigation.view(doc);
  11675. return frame.fold(constant([]), function (f) {
  11676. var parent = navigation.owner(f);
  11677. var rest = walkUp(navigation, parent);
  11678. return [f].concat(rest);
  11679. });
  11680. };
  11681. var pathTo = function (element, navigation) {
  11682. var d = navigation.owner(element);
  11683. return walkUp(navigation, d);
  11684. };
  11685. var view = function (doc) {
  11686. var _a;
  11687. var element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  11688. return element.map(SugarElement.fromDom);
  11689. };
  11690. var owner = function (element) {
  11691. return documentOrOwner(element);
  11692. };
  11693. var Navigation = /*#__PURE__*/Object.freeze({
  11694. __proto__: null,
  11695. view: view,
  11696. owner: owner
  11697. });
  11698. var find$1 = function (element) {
  11699. var doc = SugarElement.fromDom(document);
  11700. var scroll = get$8(doc);
  11701. var frames = pathTo(element, Navigation);
  11702. var offset = viewport(element);
  11703. var r = foldr(frames, function (b, a) {
  11704. var loc = viewport(a);
  11705. return {
  11706. left: b.left + loc.left,
  11707. top: b.top + loc.top
  11708. };
  11709. }, {
  11710. left: 0,
  11711. top: 0
  11712. });
  11713. return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  11714. };
  11715. var excludeFromDescend = function (element) {
  11716. return name(element) === 'textarea';
  11717. };
  11718. var fireScrollIntoViewEvent = function (editor, data) {
  11719. var scrollEvent = editor.fire('ScrollIntoView', data);
  11720. return scrollEvent.isDefaultPrevented();
  11721. };
  11722. var fireAfterScrollIntoViewEvent = function (editor, data) {
  11723. editor.fire('AfterScrollIntoView', data);
  11724. };
  11725. var descend = function (element, offset) {
  11726. var children$1 = children(element);
  11727. if (children$1.length === 0 || excludeFromDescend(element)) {
  11728. return {
  11729. element: element,
  11730. offset: offset
  11731. };
  11732. } else if (offset < children$1.length && !excludeFromDescend(children$1[offset])) {
  11733. return {
  11734. element: children$1[offset],
  11735. offset: 0
  11736. };
  11737. } else {
  11738. var last = children$1[children$1.length - 1];
  11739. if (excludeFromDescend(last)) {
  11740. return {
  11741. element: element,
  11742. offset: offset
  11743. };
  11744. } else {
  11745. if (name(last) === 'img') {
  11746. return {
  11747. element: last,
  11748. offset: 1
  11749. };
  11750. } else if (isText$8(last)) {
  11751. return {
  11752. element: last,
  11753. offset: get$2(last).length
  11754. };
  11755. } else {
  11756. return {
  11757. element: last,
  11758. offset: children(last).length
  11759. };
  11760. }
  11761. }
  11762. }
  11763. };
  11764. var markerInfo = function (element, cleanupFun) {
  11765. var pos = absolute(element);
  11766. var height = get$1(element);
  11767. return {
  11768. element: element,
  11769. bottom: pos.top + height,
  11770. height: height,
  11771. pos: pos,
  11772. cleanup: cleanupFun
  11773. };
  11774. };
  11775. var createMarker = function (element, offset) {
  11776. var startPoint = descend(element, offset);
  11777. var span = SugarElement.fromHtml('<span data-mce-bogus="all" style="display: inline-block;">' + ZWSP$1 + '</span>');
  11778. before$4(startPoint.element, span);
  11779. return markerInfo(span, function () {
  11780. return remove$7(span);
  11781. });
  11782. };
  11783. var elementMarker = function (element) {
  11784. return markerInfo(SugarElement.fromDom(element), noop);
  11785. };
  11786. var withMarker = function (editor, f, rng, alignToTop) {
  11787. preserveWith(editor, function (_s, _e) {
  11788. return applyWithMarker(editor, f, rng, alignToTop);
  11789. }, rng);
  11790. };
  11791. var withScrollEvents = function (editor, doc, f, marker, alignToTop) {
  11792. var data = {
  11793. elm: marker.element.dom,
  11794. alignToTop: alignToTop
  11795. };
  11796. if (fireScrollIntoViewEvent(editor, data)) {
  11797. return;
  11798. }
  11799. var scrollTop = get$8(doc).top;
  11800. f(doc, scrollTop, marker, alignToTop);
  11801. fireAfterScrollIntoViewEvent(editor, data);
  11802. };
  11803. var applyWithMarker = function (editor, f, rng, alignToTop) {
  11804. var body = SugarElement.fromDom(editor.getBody());
  11805. var doc = SugarElement.fromDom(editor.getDoc());
  11806. reflow(body);
  11807. var marker = createMarker(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  11808. withScrollEvents(editor, doc, f, marker, alignToTop);
  11809. marker.cleanup();
  11810. };
  11811. var withElement = function (editor, element, f, alignToTop) {
  11812. var doc = SugarElement.fromDom(editor.getDoc());
  11813. withScrollEvents(editor, doc, f, elementMarker(element), alignToTop);
  11814. };
  11815. var preserveWith = function (editor, f, rng) {
  11816. var startElement = rng.startContainer;
  11817. var startOffset = rng.startOffset;
  11818. var endElement = rng.endContainer;
  11819. var endOffset = rng.endOffset;
  11820. f(SugarElement.fromDom(startElement), SugarElement.fromDom(endElement));
  11821. var newRng = editor.dom.createRng();
  11822. newRng.setStart(startElement, startOffset);
  11823. newRng.setEnd(endElement, endOffset);
  11824. editor.selection.setRng(rng);
  11825. };
  11826. var scrollToMarker = function (marker, viewHeight, alignToTop, doc) {
  11827. var pos = marker.pos;
  11828. if (alignToTop) {
  11829. to(pos.left, pos.top, doc);
  11830. } else {
  11831. var y = pos.top - viewHeight + marker.height;
  11832. to(pos.left, y, doc);
  11833. }
  11834. };
  11835. var intoWindowIfNeeded = function (doc, scrollTop, viewHeight, marker, alignToTop) {
  11836. var viewportBottom = viewHeight + scrollTop;
  11837. var markerTop = marker.pos.top;
  11838. var markerBottom = marker.bottom;
  11839. var largerThanViewport = markerBottom - markerTop >= viewHeight;
  11840. if (markerTop < scrollTop) {
  11841. scrollToMarker(marker, viewHeight, alignToTop !== false, doc);
  11842. } else if (markerTop > viewportBottom) {
  11843. var align = largerThanViewport ? alignToTop !== false : alignToTop === true;
  11844. scrollToMarker(marker, viewHeight, align, doc);
  11845. } else if (markerBottom > viewportBottom && !largerThanViewport) {
  11846. scrollToMarker(marker, viewHeight, alignToTop === true, doc);
  11847. }
  11848. };
  11849. var intoWindow = function (doc, scrollTop, marker, alignToTop) {
  11850. var viewHeight = doc.dom.defaultView.innerHeight;
  11851. intoWindowIfNeeded(doc, scrollTop, viewHeight, marker, alignToTop);
  11852. };
  11853. var intoFrame = function (doc, scrollTop, marker, alignToTop) {
  11854. var frameViewHeight = doc.dom.defaultView.innerHeight;
  11855. intoWindowIfNeeded(doc, scrollTop, frameViewHeight, marker, alignToTop);
  11856. var op = find$1(marker.element);
  11857. var viewportBounds = getBounds(window);
  11858. if (op.top < viewportBounds.y) {
  11859. intoView(marker.element, alignToTop !== false);
  11860. } else if (op.top > viewportBounds.bottom) {
  11861. intoView(marker.element, alignToTop === true);
  11862. }
  11863. };
  11864. var rangeIntoWindow = function (editor, rng, alignToTop) {
  11865. return withMarker(editor, intoWindow, rng, alignToTop);
  11866. };
  11867. var elementIntoWindow = function (editor, element, alignToTop) {
  11868. return withElement(editor, element, intoWindow, alignToTop);
  11869. };
  11870. var rangeIntoFrame = function (editor, rng, alignToTop) {
  11871. return withMarker(editor, intoFrame, rng, alignToTop);
  11872. };
  11873. var elementIntoFrame = function (editor, element, alignToTop) {
  11874. return withElement(editor, element, intoFrame, alignToTop);
  11875. };
  11876. var scrollElementIntoView = function (editor, element, alignToTop) {
  11877. var scroller = editor.inline ? elementIntoWindow : elementIntoFrame;
  11878. scroller(editor, element, alignToTop);
  11879. };
  11880. var scrollRangeIntoView = function (editor, rng, alignToTop) {
  11881. var scroller = editor.inline ? rangeIntoWindow : rangeIntoFrame;
  11882. scroller(editor, rng, alignToTop);
  11883. };
  11884. var getDocument = function () {
  11885. return SugarElement.fromDom(document);
  11886. };
  11887. var focus$1 = function (element) {
  11888. return element.dom.focus();
  11889. };
  11890. var hasFocus$1 = function (element) {
  11891. var root = getRootNode(element).dom;
  11892. return element.dom === root.activeElement;
  11893. };
  11894. var active = function (root) {
  11895. if (root === void 0) {
  11896. root = getDocument();
  11897. }
  11898. return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  11899. };
  11900. var search = function (element) {
  11901. return active(getRootNode(element)).filter(function (e) {
  11902. return element.dom.contains(e.dom);
  11903. });
  11904. };
  11905. var create$5 = function (start, soffset, finish, foffset) {
  11906. return {
  11907. start: start,
  11908. soffset: soffset,
  11909. finish: finish,
  11910. foffset: foffset
  11911. };
  11912. };
  11913. var SimRange = { create: create$5 };
  11914. var adt$1 = Adt.generate([
  11915. { before: ['element'] },
  11916. {
  11917. on: [
  11918. 'element',
  11919. 'offset'
  11920. ]
  11921. },
  11922. { after: ['element'] }
  11923. ]);
  11924. var cata = function (subject, onBefore, onOn, onAfter) {
  11925. return subject.fold(onBefore, onOn, onAfter);
  11926. };
  11927. var getStart$2 = function (situ) {
  11928. return situ.fold(identity, identity, identity);
  11929. };
  11930. var before$1 = adt$1.before;
  11931. var on = adt$1.on;
  11932. var after$1 = adt$1.after;
  11933. var Situ = {
  11934. before: before$1,
  11935. on: on,
  11936. after: after$1,
  11937. cata: cata,
  11938. getStart: getStart$2
  11939. };
  11940. var adt = Adt.generate([
  11941. { domRange: ['rng'] },
  11942. {
  11943. relative: [
  11944. 'startSitu',
  11945. 'finishSitu'
  11946. ]
  11947. },
  11948. {
  11949. exact: [
  11950. 'start',
  11951. 'soffset',
  11952. 'finish',
  11953. 'foffset'
  11954. ]
  11955. }
  11956. ]);
  11957. var exactFromRange = function (simRange) {
  11958. return adt.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  11959. };
  11960. var getStart$1 = function (selection) {
  11961. return selection.match({
  11962. domRange: function (rng) {
  11963. return SugarElement.fromDom(rng.startContainer);
  11964. },
  11965. relative: function (startSitu, _finishSitu) {
  11966. return Situ.getStart(startSitu);
  11967. },
  11968. exact: function (start, _soffset, _finish, _foffset) {
  11969. return start;
  11970. }
  11971. });
  11972. };
  11973. var domRange = adt.domRange;
  11974. var relative = adt.relative;
  11975. var exact = adt.exact;
  11976. var getWin = function (selection) {
  11977. var start = getStart$1(selection);
  11978. return defaultView(start);
  11979. };
  11980. var range = SimRange.create;
  11981. var SimSelection = {
  11982. domRange: domRange,
  11983. relative: relative,
  11984. exact: exact,
  11985. exactFromRange: exactFromRange,
  11986. getWin: getWin,
  11987. range: range
  11988. };
  11989. var browser$1 = detect().browser;
  11990. var clamp$1 = function (offset, element) {
  11991. var max = isText$8(element) ? get$2(element).length : children(element).length + 1;
  11992. if (offset > max) {
  11993. return max;
  11994. } else if (offset < 0) {
  11995. return 0;
  11996. }
  11997. return offset;
  11998. };
  11999. var normalizeRng = function (rng) {
  12000. return SimSelection.range(rng.start, clamp$1(rng.soffset, rng.start), rng.finish, clamp$1(rng.foffset, rng.finish));
  12001. };
  12002. var isOrContains = function (root, elm) {
  12003. return !isRestrictedNode(elm.dom) && (contains$1(root, elm) || eq(root, elm));
  12004. };
  12005. var isRngInRoot = function (root) {
  12006. return function (rng) {
  12007. return isOrContains(root, rng.start) && isOrContains(root, rng.finish);
  12008. };
  12009. };
  12010. var shouldStore = function (editor) {
  12011. return editor.inline === true || browser$1.isIE();
  12012. };
  12013. var nativeRangeToSelectionRange = function (r) {
  12014. return SimSelection.range(SugarElement.fromDom(r.startContainer), r.startOffset, SugarElement.fromDom(r.endContainer), r.endOffset);
  12015. };
  12016. var readRange = function (win) {
  12017. var selection = win.getSelection();
  12018. var rng = !selection || selection.rangeCount === 0 ? Optional.none() : Optional.from(selection.getRangeAt(0));
  12019. return rng.map(nativeRangeToSelectionRange);
  12020. };
  12021. var getBookmark = function (root) {
  12022. var win = defaultView(root);
  12023. return readRange(win.dom).filter(isRngInRoot(root));
  12024. };
  12025. var validate = function (root, bookmark) {
  12026. return Optional.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
  12027. };
  12028. var bookmarkToNativeRng = function (bookmark) {
  12029. var rng = document.createRange();
  12030. try {
  12031. rng.setStart(bookmark.start.dom, bookmark.soffset);
  12032. rng.setEnd(bookmark.finish.dom, bookmark.foffset);
  12033. return Optional.some(rng);
  12034. } catch (_) {
  12035. return Optional.none();
  12036. }
  12037. };
  12038. var store = function (editor) {
  12039. var newBookmark = shouldStore(editor) ? getBookmark(SugarElement.fromDom(editor.getBody())) : Optional.none();
  12040. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12041. };
  12042. var storeNative = function (editor, rng) {
  12043. var root = SugarElement.fromDom(editor.getBody());
  12044. var range = shouldStore(editor) ? Optional.from(rng) : Optional.none();
  12045. var newBookmark = range.map(nativeRangeToSelectionRange).filter(isRngInRoot(root));
  12046. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12047. };
  12048. var getRng = function (editor) {
  12049. var bookmark = editor.bookmark ? editor.bookmark : Optional.none();
  12050. return bookmark.bind(function (x) {
  12051. return validate(SugarElement.fromDom(editor.getBody()), x);
  12052. }).bind(bookmarkToNativeRng);
  12053. };
  12054. var restore = function (editor) {
  12055. getRng(editor).each(function (rng) {
  12056. return editor.selection.setRng(rng);
  12057. });
  12058. };
  12059. var isEditorUIElement$1 = function (elm) {
  12060. var className = elm.className.toString();
  12061. return className.indexOf('tox-') !== -1 || className.indexOf('mce-') !== -1;
  12062. };
  12063. var FocusManager = { isEditorUIElement: isEditorUIElement$1 };
  12064. var isManualNodeChange = function (e) {
  12065. return e.type === 'nodechange' && e.selectionChange;
  12066. };
  12067. var registerPageMouseUp = function (editor, throttledStore) {
  12068. var mouseUpPage = function () {
  12069. throttledStore.throttle();
  12070. };
  12071. DOMUtils.DOM.bind(document, 'mouseup', mouseUpPage);
  12072. editor.on('remove', function () {
  12073. DOMUtils.DOM.unbind(document, 'mouseup', mouseUpPage);
  12074. });
  12075. };
  12076. var registerFocusOut = function (editor) {
  12077. editor.on('focusout', function () {
  12078. store(editor);
  12079. });
  12080. };
  12081. var registerMouseUp = function (editor, throttledStore) {
  12082. editor.on('mouseup touchend', function (_e) {
  12083. throttledStore.throttle();
  12084. });
  12085. };
  12086. var registerEditorEvents = function (editor, throttledStore) {
  12087. var browser = detect().browser;
  12088. if (browser.isIE()) {
  12089. registerFocusOut(editor);
  12090. } else {
  12091. registerMouseUp(editor, throttledStore);
  12092. }
  12093. editor.on('keyup NodeChange', function (e) {
  12094. if (!isManualNodeChange(e)) {
  12095. store(editor);
  12096. }
  12097. });
  12098. };
  12099. var register$3 = function (editor) {
  12100. var throttledStore = first(function () {
  12101. store(editor);
  12102. }, 0);
  12103. editor.on('init', function () {
  12104. if (editor.inline) {
  12105. registerPageMouseUp(editor, throttledStore);
  12106. }
  12107. registerEditorEvents(editor, throttledStore);
  12108. });
  12109. editor.on('remove', function () {
  12110. throttledStore.cancel();
  12111. });
  12112. };
  12113. var documentFocusInHandler;
  12114. var DOM$8 = DOMUtils.DOM;
  12115. var isEditorUIElement = function (elm) {
  12116. return FocusManager.isEditorUIElement(elm);
  12117. };
  12118. var isEditorContentAreaElement = function (elm) {
  12119. var classList = elm.classList;
  12120. if (classList !== undefined) {
  12121. return classList.contains('tox-edit-area') || classList.contains('tox-edit-area__iframe') || classList.contains('mce-content-body');
  12122. } else {
  12123. return false;
  12124. }
  12125. };
  12126. var isUIElement = function (editor, elm) {
  12127. var customSelector = getCustomUiSelector(editor);
  12128. var parent = DOM$8.getParent(elm, function (elm) {
  12129. return isEditorUIElement(elm) || (customSelector ? editor.dom.is(elm, customSelector) : false);
  12130. });
  12131. return parent !== null;
  12132. };
  12133. var getActiveElement = function (editor) {
  12134. try {
  12135. var root = getRootNode(SugarElement.fromDom(editor.getElement()));
  12136. return active(root).fold(function () {
  12137. return document.body;
  12138. }, function (x) {
  12139. return x.dom;
  12140. });
  12141. } catch (ex) {
  12142. return document.body;
  12143. }
  12144. };
  12145. var registerEvents$1 = function (editorManager, e) {
  12146. var editor = e.editor;
  12147. register$3(editor);
  12148. editor.on('focusin', function () {
  12149. var focusedEditor = editorManager.focusedEditor;
  12150. if (focusedEditor !== editor) {
  12151. if (focusedEditor) {
  12152. focusedEditor.fire('blur', { focusedEditor: editor });
  12153. }
  12154. editorManager.setActive(editor);
  12155. editorManager.focusedEditor = editor;
  12156. editor.fire('focus', { blurredEditor: focusedEditor });
  12157. editor.focus(true);
  12158. }
  12159. });
  12160. editor.on('focusout', function () {
  12161. Delay.setEditorTimeout(editor, function () {
  12162. var focusedEditor = editorManager.focusedEditor;
  12163. if (!isUIElement(editor, getActiveElement(editor)) && focusedEditor === editor) {
  12164. editor.fire('blur', { focusedEditor: null });
  12165. editorManager.focusedEditor = null;
  12166. }
  12167. });
  12168. });
  12169. if (!documentFocusInHandler) {
  12170. documentFocusInHandler = function (e) {
  12171. var activeEditor = editorManager.activeEditor;
  12172. if (activeEditor) {
  12173. getOriginalEventTarget(e).each(function (target) {
  12174. if (target.ownerDocument === document) {
  12175. if (target !== document.body && !isUIElement(activeEditor, target) && editorManager.focusedEditor === activeEditor) {
  12176. activeEditor.fire('blur', { focusedEditor: null });
  12177. editorManager.focusedEditor = null;
  12178. }
  12179. }
  12180. });
  12181. }
  12182. };
  12183. DOM$8.bind(document, 'focusin', documentFocusInHandler);
  12184. }
  12185. };
  12186. var unregisterDocumentEvents = function (editorManager, e) {
  12187. if (editorManager.focusedEditor === e.editor) {
  12188. editorManager.focusedEditor = null;
  12189. }
  12190. if (!editorManager.activeEditor) {
  12191. DOM$8.unbind(document, 'focusin', documentFocusInHandler);
  12192. documentFocusInHandler = null;
  12193. }
  12194. };
  12195. var setup$l = function (editorManager) {
  12196. editorManager.on('AddEditor', curry(registerEvents$1, editorManager));
  12197. editorManager.on('RemoveEditor', curry(unregisterDocumentEvents, editorManager));
  12198. };
  12199. var getContentEditableHost = function (editor, node) {
  12200. return editor.dom.getParent(node, function (node) {
  12201. return editor.dom.getContentEditable(node) === 'true';
  12202. });
  12203. };
  12204. var getCollapsedNode = function (rng) {
  12205. return rng.collapsed ? Optional.from(getNode$1(rng.startContainer, rng.startOffset)).map(SugarElement.fromDom) : Optional.none();
  12206. };
  12207. var getFocusInElement = function (root, rng) {
  12208. return getCollapsedNode(rng).bind(function (node) {
  12209. if (isTableSection(node)) {
  12210. return Optional.some(node);
  12211. } else if (contains$1(root, node) === false) {
  12212. return Optional.some(root);
  12213. } else {
  12214. return Optional.none();
  12215. }
  12216. });
  12217. };
  12218. var normalizeSelection$1 = function (editor, rng) {
  12219. getFocusInElement(SugarElement.fromDom(editor.getBody()), rng).bind(function (elm) {
  12220. return firstPositionIn(elm.dom);
  12221. }).fold(function () {
  12222. editor.selection.normalize();
  12223. return;
  12224. }, function (caretPos) {
  12225. return editor.selection.setRng(caretPos.toRange());
  12226. });
  12227. };
  12228. var focusBody = function (body) {
  12229. if (body.setActive) {
  12230. try {
  12231. body.setActive();
  12232. } catch (ex) {
  12233. body.focus();
  12234. }
  12235. } else {
  12236. body.focus();
  12237. }
  12238. };
  12239. var hasElementFocus = function (elm) {
  12240. return hasFocus$1(elm) || search(elm).isSome();
  12241. };
  12242. var hasIframeFocus = function (editor) {
  12243. return editor.iframeElement && hasFocus$1(SugarElement.fromDom(editor.iframeElement));
  12244. };
  12245. var hasInlineFocus = function (editor) {
  12246. var rawBody = editor.getBody();
  12247. return rawBody && hasElementFocus(SugarElement.fromDom(rawBody));
  12248. };
  12249. var hasUiFocus = function (editor) {
  12250. var dos = getRootNode(SugarElement.fromDom(editor.getElement()));
  12251. return active(dos).filter(function (elem) {
  12252. return !isEditorContentAreaElement(elem.dom) && isUIElement(editor, elem.dom);
  12253. }).isSome();
  12254. };
  12255. var hasFocus = function (editor) {
  12256. return editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
  12257. };
  12258. var hasEditorOrUiFocus = function (editor) {
  12259. return hasFocus(editor) || hasUiFocus(editor);
  12260. };
  12261. var focusEditor = function (editor) {
  12262. var selection = editor.selection;
  12263. var body = editor.getBody();
  12264. var rng = selection.getRng();
  12265. editor.quirks.refreshContentEditable();
  12266. if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  12267. getRng(editor).each(function (bookmarkRng) {
  12268. editor.selection.setRng(bookmarkRng);
  12269. rng = bookmarkRng;
  12270. });
  12271. }
  12272. var contentEditableHost = getContentEditableHost(editor, selection.getNode());
  12273. if (editor.$.contains(body, contentEditableHost)) {
  12274. focusBody(contentEditableHost);
  12275. normalizeSelection$1(editor, rng);
  12276. activateEditor(editor);
  12277. return;
  12278. }
  12279. if (!editor.inline) {
  12280. if (!Env.opera) {
  12281. focusBody(body);
  12282. }
  12283. editor.getWin().focus();
  12284. }
  12285. if (Env.gecko || editor.inline) {
  12286. focusBody(body);
  12287. normalizeSelection$1(editor, rng);
  12288. }
  12289. activateEditor(editor);
  12290. };
  12291. var activateEditor = function (editor) {
  12292. return editor.editorManager.setActive(editor);
  12293. };
  12294. var focus = function (editor, skipFocus) {
  12295. if (editor.removed) {
  12296. return;
  12297. }
  12298. if (skipFocus) {
  12299. activateEditor(editor);
  12300. } else {
  12301. focusEditor(editor);
  12302. }
  12303. };
  12304. var getEndpointElement = function (root, rng, start, real, resolve) {
  12305. var container = start ? rng.startContainer : rng.endContainer;
  12306. var offset = start ? rng.startOffset : rng.endOffset;
  12307. return Optional.from(container).map(SugarElement.fromDom).map(function (elm) {
  12308. return !real || !rng.collapsed ? child$1(elm, resolve(elm, offset)).getOr(elm) : elm;
  12309. }).bind(function (elm) {
  12310. return isElement$6(elm) ? Optional.some(elm) : parent(elm).filter(isElement$6);
  12311. }).map(function (elm) {
  12312. return elm.dom;
  12313. }).getOr(root);
  12314. };
  12315. var getStart = function (root, rng, real) {
  12316. return getEndpointElement(root, rng, true, real, function (elm, offset) {
  12317. return Math.min(childNodesCount(elm), offset);
  12318. });
  12319. };
  12320. var getEnd = function (root, rng, real) {
  12321. return getEndpointElement(root, rng, false, real, function (elm, offset) {
  12322. return offset > 0 ? offset - 1 : offset;
  12323. });
  12324. };
  12325. var skipEmptyTextNodes = function (node, forwards) {
  12326. var orig = node;
  12327. while (node && isText$7(node) && node.length === 0) {
  12328. node = forwards ? node.nextSibling : node.previousSibling;
  12329. }
  12330. return node || orig;
  12331. };
  12332. var getNode = function (root, rng) {
  12333. var elm, startContainer, endContainer;
  12334. if (!rng) {
  12335. return root;
  12336. }
  12337. startContainer = rng.startContainer;
  12338. endContainer = rng.endContainer;
  12339. var startOffset = rng.startOffset;
  12340. var endOffset = rng.endOffset;
  12341. elm = rng.commonAncestorContainer;
  12342. if (!rng.collapsed) {
  12343. if (startContainer === endContainer) {
  12344. if (endOffset - startOffset < 2) {
  12345. if (startContainer.hasChildNodes()) {
  12346. elm = startContainer.childNodes[startOffset];
  12347. }
  12348. }
  12349. }
  12350. if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
  12351. if (startContainer.length === startOffset) {
  12352. startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
  12353. } else {
  12354. startContainer = startContainer.parentNode;
  12355. }
  12356. if (endOffset === 0) {
  12357. endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
  12358. } else {
  12359. endContainer = endContainer.parentNode;
  12360. }
  12361. if (startContainer && startContainer === endContainer) {
  12362. return startContainer;
  12363. }
  12364. }
  12365. }
  12366. if (elm && elm.nodeType === 3) {
  12367. return elm.parentNode;
  12368. }
  12369. return elm;
  12370. };
  12371. var getSelectedBlocks = function (dom, rng, startElm, endElm) {
  12372. var node;
  12373. var selectedBlocks = [];
  12374. var root = dom.getRoot();
  12375. startElm = dom.getParent(startElm || getStart(root, rng, rng.collapsed), dom.isBlock);
  12376. endElm = dom.getParent(endElm || getEnd(root, rng, rng.collapsed), dom.isBlock);
  12377. if (startElm && startElm !== root) {
  12378. selectedBlocks.push(startElm);
  12379. }
  12380. if (startElm && endElm && startElm !== endElm) {
  12381. node = startElm;
  12382. var walker = new DomTreeWalker(startElm, root);
  12383. while ((node = walker.next()) && node !== endElm) {
  12384. if (dom.isBlock(node)) {
  12385. selectedBlocks.push(node);
  12386. }
  12387. }
  12388. }
  12389. if (endElm && startElm !== endElm && endElm !== root) {
  12390. selectedBlocks.push(endElm);
  12391. }
  12392. return selectedBlocks;
  12393. };
  12394. var select = function (dom, node, content) {
  12395. return Optional.from(node).map(function (node) {
  12396. var idx = dom.nodeIndex(node);
  12397. var rng = dom.createRng();
  12398. rng.setStart(node.parentNode, idx);
  12399. rng.setEnd(node.parentNode, idx + 1);
  12400. if (content) {
  12401. moveEndPoint(dom, rng, node, true);
  12402. moveEndPoint(dom, rng, node, false);
  12403. }
  12404. return rng;
  12405. });
  12406. };
  12407. var processRanges = function (editor, ranges) {
  12408. return map$3(ranges, function (range) {
  12409. var evt = editor.fire('GetSelectionRange', { range: range });
  12410. return evt.range !== range ? evt.range : range;
  12411. });
  12412. };
  12413. var typeLookup = {
  12414. '#text': 3,
  12415. '#comment': 8,
  12416. '#cdata': 4,
  12417. '#pi': 7,
  12418. '#doctype': 10,
  12419. '#document-fragment': 11
  12420. };
  12421. var walk$1 = function (node, root, prev) {
  12422. var startName = prev ? 'lastChild' : 'firstChild';
  12423. var siblingName = prev ? 'prev' : 'next';
  12424. if (node[startName]) {
  12425. return node[startName];
  12426. }
  12427. if (node !== root) {
  12428. var sibling = node[siblingName];
  12429. if (sibling) {
  12430. return sibling;
  12431. }
  12432. for (var parent_1 = node.parent; parent_1 && parent_1 !== root; parent_1 = parent_1.parent) {
  12433. sibling = parent_1[siblingName];
  12434. if (sibling) {
  12435. return sibling;
  12436. }
  12437. }
  12438. }
  12439. };
  12440. var isEmptyTextNode = function (node) {
  12441. if (!isWhitespaceText(node.value)) {
  12442. return false;
  12443. }
  12444. var parentNode = node.parent;
  12445. if (parentNode && (parentNode.name !== 'span' || parentNode.attr('style')) && /^[ ]+$/.test(node.value)) {
  12446. return false;
  12447. }
  12448. return true;
  12449. };
  12450. var isNonEmptyElement = function (node) {
  12451. var isNamedAnchor = node.name === 'a' && !node.attr('href') && node.attr('id');
  12452. return node.attr('name') || node.attr('id') && !node.firstChild || node.attr('data-mce-bookmark') || isNamedAnchor;
  12453. };
  12454. var AstNode = function () {
  12455. function AstNode(name, type) {
  12456. this.name = name;
  12457. this.type = type;
  12458. if (type === 1) {
  12459. this.attributes = [];
  12460. this.attributes.map = {};
  12461. }
  12462. }
  12463. AstNode.create = function (name, attrs) {
  12464. var node = new AstNode(name, typeLookup[name] || 1);
  12465. if (attrs) {
  12466. each$j(attrs, function (value, attrName) {
  12467. node.attr(attrName, value);
  12468. });
  12469. }
  12470. return node;
  12471. };
  12472. AstNode.prototype.replace = function (node) {
  12473. var self = this;
  12474. if (node.parent) {
  12475. node.remove();
  12476. }
  12477. self.insert(node, self);
  12478. self.remove();
  12479. return self;
  12480. };
  12481. AstNode.prototype.attr = function (name, value) {
  12482. var self = this;
  12483. var attrs;
  12484. if (typeof name !== 'string') {
  12485. if (name !== undefined && name !== null) {
  12486. each$j(name, function (value, key) {
  12487. self.attr(key, value);
  12488. });
  12489. }
  12490. return self;
  12491. }
  12492. if (attrs = self.attributes) {
  12493. if (value !== undefined) {
  12494. if (value === null) {
  12495. if (name in attrs.map) {
  12496. delete attrs.map[name];
  12497. var i = attrs.length;
  12498. while (i--) {
  12499. if (attrs[i].name === name) {
  12500. attrs.splice(i, 1);
  12501. return self;
  12502. }
  12503. }
  12504. }
  12505. return self;
  12506. }
  12507. if (name in attrs.map) {
  12508. var i = attrs.length;
  12509. while (i--) {
  12510. if (attrs[i].name === name) {
  12511. attrs[i].value = value;
  12512. break;
  12513. }
  12514. }
  12515. } else {
  12516. attrs.push({
  12517. name: name,
  12518. value: value
  12519. });
  12520. }
  12521. attrs.map[name] = value;
  12522. return self;
  12523. }
  12524. return attrs.map[name];
  12525. }
  12526. };
  12527. AstNode.prototype.clone = function () {
  12528. var self = this;
  12529. var clone = new AstNode(self.name, self.type);
  12530. var selfAttrs;
  12531. if (selfAttrs = self.attributes) {
  12532. var cloneAttrs = [];
  12533. cloneAttrs.map = {};
  12534. for (var i = 0, l = selfAttrs.length; i < l; i++) {
  12535. var selfAttr = selfAttrs[i];
  12536. if (selfAttr.name !== 'id') {
  12537. cloneAttrs[cloneAttrs.length] = {
  12538. name: selfAttr.name,
  12539. value: selfAttr.value
  12540. };
  12541. cloneAttrs.map[selfAttr.name] = selfAttr.value;
  12542. }
  12543. }
  12544. clone.attributes = cloneAttrs;
  12545. }
  12546. clone.value = self.value;
  12547. clone.shortEnded = self.shortEnded;
  12548. return clone;
  12549. };
  12550. AstNode.prototype.wrap = function (wrapper) {
  12551. var self = this;
  12552. self.parent.insert(wrapper, self);
  12553. wrapper.append(self);
  12554. return self;
  12555. };
  12556. AstNode.prototype.unwrap = function () {
  12557. var self = this;
  12558. for (var node = self.firstChild; node;) {
  12559. var next = node.next;
  12560. self.insert(node, self, true);
  12561. node = next;
  12562. }
  12563. self.remove();
  12564. };
  12565. AstNode.prototype.remove = function () {
  12566. var self = this, parent = self.parent, next = self.next, prev = self.prev;
  12567. if (parent) {
  12568. if (parent.firstChild === self) {
  12569. parent.firstChild = next;
  12570. if (next) {
  12571. next.prev = null;
  12572. }
  12573. } else {
  12574. prev.next = next;
  12575. }
  12576. if (parent.lastChild === self) {
  12577. parent.lastChild = prev;
  12578. if (prev) {
  12579. prev.next = null;
  12580. }
  12581. } else {
  12582. next.prev = prev;
  12583. }
  12584. self.parent = self.next = self.prev = null;
  12585. }
  12586. return self;
  12587. };
  12588. AstNode.prototype.append = function (node) {
  12589. var self = this;
  12590. if (node.parent) {
  12591. node.remove();
  12592. }
  12593. var last = self.lastChild;
  12594. if (last) {
  12595. last.next = node;
  12596. node.prev = last;
  12597. self.lastChild = node;
  12598. } else {
  12599. self.lastChild = self.firstChild = node;
  12600. }
  12601. node.parent = self;
  12602. return node;
  12603. };
  12604. AstNode.prototype.insert = function (node, refNode, before) {
  12605. if (node.parent) {
  12606. node.remove();
  12607. }
  12608. var parent = refNode.parent || this;
  12609. if (before) {
  12610. if (refNode === parent.firstChild) {
  12611. parent.firstChild = node;
  12612. } else {
  12613. refNode.prev.next = node;
  12614. }
  12615. node.prev = refNode.prev;
  12616. node.next = refNode;
  12617. refNode.prev = node;
  12618. } else {
  12619. if (refNode === parent.lastChild) {
  12620. parent.lastChild = node;
  12621. } else {
  12622. refNode.next.prev = node;
  12623. }
  12624. node.next = refNode.next;
  12625. node.prev = refNode;
  12626. refNode.next = node;
  12627. }
  12628. node.parent = parent;
  12629. return node;
  12630. };
  12631. AstNode.prototype.getAll = function (name) {
  12632. var self = this;
  12633. var collection = [];
  12634. for (var node = self.firstChild; node; node = walk$1(node, self)) {
  12635. if (node.name === name) {
  12636. collection.push(node);
  12637. }
  12638. }
  12639. return collection;
  12640. };
  12641. AstNode.prototype.children = function () {
  12642. var self = this;
  12643. var collection = [];
  12644. for (var node = self.firstChild; node; node = node.next) {
  12645. collection.push(node);
  12646. }
  12647. return collection;
  12648. };
  12649. AstNode.prototype.empty = function () {
  12650. var self = this;
  12651. if (self.firstChild) {
  12652. var nodes = [];
  12653. for (var node = self.firstChild; node; node = walk$1(node, self)) {
  12654. nodes.push(node);
  12655. }
  12656. var i = nodes.length;
  12657. while (i--) {
  12658. var node = nodes[i];
  12659. node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
  12660. }
  12661. }
  12662. self.firstChild = self.lastChild = null;
  12663. return self;
  12664. };
  12665. AstNode.prototype.isEmpty = function (elements, whitespace, predicate) {
  12666. if (whitespace === void 0) {
  12667. whitespace = {};
  12668. }
  12669. var self = this;
  12670. var node = self.firstChild;
  12671. if (isNonEmptyElement(self)) {
  12672. return false;
  12673. }
  12674. if (node) {
  12675. do {
  12676. if (node.type === 1) {
  12677. if (node.attr('data-mce-bogus')) {
  12678. continue;
  12679. }
  12680. if (elements[node.name]) {
  12681. return false;
  12682. }
  12683. if (isNonEmptyElement(node)) {
  12684. return false;
  12685. }
  12686. }
  12687. if (node.type === 8) {
  12688. return false;
  12689. }
  12690. if (node.type === 3 && !isEmptyTextNode(node)) {
  12691. return false;
  12692. }
  12693. if (node.type === 3 && node.parent && whitespace[node.parent.name] && isWhitespaceText(node.value)) {
  12694. return false;
  12695. }
  12696. if (predicate && predicate(node)) {
  12697. return false;
  12698. }
  12699. } while (node = walk$1(node, self));
  12700. }
  12701. return true;
  12702. };
  12703. AstNode.prototype.walk = function (prev) {
  12704. return walk$1(this, null, prev);
  12705. };
  12706. return AstNode;
  12707. }();
  12708. var extractBase64DataUris = function (html) {
  12709. var dataImageUri = /data:[^;]+;base64,([a-z0-9\+\/=\s]+)/gi;
  12710. var chunks = [];
  12711. var uris = {};
  12712. var prefix = generate('img');
  12713. var matches;
  12714. var index = 0;
  12715. var count = 0;
  12716. while (matches = dataImageUri.exec(html)) {
  12717. var uri = matches[0];
  12718. var imageId = prefix + '_' + count++;
  12719. uris[imageId] = uri;
  12720. if (index < matches.index) {
  12721. chunks.push(html.substr(index, matches.index - index));
  12722. }
  12723. chunks.push(imageId);
  12724. index = matches.index + uri.length;
  12725. }
  12726. var re = new RegExp(prefix + '_[0-9]+', 'g');
  12727. if (index === 0) {
  12728. return {
  12729. prefix: prefix,
  12730. uris: uris,
  12731. html: html,
  12732. re: re
  12733. };
  12734. } else {
  12735. if (index < html.length) {
  12736. chunks.push(html.substr(index));
  12737. }
  12738. return {
  12739. prefix: prefix,
  12740. uris: uris,
  12741. html: chunks.join(''),
  12742. re: re
  12743. };
  12744. }
  12745. };
  12746. var restoreDataUris = function (html, result) {
  12747. return html.replace(result.re, function (imageId) {
  12748. return get$9(result.uris, imageId).getOr(imageId);
  12749. });
  12750. };
  12751. var parseDataUri$1 = function (uri) {
  12752. var matches = /data:([^;]+);base64,([a-z0-9\+\/=\s]+)/i.exec(uri);
  12753. if (matches) {
  12754. return Optional.some({
  12755. type: matches[1],
  12756. data: decodeURIComponent(matches[2])
  12757. });
  12758. } else {
  12759. return Optional.none();
  12760. }
  12761. };
  12762. var each$d = Tools.each, trim = Tools.trim;
  12763. var queryParts = 'source protocol authority userInfo user password host port relative path directory file query anchor'.split(' ');
  12764. var DEFAULT_PORTS = {
  12765. ftp: 21,
  12766. http: 80,
  12767. https: 443,
  12768. mailto: 25
  12769. };
  12770. var safeSvgDataUrlElements = [
  12771. 'img',
  12772. 'video'
  12773. ];
  12774. var blockSvgDataUris = function (allowSvgDataUrls, tagName) {
  12775. if (isNonNullable(allowSvgDataUrls)) {
  12776. return !allowSvgDataUrls;
  12777. } else {
  12778. return isNonNullable(tagName) ? !contains$3(safeSvgDataUrlElements, tagName) : true;
  12779. }
  12780. };
  12781. var isInvalidUri = function (settings, uri, tagName) {
  12782. if (settings.allow_html_data_urls) {
  12783. return false;
  12784. } else if (/^data:image\//i.test(uri)) {
  12785. return blockSvgDataUris(settings.allow_svg_data_urls, tagName) && /^data:image\/svg\+xml/i.test(uri);
  12786. } else {
  12787. return /^data:/i.test(uri);
  12788. }
  12789. };
  12790. var URI = function () {
  12791. function URI(url, settings) {
  12792. url = trim(url);
  12793. this.settings = settings || {};
  12794. var baseUri = this.settings.base_uri;
  12795. var self = this;
  12796. if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
  12797. self.source = url;
  12798. return;
  12799. }
  12800. var isProtocolRelative = url.indexOf('//') === 0;
  12801. if (url.indexOf('/') === 0 && !isProtocolRelative) {
  12802. url = (baseUri ? baseUri.protocol || 'http' : 'http') + '://mce_host' + url;
  12803. }
  12804. if (!/^[\w\-]*:?\/\//.test(url)) {
  12805. var baseUrl = this.settings.base_uri ? this.settings.base_uri.path : new URI(document.location.href).directory;
  12806. if (this.settings.base_uri && this.settings.base_uri.protocol == '') {
  12807. url = '//mce_host' + self.toAbsPath(baseUrl, url);
  12808. } else {
  12809. var match = /([^#?]*)([#?]?.*)/.exec(url);
  12810. url = (baseUri && baseUri.protocol || 'http') + '://mce_host' + self.toAbsPath(baseUrl, match[1]) + match[2];
  12811. }
  12812. }
  12813. url = url.replace(/@@/g, '(mce_at)');
  12814. var urlMatch = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?(\[[a-zA-Z0-9:.%]+\]|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
  12815. each$d(queryParts, function (v, i) {
  12816. var part = urlMatch[i];
  12817. if (part) {
  12818. part = part.replace(/\(mce_at\)/g, '@@');
  12819. }
  12820. self[v] = part;
  12821. });
  12822. if (baseUri) {
  12823. if (!self.protocol) {
  12824. self.protocol = baseUri.protocol;
  12825. }
  12826. if (!self.userInfo) {
  12827. self.userInfo = baseUri.userInfo;
  12828. }
  12829. if (!self.port && self.host === 'mce_host') {
  12830. self.port = baseUri.port;
  12831. }
  12832. if (!self.host || self.host === 'mce_host') {
  12833. self.host = baseUri.host;
  12834. }
  12835. self.source = '';
  12836. }
  12837. if (isProtocolRelative) {
  12838. self.protocol = '';
  12839. }
  12840. }
  12841. URI.parseDataUri = function (uri) {
  12842. var type;
  12843. var uriComponents = decodeURIComponent(uri).split(',');
  12844. var matches = /data:([^;]+)/.exec(uriComponents[0]);
  12845. if (matches) {
  12846. type = matches[1];
  12847. }
  12848. return {
  12849. type: type,
  12850. data: uriComponents[1]
  12851. };
  12852. };
  12853. URI.isDomSafe = function (uri, context, options) {
  12854. if (options === void 0) {
  12855. options = {};
  12856. }
  12857. if (options.allow_script_urls) {
  12858. return true;
  12859. } else {
  12860. var decodedUri = Entities.decode(uri).replace(/[\s\u0000-\u001F]+/g, '');
  12861. try {
  12862. decodedUri = decodeURIComponent(decodedUri);
  12863. } catch (ex) {
  12864. decodedUri = unescape(decodedUri);
  12865. }
  12866. if (/((java|vb)script|mhtml):/i.test(decodedUri)) {
  12867. return false;
  12868. }
  12869. return !isInvalidUri(options, decodedUri, context);
  12870. }
  12871. };
  12872. URI.getDocumentBaseUrl = function (loc) {
  12873. var baseUrl;
  12874. if (loc.protocol.indexOf('http') !== 0 && loc.protocol !== 'file:') {
  12875. baseUrl = loc.href;
  12876. } else {
  12877. baseUrl = loc.protocol + '//' + loc.host + loc.pathname;
  12878. }
  12879. if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
  12880. baseUrl = baseUrl.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  12881. if (!/[\/\\]$/.test(baseUrl)) {
  12882. baseUrl += '/';
  12883. }
  12884. }
  12885. return baseUrl;
  12886. };
  12887. URI.prototype.setPath = function (path) {
  12888. var pathMatch = /^(.*?)\/?(\w+)?$/.exec(path);
  12889. this.path = pathMatch[0];
  12890. this.directory = pathMatch[1];
  12891. this.file = pathMatch[2];
  12892. this.source = '';
  12893. this.getURI();
  12894. };
  12895. URI.prototype.toRelative = function (uri) {
  12896. var output;
  12897. if (uri === './') {
  12898. return uri;
  12899. }
  12900. var relativeUri = new URI(uri, { base_uri: this });
  12901. if (relativeUri.host !== 'mce_host' && this.host !== relativeUri.host && relativeUri.host || this.port !== relativeUri.port || this.protocol !== relativeUri.protocol && relativeUri.protocol !== '') {
  12902. return relativeUri.getURI();
  12903. }
  12904. var tu = this.getURI(), uu = relativeUri.getURI();
  12905. if (tu === uu || tu.charAt(tu.length - 1) === '/' && tu.substr(0, tu.length - 1) === uu) {
  12906. return tu;
  12907. }
  12908. output = this.toRelPath(this.path, relativeUri.path);
  12909. if (relativeUri.query) {
  12910. output += '?' + relativeUri.query;
  12911. }
  12912. if (relativeUri.anchor) {
  12913. output += '#' + relativeUri.anchor;
  12914. }
  12915. return output;
  12916. };
  12917. URI.prototype.toAbsolute = function (uri, noHost) {
  12918. var absoluteUri = new URI(uri, { base_uri: this });
  12919. return absoluteUri.getURI(noHost && this.isSameOrigin(absoluteUri));
  12920. };
  12921. URI.prototype.isSameOrigin = function (uri) {
  12922. if (this.host == uri.host && this.protocol == uri.protocol) {
  12923. if (this.port == uri.port) {
  12924. return true;
  12925. }
  12926. var defaultPort = DEFAULT_PORTS[this.protocol];
  12927. if (defaultPort && (this.port || defaultPort) == (uri.port || defaultPort)) {
  12928. return true;
  12929. }
  12930. }
  12931. return false;
  12932. };
  12933. URI.prototype.toRelPath = function (base, path) {
  12934. var breakPoint = 0, out = '', i, l;
  12935. var normalizedBase = base.substring(0, base.lastIndexOf('/')).split('/');
  12936. var items = path.split('/');
  12937. if (normalizedBase.length >= items.length) {
  12938. for (i = 0, l = normalizedBase.length; i < l; i++) {
  12939. if (i >= items.length || normalizedBase[i] !== items[i]) {
  12940. breakPoint = i + 1;
  12941. break;
  12942. }
  12943. }
  12944. }
  12945. if (normalizedBase.length < items.length) {
  12946. for (i = 0, l = items.length; i < l; i++) {
  12947. if (i >= normalizedBase.length || normalizedBase[i] !== items[i]) {
  12948. breakPoint = i + 1;
  12949. break;
  12950. }
  12951. }
  12952. }
  12953. if (breakPoint === 1) {
  12954. return path;
  12955. }
  12956. for (i = 0, l = normalizedBase.length - (breakPoint - 1); i < l; i++) {
  12957. out += '../';
  12958. }
  12959. for (i = breakPoint - 1, l = items.length; i < l; i++) {
  12960. if (i !== breakPoint - 1) {
  12961. out += '/' + items[i];
  12962. } else {
  12963. out += items[i];
  12964. }
  12965. }
  12966. return out;
  12967. };
  12968. URI.prototype.toAbsPath = function (base, path) {
  12969. var i, nb = 0, o = [], outPath;
  12970. var tr = /\/$/.test(path) ? '/' : '';
  12971. var normalizedBase = base.split('/');
  12972. var normalizedPath = path.split('/');
  12973. each$d(normalizedBase, function (k) {
  12974. if (k) {
  12975. o.push(k);
  12976. }
  12977. });
  12978. normalizedBase = o;
  12979. for (i = normalizedPath.length - 1, o = []; i >= 0; i--) {
  12980. if (normalizedPath[i].length === 0 || normalizedPath[i] === '.') {
  12981. continue;
  12982. }
  12983. if (normalizedPath[i] === '..') {
  12984. nb++;
  12985. continue;
  12986. }
  12987. if (nb > 0) {
  12988. nb--;
  12989. continue;
  12990. }
  12991. o.push(normalizedPath[i]);
  12992. }
  12993. i = normalizedBase.length - nb;
  12994. if (i <= 0) {
  12995. outPath = reverse(o).join('/');
  12996. } else {
  12997. outPath = normalizedBase.slice(0, i).join('/') + '/' + reverse(o).join('/');
  12998. }
  12999. if (outPath.indexOf('/') !== 0) {
  13000. outPath = '/' + outPath;
  13001. }
  13002. if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) {
  13003. outPath += tr;
  13004. }
  13005. return outPath;
  13006. };
  13007. URI.prototype.getURI = function (noProtoHost) {
  13008. if (noProtoHost === void 0) {
  13009. noProtoHost = false;
  13010. }
  13011. var s;
  13012. if (!this.source || noProtoHost) {
  13013. s = '';
  13014. if (!noProtoHost) {
  13015. if (this.protocol) {
  13016. s += this.protocol + '://';
  13017. } else {
  13018. s += '//';
  13019. }
  13020. if (this.userInfo) {
  13021. s += this.userInfo + '@';
  13022. }
  13023. if (this.host) {
  13024. s += this.host;
  13025. }
  13026. if (this.port) {
  13027. s += ':' + this.port;
  13028. }
  13029. }
  13030. if (this.path) {
  13031. s += this.path;
  13032. }
  13033. if (this.query) {
  13034. s += '?' + this.query;
  13035. }
  13036. if (this.anchor) {
  13037. s += '#' + this.anchor;
  13038. }
  13039. this.source = s;
  13040. }
  13041. return this.source;
  13042. };
  13043. return URI;
  13044. }();
  13045. var filteredClobberElements = Tools.makeMap('button,fieldset,form,iframe,img,image,input,object,output,select,textarea');
  13046. var isValidPrefixAttrName = function (name) {
  13047. return name.indexOf('data-') === 0 || name.indexOf('aria-') === 0;
  13048. };
  13049. var findMatchingEndTagIndex = function (schema, html, startIndex) {
  13050. var startTagRegExp = /<([!?\/])?([A-Za-z0-9\-_:.]+)/g;
  13051. var endTagRegExp = /(?:\s(?:[^'">]+(?:"[^"]*"|'[^']*'))*[^"'>]*(?:"[^">]*|'[^'>]*)?|\s*|\/)>/g;
  13052. var shortEndedElements = schema.getShortEndedElements();
  13053. var count = 1, index = startIndex;
  13054. while (count !== 0) {
  13055. startTagRegExp.lastIndex = index;
  13056. while (true) {
  13057. var startMatch = startTagRegExp.exec(html);
  13058. if (startMatch === null) {
  13059. return index;
  13060. } else if (startMatch[1] === '!') {
  13061. if (startsWith(startMatch[2], '--')) {
  13062. index = findCommentEndIndex(html, false, startMatch.index + '!--'.length);
  13063. } else {
  13064. index = findCommentEndIndex(html, true, startMatch.index + 1);
  13065. }
  13066. break;
  13067. } else {
  13068. endTagRegExp.lastIndex = startTagRegExp.lastIndex;
  13069. var endMatch = endTagRegExp.exec(html);
  13070. if (isNull(endMatch) || endMatch.index !== startTagRegExp.lastIndex) {
  13071. continue;
  13072. }
  13073. if (startMatch[1] === '/') {
  13074. count -= 1;
  13075. } else if (!has$2(shortEndedElements, startMatch[2])) {
  13076. count += 1;
  13077. }
  13078. index = startTagRegExp.lastIndex + endMatch[0].length;
  13079. break;
  13080. }
  13081. }
  13082. }
  13083. return index;
  13084. };
  13085. var isConditionalComment = function (html, startIndex) {
  13086. return /^\s*\[if [\w\W]+\]>.*<!\[endif\](--!?)?>/.test(html.substr(startIndex));
  13087. };
  13088. var findCommentEndIndex = function (html, isBogus, startIndex) {
  13089. if (startIndex === void 0) {
  13090. startIndex = 0;
  13091. }
  13092. var lcHtml = html.toLowerCase();
  13093. if (lcHtml.indexOf('[if ', startIndex) !== -1 && isConditionalComment(lcHtml, startIndex)) {
  13094. var endIfIndex = lcHtml.indexOf('[endif]', startIndex);
  13095. return lcHtml.indexOf('>', endIfIndex);
  13096. } else {
  13097. if (isBogus) {
  13098. var endIndex = lcHtml.indexOf('>', startIndex);
  13099. return endIndex !== -1 ? endIndex : lcHtml.length;
  13100. } else {
  13101. var endCommentRegexp = /--!?>/g;
  13102. endCommentRegexp.lastIndex = startIndex;
  13103. var match = endCommentRegexp.exec(html);
  13104. return match ? match.index + match[0].length : lcHtml.length;
  13105. }
  13106. }
  13107. };
  13108. var checkBogusAttribute = function (regExp, attrString) {
  13109. var matches = regExp.exec(attrString);
  13110. if (matches) {
  13111. var name_1 = matches[1];
  13112. var value = matches[2];
  13113. return typeof name_1 === 'string' && name_1.toLowerCase() === 'data-mce-bogus' ? value : null;
  13114. } else {
  13115. return null;
  13116. }
  13117. };
  13118. var SaxParser = function (settings, schema) {
  13119. var _a;
  13120. if (schema === void 0) {
  13121. schema = Schema();
  13122. }
  13123. settings = settings || {};
  13124. var doc = (_a = settings.document) !== null && _a !== void 0 ? _a : document;
  13125. var form = doc.createElement('form');
  13126. if (settings.fix_self_closing !== false) {
  13127. settings.fix_self_closing = true;
  13128. }
  13129. var comment = settings.comment ? settings.comment : noop;
  13130. var cdata = settings.cdata ? settings.cdata : noop;
  13131. var text = settings.text ? settings.text : noop;
  13132. var start = settings.start ? settings.start : noop;
  13133. var end = settings.end ? settings.end : noop;
  13134. var pi = settings.pi ? settings.pi : noop;
  13135. var doctype = settings.doctype ? settings.doctype : noop;
  13136. var parseInternal = function (base64Extract, format) {
  13137. if (format === void 0) {
  13138. format = 'html';
  13139. }
  13140. var html = base64Extract.html;
  13141. var matches, index = 0, value, endRegExp;
  13142. var stack = [];
  13143. var attrList, i, textData, name;
  13144. var isInternalElement, isShortEnded;
  13145. var elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns;
  13146. var attributesRequired, attributesDefault, attributesForced;
  13147. var anyAttributesRequired, attrValue, idCount = 0;
  13148. var decode = Entities.decode;
  13149. var filteredUrlAttrs = Tools.makeMap('src,href,data,background,action,formaction,poster,xlink:href');
  13150. var parsingMode = format === 'html' ? 0 : 1;
  13151. var processEndTag = function (name) {
  13152. var pos, i;
  13153. pos = stack.length;
  13154. while (pos--) {
  13155. if (stack[pos].name === name) {
  13156. break;
  13157. }
  13158. }
  13159. if (pos >= 0) {
  13160. for (i = stack.length - 1; i >= pos; i--) {
  13161. name = stack[i];
  13162. if (name.valid) {
  13163. end(name.name);
  13164. }
  13165. }
  13166. stack.length = pos;
  13167. }
  13168. };
  13169. var processText = function (value, raw) {
  13170. return text(restoreDataUris(value, base64Extract), raw);
  13171. };
  13172. var processComment = function (value) {
  13173. if (value === '') {
  13174. return;
  13175. }
  13176. if (value.charAt(0) === '>') {
  13177. value = ' ' + value;
  13178. }
  13179. if (!settings.allow_conditional_comments && value.substr(0, 3).toLowerCase() === '[if') {
  13180. value = ' ' + value;
  13181. }
  13182. comment(restoreDataUris(value, base64Extract));
  13183. };
  13184. var processAttr = function (value) {
  13185. return restoreDataUris(value, base64Extract);
  13186. };
  13187. var processMalformedComment = function (value, startIndex) {
  13188. var startTag = value || '';
  13189. var isBogus = !startsWith(startTag, '--');
  13190. var endIndex = findCommentEndIndex(html, isBogus, startIndex);
  13191. value = html.substr(startIndex, endIndex - startIndex);
  13192. processComment(isBogus ? startTag + value : value);
  13193. return endIndex + 1;
  13194. };
  13195. var parseAttribute = function (tagName, name, value, val2, val3) {
  13196. name = name.toLowerCase();
  13197. value = processAttr(name in fillAttrsMap ? name : decode(value || val2 || val3 || ''));
  13198. if (validate && !isInternalElement && isValidPrefixAttrName(name) === false) {
  13199. var attrRule = validAttributesMap[name];
  13200. if (!attrRule && validAttributePatterns) {
  13201. var i_1 = validAttributePatterns.length;
  13202. while (i_1--) {
  13203. attrRule = validAttributePatterns[i_1];
  13204. if (attrRule.pattern.test(name)) {
  13205. break;
  13206. }
  13207. }
  13208. if (i_1 === -1) {
  13209. attrRule = null;
  13210. }
  13211. }
  13212. if (!attrRule) {
  13213. return;
  13214. }
  13215. if (attrRule.validValues && !(value in attrRule.validValues)) {
  13216. return;
  13217. }
  13218. }
  13219. var isNameOrId = name === 'name' || name === 'id';
  13220. if (isNameOrId && tagName in filteredClobberElements && (value in doc || value in form)) {
  13221. return;
  13222. }
  13223. if (filteredUrlAttrs[name] && !URI.isDomSafe(value, tagName, settings)) {
  13224. return;
  13225. }
  13226. if (isInternalElement && (name in filteredUrlAttrs || name.indexOf('on') === 0)) {
  13227. return;
  13228. }
  13229. attrList.map[name] = value;
  13230. attrList.push({
  13231. name: name,
  13232. value: value
  13233. });
  13234. };
  13235. 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');
  13236. var attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g;
  13237. var shortEndedElements = schema.getShortEndedElements();
  13238. var selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
  13239. var fillAttrsMap = schema.getBoolAttrs();
  13240. var validate = settings.validate;
  13241. var removeInternalElements = settings.remove_internals;
  13242. var fixSelfClosing = settings.fix_self_closing;
  13243. var specialElements = schema.getSpecialElements();
  13244. var processHtml = html + '>';
  13245. while (matches = tokenRegExp.exec(processHtml)) {
  13246. var matchText = matches[0];
  13247. if (index < matches.index) {
  13248. processText(decode(html.substr(index, matches.index - index)));
  13249. }
  13250. if (value = matches[7]) {
  13251. value = value.toLowerCase();
  13252. if (value.charAt(0) === ':') {
  13253. value = value.substr(1);
  13254. }
  13255. processEndTag(value);
  13256. } else if (value = matches[8]) {
  13257. if (matches.index + matchText.length > html.length) {
  13258. processText(decode(html.substr(matches.index)));
  13259. index = matches.index + matchText.length;
  13260. continue;
  13261. }
  13262. value = value.toLowerCase();
  13263. if (value.charAt(0) === ':') {
  13264. value = value.substr(1);
  13265. }
  13266. isShortEnded = value in shortEndedElements;
  13267. if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value) {
  13268. processEndTag(value);
  13269. }
  13270. var bogusValue = checkBogusAttribute(attrRegExp, matches[9]);
  13271. if (bogusValue !== null) {
  13272. if (bogusValue === 'all') {
  13273. index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
  13274. tokenRegExp.lastIndex = index;
  13275. continue;
  13276. }
  13277. isValidElement = false;
  13278. }
  13279. if (!validate || (elementRule = schema.getElementRule(value))) {
  13280. isValidElement = true;
  13281. if (validate) {
  13282. validAttributesMap = elementRule.attributes;
  13283. validAttributePatterns = elementRule.attributePatterns;
  13284. }
  13285. if (attribsValue = matches[9]) {
  13286. isInternalElement = attribsValue.indexOf('data-mce-type') !== -1;
  13287. if (isInternalElement && removeInternalElements) {
  13288. isValidElement = false;
  13289. }
  13290. attrList = [];
  13291. attrList.map = {};
  13292. attribsValue.replace(attrRegExp, function (match, name, val, val2, val3) {
  13293. parseAttribute(value, name, val, val2, val3);
  13294. return '';
  13295. });
  13296. } else {
  13297. attrList = [];
  13298. attrList.map = {};
  13299. }
  13300. if (validate && !isInternalElement) {
  13301. attributesRequired = elementRule.attributesRequired;
  13302. attributesDefault = elementRule.attributesDefault;
  13303. attributesForced = elementRule.attributesForced;
  13304. anyAttributesRequired = elementRule.removeEmptyAttrs;
  13305. if (anyAttributesRequired && !attrList.length) {
  13306. isValidElement = false;
  13307. }
  13308. if (attributesForced) {
  13309. i = attributesForced.length;
  13310. while (i--) {
  13311. attr = attributesForced[i];
  13312. name = attr.name;
  13313. attrValue = attr.value;
  13314. if (attrValue === '{$uid}') {
  13315. attrValue = 'mce_' + idCount++;
  13316. }
  13317. attrList.map[name] = attrValue;
  13318. attrList.push({
  13319. name: name,
  13320. value: attrValue
  13321. });
  13322. }
  13323. }
  13324. if (attributesDefault) {
  13325. i = attributesDefault.length;
  13326. while (i--) {
  13327. attr = attributesDefault[i];
  13328. name = attr.name;
  13329. if (!(name in attrList.map)) {
  13330. attrValue = attr.value;
  13331. if (attrValue === '{$uid}') {
  13332. attrValue = 'mce_' + idCount++;
  13333. }
  13334. attrList.map[name] = attrValue;
  13335. attrList.push({
  13336. name: name,
  13337. value: attrValue
  13338. });
  13339. }
  13340. }
  13341. }
  13342. if (attributesRequired) {
  13343. i = attributesRequired.length;
  13344. while (i--) {
  13345. if (attributesRequired[i] in attrList.map) {
  13346. break;
  13347. }
  13348. }
  13349. if (i === -1) {
  13350. isValidElement = false;
  13351. }
  13352. }
  13353. if (attr = attrList.map['data-mce-bogus']) {
  13354. if (attr === 'all') {
  13355. index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
  13356. tokenRegExp.lastIndex = index;
  13357. continue;
  13358. }
  13359. isValidElement = false;
  13360. }
  13361. }
  13362. if (isValidElement) {
  13363. start(value, attrList, isShortEnded);
  13364. }
  13365. } else {
  13366. isValidElement = false;
  13367. }
  13368. if (endRegExp = specialElements[value]) {
  13369. endRegExp.lastIndex = index = matches.index + matchText.length;
  13370. if (matches = endRegExp.exec(html)) {
  13371. if (isValidElement) {
  13372. textData = html.substr(index, matches.index - index);
  13373. }
  13374. index = matches.index + matches[0].length;
  13375. } else {
  13376. textData = html.substr(index);
  13377. index = html.length;
  13378. }
  13379. if (isValidElement) {
  13380. if (textData.length > 0) {
  13381. processText(textData, true);
  13382. }
  13383. end(value);
  13384. }
  13385. tokenRegExp.lastIndex = index;
  13386. continue;
  13387. }
  13388. if (!isShortEnded) {
  13389. if (!attribsValue || attribsValue.indexOf('/') !== attribsValue.length - 1) {
  13390. stack.push({
  13391. name: value,
  13392. valid: isValidElement
  13393. });
  13394. } else if (isValidElement) {
  13395. end(value);
  13396. }
  13397. }
  13398. } else if (value = matches[1]) {
  13399. processComment(value);
  13400. } else if (value = matches[2]) {
  13401. var isValidCdataSection = parsingMode === 1 || settings.preserve_cdata || stack.length > 0 && schema.isValidChild(stack[stack.length - 1].name, '#cdata');
  13402. if (isValidCdataSection) {
  13403. cdata(value);
  13404. } else {
  13405. index = processMalformedComment('', matches.index + 2);
  13406. tokenRegExp.lastIndex = index;
  13407. continue;
  13408. }
  13409. } else if (value = matches[3]) {
  13410. doctype(value);
  13411. } else if ((value = matches[4]) || matchText === '<!') {
  13412. index = processMalformedComment(value, matches.index + matchText.length);
  13413. tokenRegExp.lastIndex = index;
  13414. continue;
  13415. } else if (value = matches[5]) {
  13416. if (parsingMode === 1) {
  13417. pi(value, matches[6]);
  13418. } else {
  13419. index = processMalformedComment('?', matches.index + 2);
  13420. tokenRegExp.lastIndex = index;
  13421. continue;
  13422. }
  13423. }
  13424. index = matches.index + matchText.length;
  13425. }
  13426. if (index < html.length) {
  13427. processText(decode(html.substr(index)));
  13428. }
  13429. for (i = stack.length - 1; i >= 0; i--) {
  13430. value = stack[i];
  13431. if (value.valid) {
  13432. end(value.name);
  13433. }
  13434. }
  13435. };
  13436. var parse = function (html, format) {
  13437. if (format === void 0) {
  13438. format = 'html';
  13439. }
  13440. parseInternal(extractBase64DataUris(html), format);
  13441. };
  13442. return { parse: parse };
  13443. };
  13444. SaxParser.findEndTag = findMatchingEndTagIndex;
  13445. var trimHtml = function (tempAttrs, html) {
  13446. var trimContentRegExp = new RegExp(['\\s?(' + tempAttrs.join('|') + ')="[^"]+"'].join('|'), 'gi');
  13447. return html.replace(trimContentRegExp, '');
  13448. };
  13449. var trimInternal = function (serializer, html) {
  13450. var bogusAllRegExp = /<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g;
  13451. var schema = serializer.schema;
  13452. var content = trimHtml(serializer.getTempAttrs(), html);
  13453. var shortEndedElements = schema.getShortEndedElements();
  13454. var matches;
  13455. while (matches = bogusAllRegExp.exec(content)) {
  13456. var index = bogusAllRegExp.lastIndex;
  13457. var matchLength = matches[0].length;
  13458. var endTagIndex = void 0;
  13459. if (shortEndedElements[matches[1]]) {
  13460. endTagIndex = index;
  13461. } else {
  13462. endTagIndex = SaxParser.findEndTag(schema, content, index);
  13463. }
  13464. content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
  13465. bogusAllRegExp.lastIndex = index - matchLength;
  13466. }
  13467. return trim$2(content);
  13468. };
  13469. var trimExternal = trimInternal;
  13470. var trimEmptyContents = function (editor, html) {
  13471. var blockName = getForcedRootBlock(editor);
  13472. var emptyRegExp = new RegExp('^(<' + blockName + '[^>]*>(&nbsp;|&#160;|\\s|\xA0|<br \\/>|)<\\/' + blockName + '>[\r\n]*|<br \\/>[\r\n]*)$');
  13473. return html.replace(emptyRegExp, '');
  13474. };
  13475. var setupArgs$3 = function (args, format) {
  13476. return __assign(__assign({}, args), {
  13477. format: format,
  13478. get: true,
  13479. getInner: true
  13480. });
  13481. };
  13482. var getContentFromBody = function (editor, args, format, body) {
  13483. var defaultedArgs = setupArgs$3(args, format);
  13484. var updatedArgs = args.no_events ? defaultedArgs : editor.fire('BeforeGetContent', defaultedArgs);
  13485. var content;
  13486. if (updatedArgs.format === 'raw') {
  13487. content = Tools.trim(trimExternal(editor.serializer, body.innerHTML));
  13488. } else if (updatedArgs.format === 'text') {
  13489. content = editor.dom.isEmpty(body) ? '' : trim$2(body.innerText || body.textContent);
  13490. } else if (updatedArgs.format === 'tree') {
  13491. content = editor.serializer.serialize(body, updatedArgs);
  13492. } else {
  13493. content = trimEmptyContents(editor, editor.serializer.serialize(body, updatedArgs));
  13494. }
  13495. if (!contains$3([
  13496. 'text',
  13497. 'tree'
  13498. ], updatedArgs.format) && !isWsPreserveElement(SugarElement.fromDom(body))) {
  13499. updatedArgs.content = Tools.trim(content);
  13500. } else {
  13501. updatedArgs.content = content;
  13502. }
  13503. if (updatedArgs.no_events) {
  13504. return updatedArgs.content;
  13505. } else {
  13506. return editor.fire('GetContent', updatedArgs).content;
  13507. }
  13508. };
  13509. var getContentInternal = function (editor, args, format) {
  13510. return Optional.from(editor.getBody()).fold(constant(args.format === 'tree' ? new AstNode('body', 11) : ''), function (body) {
  13511. return getContentFromBody(editor, args, format, body);
  13512. });
  13513. };
  13514. var each$c = Tools.each;
  13515. var ElementUtils = function (dom) {
  13516. var compare = function (node1, node2) {
  13517. if (node1.nodeName !== node2.nodeName) {
  13518. return false;
  13519. }
  13520. var getAttribs = function (node) {
  13521. var attribs = {};
  13522. each$c(dom.getAttribs(node), function (attr) {
  13523. var name = attr.nodeName.toLowerCase();
  13524. if (name.indexOf('_') !== 0 && name !== 'style' && name.indexOf('data-') !== 0) {
  13525. attribs[name] = dom.getAttrib(node, name);
  13526. }
  13527. });
  13528. return attribs;
  13529. };
  13530. var compareObjects = function (obj1, obj2) {
  13531. var value, name;
  13532. for (name in obj1) {
  13533. if (has$2(obj1, name)) {
  13534. value = obj2[name];
  13535. if (typeof value === 'undefined') {
  13536. return false;
  13537. }
  13538. if (obj1[name] !== value) {
  13539. return false;
  13540. }
  13541. delete obj2[name];
  13542. }
  13543. }
  13544. for (name in obj2) {
  13545. if (has$2(obj2, name)) {
  13546. return false;
  13547. }
  13548. }
  13549. return true;
  13550. };
  13551. if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
  13552. return false;
  13553. }
  13554. if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
  13555. return false;
  13556. }
  13557. return !isBookmarkNode$1(node1) && !isBookmarkNode$1(node2);
  13558. };
  13559. return { compare: compare };
  13560. };
  13561. var makeMap$1 = Tools.makeMap;
  13562. var Writer = function (settings) {
  13563. var html = [];
  13564. settings = settings || {};
  13565. var indent = settings.indent;
  13566. var indentBefore = makeMap$1(settings.indent_before || '');
  13567. var indentAfter = makeMap$1(settings.indent_after || '');
  13568. var encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
  13569. var htmlOutput = settings.element_format === 'html';
  13570. return {
  13571. start: function (name, attrs, empty) {
  13572. var i, l, attr, value;
  13573. if (indent && indentBefore[name] && html.length > 0) {
  13574. value = html[html.length - 1];
  13575. if (value.length > 0 && value !== '\n') {
  13576. html.push('\n');
  13577. }
  13578. }
  13579. html.push('<', name);
  13580. if (attrs) {
  13581. for (i = 0, l = attrs.length; i < l; i++) {
  13582. attr = attrs[i];
  13583. html.push(' ', attr.name, '="', encode(attr.value, true), '"');
  13584. }
  13585. }
  13586. if (!empty || htmlOutput) {
  13587. html[html.length] = '>';
  13588. } else {
  13589. html[html.length] = ' />';
  13590. }
  13591. if (empty && indent && indentAfter[name] && html.length > 0) {
  13592. value = html[html.length - 1];
  13593. if (value.length > 0 && value !== '\n') {
  13594. html.push('\n');
  13595. }
  13596. }
  13597. },
  13598. end: function (name) {
  13599. var value;
  13600. html.push('</', name, '>');
  13601. if (indent && indentAfter[name] && html.length > 0) {
  13602. value = html[html.length - 1];
  13603. if (value.length > 0 && value !== '\n') {
  13604. html.push('\n');
  13605. }
  13606. }
  13607. },
  13608. text: function (text, raw) {
  13609. if (text.length > 0) {
  13610. html[html.length] = raw ? text : encode(text);
  13611. }
  13612. },
  13613. cdata: function (text) {
  13614. html.push('<![CDATA[', text, ']]>');
  13615. },
  13616. comment: function (text) {
  13617. html.push('<!--', text, '-->');
  13618. },
  13619. pi: function (name, text) {
  13620. if (text) {
  13621. html.push('<?', name, ' ', encode(text), '?>');
  13622. } else {
  13623. html.push('<?', name, '?>');
  13624. }
  13625. if (indent) {
  13626. html.push('\n');
  13627. }
  13628. },
  13629. doctype: function (text) {
  13630. html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
  13631. },
  13632. reset: function () {
  13633. html.length = 0;
  13634. },
  13635. getContent: function () {
  13636. return html.join('').replace(/\n$/, '');
  13637. }
  13638. };
  13639. };
  13640. var HtmlSerializer = function (settings, schema) {
  13641. if (schema === void 0) {
  13642. schema = Schema();
  13643. }
  13644. var writer = Writer(settings);
  13645. settings = settings || {};
  13646. settings.validate = 'validate' in settings ? settings.validate : true;
  13647. var serialize = function (node) {
  13648. var validate = settings.validate;
  13649. var handlers = {
  13650. 3: function (node) {
  13651. writer.text(node.value, node.raw);
  13652. },
  13653. 8: function (node) {
  13654. writer.comment(node.value);
  13655. },
  13656. 7: function (node) {
  13657. writer.pi(node.name, node.value);
  13658. },
  13659. 10: function (node) {
  13660. writer.doctype(node.value);
  13661. },
  13662. 4: function (node) {
  13663. writer.cdata(node.value);
  13664. },
  13665. 11: function (node) {
  13666. if (node = node.firstChild) {
  13667. do {
  13668. walk(node);
  13669. } while (node = node.next);
  13670. }
  13671. }
  13672. };
  13673. writer.reset();
  13674. var walk = function (node) {
  13675. var handler = handlers[node.type];
  13676. if (!handler) {
  13677. var name_1 = node.name;
  13678. var isEmpty = node.shortEnded;
  13679. var attrs = node.attributes;
  13680. if (validate && attrs && attrs.length > 1) {
  13681. var sortedAttrs = [];
  13682. sortedAttrs.map = {};
  13683. var elementRule = schema.getElementRule(node.name);
  13684. if (elementRule) {
  13685. for (var i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
  13686. var attrName = elementRule.attributesOrder[i];
  13687. if (attrName in attrs.map) {
  13688. var attrValue = attrs.map[attrName];
  13689. sortedAttrs.map[attrName] = attrValue;
  13690. sortedAttrs.push({
  13691. name: attrName,
  13692. value: attrValue
  13693. });
  13694. }
  13695. }
  13696. for (var i = 0, l = attrs.length; i < l; i++) {
  13697. var attrName = attrs[i].name;
  13698. if (!(attrName in sortedAttrs.map)) {
  13699. var attrValue = attrs.map[attrName];
  13700. sortedAttrs.map[attrName] = attrValue;
  13701. sortedAttrs.push({
  13702. name: attrName,
  13703. value: attrValue
  13704. });
  13705. }
  13706. }
  13707. attrs = sortedAttrs;
  13708. }
  13709. }
  13710. writer.start(node.name, attrs, isEmpty);
  13711. if (!isEmpty) {
  13712. if (node = node.firstChild) {
  13713. do {
  13714. walk(node);
  13715. } while (node = node.next);
  13716. }
  13717. writer.end(name_1);
  13718. }
  13719. } else {
  13720. handler(node);
  13721. }
  13722. };
  13723. if (node.type === 1 && !settings.inner) {
  13724. walk(node);
  13725. } else {
  13726. handlers[11](node);
  13727. }
  13728. return writer.getContent();
  13729. };
  13730. return { serialize: serialize };
  13731. };
  13732. var nonInheritableStyles = new Set();
  13733. (function () {
  13734. var nonInheritableStylesArr = [
  13735. 'margin',
  13736. 'margin-left',
  13737. 'margin-right',
  13738. 'margin-top',
  13739. 'margin-bottom',
  13740. 'padding',
  13741. 'padding-left',
  13742. 'padding-right',
  13743. 'padding-top',
  13744. 'padding-bottom',
  13745. 'border',
  13746. 'border-width',
  13747. 'border-style',
  13748. 'border-color',
  13749. 'background',
  13750. 'background-attachment',
  13751. 'background-clip',
  13752. 'background-color',
  13753. 'background-image',
  13754. 'background-origin',
  13755. 'background-position',
  13756. 'background-repeat',
  13757. 'background-size',
  13758. 'float',
  13759. 'position',
  13760. 'left',
  13761. 'right',
  13762. 'top',
  13763. 'bottom',
  13764. 'z-index',
  13765. 'display',
  13766. 'transform',
  13767. 'width',
  13768. 'max-width',
  13769. 'min-width',
  13770. 'height',
  13771. 'max-height',
  13772. 'min-height',
  13773. 'overflow',
  13774. 'overflow-x',
  13775. 'overflow-y',
  13776. 'text-overflow',
  13777. 'vertical-align',
  13778. 'transition',
  13779. 'transition-delay',
  13780. 'transition-duration',
  13781. 'transition-property',
  13782. 'transition-timing-function'
  13783. ];
  13784. each$k(nonInheritableStylesArr, function (style) {
  13785. nonInheritableStyles.add(style);
  13786. });
  13787. }());
  13788. var shorthandStyleProps = [
  13789. 'font',
  13790. 'text-decoration',
  13791. 'text-emphasis'
  13792. ];
  13793. var getStyleProps = function (dom, node) {
  13794. return keys(dom.parseStyle(dom.getAttrib(node, 'style')));
  13795. };
  13796. var isNonInheritableStyle = function (style) {
  13797. return nonInheritableStyles.has(style);
  13798. };
  13799. var hasInheritableStyles = function (dom, node) {
  13800. return forall(getStyleProps(dom, node), function (style) {
  13801. return !isNonInheritableStyle(style);
  13802. });
  13803. };
  13804. var getLonghandStyleProps = function (styles) {
  13805. return filter$4(styles, function (style) {
  13806. return exists(shorthandStyleProps, function (prop) {
  13807. return startsWith(style, prop);
  13808. });
  13809. });
  13810. };
  13811. var hasStyleConflict = function (dom, node, parentNode) {
  13812. var nodeStyleProps = getStyleProps(dom, node);
  13813. var parentNodeStyleProps = getStyleProps(dom, parentNode);
  13814. var valueMismatch = function (prop) {
  13815. var nodeValue = dom.getStyle(node, prop);
  13816. var parentValue = dom.getStyle(parentNode, prop);
  13817. return isNotEmpty(nodeValue) && isNotEmpty(parentValue) && nodeValue !== parentValue;
  13818. };
  13819. return exists(nodeStyleProps, function (nodeStyleProp) {
  13820. var propExists = function (props) {
  13821. return exists(props, function (prop) {
  13822. return prop === nodeStyleProp;
  13823. });
  13824. };
  13825. if (!propExists(parentNodeStyleProps) && propExists(shorthandStyleProps)) {
  13826. var longhandProps = getLonghandStyleProps(parentNodeStyleProps);
  13827. return exists(longhandProps, valueMismatch);
  13828. } else {
  13829. return valueMismatch(nodeStyleProp);
  13830. }
  13831. });
  13832. };
  13833. var isChar = function (forward, predicate, pos) {
  13834. return Optional.from(pos.container()).filter(isText$7).exists(function (text) {
  13835. var delta = forward ? 0 : -1;
  13836. return predicate(text.data.charAt(pos.offset() + delta));
  13837. });
  13838. };
  13839. var isBeforeSpace = curry(isChar, true, isWhiteSpace);
  13840. var isAfterSpace = curry(isChar, false, isWhiteSpace);
  13841. var isEmptyText = function (pos) {
  13842. var container = pos.container();
  13843. return isText$7(container) && (container.data.length === 0 || isZwsp(container.data) && BookmarkManager.isBookmarkNode(container.parentNode));
  13844. };
  13845. var matchesElementPosition = function (before, predicate) {
  13846. return function (pos) {
  13847. return Optional.from(getChildNodeAtRelativeOffset(before ? 0 : -1, pos)).filter(predicate).isSome();
  13848. };
  13849. };
  13850. var isImageBlock = function (node) {
  13851. return isImg(node) && get$5(SugarElement.fromDom(node), 'display') === 'block';
  13852. };
  13853. var isCefNode = function (node) {
  13854. return isContentEditableFalse$b(node) && !isBogusAll$1(node);
  13855. };
  13856. var isBeforeImageBlock = matchesElementPosition(true, isImageBlock);
  13857. var isAfterImageBlock = matchesElementPosition(false, isImageBlock);
  13858. var isBeforeMedia = matchesElementPosition(true, isMedia$2);
  13859. var isAfterMedia = matchesElementPosition(false, isMedia$2);
  13860. var isBeforeTable = matchesElementPosition(true, isTable$3);
  13861. var isAfterTable = matchesElementPosition(false, isTable$3);
  13862. var isBeforeContentEditableFalse = matchesElementPosition(true, isCefNode);
  13863. var isAfterContentEditableFalse = matchesElementPosition(false, isCefNode);
  13864. var getLastChildren = function (elm) {
  13865. var children = [];
  13866. var rawNode = elm.dom;
  13867. while (rawNode) {
  13868. children.push(SugarElement.fromDom(rawNode));
  13869. rawNode = rawNode.lastChild;
  13870. }
  13871. return children;
  13872. };
  13873. var removeTrailingBr = function (elm) {
  13874. var allBrs = descendants(elm, 'br');
  13875. var brs = filter$4(getLastChildren(elm).slice(-1), isBr$4);
  13876. if (allBrs.length === brs.length) {
  13877. each$k(brs, remove$7);
  13878. }
  13879. };
  13880. var fillWithPaddingBr = function (elm) {
  13881. empty(elm);
  13882. append$1(elm, SugarElement.fromHtml('<br data-mce-bogus="1">'));
  13883. };
  13884. var trimBlockTrailingBr = function (elm) {
  13885. lastChild(elm).each(function (lastChild) {
  13886. prevSibling(lastChild).each(function (lastChildPrevSibling) {
  13887. if (isBlock$2(elm) && isBr$4(lastChild) && isBlock$2(lastChildPrevSibling)) {
  13888. remove$7(lastChild);
  13889. }
  13890. });
  13891. });
  13892. };
  13893. var dropLast = function (xs) {
  13894. return xs.slice(0, -1);
  13895. };
  13896. var parentsUntil = function (start, root, predicate) {
  13897. if (contains$1(root, start)) {
  13898. return dropLast(parents$1(start, function (elm) {
  13899. return predicate(elm) || eq(elm, root);
  13900. }));
  13901. } else {
  13902. return [];
  13903. }
  13904. };
  13905. var parents = function (start, root) {
  13906. return parentsUntil(start, root, never);
  13907. };
  13908. var parentsAndSelf = function (start, root) {
  13909. return [start].concat(parents(start, root));
  13910. };
  13911. var navigateIgnoreEmptyTextNodes = function (forward, root, from) {
  13912. return navigateIgnore(forward, root, from, isEmptyText);
  13913. };
  13914. var getClosestBlock$1 = function (root, pos) {
  13915. return find$3(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  13916. };
  13917. var isAtBeforeAfterBlockBoundary = function (forward, root, pos) {
  13918. return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  13919. return getClosestBlock$1(root, pos).fold(function () {
  13920. return isInSameBlock(newPos, pos, root.dom) === false;
  13921. }, function (fromBlock) {
  13922. return isInSameBlock(newPos, pos, root.dom) === false && contains$1(fromBlock, SugarElement.fromDom(newPos.container()));
  13923. });
  13924. });
  13925. };
  13926. var isAtBlockBoundary = function (forward, root, pos) {
  13927. return getClosestBlock$1(root, pos).fold(function () {
  13928. return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  13929. return isInSameBlock(newPos, pos, root.dom) === false;
  13930. });
  13931. }, function (parent) {
  13932. return navigateIgnoreEmptyTextNodes(forward, parent.dom, pos).isNone();
  13933. });
  13934. };
  13935. var isAtStartOfBlock = curry(isAtBlockBoundary, false);
  13936. var isAtEndOfBlock = curry(isAtBlockBoundary, true);
  13937. var isBeforeBlock = curry(isAtBeforeAfterBlockBoundary, false);
  13938. var isAfterBlock = curry(isAtBeforeAfterBlockBoundary, true);
  13939. var isBr = function (pos) {
  13940. return getElementFromPosition(pos).exists(isBr$4);
  13941. };
  13942. var findBr = function (forward, root, pos) {
  13943. var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  13944. var scope = head(parentBlocks).getOr(root);
  13945. return fromPosition(forward, scope.dom, pos).filter(isBr);
  13946. };
  13947. var isBeforeBr$1 = function (root, pos) {
  13948. return getElementFromPosition(pos).exists(isBr$4) || findBr(true, root, pos).isSome();
  13949. };
  13950. var isAfterBr = function (root, pos) {
  13951. return getElementFromPrevPosition(pos).exists(isBr$4) || findBr(false, root, pos).isSome();
  13952. };
  13953. var findPreviousBr = curry(findBr, false);
  13954. var findNextBr = curry(findBr, true);
  13955. var isInMiddleOfText = function (pos) {
  13956. return CaretPosition.isTextPosition(pos) && !pos.isAtStart() && !pos.isAtEnd();
  13957. };
  13958. var getClosestBlock = function (root, pos) {
  13959. var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  13960. return head(parentBlocks).getOr(root);
  13961. };
  13962. var hasSpaceBefore = function (root, pos) {
  13963. if (isInMiddleOfText(pos)) {
  13964. return isAfterSpace(pos);
  13965. } else {
  13966. return isAfterSpace(pos) || prevPosition(getClosestBlock(root, pos).dom, pos).exists(isAfterSpace);
  13967. }
  13968. };
  13969. var hasSpaceAfter = function (root, pos) {
  13970. if (isInMiddleOfText(pos)) {
  13971. return isBeforeSpace(pos);
  13972. } else {
  13973. return isBeforeSpace(pos) || nextPosition(getClosestBlock(root, pos).dom, pos).exists(isBeforeSpace);
  13974. }
  13975. };
  13976. var isPreValue = function (value) {
  13977. return contains$3([
  13978. 'pre',
  13979. 'pre-wrap'
  13980. ], value);
  13981. };
  13982. var isInPre = function (pos) {
  13983. return getElementFromPosition(pos).bind(function (elm) {
  13984. return closest$3(elm, isElement$6);
  13985. }).exists(function (elm) {
  13986. return isPreValue(get$5(elm, 'white-space'));
  13987. });
  13988. };
  13989. var isAtBeginningOfBody = function (root, pos) {
  13990. return prevPosition(root.dom, pos).isNone();
  13991. };
  13992. var isAtEndOfBody = function (root, pos) {
  13993. return nextPosition(root.dom, pos).isNone();
  13994. };
  13995. var isAtLineBoundary = function (root, pos) {
  13996. return isAtBeginningOfBody(root, pos) || isAtEndOfBody(root, pos) || isAtStartOfBlock(root, pos) || isAtEndOfBlock(root, pos) || isAfterBr(root, pos) || isBeforeBr$1(root, pos);
  13997. };
  13998. var needsToHaveNbsp = function (root, pos) {
  13999. if (isInPre(pos)) {
  14000. return false;
  14001. } else {
  14002. return isAtLineBoundary(root, pos) || hasSpaceBefore(root, pos) || hasSpaceAfter(root, pos);
  14003. }
  14004. };
  14005. var needsToBeNbspLeft = function (root, pos) {
  14006. if (isInPre(pos)) {
  14007. return false;
  14008. } else {
  14009. return isAtStartOfBlock(root, pos) || isBeforeBlock(root, pos) || isAfterBr(root, pos) || hasSpaceBefore(root, pos);
  14010. }
  14011. };
  14012. var leanRight = function (pos) {
  14013. var container = pos.container();
  14014. var offset = pos.offset();
  14015. if (isText$7(container) && offset < container.data.length) {
  14016. return CaretPosition(container, offset + 1);
  14017. } else {
  14018. return pos;
  14019. }
  14020. };
  14021. var needsToBeNbspRight = function (root, pos) {
  14022. if (isInPre(pos)) {
  14023. return false;
  14024. } else {
  14025. return isAtEndOfBlock(root, pos) || isAfterBlock(root, pos) || isBeforeBr$1(root, pos) || hasSpaceAfter(root, pos);
  14026. }
  14027. };
  14028. var needsToBeNbsp = function (root, pos) {
  14029. return needsToBeNbspLeft(root, pos) || needsToBeNbspRight(root, leanRight(pos));
  14030. };
  14031. var isNbspAt = function (text, offset) {
  14032. return isNbsp(text.charAt(offset));
  14033. };
  14034. var hasNbsp = function (pos) {
  14035. var container = pos.container();
  14036. return isText$7(container) && contains$2(container.data, nbsp);
  14037. };
  14038. var normalizeNbspMiddle = function (text) {
  14039. var chars = text.split('');
  14040. return map$3(chars, function (chr, i) {
  14041. if (isNbsp(chr) && i > 0 && i < chars.length - 1 && isContent(chars[i - 1]) && isContent(chars[i + 1])) {
  14042. return ' ';
  14043. } else {
  14044. return chr;
  14045. }
  14046. }).join('');
  14047. };
  14048. var normalizeNbspAtStart = function (root, node) {
  14049. var text = node.data;
  14050. var firstPos = CaretPosition(node, 0);
  14051. if (isNbspAt(text, 0) && !needsToBeNbsp(root, firstPos)) {
  14052. node.data = ' ' + text.slice(1);
  14053. return true;
  14054. } else {
  14055. return false;
  14056. }
  14057. };
  14058. var normalizeNbspInMiddleOfTextNode = function (node) {
  14059. var text = node.data;
  14060. var newText = normalizeNbspMiddle(text);
  14061. if (newText !== text) {
  14062. node.data = newText;
  14063. return true;
  14064. } else {
  14065. return false;
  14066. }
  14067. };
  14068. var normalizeNbspAtEnd = function (root, node) {
  14069. var text = node.data;
  14070. var lastPos = CaretPosition(node, text.length - 1);
  14071. if (isNbspAt(text, text.length - 1) && !needsToBeNbsp(root, lastPos)) {
  14072. node.data = text.slice(0, -1) + ' ';
  14073. return true;
  14074. } else {
  14075. return false;
  14076. }
  14077. };
  14078. var normalizeNbsps = function (root, pos) {
  14079. return Optional.some(pos).filter(hasNbsp).bind(function (pos) {
  14080. var container = pos.container();
  14081. var normalized = normalizeNbspAtStart(root, container) || normalizeNbspInMiddleOfTextNode(container) || normalizeNbspAtEnd(root, container);
  14082. return normalized ? Optional.some(pos) : Optional.none();
  14083. });
  14084. };
  14085. var normalizeNbspsInEditor = function (editor) {
  14086. var root = SugarElement.fromDom(editor.getBody());
  14087. if (editor.selection.isCollapsed()) {
  14088. normalizeNbsps(root, CaretPosition.fromRangeStart(editor.selection.getRng())).each(function (pos) {
  14089. editor.selection.setRng(pos.toRange());
  14090. });
  14091. }
  14092. };
  14093. var normalizeContent = function (content, isStartOfContent, isEndOfContent) {
  14094. var result = foldl(content, function (acc, c) {
  14095. if (isWhiteSpace(c) || isNbsp(c)) {
  14096. if (acc.previousCharIsSpace || acc.str === '' && isStartOfContent || acc.str.length === content.length - 1 && isEndOfContent) {
  14097. return {
  14098. previousCharIsSpace: false,
  14099. str: acc.str + nbsp
  14100. };
  14101. } else {
  14102. return {
  14103. previousCharIsSpace: true,
  14104. str: acc.str + ' '
  14105. };
  14106. }
  14107. } else {
  14108. return {
  14109. previousCharIsSpace: false,
  14110. str: acc.str + c
  14111. };
  14112. }
  14113. }, {
  14114. previousCharIsSpace: false,
  14115. str: ''
  14116. });
  14117. return result.str;
  14118. };
  14119. var normalize$1 = function (node, offset, count) {
  14120. if (count === 0) {
  14121. return;
  14122. }
  14123. var elm = SugarElement.fromDom(node);
  14124. var root = ancestor$3(elm, isBlock$2).getOr(elm);
  14125. var whitespace = node.data.slice(offset, offset + count);
  14126. var isEndOfContent = offset + count >= node.data.length && needsToBeNbspRight(root, CaretPosition(node, node.data.length));
  14127. var isStartOfContent = offset === 0 && needsToBeNbspLeft(root, CaretPosition(node, 0));
  14128. node.replaceData(offset, count, normalizeContent(whitespace, isStartOfContent, isEndOfContent));
  14129. };
  14130. var normalizeWhitespaceAfter = function (node, offset) {
  14131. var content = node.data.slice(offset);
  14132. var whitespaceCount = content.length - lTrim(content).length;
  14133. normalize$1(node, offset, whitespaceCount);
  14134. };
  14135. var normalizeWhitespaceBefore = function (node, offset) {
  14136. var content = node.data.slice(0, offset);
  14137. var whitespaceCount = content.length - rTrim(content).length;
  14138. normalize$1(node, offset - whitespaceCount, whitespaceCount);
  14139. };
  14140. var mergeTextNodes = function (prevNode, nextNode, normalizeWhitespace, mergeToPrev) {
  14141. if (mergeToPrev === void 0) {
  14142. mergeToPrev = true;
  14143. }
  14144. var whitespaceOffset = rTrim(prevNode.data).length;
  14145. var newNode = mergeToPrev ? prevNode : nextNode;
  14146. var removeNode = mergeToPrev ? nextNode : prevNode;
  14147. if (mergeToPrev) {
  14148. newNode.appendData(removeNode.data);
  14149. } else {
  14150. newNode.insertData(0, removeNode.data);
  14151. }
  14152. remove$7(SugarElement.fromDom(removeNode));
  14153. if (normalizeWhitespace) {
  14154. normalizeWhitespaceAfter(newNode, whitespaceOffset);
  14155. }
  14156. return newNode;
  14157. };
  14158. var needsReposition = function (pos, elm) {
  14159. var container = pos.container();
  14160. var offset = pos.offset();
  14161. return CaretPosition.isTextPosition(pos) === false && container === elm.parentNode && offset > CaretPosition.before(elm).offset();
  14162. };
  14163. var reposition = function (elm, pos) {
  14164. return needsReposition(pos, elm) ? CaretPosition(pos.container(), pos.offset() - 1) : pos;
  14165. };
  14166. var beforeOrStartOf = function (node) {
  14167. return isText$7(node) ? CaretPosition(node, 0) : CaretPosition.before(node);
  14168. };
  14169. var afterOrEndOf = function (node) {
  14170. return isText$7(node) ? CaretPosition(node, node.data.length) : CaretPosition.after(node);
  14171. };
  14172. var getPreviousSiblingCaretPosition = function (elm) {
  14173. if (isCaretCandidate$3(elm.previousSibling)) {
  14174. return Optional.some(afterOrEndOf(elm.previousSibling));
  14175. } else {
  14176. return elm.previousSibling ? lastPositionIn(elm.previousSibling) : Optional.none();
  14177. }
  14178. };
  14179. var getNextSiblingCaretPosition = function (elm) {
  14180. if (isCaretCandidate$3(elm.nextSibling)) {
  14181. return Optional.some(beforeOrStartOf(elm.nextSibling));
  14182. } else {
  14183. return elm.nextSibling ? firstPositionIn(elm.nextSibling) : Optional.none();
  14184. }
  14185. };
  14186. var findCaretPositionBackwardsFromElm = function (rootElement, elm) {
  14187. var startPosition = CaretPosition.before(elm.previousSibling ? elm.previousSibling : elm.parentNode);
  14188. return prevPosition(rootElement, startPosition).fold(function () {
  14189. return nextPosition(rootElement, CaretPosition.after(elm));
  14190. }, Optional.some);
  14191. };
  14192. var findCaretPositionForwardsFromElm = function (rootElement, elm) {
  14193. return nextPosition(rootElement, CaretPosition.after(elm)).fold(function () {
  14194. return prevPosition(rootElement, CaretPosition.before(elm));
  14195. }, Optional.some);
  14196. };
  14197. var findCaretPositionBackwards = function (rootElement, elm) {
  14198. return getPreviousSiblingCaretPosition(elm).orThunk(function () {
  14199. return getNextSiblingCaretPosition(elm);
  14200. }).orThunk(function () {
  14201. return findCaretPositionBackwardsFromElm(rootElement, elm);
  14202. });
  14203. };
  14204. var findCaretPositionForward = function (rootElement, elm) {
  14205. return getNextSiblingCaretPosition(elm).orThunk(function () {
  14206. return getPreviousSiblingCaretPosition(elm);
  14207. }).orThunk(function () {
  14208. return findCaretPositionForwardsFromElm(rootElement, elm);
  14209. });
  14210. };
  14211. var findCaretPosition = function (forward, rootElement, elm) {
  14212. return forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
  14213. };
  14214. var findCaretPosOutsideElmAfterDelete = function (forward, rootElement, elm) {
  14215. return findCaretPosition(forward, rootElement, elm).map(curry(reposition, elm));
  14216. };
  14217. var setSelection$1 = function (editor, forward, pos) {
  14218. pos.fold(function () {
  14219. editor.focus();
  14220. }, function (pos) {
  14221. editor.selection.setRng(pos.toRange(), forward);
  14222. });
  14223. };
  14224. var eqRawNode = function (rawNode) {
  14225. return function (elm) {
  14226. return elm.dom === rawNode;
  14227. };
  14228. };
  14229. var isBlock = function (editor, elm) {
  14230. return elm && has$2(editor.schema.getBlockElements(), name(elm));
  14231. };
  14232. var paddEmptyBlock = function (elm) {
  14233. if (isEmpty$2(elm)) {
  14234. var br = SugarElement.fromHtml('<br data-mce-bogus="1">');
  14235. empty(elm);
  14236. append$1(elm, br);
  14237. return Optional.some(CaretPosition.before(br.dom));
  14238. } else {
  14239. return Optional.none();
  14240. }
  14241. };
  14242. var deleteNormalized = function (elm, afterDeletePosOpt, normalizeWhitespace) {
  14243. var prevTextOpt = prevSibling(elm).filter(isText$8);
  14244. var nextTextOpt = nextSibling(elm).filter(isText$8);
  14245. remove$7(elm);
  14246. return lift3(prevTextOpt, nextTextOpt, afterDeletePosOpt, function (prev, next, pos) {
  14247. var prevNode = prev.dom, nextNode = next.dom;
  14248. var offset = prevNode.data.length;
  14249. mergeTextNodes(prevNode, nextNode, normalizeWhitespace);
  14250. return pos.container() === nextNode ? CaretPosition(prevNode, offset) : pos;
  14251. }).orThunk(function () {
  14252. if (normalizeWhitespace) {
  14253. prevTextOpt.each(function (elm) {
  14254. return normalizeWhitespaceBefore(elm.dom, elm.dom.length);
  14255. });
  14256. nextTextOpt.each(function (elm) {
  14257. return normalizeWhitespaceAfter(elm.dom, 0);
  14258. });
  14259. }
  14260. return afterDeletePosOpt;
  14261. });
  14262. };
  14263. var isInlineElement = function (editor, element) {
  14264. return has$2(editor.schema.getTextInlineElements(), name(element));
  14265. };
  14266. var deleteElement$2 = function (editor, forward, elm, moveCaret) {
  14267. if (moveCaret === void 0) {
  14268. moveCaret = true;
  14269. }
  14270. var afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom);
  14271. var parentBlock = ancestor$3(elm, curry(isBlock, editor), eqRawNode(editor.getBody()));
  14272. var normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos, isInlineElement(editor, elm));
  14273. if (editor.dom.isEmpty(editor.getBody())) {
  14274. editor.setContent('');
  14275. editor.selection.setCursorLocation();
  14276. } else {
  14277. parentBlock.bind(paddEmptyBlock).fold(function () {
  14278. if (moveCaret) {
  14279. setSelection$1(editor, forward, normalizedAfterDeletePos);
  14280. }
  14281. }, function (paddPos) {
  14282. if (moveCaret) {
  14283. setSelection$1(editor, forward, Optional.some(paddPos));
  14284. }
  14285. });
  14286. }
  14287. };
  14288. var isRootFromElement = function (root) {
  14289. return function (cur) {
  14290. return eq(root, cur);
  14291. };
  14292. };
  14293. var getTableCells = function (table) {
  14294. return descendants(table, 'td,th');
  14295. };
  14296. var getTableDetailsFromRange = function (rng, isRoot) {
  14297. var getTable = function (node) {
  14298. return getClosestTable(SugarElement.fromDom(node), isRoot);
  14299. };
  14300. var startTable = getTable(rng.startContainer);
  14301. var endTable = getTable(rng.endContainer);
  14302. var isStartInTable = startTable.isSome();
  14303. var isEndInTable = endTable.isSome();
  14304. var isSameTable = lift2(startTable, endTable, eq).getOr(false);
  14305. var isMultiTable = !isSameTable && isStartInTable && isEndInTable;
  14306. return {
  14307. startTable: startTable,
  14308. endTable: endTable,
  14309. isStartInTable: isStartInTable,
  14310. isEndInTable: isEndInTable,
  14311. isSameTable: isSameTable,
  14312. isMultiTable: isMultiTable
  14313. };
  14314. };
  14315. var tableCellRng = function (start, end) {
  14316. return {
  14317. start: start,
  14318. end: end
  14319. };
  14320. };
  14321. var tableSelection = function (rng, table, cells) {
  14322. return {
  14323. rng: rng,
  14324. table: table,
  14325. cells: cells
  14326. };
  14327. };
  14328. var deleteAction = Adt.generate([
  14329. {
  14330. singleCellTable: [
  14331. 'rng',
  14332. 'cell'
  14333. ]
  14334. },
  14335. { fullTable: ['table'] },
  14336. {
  14337. partialTable: [
  14338. 'cells',
  14339. 'outsideDetails'
  14340. ]
  14341. },
  14342. {
  14343. multiTable: [
  14344. 'startTableCells',
  14345. 'endTableCells',
  14346. 'betweenRng'
  14347. ]
  14348. }
  14349. ]);
  14350. var getClosestCell$1 = function (container, isRoot) {
  14351. return closest$2(SugarElement.fromDom(container), 'td,th', isRoot);
  14352. };
  14353. var isExpandedCellRng = function (cellRng) {
  14354. return !eq(cellRng.start, cellRng.end);
  14355. };
  14356. var getTableFromCellRng = function (cellRng, isRoot) {
  14357. return getClosestTable(cellRng.start, isRoot).bind(function (startParentTable) {
  14358. return getClosestTable(cellRng.end, isRoot).bind(function (endParentTable) {
  14359. return someIf(eq(startParentTable, endParentTable), startParentTable);
  14360. });
  14361. });
  14362. };
  14363. var isSingleCellTable = function (cellRng, isRoot) {
  14364. return !isExpandedCellRng(cellRng) && getTableFromCellRng(cellRng, isRoot).exists(function (table) {
  14365. var rows = table.dom.rows;
  14366. return rows.length === 1 && rows[0].cells.length === 1;
  14367. });
  14368. };
  14369. var getCellRng = function (rng, isRoot) {
  14370. var startCell = getClosestCell$1(rng.startContainer, isRoot);
  14371. var endCell = getClosestCell$1(rng.endContainer, isRoot);
  14372. return lift2(startCell, endCell, tableCellRng);
  14373. };
  14374. var getCellRangeFromStartTable = function (isRoot) {
  14375. return function (startCell) {
  14376. return getClosestTable(startCell, isRoot).bind(function (table) {
  14377. return last$2(getTableCells(table)).map(function (endCell) {
  14378. return tableCellRng(startCell, endCell);
  14379. });
  14380. });
  14381. };
  14382. };
  14383. var getCellRangeFromEndTable = function (isRoot) {
  14384. return function (endCell) {
  14385. return getClosestTable(endCell, isRoot).bind(function (table) {
  14386. return head(getTableCells(table)).map(function (startCell) {
  14387. return tableCellRng(startCell, endCell);
  14388. });
  14389. });
  14390. };
  14391. };
  14392. var getTableSelectionFromCellRng = function (isRoot) {
  14393. return function (cellRng) {
  14394. return getTableFromCellRng(cellRng, isRoot).map(function (table) {
  14395. return tableSelection(cellRng, table, getTableCells(table));
  14396. });
  14397. };
  14398. };
  14399. var getTableSelections = function (cellRng, selectionDetails, rng, isRoot) {
  14400. if (rng.collapsed || !cellRng.forall(isExpandedCellRng)) {
  14401. return Optional.none();
  14402. } else if (selectionDetails.isSameTable) {
  14403. var sameTableSelection = cellRng.bind(getTableSelectionFromCellRng(isRoot));
  14404. return Optional.some({
  14405. start: sameTableSelection,
  14406. end: sameTableSelection
  14407. });
  14408. } else {
  14409. var startCell = getClosestCell$1(rng.startContainer, isRoot);
  14410. var endCell = getClosestCell$1(rng.endContainer, isRoot);
  14411. var startTableSelection = startCell.bind(getCellRangeFromStartTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  14412. var endTableSelection = endCell.bind(getCellRangeFromEndTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  14413. return Optional.some({
  14414. start: startTableSelection,
  14415. end: endTableSelection
  14416. });
  14417. }
  14418. };
  14419. var getCellIndex = function (cells, cell) {
  14420. return findIndex$2(cells, function (x) {
  14421. return eq(x, cell);
  14422. });
  14423. };
  14424. var getSelectedCells = function (tableSelection) {
  14425. return lift2(getCellIndex(tableSelection.cells, tableSelection.rng.start), getCellIndex(tableSelection.cells, tableSelection.rng.end), function (startIndex, endIndex) {
  14426. return tableSelection.cells.slice(startIndex, endIndex + 1);
  14427. });
  14428. };
  14429. var isSingleCellTableContentSelected = function (optCellRng, rng, isRoot) {
  14430. return optCellRng.exists(function (cellRng) {
  14431. return isSingleCellTable(cellRng, isRoot) && hasAllContentsSelected(cellRng.start, rng);
  14432. });
  14433. };
  14434. var unselectCells = function (rng, selectionDetails) {
  14435. var startTable = selectionDetails.startTable, endTable = selectionDetails.endTable;
  14436. var otherContentRng = rng.cloneRange();
  14437. startTable.each(function (table) {
  14438. return otherContentRng.setStartAfter(table.dom);
  14439. });
  14440. endTable.each(function (table) {
  14441. return otherContentRng.setEndBefore(table.dom);
  14442. });
  14443. return otherContentRng;
  14444. };
  14445. var handleSingleTable = function (cellRng, selectionDetails, rng, isRoot) {
  14446. return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function (_a) {
  14447. var start = _a.start, end = _a.end;
  14448. return start.or(end);
  14449. }).bind(function (tableSelection) {
  14450. var isSameTable = selectionDetails.isSameTable;
  14451. var selectedCells = getSelectedCells(tableSelection).getOr([]);
  14452. if (isSameTable && tableSelection.cells.length === selectedCells.length) {
  14453. return Optional.some(deleteAction.fullTable(tableSelection.table));
  14454. } else if (selectedCells.length > 0) {
  14455. if (isSameTable) {
  14456. return Optional.some(deleteAction.partialTable(selectedCells, Optional.none()));
  14457. } else {
  14458. var otherContentRng = unselectCells(rng, selectionDetails);
  14459. return Optional.some(deleteAction.partialTable(selectedCells, Optional.some(__assign(__assign({}, selectionDetails), { rng: otherContentRng }))));
  14460. }
  14461. } else {
  14462. return Optional.none();
  14463. }
  14464. });
  14465. };
  14466. var handleMultiTable = function (cellRng, selectionDetails, rng, isRoot) {
  14467. return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function (_a) {
  14468. var start = _a.start, end = _a.end;
  14469. var startTableSelectedCells = start.bind(getSelectedCells).getOr([]);
  14470. var endTableSelectedCells = end.bind(getSelectedCells).getOr([]);
  14471. if (startTableSelectedCells.length > 0 && endTableSelectedCells.length > 0) {
  14472. var otherContentRng = unselectCells(rng, selectionDetails);
  14473. return Optional.some(deleteAction.multiTable(startTableSelectedCells, endTableSelectedCells, otherContentRng));
  14474. } else {
  14475. return Optional.none();
  14476. }
  14477. });
  14478. };
  14479. var getActionFromRange = function (root, rng) {
  14480. var isRoot = isRootFromElement(root);
  14481. var optCellRng = getCellRng(rng, isRoot);
  14482. var selectionDetails = getTableDetailsFromRange(rng, isRoot);
  14483. if (isSingleCellTableContentSelected(optCellRng, rng, isRoot)) {
  14484. return optCellRng.map(function (cellRng) {
  14485. return deleteAction.singleCellTable(rng, cellRng.start);
  14486. });
  14487. } else if (selectionDetails.isMultiTable) {
  14488. return handleMultiTable(optCellRng, selectionDetails, rng, isRoot);
  14489. } else {
  14490. return handleSingleTable(optCellRng, selectionDetails, rng, isRoot);
  14491. }
  14492. };
  14493. var freefallRtl = function (root) {
  14494. var child = isComment$1(root) ? prevSibling(root) : lastChild(root);
  14495. return child.bind(freefallRtl).orThunk(function () {
  14496. return Optional.some(root);
  14497. });
  14498. };
  14499. var cleanCells = function (cells) {
  14500. return each$k(cells, function (cell) {
  14501. remove$6(cell, 'contenteditable');
  14502. fillWithPaddingBr(cell);
  14503. });
  14504. };
  14505. var getOutsideBlock = function (editor, container) {
  14506. return Optional.from(editor.dom.getParent(container, editor.dom.isBlock)).map(SugarElement.fromDom);
  14507. };
  14508. var handleEmptyBlock = function (editor, startInTable, emptyBlock) {
  14509. emptyBlock.each(function (block) {
  14510. if (startInTable) {
  14511. remove$7(block);
  14512. } else {
  14513. fillWithPaddingBr(block);
  14514. editor.selection.setCursorLocation(block.dom, 0);
  14515. }
  14516. });
  14517. };
  14518. var deleteContentInsideCell = function (editor, cell, rng, isFirstCellInSelection) {
  14519. var insideTableRng = rng.cloneRange();
  14520. if (isFirstCellInSelection) {
  14521. insideTableRng.setStart(rng.startContainer, rng.startOffset);
  14522. insideTableRng.setEndAfter(cell.dom.lastChild);
  14523. } else {
  14524. insideTableRng.setStartBefore(cell.dom.firstChild);
  14525. insideTableRng.setEnd(rng.endContainer, rng.endOffset);
  14526. }
  14527. deleteCellContents(editor, insideTableRng, cell, false);
  14528. };
  14529. var collapseAndRestoreCellSelection = function (editor) {
  14530. var selectedCells = getCellsFromEditor(editor);
  14531. var selectedNode = SugarElement.fromDom(editor.selection.getNode());
  14532. if (isTableCell$5(selectedNode.dom) && isEmpty$2(selectedNode)) {
  14533. editor.selection.setCursorLocation(selectedNode.dom, 0);
  14534. } else {
  14535. editor.selection.collapse(true);
  14536. }
  14537. if (selectedCells.length > 1 && exists(selectedCells, function (cell) {
  14538. return eq(cell, selectedNode);
  14539. })) {
  14540. set$1(selectedNode, 'data-mce-selected', '1');
  14541. }
  14542. };
  14543. var emptySingleTableCells = function (editor, cells, outsideDetails) {
  14544. var editorRng = editor.selection.getRng();
  14545. var cellsToClean = outsideDetails.bind(function (_a) {
  14546. var rng = _a.rng, isStartInTable = _a.isStartInTable;
  14547. var outsideBlock = getOutsideBlock(editor, isStartInTable ? rng.endContainer : rng.startContainer);
  14548. rng.deleteContents();
  14549. handleEmptyBlock(editor, isStartInTable, outsideBlock.filter(isEmpty$2));
  14550. var endPointCell = isStartInTable ? cells[0] : cells[cells.length - 1];
  14551. deleteContentInsideCell(editor, endPointCell, editorRng, isStartInTable);
  14552. if (!isEmpty$2(endPointCell)) {
  14553. return Optional.some(isStartInTable ? cells.slice(1) : cells.slice(0, -1));
  14554. } else {
  14555. return Optional.none();
  14556. }
  14557. }).getOr(cells);
  14558. cleanCells(cellsToClean);
  14559. collapseAndRestoreCellSelection(editor);
  14560. return true;
  14561. };
  14562. var emptyMultiTableCells = function (editor, startTableCells, endTableCells, betweenRng) {
  14563. var rng = editor.selection.getRng();
  14564. var startCell = startTableCells[0];
  14565. var endCell = endTableCells[endTableCells.length - 1];
  14566. deleteContentInsideCell(editor, startCell, rng, true);
  14567. deleteContentInsideCell(editor, endCell, rng, false);
  14568. var startTableCellsToClean = isEmpty$2(startCell) ? startTableCells : startTableCells.slice(1);
  14569. var endTableCellsToClean = isEmpty$2(endCell) ? endTableCells : endTableCells.slice(0, -1);
  14570. cleanCells(startTableCellsToClean.concat(endTableCellsToClean));
  14571. betweenRng.deleteContents();
  14572. collapseAndRestoreCellSelection(editor);
  14573. return true;
  14574. };
  14575. var deleteCellContents = function (editor, rng, cell, moveSelection) {
  14576. if (moveSelection === void 0) {
  14577. moveSelection = true;
  14578. }
  14579. rng.deleteContents();
  14580. var lastNode = freefallRtl(cell).getOr(cell);
  14581. var lastBlock = SugarElement.fromDom(editor.dom.getParent(lastNode.dom, editor.dom.isBlock));
  14582. if (isEmpty$2(lastBlock)) {
  14583. fillWithPaddingBr(lastBlock);
  14584. if (moveSelection) {
  14585. editor.selection.setCursorLocation(lastBlock.dom, 0);
  14586. }
  14587. }
  14588. if (!eq(cell, lastBlock)) {
  14589. var additionalCleanupNodes = is$1(parent(lastBlock), cell) ? [] : siblings(lastBlock);
  14590. each$k(additionalCleanupNodes.concat(children(cell)), function (node) {
  14591. if (!eq(node, lastBlock) && !contains$1(node, lastBlock) && isEmpty$2(node)) {
  14592. remove$7(node);
  14593. }
  14594. });
  14595. }
  14596. return true;
  14597. };
  14598. var deleteTableElement = function (editor, table) {
  14599. deleteElement$2(editor, false, table);
  14600. return true;
  14601. };
  14602. var deleteCellRange = function (editor, rootElm, rng) {
  14603. return getActionFromRange(rootElm, rng).map(function (action) {
  14604. return action.fold(curry(deleteCellContents, editor), curry(deleteTableElement, editor), curry(emptySingleTableCells, editor), curry(emptyMultiTableCells, editor));
  14605. });
  14606. };
  14607. var deleteCaptionRange = function (editor, caption) {
  14608. return emptyElement(editor, caption);
  14609. };
  14610. var deleteTableRange = function (editor, rootElm, rng, startElm) {
  14611. return getParentCaption(rootElm, startElm).fold(function () {
  14612. return deleteCellRange(editor, rootElm, rng);
  14613. }, function (caption) {
  14614. return deleteCaptionRange(editor, caption);
  14615. }).getOr(false);
  14616. };
  14617. var deleteRange$2 = function (editor, startElm, selectedCells) {
  14618. var rootNode = SugarElement.fromDom(editor.getBody());
  14619. var rng = editor.selection.getRng();
  14620. return selectedCells.length !== 0 ? emptySingleTableCells(editor, selectedCells, Optional.none()) : deleteTableRange(editor, rootNode, rng, startElm);
  14621. };
  14622. var getParentCell = function (rootElm, elm) {
  14623. return find$3(parentsAndSelf(elm, rootElm), isTableCell$4);
  14624. };
  14625. var getParentCaption = function (rootElm, elm) {
  14626. return find$3(parentsAndSelf(elm, rootElm), isTag('caption'));
  14627. };
  14628. var deleteBetweenCells = function (editor, rootElm, forward, fromCell, from) {
  14629. return navigate(forward, editor.getBody(), from).bind(function (to) {
  14630. return getParentCell(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCell) {
  14631. return eq(toCell, fromCell) === false;
  14632. });
  14633. });
  14634. };
  14635. var emptyElement = function (editor, elm) {
  14636. fillWithPaddingBr(elm);
  14637. editor.selection.setCursorLocation(elm.dom, 0);
  14638. return Optional.some(true);
  14639. };
  14640. var isDeleteOfLastCharPos = function (fromCaption, forward, from, to) {
  14641. return firstPositionIn(fromCaption.dom).bind(function (first) {
  14642. return lastPositionIn(fromCaption.dom).map(function (last) {
  14643. return forward ? from.isEqual(first) && to.isEqual(last) : from.isEqual(last) && to.isEqual(first);
  14644. });
  14645. }).getOr(true);
  14646. };
  14647. var emptyCaretCaption = function (editor, elm) {
  14648. return emptyElement(editor, elm);
  14649. };
  14650. var validateCaretCaption = function (rootElm, fromCaption, to) {
  14651. return getParentCaption(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCaption) {
  14652. return eq(toCaption, fromCaption) === false;
  14653. });
  14654. };
  14655. var deleteCaretInsideCaption = function (editor, rootElm, forward, fromCaption, from) {
  14656. return navigate(forward, editor.getBody(), from).bind(function (to) {
  14657. return isDeleteOfLastCharPos(fromCaption, forward, from, to) ? emptyCaretCaption(editor, fromCaption) : validateCaretCaption(rootElm, fromCaption, to);
  14658. }).or(Optional.some(true));
  14659. };
  14660. var deleteCaretCells = function (editor, forward, rootElm, startElm) {
  14661. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  14662. return getParentCell(rootElm, startElm).bind(function (fromCell) {
  14663. return isEmpty$2(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from);
  14664. }).getOr(false);
  14665. };
  14666. var deleteCaretCaption = function (editor, forward, rootElm, fromCaption) {
  14667. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  14668. return isEmpty$2(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from);
  14669. };
  14670. var isNearTable = function (forward, pos) {
  14671. return forward ? isBeforeTable(pos) : isAfterTable(pos);
  14672. };
  14673. var isBeforeOrAfterTable = function (editor, forward) {
  14674. var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  14675. return isNearTable(forward, fromPos) || fromPosition(forward, editor.getBody(), fromPos).exists(function (pos) {
  14676. return isNearTable(forward, pos);
  14677. });
  14678. };
  14679. var deleteCaret$3 = function (editor, forward, startElm) {
  14680. var rootElm = SugarElement.fromDom(editor.getBody());
  14681. return getParentCaption(rootElm, startElm).fold(function () {
  14682. return deleteCaretCells(editor, forward, rootElm, startElm) || isBeforeOrAfterTable(editor, forward);
  14683. }, function (fromCaption) {
  14684. return deleteCaretCaption(editor, forward, rootElm, fromCaption).getOr(false);
  14685. });
  14686. };
  14687. var backspaceDelete$9 = function (editor, forward) {
  14688. var startElm = SugarElement.fromDom(editor.selection.getStart(true));
  14689. var cells = getCellsFromEditor(editor);
  14690. return editor.selection.isCollapsed() && cells.length === 0 ? deleteCaret$3(editor, forward, startElm) : deleteRange$2(editor, startElm, cells);
  14691. };
  14692. var createRange = function (sc, so, ec, eo) {
  14693. var rng = document.createRange();
  14694. rng.setStart(sc, so);
  14695. rng.setEnd(ec, eo);
  14696. return rng;
  14697. };
  14698. var normalizeBlockSelectionRange = function (rng) {
  14699. var startPos = CaretPosition.fromRangeStart(rng);
  14700. var endPos = CaretPosition.fromRangeEnd(rng);
  14701. var rootNode = rng.commonAncestorContainer;
  14702. return fromPosition(false, rootNode, endPos).map(function (newEndPos) {
  14703. if (!isInSameBlock(startPos, endPos, rootNode) && isInSameBlock(startPos, newEndPos, rootNode)) {
  14704. return createRange(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
  14705. } else {
  14706. return rng;
  14707. }
  14708. }).getOr(rng);
  14709. };
  14710. var normalize = function (rng) {
  14711. return rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
  14712. };
  14713. var hasOnlyOneChild$1 = function (node) {
  14714. return node.firstChild && node.firstChild === node.lastChild;
  14715. };
  14716. var isPaddingNode = function (node) {
  14717. return node.name === 'br' || node.value === nbsp;
  14718. };
  14719. var isPaddedEmptyBlock = function (schema, node) {
  14720. var blockElements = schema.getBlockElements();
  14721. return blockElements[node.name] && hasOnlyOneChild$1(node) && isPaddingNode(node.firstChild);
  14722. };
  14723. var isEmptyFragmentElement = function (schema, node) {
  14724. var nonEmptyElements = schema.getNonEmptyElements();
  14725. return node && (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
  14726. };
  14727. var isListFragment = function (schema, fragment) {
  14728. var firstChild = fragment.firstChild;
  14729. var lastChild = fragment.lastChild;
  14730. if (firstChild && firstChild.name === 'meta') {
  14731. firstChild = firstChild.next;
  14732. }
  14733. if (lastChild && lastChild.attr('id') === 'mce_marker') {
  14734. lastChild = lastChild.prev;
  14735. }
  14736. if (isEmptyFragmentElement(schema, lastChild)) {
  14737. lastChild = lastChild.prev;
  14738. }
  14739. if (!firstChild || firstChild !== lastChild) {
  14740. return false;
  14741. }
  14742. return firstChild.name === 'ul' || firstChild.name === 'ol';
  14743. };
  14744. var cleanupDomFragment = function (domFragment) {
  14745. var firstChild = domFragment.firstChild;
  14746. var lastChild = domFragment.lastChild;
  14747. if (firstChild && firstChild.nodeName === 'META') {
  14748. firstChild.parentNode.removeChild(firstChild);
  14749. }
  14750. if (lastChild && lastChild.id === 'mce_marker') {
  14751. lastChild.parentNode.removeChild(lastChild);
  14752. }
  14753. return domFragment;
  14754. };
  14755. var toDomFragment = function (dom, serializer, fragment) {
  14756. var html = serializer.serialize(fragment);
  14757. var domFragment = dom.createFragment(html);
  14758. return cleanupDomFragment(domFragment);
  14759. };
  14760. var listItems = function (elm) {
  14761. return filter$4(elm.childNodes, function (child) {
  14762. return child.nodeName === 'LI';
  14763. });
  14764. };
  14765. var isPadding = function (node) {
  14766. return node.data === nbsp || isBr$5(node);
  14767. };
  14768. var isListItemPadded = function (node) {
  14769. return node && node.firstChild && node.firstChild === node.lastChild && isPadding(node.firstChild);
  14770. };
  14771. var isEmptyOrPadded = function (elm) {
  14772. return !elm.firstChild || isListItemPadded(elm);
  14773. };
  14774. var trimListItems = function (elms) {
  14775. return elms.length > 0 && isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
  14776. };
  14777. var getParentLi = function (dom, node) {
  14778. var parentBlock = dom.getParent(node, dom.isBlock);
  14779. return parentBlock && parentBlock.nodeName === 'LI' ? parentBlock : null;
  14780. };
  14781. var isParentBlockLi = function (dom, node) {
  14782. return !!getParentLi(dom, node);
  14783. };
  14784. var getSplit = function (parentNode, rng) {
  14785. var beforeRng = rng.cloneRange();
  14786. var afterRng = rng.cloneRange();
  14787. beforeRng.setStartBefore(parentNode);
  14788. afterRng.setEndAfter(parentNode);
  14789. return [
  14790. beforeRng.cloneContents(),
  14791. afterRng.cloneContents()
  14792. ];
  14793. };
  14794. var findFirstIn = function (node, rootNode) {
  14795. var caretPos = CaretPosition.before(node);
  14796. var caretWalker = CaretWalker(rootNode);
  14797. var newCaretPos = caretWalker.next(caretPos);
  14798. return newCaretPos ? newCaretPos.toRange() : null;
  14799. };
  14800. var findLastOf = function (node, rootNode) {
  14801. var caretPos = CaretPosition.after(node);
  14802. var caretWalker = CaretWalker(rootNode);
  14803. var newCaretPos = caretWalker.prev(caretPos);
  14804. return newCaretPos ? newCaretPos.toRange() : null;
  14805. };
  14806. var insertMiddle = function (target, elms, rootNode, rng) {
  14807. var parts = getSplit(target, rng);
  14808. var parentElm = target.parentNode;
  14809. parentElm.insertBefore(parts[0], target);
  14810. Tools.each(elms, function (li) {
  14811. parentElm.insertBefore(li, target);
  14812. });
  14813. parentElm.insertBefore(parts[1], target);
  14814. parentElm.removeChild(target);
  14815. return findLastOf(elms[elms.length - 1], rootNode);
  14816. };
  14817. var insertBefore$1 = function (target, elms, rootNode) {
  14818. var parentElm = target.parentNode;
  14819. Tools.each(elms, function (elm) {
  14820. parentElm.insertBefore(elm, target);
  14821. });
  14822. return findFirstIn(target, rootNode);
  14823. };
  14824. var insertAfter$1 = function (target, elms, rootNode, dom) {
  14825. dom.insertAfter(elms.reverse(), target);
  14826. return findLastOf(elms[0], rootNode);
  14827. };
  14828. var insertAtCaret$1 = function (serializer, dom, rng, fragment) {
  14829. var domFragment = toDomFragment(dom, serializer, fragment);
  14830. var liTarget = getParentLi(dom, rng.startContainer);
  14831. var liElms = trimListItems(listItems(domFragment.firstChild));
  14832. var BEGINNING = 1, END = 2;
  14833. var rootNode = dom.getRoot();
  14834. var isAt = function (location) {
  14835. var caretPos = CaretPosition.fromRangeStart(rng);
  14836. var caretWalker = CaretWalker(dom.getRoot());
  14837. var newPos = location === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
  14838. return newPos ? getParentLi(dom, newPos.getNode()) !== liTarget : true;
  14839. };
  14840. if (isAt(BEGINNING)) {
  14841. return insertBefore$1(liTarget, liElms, rootNode);
  14842. } else if (isAt(END)) {
  14843. return insertAfter$1(liTarget, liElms, rootNode, dom);
  14844. }
  14845. return insertMiddle(liTarget, liElms, rootNode, rng);
  14846. };
  14847. var trimOrPadLeftRight = function (dom, rng, html) {
  14848. var root = SugarElement.fromDom(dom.getRoot());
  14849. if (needsToBeNbspLeft(root, CaretPosition.fromRangeStart(rng))) {
  14850. html = html.replace(/^ /, '&nbsp;');
  14851. } else {
  14852. html = html.replace(/^&nbsp;/, ' ');
  14853. }
  14854. if (needsToBeNbspRight(root, CaretPosition.fromRangeEnd(rng))) {
  14855. html = html.replace(/(&nbsp;| )(<br( \/)>)?$/, '&nbsp;');
  14856. } else {
  14857. html = html.replace(/&nbsp;(<br( \/)?>)?$/, ' ');
  14858. }
  14859. return html;
  14860. };
  14861. var isTableCell$1 = isTableCell$5;
  14862. var isTableCellContentSelected = function (dom, rng, cell) {
  14863. if (cell !== null) {
  14864. var endCell = dom.getParent(rng.endContainer, isTableCell$1);
  14865. return cell === endCell && hasAllContentsSelected(SugarElement.fromDom(cell), rng);
  14866. } else {
  14867. return false;
  14868. }
  14869. };
  14870. var validInsertion = function (editor, value, parentNode) {
  14871. if (parentNode.getAttribute('data-mce-bogus') === 'all') {
  14872. parentNode.parentNode.insertBefore(editor.dom.createFragment(value), parentNode);
  14873. } else {
  14874. var node = parentNode.firstChild;
  14875. var node2 = parentNode.lastChild;
  14876. if (!node || node === node2 && node.nodeName === 'BR') {
  14877. editor.dom.setHTML(parentNode, value);
  14878. } else {
  14879. editor.selection.setContent(value);
  14880. }
  14881. }
  14882. };
  14883. var trimBrsFromTableCell = function (dom, elm) {
  14884. Optional.from(dom.getParent(elm, 'td,th')).map(SugarElement.fromDom).each(trimBlockTrailingBr);
  14885. };
  14886. var reduceInlineTextElements = function (editor, merge) {
  14887. var textInlineElements = editor.schema.getTextInlineElements();
  14888. var dom = editor.dom;
  14889. if (merge) {
  14890. var root_1 = editor.getBody();
  14891. var elementUtils_1 = ElementUtils(dom);
  14892. Tools.each(dom.select('*[data-mce-fragment]'), function (node) {
  14893. var isInline = isNonNullable(textInlineElements[node.nodeName.toLowerCase()]);
  14894. if (isInline && hasInheritableStyles(dom, node)) {
  14895. for (var parentNode = node.parentNode; isNonNullable(parentNode) && parentNode !== root_1; parentNode = parentNode.parentNode) {
  14896. var styleConflict = hasStyleConflict(dom, node, parentNode);
  14897. if (styleConflict) {
  14898. break;
  14899. }
  14900. if (elementUtils_1.compare(parentNode, node)) {
  14901. dom.remove(node, true);
  14902. break;
  14903. }
  14904. }
  14905. }
  14906. });
  14907. }
  14908. };
  14909. var markFragmentElements = function (fragment) {
  14910. var node = fragment;
  14911. while (node = node.walk()) {
  14912. if (node.type === 1) {
  14913. node.attr('data-mce-fragment', '1');
  14914. }
  14915. }
  14916. };
  14917. var unmarkFragmentElements = function (elm) {
  14918. Tools.each(elm.getElementsByTagName('*'), function (elm) {
  14919. elm.removeAttribute('data-mce-fragment');
  14920. });
  14921. };
  14922. var isPartOfFragment = function (node) {
  14923. return !!node.getAttribute('data-mce-fragment');
  14924. };
  14925. var canHaveChildren = function (editor, node) {
  14926. return node && !editor.schema.getShortEndedElements()[node.nodeName];
  14927. };
  14928. var moveSelectionToMarker = function (editor, marker) {
  14929. var nextRng;
  14930. var dom = editor.dom;
  14931. var selection = editor.selection;
  14932. if (!marker) {
  14933. return;
  14934. }
  14935. selection.scrollIntoView(marker);
  14936. var parentEditableElm = getContentEditableRoot$1(editor.getBody(), marker);
  14937. if (dom.getContentEditable(parentEditableElm) === 'false') {
  14938. dom.remove(marker);
  14939. selection.select(parentEditableElm);
  14940. return;
  14941. }
  14942. var rng = dom.createRng();
  14943. var node = marker.previousSibling;
  14944. if (isText$7(node)) {
  14945. rng.setStart(node, node.nodeValue.length);
  14946. if (!Env.ie) {
  14947. var node2 = marker.nextSibling;
  14948. if (isText$7(node2)) {
  14949. node.appendData(node2.data);
  14950. node2.parentNode.removeChild(node2);
  14951. }
  14952. }
  14953. } else {
  14954. rng.setStartBefore(marker);
  14955. rng.setEndBefore(marker);
  14956. }
  14957. var findNextCaretRng = function (rng) {
  14958. var caretPos = CaretPosition.fromRangeStart(rng);
  14959. var caretWalker = CaretWalker(editor.getBody());
  14960. caretPos = caretWalker.next(caretPos);
  14961. if (caretPos) {
  14962. return caretPos.toRange();
  14963. }
  14964. };
  14965. var parentBlock = dom.getParent(marker, dom.isBlock);
  14966. dom.remove(marker);
  14967. if (parentBlock && dom.isEmpty(parentBlock)) {
  14968. editor.$(parentBlock).empty();
  14969. rng.setStart(parentBlock, 0);
  14970. rng.setEnd(parentBlock, 0);
  14971. if (!isTableCell$1(parentBlock) && !isPartOfFragment(parentBlock) && (nextRng = findNextCaretRng(rng))) {
  14972. rng = nextRng;
  14973. dom.remove(parentBlock);
  14974. } else {
  14975. dom.add(parentBlock, dom.create('br', { 'data-mce-bogus': '1' }));
  14976. }
  14977. }
  14978. selection.setRng(rng);
  14979. };
  14980. var deleteSelectedContent = function (editor) {
  14981. var dom = editor.dom;
  14982. var rng = normalize(editor.selection.getRng());
  14983. editor.selection.setRng(rng);
  14984. var startCell = dom.getParent(rng.startContainer, isTableCell$1);
  14985. if (isTableCellContentSelected(dom, rng, startCell)) {
  14986. deleteCellContents(editor, rng, SugarElement.fromDom(startCell));
  14987. } else {
  14988. editor.getDoc().execCommand('Delete', false, null);
  14989. }
  14990. };
  14991. var insertHtmlAtCaret = function (editor, value, details) {
  14992. var parentNode;
  14993. var rng, node;
  14994. var selection = editor.selection;
  14995. var dom = editor.dom;
  14996. if (/^ | $/.test(value)) {
  14997. value = trimOrPadLeftRight(dom, selection.getRng(), value);
  14998. }
  14999. var parser = editor.parser;
  15000. var merge = details.merge;
  15001. var serializer = HtmlSerializer({ validate: shouldValidate(editor) }, editor.schema);
  15002. var bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>';
  15003. var args = editor.fire('BeforeSetContent', {
  15004. content: value,
  15005. format: 'html',
  15006. selection: true,
  15007. paste: details.paste
  15008. });
  15009. if (args.isDefaultPrevented()) {
  15010. editor.fire('SetContent', {
  15011. content: args.content,
  15012. format: 'html',
  15013. selection: true,
  15014. paste: details.paste
  15015. });
  15016. return;
  15017. }
  15018. value = args.content;
  15019. if (value.indexOf('{$caret}') === -1) {
  15020. value += '{$caret}';
  15021. }
  15022. value = value.replace(/\{\$caret\}/, bookmarkHtml);
  15023. rng = selection.getRng();
  15024. var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
  15025. var body = editor.getBody();
  15026. if (caretElement === body && selection.isCollapsed()) {
  15027. if (dom.isBlock(body.firstChild) && canHaveChildren(editor, body.firstChild) && dom.isEmpty(body.firstChild)) {
  15028. rng = dom.createRng();
  15029. rng.setStart(body.firstChild, 0);
  15030. rng.setEnd(body.firstChild, 0);
  15031. selection.setRng(rng);
  15032. }
  15033. }
  15034. if (!selection.isCollapsed()) {
  15035. deleteSelectedContent(editor);
  15036. }
  15037. parentNode = selection.getNode();
  15038. var parserArgs = {
  15039. context: parentNode.nodeName.toLowerCase(),
  15040. data: details.data,
  15041. insert: true
  15042. };
  15043. var fragment = parser.parse(value, parserArgs);
  15044. if (details.paste === true && isListFragment(editor.schema, fragment) && isParentBlockLi(dom, parentNode)) {
  15045. rng = insertAtCaret$1(serializer, dom, selection.getRng(), fragment);
  15046. selection.setRng(rng);
  15047. editor.fire('SetContent', args);
  15048. return;
  15049. }
  15050. markFragmentElements(fragment);
  15051. node = fragment.lastChild;
  15052. if (node.attr('id') === 'mce_marker') {
  15053. var marker = node;
  15054. for (node = node.prev; node; node = node.walk(true)) {
  15055. if (node.type === 3 || !dom.isBlock(node.name)) {
  15056. if (editor.schema.isValidChild(node.parent.name, 'span')) {
  15057. node.parent.insert(marker, node, node.name === 'br');
  15058. }
  15059. break;
  15060. }
  15061. }
  15062. }
  15063. editor._selectionOverrides.showBlockCaretContainer(parentNode);
  15064. if (!parserArgs.invalid) {
  15065. value = serializer.serialize(fragment);
  15066. validInsertion(editor, value, parentNode);
  15067. } else {
  15068. editor.selection.setContent(bookmarkHtml);
  15069. parentNode = selection.getNode();
  15070. var rootNode = editor.getBody();
  15071. if (parentNode.nodeType === 9) {
  15072. parentNode = node = rootNode;
  15073. } else {
  15074. node = parentNode;
  15075. }
  15076. while (node !== rootNode) {
  15077. parentNode = node;
  15078. node = node.parentNode;
  15079. }
  15080. value = parentNode === rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
  15081. value = serializer.serialize(parser.parse(value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function () {
  15082. return serializer.serialize(fragment);
  15083. })));
  15084. if (parentNode === rootNode) {
  15085. dom.setHTML(rootNode, value);
  15086. } else {
  15087. dom.setOuterHTML(parentNode, value);
  15088. }
  15089. }
  15090. reduceInlineTextElements(editor, merge);
  15091. moveSelectionToMarker(editor, dom.get('mce_marker'));
  15092. unmarkFragmentElements(editor.getBody());
  15093. trimBrsFromTableCell(dom, selection.getStart());
  15094. editor.fire('SetContent', args);
  15095. editor.addVisual();
  15096. };
  15097. var traverse = function (node, fn) {
  15098. fn(node);
  15099. if (node.firstChild) {
  15100. traverse(node.firstChild, fn);
  15101. }
  15102. if (node.next) {
  15103. traverse(node.next, fn);
  15104. }
  15105. };
  15106. var findMatchingNodes = function (nodeFilters, attributeFilters, node) {
  15107. var nodeMatches = {};
  15108. var attrMatches = {};
  15109. var matches = [];
  15110. if (node.firstChild) {
  15111. traverse(node.firstChild, function (node) {
  15112. each$k(nodeFilters, function (filter) {
  15113. if (filter.name === node.name) {
  15114. if (nodeMatches[filter.name]) {
  15115. nodeMatches[filter.name].nodes.push(node);
  15116. } else {
  15117. nodeMatches[filter.name] = {
  15118. filter: filter,
  15119. nodes: [node]
  15120. };
  15121. }
  15122. }
  15123. });
  15124. each$k(attributeFilters, function (filter) {
  15125. if (typeof node.attr(filter.name) === 'string') {
  15126. if (attrMatches[filter.name]) {
  15127. attrMatches[filter.name].nodes.push(node);
  15128. } else {
  15129. attrMatches[filter.name] = {
  15130. filter: filter,
  15131. nodes: [node]
  15132. };
  15133. }
  15134. }
  15135. });
  15136. });
  15137. }
  15138. for (var name_1 in nodeMatches) {
  15139. if (has$2(nodeMatches, name_1)) {
  15140. matches.push(nodeMatches[name_1]);
  15141. }
  15142. }
  15143. for (var name_2 in attrMatches) {
  15144. if (has$2(attrMatches, name_2)) {
  15145. matches.push(attrMatches[name_2]);
  15146. }
  15147. }
  15148. return matches;
  15149. };
  15150. var filter$1 = function (nodeFilters, attributeFilters, node) {
  15151. var matches = findMatchingNodes(nodeFilters, attributeFilters, node);
  15152. each$k(matches, function (match) {
  15153. each$k(match.filter.callbacks, function (callback) {
  15154. callback(match.nodes, match.filter.name, {});
  15155. });
  15156. });
  15157. };
  15158. var defaultFormat$1 = 'html';
  15159. var isTreeNode = function (content) {
  15160. return content instanceof AstNode;
  15161. };
  15162. var moveSelection = function (editor) {
  15163. if (hasFocus(editor)) {
  15164. firstPositionIn(editor.getBody()).each(function (pos) {
  15165. var node = pos.getNode();
  15166. var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  15167. editor.selection.setRng(caretPos.toRange());
  15168. });
  15169. }
  15170. };
  15171. var setEditorHtml = function (editor, html, noSelection) {
  15172. editor.dom.setHTML(editor.getBody(), html);
  15173. if (noSelection !== true) {
  15174. moveSelection(editor);
  15175. }
  15176. };
  15177. var setContentString = function (editor, body, content, args) {
  15178. if (content.length === 0 || /^\s+$/.test(content)) {
  15179. var padd = '<br data-mce-bogus="1">';
  15180. if (body.nodeName === 'TABLE') {
  15181. content = '<tr><td>' + padd + '</td></tr>';
  15182. } else if (/^(UL|OL)$/.test(body.nodeName)) {
  15183. content = '<li>' + padd + '</li>';
  15184. }
  15185. var forcedRootBlockName = getForcedRootBlock(editor);
  15186. if (forcedRootBlockName && editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
  15187. content = padd;
  15188. content = editor.dom.createHTML(forcedRootBlockName, getForcedRootBlockAttrs(editor), content);
  15189. } else if (!content) {
  15190. content = '<br data-mce-bogus="1">';
  15191. }
  15192. setEditorHtml(editor, content, args.no_selection);
  15193. editor.fire('SetContent', args);
  15194. } else {
  15195. if (args.format !== 'raw') {
  15196. content = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(editor.parser.parse(content, {
  15197. isRootContent: true,
  15198. insert: true
  15199. }));
  15200. }
  15201. args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? content : Tools.trim(content);
  15202. setEditorHtml(editor, args.content, args.no_selection);
  15203. if (!args.no_events) {
  15204. editor.fire('SetContent', args);
  15205. }
  15206. }
  15207. return args.content;
  15208. };
  15209. var setContentTree = function (editor, body, content, args) {
  15210. filter$1(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
  15211. var html = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(content);
  15212. args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? html : Tools.trim(html);
  15213. setEditorHtml(editor, args.content, args.no_selection);
  15214. if (!args.no_events) {
  15215. editor.fire('SetContent', args);
  15216. }
  15217. return content;
  15218. };
  15219. var setupArgs$2 = function (args, content) {
  15220. return __assign(__assign({ format: defaultFormat$1 }, args), {
  15221. set: true,
  15222. content: isTreeNode(content) ? '' : content
  15223. });
  15224. };
  15225. var setContentInternal = function (editor, content, args) {
  15226. var defaultedArgs = setupArgs$2(args, content);
  15227. var updatedArgs = args.no_events ? defaultedArgs : editor.fire('BeforeSetContent', defaultedArgs);
  15228. if (!isTreeNode(content)) {
  15229. content = updatedArgs.content;
  15230. }
  15231. return Optional.from(editor.getBody()).fold(constant(content), function (body) {
  15232. return isTreeNode(content) ? setContentTree(editor, body, content, updatedArgs) : setContentString(editor, body, content, updatedArgs);
  15233. });
  15234. };
  15235. var sibling = function (scope, predicate) {
  15236. return sibling$2(scope, predicate).isSome();
  15237. };
  15238. var ensureIsRoot = function (isRoot) {
  15239. return isFunction(isRoot) ? isRoot : never;
  15240. };
  15241. var ancestor = function (scope, transform, isRoot) {
  15242. var element = scope.dom;
  15243. var stop = ensureIsRoot(isRoot);
  15244. while (element.parentNode) {
  15245. element = element.parentNode;
  15246. var el = SugarElement.fromDom(element);
  15247. var transformed = transform(el);
  15248. if (transformed.isSome()) {
  15249. return transformed;
  15250. } else if (stop(el)) {
  15251. break;
  15252. }
  15253. }
  15254. return Optional.none();
  15255. };
  15256. var closest$1 = function (scope, transform, isRoot) {
  15257. var current = transform(scope);
  15258. var stop = ensureIsRoot(isRoot);
  15259. return current.orThunk(function () {
  15260. return stop(scope) ? Optional.none() : ancestor(scope, transform, stop);
  15261. });
  15262. };
  15263. var isEq$3 = isEq$5;
  15264. var matchesUnInheritedFormatSelector = function (ed, node, name) {
  15265. var formatList = ed.formatter.get(name);
  15266. if (formatList) {
  15267. for (var i = 0; i < formatList.length; i++) {
  15268. var format = formatList[i];
  15269. if (isSelectorFormat(format) && format.inherit === false && ed.dom.is(node, format.selector)) {
  15270. return true;
  15271. }
  15272. }
  15273. }
  15274. return false;
  15275. };
  15276. var matchParents = function (editor, node, name, vars, similar) {
  15277. var root = editor.dom.getRoot();
  15278. if (node === root) {
  15279. return false;
  15280. }
  15281. node = editor.dom.getParent(node, function (node) {
  15282. if (matchesUnInheritedFormatSelector(editor, node, name)) {
  15283. return true;
  15284. }
  15285. return node.parentNode === root || !!matchNode(editor, node, name, vars, true);
  15286. });
  15287. return !!matchNode(editor, node, name, vars, similar);
  15288. };
  15289. var matchName$1 = function (dom, node, format) {
  15290. if (isEq$3(node, format.inline)) {
  15291. return true;
  15292. }
  15293. if (isEq$3(node, format.block)) {
  15294. return true;
  15295. }
  15296. if (format.selector) {
  15297. return node.nodeType === 1 && dom.is(node, format.selector);
  15298. }
  15299. };
  15300. var matchItems = function (dom, node, format, itemName, similar, vars) {
  15301. var items = format[itemName];
  15302. if (isFunction(format.onmatch)) {
  15303. return format.onmatch(node, format, itemName);
  15304. }
  15305. if (items) {
  15306. if (isUndefined(items.length)) {
  15307. for (var key in items) {
  15308. if (has$2(items, key)) {
  15309. var value = itemName === 'attributes' ? dom.getAttrib(node, key) : getStyle(dom, node, key);
  15310. var expectedValue = replaceVars(items[key], vars);
  15311. var isEmptyValue = isNullable(value) || isEmpty$3(value);
  15312. if (isEmptyValue && isNullable(expectedValue)) {
  15313. continue;
  15314. }
  15315. if (similar && isEmptyValue && !format.exact) {
  15316. return false;
  15317. }
  15318. if ((!similar || format.exact) && !isEq$3(value, normalizeStyleValue(dom, expectedValue, key))) {
  15319. return false;
  15320. }
  15321. }
  15322. }
  15323. } else {
  15324. for (var i = 0; i < items.length; i++) {
  15325. if (itemName === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(dom, node, items[i])) {
  15326. return true;
  15327. }
  15328. }
  15329. }
  15330. }
  15331. return true;
  15332. };
  15333. var matchNode = function (ed, node, name, vars, similar) {
  15334. var formatList = ed.formatter.get(name);
  15335. var dom = ed.dom;
  15336. if (formatList && node) {
  15337. for (var i = 0; i < formatList.length; i++) {
  15338. var format = formatList[i];
  15339. if (matchName$1(ed.dom, node, format) && matchItems(dom, node, format, 'attributes', similar, vars) && matchItems(dom, node, format, 'styles', similar, vars)) {
  15340. var classes = format.classes;
  15341. if (classes) {
  15342. for (var x = 0; x < classes.length; x++) {
  15343. if (!ed.dom.hasClass(node, replaceVars(classes[x], vars))) {
  15344. return;
  15345. }
  15346. }
  15347. }
  15348. return format;
  15349. }
  15350. }
  15351. }
  15352. };
  15353. var match$2 = function (editor, name, vars, node, similar) {
  15354. if (node) {
  15355. return matchParents(editor, node, name, vars, similar);
  15356. }
  15357. node = editor.selection.getNode();
  15358. if (matchParents(editor, node, name, vars, similar)) {
  15359. return true;
  15360. }
  15361. var startNode = editor.selection.getStart();
  15362. if (startNode !== node) {
  15363. if (matchParents(editor, startNode, name, vars, similar)) {
  15364. return true;
  15365. }
  15366. }
  15367. return false;
  15368. };
  15369. var matchAll = function (editor, names, vars) {
  15370. var matchedFormatNames = [];
  15371. var checkedMap = {};
  15372. var startElement = editor.selection.getStart();
  15373. editor.dom.getParent(startElement, function (node) {
  15374. for (var i = 0; i < names.length; i++) {
  15375. var name_1 = names[i];
  15376. if (!checkedMap[name_1] && matchNode(editor, node, name_1, vars)) {
  15377. checkedMap[name_1] = true;
  15378. matchedFormatNames.push(name_1);
  15379. }
  15380. }
  15381. }, editor.dom.getRoot());
  15382. return matchedFormatNames;
  15383. };
  15384. var closest = function (editor, names) {
  15385. var isRoot = function (elm) {
  15386. return eq(elm, SugarElement.fromDom(editor.getBody()));
  15387. };
  15388. var match = function (elm, name) {
  15389. return matchNode(editor, elm.dom, name) ? Optional.some(name) : Optional.none();
  15390. };
  15391. return Optional.from(editor.selection.getStart(true)).bind(function (rawElm) {
  15392. return closest$1(SugarElement.fromDom(rawElm), function (elm) {
  15393. return findMap(names, function (name) {
  15394. return match(elm, name);
  15395. });
  15396. }, isRoot);
  15397. }).getOrNull();
  15398. };
  15399. var canApply = function (editor, name) {
  15400. var formatList = editor.formatter.get(name);
  15401. var dom = editor.dom;
  15402. if (formatList) {
  15403. var startNode = editor.selection.getStart();
  15404. var parents = getParents$2(dom, startNode);
  15405. for (var x = formatList.length - 1; x >= 0; x--) {
  15406. var format = formatList[x];
  15407. if (!isSelectorFormat(format) || isNonNullable(format.defaultBlock)) {
  15408. return true;
  15409. }
  15410. for (var i = parents.length - 1; i >= 0; i--) {
  15411. if (dom.is(parents[i], format.selector)) {
  15412. return true;
  15413. }
  15414. }
  15415. }
  15416. }
  15417. return false;
  15418. };
  15419. var matchAllOnNode = function (editor, node, formatNames) {
  15420. return foldl(formatNames, function (acc, name) {
  15421. var matchSimilar = isVariableFormatName(editor, name);
  15422. if (editor.formatter.matchNode(node, name, {}, matchSimilar)) {
  15423. return acc.concat([name]);
  15424. } else {
  15425. return acc;
  15426. }
  15427. }, []);
  15428. };
  15429. var ZWSP = ZWSP$1, CARET_ID = '_mce_caret';
  15430. var importNode = function (ownerDocument, node) {
  15431. return ownerDocument.importNode(node, true);
  15432. };
  15433. var getEmptyCaretContainers = function (node) {
  15434. var nodes = [];
  15435. while (node) {
  15436. if (node.nodeType === 3 && node.nodeValue !== ZWSP || node.childNodes.length > 1) {
  15437. return [];
  15438. }
  15439. if (node.nodeType === 1) {
  15440. nodes.push(node);
  15441. }
  15442. node = node.firstChild;
  15443. }
  15444. return nodes;
  15445. };
  15446. var isCaretContainerEmpty = function (node) {
  15447. return getEmptyCaretContainers(node).length > 0;
  15448. };
  15449. var findFirstTextNode = function (node) {
  15450. if (node) {
  15451. var walker = new DomTreeWalker(node, node);
  15452. for (node = walker.current(); node; node = walker.next()) {
  15453. if (isText$7(node)) {
  15454. return node;
  15455. }
  15456. }
  15457. }
  15458. return null;
  15459. };
  15460. var createCaretContainer = function (fill) {
  15461. var caretContainer = SugarElement.fromTag('span');
  15462. setAll$1(caretContainer, {
  15463. 'id': CARET_ID,
  15464. 'data-mce-bogus': '1',
  15465. 'data-mce-type': 'format-caret'
  15466. });
  15467. if (fill) {
  15468. append$1(caretContainer, SugarElement.fromText(ZWSP));
  15469. }
  15470. return caretContainer;
  15471. };
  15472. var trimZwspFromCaretContainer = function (caretContainerNode) {
  15473. var textNode = findFirstTextNode(caretContainerNode);
  15474. if (textNode && textNode.nodeValue.charAt(0) === ZWSP) {
  15475. textNode.deleteData(0, 1);
  15476. }
  15477. return textNode;
  15478. };
  15479. var removeCaretContainerNode = function (editor, node, moveCaret) {
  15480. if (moveCaret === void 0) {
  15481. moveCaret = true;
  15482. }
  15483. var dom = editor.dom, selection = editor.selection;
  15484. if (isCaretContainerEmpty(node)) {
  15485. deleteElement$2(editor, false, SugarElement.fromDom(node), moveCaret);
  15486. } else {
  15487. var rng = selection.getRng();
  15488. var block = dom.getParent(node, dom.isBlock);
  15489. var startContainer = rng.startContainer;
  15490. var startOffset = rng.startOffset;
  15491. var endContainer = rng.endContainer;
  15492. var endOffset = rng.endOffset;
  15493. var textNode = trimZwspFromCaretContainer(node);
  15494. dom.remove(node, true);
  15495. if (startContainer === textNode && startOffset > 0) {
  15496. rng.setStart(textNode, startOffset - 1);
  15497. }
  15498. if (endContainer === textNode && endOffset > 0) {
  15499. rng.setEnd(textNode, endOffset - 1);
  15500. }
  15501. if (block && dom.isEmpty(block)) {
  15502. fillWithPaddingBr(SugarElement.fromDom(block));
  15503. }
  15504. selection.setRng(rng);
  15505. }
  15506. };
  15507. var removeCaretContainer = function (editor, node, moveCaret) {
  15508. if (moveCaret === void 0) {
  15509. moveCaret = true;
  15510. }
  15511. var dom = editor.dom, selection = editor.selection;
  15512. if (!node) {
  15513. node = getParentCaretContainer(editor.getBody(), selection.getStart());
  15514. if (!node) {
  15515. while (node = dom.get(CARET_ID)) {
  15516. removeCaretContainerNode(editor, node, false);
  15517. }
  15518. }
  15519. } else {
  15520. removeCaretContainerNode(editor, node, moveCaret);
  15521. }
  15522. };
  15523. var insertCaretContainerNode = function (editor, caretContainer, formatNode) {
  15524. var dom = editor.dom, block = dom.getParent(formatNode, curry(isTextBlock$1, editor));
  15525. if (block && dom.isEmpty(block)) {
  15526. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15527. } else {
  15528. removeTrailingBr(SugarElement.fromDom(formatNode));
  15529. if (dom.isEmpty(formatNode)) {
  15530. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15531. } else {
  15532. dom.insertAfter(caretContainer, formatNode);
  15533. }
  15534. }
  15535. };
  15536. var appendNode = function (parentNode, node) {
  15537. parentNode.appendChild(node);
  15538. return node;
  15539. };
  15540. var insertFormatNodesIntoCaretContainer = function (formatNodes, caretContainer) {
  15541. var innerMostFormatNode = foldr(formatNodes, function (parentNode, formatNode) {
  15542. return appendNode(parentNode, formatNode.cloneNode(false));
  15543. }, caretContainer);
  15544. return appendNode(innerMostFormatNode, innerMostFormatNode.ownerDocument.createTextNode(ZWSP));
  15545. };
  15546. var cleanFormatNode = function (editor, caretContainer, formatNode, name, vars, similar) {
  15547. var formatter = editor.formatter;
  15548. var dom = editor.dom;
  15549. var validFormats = filter$4(keys(formatter.get()), function (formatName) {
  15550. return formatName !== name && !contains$2(formatName, 'removeformat');
  15551. });
  15552. var matchedFormats = matchAllOnNode(editor, formatNode, validFormats);
  15553. var uniqueFormats = filter$4(matchedFormats, function (fmtName) {
  15554. return !areSimilarFormats(editor, fmtName, name);
  15555. });
  15556. if (uniqueFormats.length > 0) {
  15557. var clonedFormatNode = formatNode.cloneNode(false);
  15558. dom.add(caretContainer, clonedFormatNode);
  15559. formatter.remove(name, vars, clonedFormatNode, similar);
  15560. dom.remove(clonedFormatNode);
  15561. return Optional.some(clonedFormatNode);
  15562. } else {
  15563. return Optional.none();
  15564. }
  15565. };
  15566. var applyCaretFormat = function (editor, name, vars) {
  15567. var caretContainer, textNode;
  15568. var selection = editor.selection;
  15569. var selectionRng = selection.getRng();
  15570. var offset = selectionRng.startOffset;
  15571. var container = selectionRng.startContainer;
  15572. var text = container.nodeValue;
  15573. caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
  15574. if (caretContainer) {
  15575. textNode = findFirstTextNode(caretContainer);
  15576. }
  15577. var wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
  15578. if (text && offset > 0 && offset < text.length && wordcharRegex.test(text.charAt(offset)) && wordcharRegex.test(text.charAt(offset - 1))) {
  15579. var bookmark = selection.getBookmark();
  15580. selectionRng.collapse(true);
  15581. var rng = expandRng(editor, selectionRng, editor.formatter.get(name));
  15582. rng = split(rng);
  15583. editor.formatter.apply(name, vars, rng);
  15584. selection.moveToBookmark(bookmark);
  15585. } else {
  15586. if (!caretContainer || textNode.nodeValue !== ZWSP) {
  15587. caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom);
  15588. textNode = caretContainer.firstChild;
  15589. selectionRng.insertNode(caretContainer);
  15590. offset = 1;
  15591. editor.formatter.apply(name, vars, caretContainer);
  15592. } else {
  15593. editor.formatter.apply(name, vars, caretContainer);
  15594. }
  15595. selection.setCursorLocation(textNode, offset);
  15596. }
  15597. };
  15598. var removeCaretFormat = function (editor, name, vars, similar) {
  15599. var dom = editor.dom;
  15600. var selection = editor.selection;
  15601. var hasContentAfter, node, formatNode;
  15602. var parents = [];
  15603. var rng = selection.getRng();
  15604. var container = rng.startContainer;
  15605. var offset = rng.startOffset;
  15606. node = container;
  15607. if (container.nodeType === 3) {
  15608. if (offset !== container.nodeValue.length) {
  15609. hasContentAfter = true;
  15610. }
  15611. node = node.parentNode;
  15612. }
  15613. while (node) {
  15614. if (matchNode(editor, node, name, vars, similar)) {
  15615. formatNode = node;
  15616. break;
  15617. }
  15618. if (node.nextSibling) {
  15619. hasContentAfter = true;
  15620. }
  15621. parents.push(node);
  15622. node = node.parentNode;
  15623. }
  15624. if (!formatNode) {
  15625. return;
  15626. }
  15627. if (hasContentAfter) {
  15628. var bookmark = selection.getBookmark();
  15629. rng.collapse(true);
  15630. var expandedRng = expandRng(editor, rng, editor.formatter.get(name), true);
  15631. expandedRng = split(expandedRng);
  15632. editor.formatter.remove(name, vars, expandedRng, similar);
  15633. selection.moveToBookmark(bookmark);
  15634. } else {
  15635. var caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
  15636. var newCaretContainer = createCaretContainer(false).dom;
  15637. insertCaretContainerNode(editor, newCaretContainer, caretContainer !== null ? caretContainer : formatNode);
  15638. var cleanedFormatNode = cleanFormatNode(editor, newCaretContainer, formatNode, name, vars, similar);
  15639. var caretTextNode = insertFormatNodesIntoCaretContainer(parents.concat(cleanedFormatNode.toArray()), newCaretContainer);
  15640. removeCaretContainerNode(editor, caretContainer, false);
  15641. selection.setCursorLocation(caretTextNode, 1);
  15642. if (dom.isEmpty(formatNode)) {
  15643. dom.remove(formatNode);
  15644. }
  15645. }
  15646. };
  15647. var disableCaretContainer = function (editor, keyCode) {
  15648. var selection = editor.selection, body = editor.getBody();
  15649. removeCaretContainer(editor, null, false);
  15650. if ((keyCode === 8 || keyCode === 46) && selection.isCollapsed() && selection.getStart().innerHTML === ZWSP) {
  15651. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15652. }
  15653. if (keyCode === 37 || keyCode === 39) {
  15654. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15655. }
  15656. };
  15657. var setup$k = function (editor) {
  15658. editor.on('mouseup keydown', function (e) {
  15659. disableCaretContainer(editor, e.keyCode);
  15660. });
  15661. };
  15662. var replaceWithCaretFormat = function (targetNode, formatNodes) {
  15663. var caretContainer = createCaretContainer(false);
  15664. var innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom);
  15665. before$4(SugarElement.fromDom(targetNode), caretContainer);
  15666. remove$7(SugarElement.fromDom(targetNode));
  15667. return CaretPosition(innerMost, 0);
  15668. };
  15669. var isFormatElement = function (editor, element) {
  15670. var inlineElements = editor.schema.getTextInlineElements();
  15671. return has$2(inlineElements, name(element)) && !isCaretNode(element.dom) && !isBogus$2(element.dom);
  15672. };
  15673. var isEmptyCaretFormatElement = function (element) {
  15674. return isCaretNode(element.dom) && isCaretContainerEmpty(element.dom);
  15675. };
  15676. var postProcessHooks = {};
  15677. var filter = filter$2;
  15678. var each$b = each$i;
  15679. var addPostProcessHook = function (name, hook) {
  15680. var hooks = postProcessHooks[name];
  15681. if (!hooks) {
  15682. postProcessHooks[name] = [];
  15683. }
  15684. postProcessHooks[name].push(hook);
  15685. };
  15686. var postProcess$1 = function (name, editor) {
  15687. each$b(postProcessHooks[name], function (hook) {
  15688. hook(editor);
  15689. });
  15690. };
  15691. addPostProcessHook('pre', function (editor) {
  15692. var rng = editor.selection.getRng();
  15693. var blocks;
  15694. var hasPreSibling = function (pre) {
  15695. return isPre(pre.previousSibling) && indexOf$1(blocks, pre.previousSibling) !== -1;
  15696. };
  15697. var joinPre = function (pre1, pre2) {
  15698. DomQuery(pre2).remove();
  15699. DomQuery(pre1).append('<br><br>').append(pre2.childNodes);
  15700. };
  15701. var isPre = matchNodeNames(['pre']);
  15702. if (!rng.collapsed) {
  15703. blocks = editor.selection.getSelectedBlocks();
  15704. each$b(filter(filter(blocks, isPre), hasPreSibling), function (pre) {
  15705. joinPre(pre.previousSibling, pre);
  15706. });
  15707. }
  15708. });
  15709. var each$a = Tools.each;
  15710. var isElementNode$1 = function (node) {
  15711. return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  15712. };
  15713. var findElementSibling = function (node, siblingName) {
  15714. for (var sibling = node; sibling; sibling = sibling[siblingName]) {
  15715. if (isText$7(sibling) && isNotEmpty(sibling.data)) {
  15716. return node;
  15717. }
  15718. if (isElement$5(sibling) && !isBookmarkNode$1(sibling)) {
  15719. return sibling;
  15720. }
  15721. }
  15722. return node;
  15723. };
  15724. var mergeSiblingsNodes = function (dom, prev, next) {
  15725. var elementUtils = ElementUtils(dom);
  15726. if (prev && next) {
  15727. prev = findElementSibling(prev, 'previousSibling');
  15728. next = findElementSibling(next, 'nextSibling');
  15729. if (elementUtils.compare(prev, next)) {
  15730. for (var sibling = prev.nextSibling; sibling && sibling !== next;) {
  15731. var tmpSibling = sibling;
  15732. sibling = sibling.nextSibling;
  15733. prev.appendChild(tmpSibling);
  15734. }
  15735. dom.remove(next);
  15736. Tools.each(Tools.grep(next.childNodes), function (node) {
  15737. prev.appendChild(node);
  15738. });
  15739. return prev;
  15740. }
  15741. }
  15742. return next;
  15743. };
  15744. var mergeSiblings = function (dom, format, vars, node) {
  15745. if (node && format.merge_siblings !== false) {
  15746. var newNode = mergeSiblingsNodes(dom, getNonWhiteSpaceSibling(node), node);
  15747. mergeSiblingsNodes(dom, newNode, getNonWhiteSpaceSibling(newNode, true));
  15748. }
  15749. };
  15750. var clearChildStyles = function (dom, format, node) {
  15751. if (format.clear_child_styles) {
  15752. var selector = format.links ? '*:not(a)' : '*';
  15753. each$a(dom.select(selector, node), function (node) {
  15754. if (isElementNode$1(node)) {
  15755. each$a(format.styles, function (value, name) {
  15756. dom.setStyle(node, name, '');
  15757. });
  15758. }
  15759. });
  15760. }
  15761. };
  15762. var processChildElements = function (node, filter, process) {
  15763. each$a(node.childNodes, function (node) {
  15764. if (isElementNode$1(node)) {
  15765. if (filter(node)) {
  15766. process(node);
  15767. }
  15768. if (node.hasChildNodes()) {
  15769. processChildElements(node, filter, process);
  15770. }
  15771. }
  15772. });
  15773. };
  15774. var unwrapEmptySpan = function (dom, node) {
  15775. if (node.nodeName === 'SPAN' && dom.getAttribs(node).length === 0) {
  15776. dom.remove(node, true);
  15777. }
  15778. };
  15779. var hasStyle = function (dom, name) {
  15780. return function (node) {
  15781. return !!(node && getStyle(dom, node, name));
  15782. };
  15783. };
  15784. var applyStyle = function (dom, name, value) {
  15785. return function (node) {
  15786. dom.setStyle(node, name, value);
  15787. if (node.getAttribute('style') === '') {
  15788. node.removeAttribute('style');
  15789. }
  15790. unwrapEmptySpan(dom, node);
  15791. };
  15792. };
  15793. var removeResult = Adt.generate([
  15794. { keep: [] },
  15795. { rename: ['name'] },
  15796. { removed: [] }
  15797. ]);
  15798. var MCE_ATTR_RE = /^(src|href|style)$/;
  15799. var each$9 = Tools.each;
  15800. var isEq$2 = isEq$5;
  15801. var isTableCellOrRow = function (node) {
  15802. return /^(TR|TH|TD)$/.test(node.nodeName);
  15803. };
  15804. var isChildOfInlineParent = function (dom, node, parent) {
  15805. return dom.isChildOf(node, parent) && node !== parent && !dom.isBlock(parent);
  15806. };
  15807. var getContainer = function (ed, rng, start) {
  15808. var container = rng[start ? 'startContainer' : 'endContainer'];
  15809. var offset = rng[start ? 'startOffset' : 'endOffset'];
  15810. if (isElement$5(container)) {
  15811. var lastIdx = container.childNodes.length - 1;
  15812. if (!start && offset) {
  15813. offset--;
  15814. }
  15815. container = container.childNodes[offset > lastIdx ? lastIdx : offset];
  15816. }
  15817. if (isText$7(container) && start && offset >= container.nodeValue.length) {
  15818. container = new DomTreeWalker(container, ed.getBody()).next() || container;
  15819. }
  15820. if (isText$7(container) && !start && offset === 0) {
  15821. container = new DomTreeWalker(container, ed.getBody()).prev() || container;
  15822. }
  15823. return container;
  15824. };
  15825. var normalizeTableSelection = function (node, start) {
  15826. var prop = start ? 'firstChild' : 'lastChild';
  15827. if (isTableCellOrRow(node) && node[prop]) {
  15828. var childNode = node[prop];
  15829. if (node.nodeName === 'TR') {
  15830. return childNode[prop] || childNode;
  15831. } else {
  15832. return childNode;
  15833. }
  15834. }
  15835. return node;
  15836. };
  15837. var wrap$1 = function (dom, node, name, attrs) {
  15838. var wrapper = dom.create(name, attrs);
  15839. node.parentNode.insertBefore(wrapper, node);
  15840. wrapper.appendChild(node);
  15841. return wrapper;
  15842. };
  15843. var wrapWithSiblings = function (dom, node, next, name, attrs) {
  15844. var start = SugarElement.fromDom(node);
  15845. var wrapper = SugarElement.fromDom(dom.create(name, attrs));
  15846. var siblings = next ? nextSiblings(start) : prevSiblings(start);
  15847. append(wrapper, siblings);
  15848. if (next) {
  15849. before$4(start, wrapper);
  15850. prepend(wrapper, start);
  15851. } else {
  15852. after$3(start, wrapper);
  15853. append$1(wrapper, start);
  15854. }
  15855. return wrapper.dom;
  15856. };
  15857. var matchName = function (dom, node, format) {
  15858. if (isInlineFormat(format) && isEq$2(node, format.inline)) {
  15859. return true;
  15860. }
  15861. if (isBlockFormat(format) && isEq$2(node, format.block)) {
  15862. return true;
  15863. }
  15864. if (isSelectorFormat(format)) {
  15865. return isElement$5(node) && dom.is(node, format.selector);
  15866. }
  15867. };
  15868. var isColorFormatAndAnchor = function (node, format) {
  15869. return format.links && node.nodeName === 'A';
  15870. };
  15871. var find = function (dom, node, next, inc) {
  15872. var sibling = getNonWhiteSpaceSibling(node, next, inc);
  15873. return isNullable(sibling) || sibling.nodeName === 'BR' || dom.isBlock(sibling);
  15874. };
  15875. var removeNode = function (ed, node, format) {
  15876. var parentNode = node.parentNode;
  15877. var rootBlockElm;
  15878. var dom = ed.dom, forcedRootBlock = getForcedRootBlock(ed);
  15879. if (isBlockFormat(format)) {
  15880. if (!forcedRootBlock) {
  15881. if (dom.isBlock(node) && !dom.isBlock(parentNode)) {
  15882. if (!find(dom, node, false) && !find(dom, node.firstChild, true, true)) {
  15883. node.insertBefore(dom.create('br'), node.firstChild);
  15884. }
  15885. if (!find(dom, node, true) && !find(dom, node.lastChild, false, true)) {
  15886. node.appendChild(dom.create('br'));
  15887. }
  15888. }
  15889. } else {
  15890. if (parentNode === dom.getRoot()) {
  15891. if (!format.list_block || !isEq$2(node, format.list_block)) {
  15892. each$k(from(node.childNodes), function (node) {
  15893. if (isValid(ed, forcedRootBlock, node.nodeName.toLowerCase())) {
  15894. if (!rootBlockElm) {
  15895. rootBlockElm = wrap$1(dom, node, forcedRootBlock);
  15896. dom.setAttribs(rootBlockElm, ed.settings.forced_root_block_attrs);
  15897. } else {
  15898. rootBlockElm.appendChild(node);
  15899. }
  15900. } else {
  15901. rootBlockElm = null;
  15902. }
  15903. });
  15904. }
  15905. }
  15906. }
  15907. }
  15908. if (isMixedFormat(format) && !isEq$2(format.inline, node)) {
  15909. return;
  15910. }
  15911. dom.remove(node, true);
  15912. };
  15913. var removeFormatInternal = function (ed, format, vars, node, compareNode) {
  15914. var stylesModified;
  15915. var dom = ed.dom;
  15916. if (!matchName(dom, node, format) && !isColorFormatAndAnchor(node, format)) {
  15917. return removeResult.keep();
  15918. }
  15919. var elm = node;
  15920. if (isInlineFormat(format) && format.remove === 'all' && isArray$1(format.preserve_attributes)) {
  15921. var attrsToPreserve = filter$4(dom.getAttribs(elm), function (attr) {
  15922. return contains$3(format.preserve_attributes, attr.name.toLowerCase());
  15923. });
  15924. dom.removeAllAttribs(elm);
  15925. each$k(attrsToPreserve, function (attr) {
  15926. return dom.setAttrib(elm, attr.name, attr.value);
  15927. });
  15928. if (attrsToPreserve.length > 0) {
  15929. return removeResult.rename('span');
  15930. }
  15931. }
  15932. if (format.remove !== 'all') {
  15933. each$9(format.styles, function (value, name) {
  15934. value = normalizeStyleValue(dom, replaceVars(value, vars), name + '');
  15935. if (isNumber(name)) {
  15936. name = value;
  15937. compareNode = null;
  15938. }
  15939. if (format.remove_similar || (!compareNode || isEq$2(getStyle(dom, compareNode, name), value))) {
  15940. dom.setStyle(elm, name, '');
  15941. }
  15942. stylesModified = true;
  15943. });
  15944. if (stylesModified && dom.getAttrib(elm, 'style') === '') {
  15945. elm.removeAttribute('style');
  15946. elm.removeAttribute('data-mce-style');
  15947. }
  15948. each$9(format.attributes, function (value, name) {
  15949. var valueOut;
  15950. value = replaceVars(value, vars);
  15951. if (isNumber(name)) {
  15952. name = value;
  15953. compareNode = null;
  15954. }
  15955. if (format.remove_similar || (!compareNode || isEq$2(dom.getAttrib(compareNode, name), value))) {
  15956. if (name === 'class') {
  15957. value = dom.getAttrib(elm, name);
  15958. if (value) {
  15959. valueOut = '';
  15960. each$k(value.split(/\s+/), function (cls) {
  15961. if (/mce\-\w+/.test(cls)) {
  15962. valueOut += (valueOut ? ' ' : '') + cls;
  15963. }
  15964. });
  15965. if (valueOut) {
  15966. dom.setAttrib(elm, name, valueOut);
  15967. return;
  15968. }
  15969. }
  15970. }
  15971. if (MCE_ATTR_RE.test(name)) {
  15972. elm.removeAttribute('data-mce-' + name);
  15973. }
  15974. if (name === 'style' && matchNodeNames(['li'])(elm) && dom.getStyle(elm, 'list-style-type') === 'none') {
  15975. elm.removeAttribute(name);
  15976. dom.setStyle(elm, 'list-style-type', 'none');
  15977. return;
  15978. }
  15979. if (name === 'class') {
  15980. elm.removeAttribute('className');
  15981. }
  15982. elm.removeAttribute(name);
  15983. }
  15984. });
  15985. each$9(format.classes, function (value) {
  15986. value = replaceVars(value, vars);
  15987. if (!compareNode || dom.hasClass(compareNode, value)) {
  15988. dom.removeClass(elm, value);
  15989. }
  15990. });
  15991. var attrs = dom.getAttribs(elm);
  15992. for (var i = 0; i < attrs.length; i++) {
  15993. var attrName = attrs[i].nodeName;
  15994. if (attrName.indexOf('_') !== 0 && attrName.indexOf('data-') !== 0) {
  15995. return removeResult.keep();
  15996. }
  15997. }
  15998. }
  15999. if (format.remove !== 'none') {
  16000. removeNode(ed, elm, format);
  16001. return removeResult.removed();
  16002. }
  16003. return removeResult.keep();
  16004. };
  16005. var removeFormat$1 = function (ed, format, vars, node, compareNode) {
  16006. return removeFormatInternal(ed, format, vars, node, compareNode).fold(never, function (newName) {
  16007. ed.dom.rename(node, newName);
  16008. return true;
  16009. }, always);
  16010. };
  16011. var findFormatRoot = function (editor, container, name, vars, similar) {
  16012. var formatRoot;
  16013. each$k(getParents$2(editor.dom, container.parentNode).reverse(), function (parent) {
  16014. if (!formatRoot && parent.id !== '_start' && parent.id !== '_end') {
  16015. var format = matchNode(editor, parent, name, vars, similar);
  16016. if (format && format.split !== false) {
  16017. formatRoot = parent;
  16018. }
  16019. }
  16020. });
  16021. return formatRoot;
  16022. };
  16023. var removeFormatFromClone = function (editor, format, vars, clone) {
  16024. return removeFormatInternal(editor, format, vars, clone, clone).fold(constant(clone), function (newName) {
  16025. var fragment = editor.dom.createFragment();
  16026. fragment.appendChild(clone);
  16027. return editor.dom.rename(clone, newName);
  16028. }, constant(null));
  16029. };
  16030. var wrapAndSplit = function (editor, formatList, formatRoot, container, target, split, format, vars) {
  16031. var clone, lastClone, firstClone;
  16032. var dom = editor.dom;
  16033. if (formatRoot) {
  16034. var formatRootParent = formatRoot.parentNode;
  16035. for (var parent_1 = container.parentNode; parent_1 && parent_1 !== formatRootParent; parent_1 = parent_1.parentNode) {
  16036. clone = dom.clone(parent_1, false);
  16037. for (var i = 0; i < formatList.length; i++) {
  16038. clone = removeFormatFromClone(editor, formatList[i], vars, clone);
  16039. if (clone === null) {
  16040. break;
  16041. }
  16042. }
  16043. if (clone) {
  16044. if (lastClone) {
  16045. clone.appendChild(lastClone);
  16046. }
  16047. if (!firstClone) {
  16048. firstClone = clone;
  16049. }
  16050. lastClone = clone;
  16051. }
  16052. }
  16053. if (split && (!format.mixed || !dom.isBlock(formatRoot))) {
  16054. container = dom.split(formatRoot, container);
  16055. }
  16056. if (lastClone) {
  16057. target.parentNode.insertBefore(lastClone, target);
  16058. firstClone.appendChild(target);
  16059. if (isInlineFormat(format)) {
  16060. mergeSiblings(dom, format, vars, lastClone);
  16061. }
  16062. }
  16063. }
  16064. return container;
  16065. };
  16066. var remove$1 = function (ed, name, vars, node, similar) {
  16067. var formatList = ed.formatter.get(name);
  16068. var format = formatList[0];
  16069. var contentEditable = true;
  16070. var dom = ed.dom;
  16071. var selection = ed.selection;
  16072. var splitToFormatRoot = function (container) {
  16073. var formatRoot = findFormatRoot(ed, container, name, vars, similar);
  16074. return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format, vars);
  16075. };
  16076. var isRemoveBookmarkNode = function (node) {
  16077. return isBookmarkNode$1(node) && isElement$5(node) && (node.id === '_start' || node.id === '_end');
  16078. };
  16079. var removeNodeFormat = function (node) {
  16080. return exists(formatList, function (fmt) {
  16081. return removeFormat$1(ed, fmt, vars, node, node);
  16082. });
  16083. };
  16084. var process = function (node) {
  16085. var lastContentEditable = true;
  16086. var hasContentEditableState = false;
  16087. if (isElement$5(node) && dom.getContentEditable(node)) {
  16088. lastContentEditable = contentEditable;
  16089. contentEditable = dom.getContentEditable(node) === 'true';
  16090. hasContentEditableState = true;
  16091. }
  16092. var children = from(node.childNodes);
  16093. if (contentEditable && !hasContentEditableState) {
  16094. var removed = removeNodeFormat(node);
  16095. var parentNode = node.parentNode;
  16096. if (!removed && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  16097. removeNodeFormat(parentNode);
  16098. }
  16099. }
  16100. if (format.deep) {
  16101. if (children.length) {
  16102. for (var i = 0; i < children.length; i++) {
  16103. process(children[i]);
  16104. }
  16105. if (hasContentEditableState) {
  16106. contentEditable = lastContentEditable;
  16107. }
  16108. }
  16109. }
  16110. var textDecorations = [
  16111. 'underline',
  16112. 'line-through',
  16113. 'overline'
  16114. ];
  16115. each$k(textDecorations, function (decoration) {
  16116. if (isElement$5(node) && ed.dom.getStyle(node, 'text-decoration') === decoration && node.parentNode && getTextDecoration(dom, node.parentNode) === decoration) {
  16117. removeFormat$1(ed, {
  16118. deep: false,
  16119. exact: true,
  16120. inline: 'span',
  16121. styles: { textDecoration: decoration }
  16122. }, null, node);
  16123. }
  16124. });
  16125. };
  16126. var unwrap = function (start) {
  16127. var node = dom.get(start ? '_start' : '_end');
  16128. var out = node[start ? 'firstChild' : 'lastChild'];
  16129. if (isRemoveBookmarkNode(out)) {
  16130. out = out[start ? 'firstChild' : 'lastChild'];
  16131. }
  16132. if (isText$7(out) && out.data.length === 0) {
  16133. out = start ? node.previousSibling || node.nextSibling : node.nextSibling || node.previousSibling;
  16134. }
  16135. dom.remove(node, true);
  16136. return out;
  16137. };
  16138. var removeRngStyle = function (rng) {
  16139. var startContainer, endContainer;
  16140. var expandedRng = expandRng(ed, rng, formatList, rng.collapsed);
  16141. if (format.split) {
  16142. expandedRng = split(expandedRng);
  16143. startContainer = getContainer(ed, expandedRng, true);
  16144. endContainer = getContainer(ed, expandedRng);
  16145. if (startContainer !== endContainer) {
  16146. startContainer = normalizeTableSelection(startContainer, true);
  16147. endContainer = normalizeTableSelection(endContainer, false);
  16148. if (isChildOfInlineParent(dom, startContainer, endContainer)) {
  16149. var marker = Optional.from(startContainer.firstChild).getOr(startContainer);
  16150. splitToFormatRoot(wrapWithSiblings(dom, marker, true, 'span', {
  16151. 'id': '_start',
  16152. 'data-mce-type': 'bookmark'
  16153. }));
  16154. unwrap(true);
  16155. return;
  16156. }
  16157. if (isChildOfInlineParent(dom, endContainer, startContainer)) {
  16158. var marker = Optional.from(endContainer.lastChild).getOr(endContainer);
  16159. splitToFormatRoot(wrapWithSiblings(dom, marker, false, 'span', {
  16160. 'id': '_end',
  16161. 'data-mce-type': 'bookmark'
  16162. }));
  16163. unwrap(false);
  16164. return;
  16165. }
  16166. startContainer = wrap$1(dom, startContainer, 'span', {
  16167. 'id': '_start',
  16168. 'data-mce-type': 'bookmark'
  16169. });
  16170. endContainer = wrap$1(dom, endContainer, 'span', {
  16171. 'id': '_end',
  16172. 'data-mce-type': 'bookmark'
  16173. });
  16174. var newRng = dom.createRng();
  16175. newRng.setStartAfter(startContainer);
  16176. newRng.setEndBefore(endContainer);
  16177. walk$2(dom, newRng, function (nodes) {
  16178. each$k(nodes, function (n) {
  16179. if (!isBookmarkNode$1(n) && !isBookmarkNode$1(n.parentNode)) {
  16180. splitToFormatRoot(n);
  16181. }
  16182. });
  16183. });
  16184. splitToFormatRoot(startContainer);
  16185. splitToFormatRoot(endContainer);
  16186. startContainer = unwrap(true);
  16187. endContainer = unwrap();
  16188. } else {
  16189. startContainer = endContainer = splitToFormatRoot(startContainer);
  16190. }
  16191. expandedRng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
  16192. expandedRng.startOffset = dom.nodeIndex(startContainer);
  16193. expandedRng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
  16194. expandedRng.endOffset = dom.nodeIndex(endContainer) + 1;
  16195. }
  16196. walk$2(dom, expandedRng, function (nodes) {
  16197. each$k(nodes, process);
  16198. });
  16199. };
  16200. if (node) {
  16201. if (isNode(node)) {
  16202. var rng = dom.createRng();
  16203. rng.setStartBefore(node);
  16204. rng.setEndAfter(node);
  16205. removeRngStyle(rng);
  16206. } else {
  16207. removeRngStyle(node);
  16208. }
  16209. fireFormatRemove(ed, name, node, vars);
  16210. return;
  16211. }
  16212. if (dom.getContentEditable(selection.getNode()) === 'false') {
  16213. node = selection.getNode();
  16214. for (var i = 0; i < formatList.length; i++) {
  16215. if (formatList[i].ceFalseOverride) {
  16216. if (removeFormat$1(ed, formatList[i], vars, node, node)) {
  16217. break;
  16218. }
  16219. }
  16220. }
  16221. fireFormatRemove(ed, name, node, vars);
  16222. return;
  16223. }
  16224. if (!selection.isCollapsed() || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  16225. preserve(selection, true, function () {
  16226. runOnRanges(ed, removeRngStyle);
  16227. });
  16228. if (isInlineFormat(format) && match$2(ed, name, vars, selection.getStart())) {
  16229. moveStart(dom, selection, selection.getRng());
  16230. }
  16231. ed.nodeChanged();
  16232. } else {
  16233. removeCaretFormat(ed, name, vars, similar);
  16234. }
  16235. fireFormatRemove(ed, name, node, vars);
  16236. };
  16237. var each$8 = Tools.each;
  16238. var mergeTextDecorationsAndColor = function (dom, format, vars, node) {
  16239. var processTextDecorationsAndColor = function (n) {
  16240. if (n.nodeType === 1 && n.parentNode && n.parentNode.nodeType === 1) {
  16241. var textDecoration = getTextDecoration(dom, n.parentNode);
  16242. if (dom.getStyle(n, 'color') && textDecoration) {
  16243. dom.setStyle(n, 'text-decoration', textDecoration);
  16244. } else if (dom.getStyle(n, 'text-decoration') === textDecoration) {
  16245. dom.setStyle(n, 'text-decoration', null);
  16246. }
  16247. }
  16248. };
  16249. if (format.styles && (format.styles.color || format.styles.textDecoration)) {
  16250. Tools.walk(node, processTextDecorationsAndColor, 'childNodes');
  16251. processTextDecorationsAndColor(node);
  16252. }
  16253. };
  16254. var mergeBackgroundColorAndFontSize = function (dom, format, vars, node) {
  16255. if (format.styles && format.styles.backgroundColor) {
  16256. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'backgroundColor', replaceVars(format.styles.backgroundColor, vars)));
  16257. }
  16258. };
  16259. var mergeSubSup = function (dom, format, vars, node) {
  16260. if (isInlineFormat(format) && (format.inline === 'sub' || format.inline === 'sup')) {
  16261. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'fontSize', ''));
  16262. dom.remove(dom.select(format.inline === 'sup' ? 'sub' : 'sup', node), true);
  16263. }
  16264. };
  16265. var mergeWithChildren = function (editor, formatList, vars, node) {
  16266. each$8(formatList, function (format) {
  16267. if (isInlineFormat(format)) {
  16268. each$8(editor.dom.select(format.inline, node), function (child) {
  16269. if (!isElementNode$1(child)) {
  16270. return;
  16271. }
  16272. removeFormat$1(editor, format, vars, child, format.exact ? child : null);
  16273. });
  16274. }
  16275. clearChildStyles(editor.dom, format, node);
  16276. });
  16277. };
  16278. var mergeWithParents = function (editor, format, name, vars, node) {
  16279. if (matchNode(editor, node.parentNode, name, vars)) {
  16280. if (removeFormat$1(editor, format, vars, node)) {
  16281. return;
  16282. }
  16283. }
  16284. if (format.merge_with_parents) {
  16285. editor.dom.getParent(node.parentNode, function (parent) {
  16286. if (matchNode(editor, parent, name, vars)) {
  16287. removeFormat$1(editor, format, vars, node);
  16288. return true;
  16289. }
  16290. });
  16291. }
  16292. };
  16293. var each$7 = Tools.each;
  16294. var isElementNode = function (node) {
  16295. return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  16296. };
  16297. var canFormatBR = function (editor, format, node, parentName) {
  16298. if (canFormatEmptyLines(editor) && isInlineFormat(format)) {
  16299. var validBRParentElements = __assign(__assign({}, editor.schema.getTextBlockElements()), {
  16300. td: {},
  16301. th: {},
  16302. li: {},
  16303. dt: {},
  16304. dd: {},
  16305. figcaption: {},
  16306. caption: {},
  16307. details: {},
  16308. summary: {}
  16309. });
  16310. var hasCaretNodeSibling = sibling(SugarElement.fromDom(node), function (sibling) {
  16311. return isCaretNode(sibling.dom);
  16312. });
  16313. return hasNonNullableKey(validBRParentElements, parentName) && isEmpty$2(SugarElement.fromDom(node.parentNode), false) && !hasCaretNodeSibling;
  16314. } else {
  16315. return false;
  16316. }
  16317. };
  16318. var applyFormat$1 = function (ed, name, vars, node) {
  16319. var formatList = ed.formatter.get(name);
  16320. var format = formatList[0];
  16321. var isCollapsed = !node && ed.selection.isCollapsed();
  16322. var dom = ed.dom;
  16323. var selection = ed.selection;
  16324. var setElementFormat = function (elm, fmt) {
  16325. if (fmt === void 0) {
  16326. fmt = format;
  16327. }
  16328. if (isFunction(fmt.onformat)) {
  16329. fmt.onformat(elm, fmt, vars, node);
  16330. }
  16331. each$7(fmt.styles, function (value, name) {
  16332. dom.setStyle(elm, name, replaceVars(value, vars));
  16333. });
  16334. if (fmt.styles) {
  16335. var styleVal = dom.getAttrib(elm, 'style');
  16336. if (styleVal) {
  16337. dom.setAttrib(elm, 'data-mce-style', styleVal);
  16338. }
  16339. }
  16340. each$7(fmt.attributes, function (value, name) {
  16341. dom.setAttrib(elm, name, replaceVars(value, vars));
  16342. });
  16343. each$7(fmt.classes, function (value) {
  16344. value = replaceVars(value, vars);
  16345. if (!dom.hasClass(elm, value)) {
  16346. dom.addClass(elm, value);
  16347. }
  16348. });
  16349. };
  16350. var applyNodeStyle = function (formatList, node) {
  16351. var found = false;
  16352. each$7(formatList, function (format) {
  16353. if (!isSelectorFormat(format)) {
  16354. return false;
  16355. }
  16356. if (isNonNullable(format.collapsed) && format.collapsed !== isCollapsed) {
  16357. return;
  16358. }
  16359. if (dom.is(node, format.selector) && !isCaretNode(node)) {
  16360. setElementFormat(node, format);
  16361. found = true;
  16362. return false;
  16363. }
  16364. });
  16365. return found;
  16366. };
  16367. var createWrapElement = function (wrapName) {
  16368. if (isString$1(wrapName)) {
  16369. var wrapElm = dom.create(wrapName);
  16370. setElementFormat(wrapElm);
  16371. return wrapElm;
  16372. } else {
  16373. return null;
  16374. }
  16375. };
  16376. var applyRngStyle = function (dom, rng, nodeSpecific) {
  16377. var newWrappers = [];
  16378. var contentEditable = true;
  16379. var wrapName = format.inline || format.block;
  16380. var wrapElm = createWrapElement(wrapName);
  16381. walk$2(dom, rng, function (nodes) {
  16382. var currentWrapElm;
  16383. var process = function (node) {
  16384. var hasContentEditableState = false;
  16385. var lastContentEditable = contentEditable;
  16386. var nodeName = node.nodeName.toLowerCase();
  16387. var parentNode = node.parentNode;
  16388. var parentName = parentNode.nodeName.toLowerCase();
  16389. if (isElement$5(node) && dom.getContentEditable(node)) {
  16390. lastContentEditable = contentEditable;
  16391. contentEditable = dom.getContentEditable(node) === 'true';
  16392. hasContentEditableState = true;
  16393. }
  16394. if (isBr$5(node) && !canFormatBR(ed, format, node, parentName)) {
  16395. currentWrapElm = null;
  16396. if (isBlockFormat(format)) {
  16397. dom.remove(node);
  16398. }
  16399. return;
  16400. }
  16401. if (isBlockFormat(format) && format.wrapper && matchNode(ed, node, name, vars)) {
  16402. currentWrapElm = null;
  16403. return;
  16404. }
  16405. if (contentEditable && !hasContentEditableState && isBlockFormat(format) && !format.wrapper && isTextBlock$1(ed, nodeName) && isValid(ed, parentName, wrapName)) {
  16406. var elm = dom.rename(node, wrapName);
  16407. setElementFormat(elm);
  16408. newWrappers.push(elm);
  16409. currentWrapElm = null;
  16410. return;
  16411. }
  16412. if (isSelectorFormat(format)) {
  16413. var found = applyNodeStyle(formatList, node);
  16414. if (!found && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  16415. found = applyNodeStyle(formatList, parentNode);
  16416. }
  16417. if (!isInlineFormat(format) || found) {
  16418. currentWrapElm = null;
  16419. return;
  16420. }
  16421. }
  16422. if (contentEditable && !hasContentEditableState && isValid(ed, wrapName, nodeName) && isValid(ed, parentName, wrapName) && !(!nodeSpecific && isText$7(node) && isZwsp(node.data)) && !isCaretNode(node) && (!isInlineFormat(format) || !dom.isBlock(node))) {
  16423. if (!currentWrapElm) {
  16424. currentWrapElm = dom.clone(wrapElm, false);
  16425. node.parentNode.insertBefore(currentWrapElm, node);
  16426. newWrappers.push(currentWrapElm);
  16427. }
  16428. currentWrapElm.appendChild(node);
  16429. } else {
  16430. currentWrapElm = null;
  16431. each$k(from(node.childNodes), process);
  16432. if (hasContentEditableState) {
  16433. contentEditable = lastContentEditable;
  16434. }
  16435. currentWrapElm = null;
  16436. }
  16437. };
  16438. each$k(nodes, process);
  16439. });
  16440. if (format.links === true) {
  16441. each$k(newWrappers, function (node) {
  16442. var process = function (node) {
  16443. if (node.nodeName === 'A') {
  16444. setElementFormat(node, format);
  16445. }
  16446. each$k(from(node.childNodes), process);
  16447. };
  16448. process(node);
  16449. });
  16450. }
  16451. each$k(newWrappers, function (node) {
  16452. var getChildCount = function (node) {
  16453. var count = 0;
  16454. each$k(node.childNodes, function (node) {
  16455. if (!isEmptyTextNode$1(node) && !isBookmarkNode$1(node)) {
  16456. count++;
  16457. }
  16458. });
  16459. return count;
  16460. };
  16461. var mergeStyles = function (node) {
  16462. var childElement = find$3(node.childNodes, isElementNode).filter(function (child) {
  16463. return matchName$1(dom, child, format);
  16464. });
  16465. return childElement.map(function (child) {
  16466. var clone = dom.clone(child, false);
  16467. setElementFormat(clone);
  16468. dom.replace(clone, node, true);
  16469. dom.remove(child, true);
  16470. return clone;
  16471. }).getOr(node);
  16472. };
  16473. var childCount = getChildCount(node);
  16474. if ((newWrappers.length > 1 || !dom.isBlock(node)) && childCount === 0) {
  16475. dom.remove(node, true);
  16476. return;
  16477. }
  16478. if (isInlineFormat(format) || isBlockFormat(format) && format.wrapper) {
  16479. if (!format.exact && childCount === 1) {
  16480. node = mergeStyles(node);
  16481. }
  16482. mergeWithChildren(ed, formatList, vars, node);
  16483. mergeWithParents(ed, format, name, vars, node);
  16484. mergeBackgroundColorAndFontSize(dom, format, vars, node);
  16485. mergeTextDecorationsAndColor(dom, format, vars, node);
  16486. mergeSubSup(dom, format, vars, node);
  16487. mergeSiblings(dom, format, vars, node);
  16488. }
  16489. });
  16490. };
  16491. if (dom.getContentEditable(selection.getNode()) === 'false') {
  16492. node = selection.getNode();
  16493. for (var i = 0, l = formatList.length; i < l; i++) {
  16494. var formatItem = formatList[i];
  16495. if (formatItem.ceFalseOverride && isSelectorFormat(formatItem) && dom.is(node, formatItem.selector)) {
  16496. setElementFormat(node, formatItem);
  16497. break;
  16498. }
  16499. }
  16500. fireFormatApply(ed, name, node, vars);
  16501. return;
  16502. }
  16503. if (format) {
  16504. if (node) {
  16505. if (isNode(node)) {
  16506. if (!applyNodeStyle(formatList, node)) {
  16507. var rng = dom.createRng();
  16508. rng.setStartBefore(node);
  16509. rng.setEndAfter(node);
  16510. applyRngStyle(dom, expandRng(ed, rng, formatList), true);
  16511. }
  16512. } else {
  16513. applyRngStyle(dom, node, true);
  16514. }
  16515. } else {
  16516. if (!isCollapsed || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  16517. var curSelNode = selection.getNode();
  16518. var firstFormat = formatList[0];
  16519. if (!ed.settings.forced_root_block && firstFormat.defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) {
  16520. applyFormat$1(ed, firstFormat.defaultBlock);
  16521. }
  16522. selection.setRng(normalize(selection.getRng()));
  16523. preserve(selection, true, function () {
  16524. runOnRanges(ed, function (selectionRng, fake) {
  16525. var expandedRng = fake ? selectionRng : expandRng(ed, selectionRng, formatList);
  16526. applyRngStyle(dom, expandedRng, false);
  16527. });
  16528. });
  16529. moveStart(dom, selection, selection.getRng());
  16530. ed.nodeChanged();
  16531. } else {
  16532. applyCaretFormat(ed, name, vars);
  16533. }
  16534. }
  16535. postProcess$1(name, ed);
  16536. }
  16537. fireFormatApply(ed, name, node, vars);
  16538. };
  16539. var hasVars = function (value) {
  16540. return has$2(value, 'vars');
  16541. };
  16542. var setup$j = function (registeredFormatListeners, editor) {
  16543. registeredFormatListeners.set({});
  16544. editor.on('NodeChange', function (e) {
  16545. updateAndFireChangeCallbacks(editor, e.element, registeredFormatListeners.get());
  16546. });
  16547. editor.on('FormatApply FormatRemove', function (e) {
  16548. var element = Optional.from(e.node).map(function (nodeOrRange) {
  16549. return isNode(nodeOrRange) ? nodeOrRange : nodeOrRange.startContainer;
  16550. }).bind(function (node) {
  16551. return isElement$5(node) ? Optional.some(node) : Optional.from(node.parentElement);
  16552. }).getOrThunk(function () {
  16553. return fallbackElement(editor);
  16554. });
  16555. updateAndFireChangeCallbacks(editor, element, registeredFormatListeners.get());
  16556. });
  16557. };
  16558. var fallbackElement = function (editor) {
  16559. return editor.selection.getStart();
  16560. };
  16561. var matchingNode = function (editor, parents, format, similar, vars) {
  16562. var isMatchingNode = function (node) {
  16563. var matchingFormat = editor.formatter.matchNode(node, format, vars !== null && vars !== void 0 ? vars : {}, similar);
  16564. return !isUndefined(matchingFormat);
  16565. };
  16566. var isUnableToMatch = function (node) {
  16567. if (matchesUnInheritedFormatSelector(editor, node, format)) {
  16568. return true;
  16569. } else {
  16570. if (!similar) {
  16571. return isNonNullable(editor.formatter.matchNode(node, format, vars, true));
  16572. } else {
  16573. return false;
  16574. }
  16575. }
  16576. };
  16577. return findUntil$1(parents, isMatchingNode, isUnableToMatch);
  16578. };
  16579. var getParents = function (editor, elm) {
  16580. var element = elm !== null && elm !== void 0 ? elm : fallbackElement(editor);
  16581. return filter$4(getParents$2(editor.dom, element), function (node) {
  16582. return isElement$5(node) && !isBogus$2(node);
  16583. });
  16584. };
  16585. var updateAndFireChangeCallbacks = function (editor, elm, registeredCallbacks) {
  16586. var parents = getParents(editor, elm);
  16587. each$j(registeredCallbacks, function (data, format) {
  16588. var runIfChanged = function (spec) {
  16589. var match = matchingNode(editor, parents, format, spec.similar, hasVars(spec) ? spec.vars : undefined);
  16590. var isSet = match.isSome();
  16591. if (spec.state.get() !== isSet) {
  16592. spec.state.set(isSet);
  16593. var node_1 = match.getOr(elm);
  16594. if (hasVars(spec)) {
  16595. spec.callback(isSet, {
  16596. node: node_1,
  16597. format: format,
  16598. parents: parents
  16599. });
  16600. } else {
  16601. each$k(spec.callbacks, function (callback) {
  16602. return callback(isSet, {
  16603. node: node_1,
  16604. format: format,
  16605. parents: parents
  16606. });
  16607. });
  16608. }
  16609. }
  16610. };
  16611. each$k([
  16612. data.withSimilar,
  16613. data.withoutSimilar
  16614. ], runIfChanged);
  16615. each$k(data.withVars, runIfChanged);
  16616. });
  16617. };
  16618. var addListeners = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  16619. var formatChangeItems = registeredFormatListeners.get();
  16620. each$k(formats.split(','), function (format) {
  16621. var group = get$9(formatChangeItems, format).getOrThunk(function () {
  16622. var base = {
  16623. withSimilar: {
  16624. state: Cell(false),
  16625. similar: true,
  16626. callbacks: []
  16627. },
  16628. withoutSimilar: {
  16629. state: Cell(false),
  16630. similar: false,
  16631. callbacks: []
  16632. },
  16633. withVars: []
  16634. };
  16635. formatChangeItems[format] = base;
  16636. return base;
  16637. });
  16638. var getCurrent = function () {
  16639. var parents = getParents(editor);
  16640. return matchingNode(editor, parents, format, similar, vars).isSome();
  16641. };
  16642. if (isUndefined(vars)) {
  16643. var toAppendTo = similar ? group.withSimilar : group.withoutSimilar;
  16644. toAppendTo.callbacks.push(callback);
  16645. if (toAppendTo.callbacks.length === 1) {
  16646. toAppendTo.state.set(getCurrent());
  16647. }
  16648. } else {
  16649. group.withVars.push({
  16650. state: Cell(getCurrent()),
  16651. similar: similar,
  16652. vars: vars,
  16653. callback: callback
  16654. });
  16655. }
  16656. });
  16657. registeredFormatListeners.set(formatChangeItems);
  16658. };
  16659. var removeListeners = function (registeredFormatListeners, formats, callback) {
  16660. var formatChangeItems = registeredFormatListeners.get();
  16661. each$k(formats.split(','), function (format) {
  16662. return get$9(formatChangeItems, format).each(function (group) {
  16663. formatChangeItems[format] = {
  16664. withSimilar: __assign(__assign({}, group.withSimilar), {
  16665. callbacks: filter$4(group.withSimilar.callbacks, function (cb) {
  16666. return cb !== callback;
  16667. })
  16668. }),
  16669. withoutSimilar: __assign(__assign({}, group.withoutSimilar), {
  16670. callbacks: filter$4(group.withoutSimilar.callbacks, function (cb) {
  16671. return cb !== callback;
  16672. })
  16673. }),
  16674. withVars: filter$4(group.withVars, function (item) {
  16675. return item.callback !== callback;
  16676. })
  16677. };
  16678. });
  16679. });
  16680. registeredFormatListeners.set(formatChangeItems);
  16681. };
  16682. var formatChangedInternal = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  16683. if (registeredFormatListeners.get() === null) {
  16684. setup$j(registeredFormatListeners, editor);
  16685. }
  16686. addListeners(editor, registeredFormatListeners, formats, callback, similar, vars);
  16687. return {
  16688. unbind: function () {
  16689. return removeListeners(registeredFormatListeners, formats, callback);
  16690. }
  16691. };
  16692. };
  16693. var toggle = function (editor, name, vars, node) {
  16694. var fmt = editor.formatter.get(name);
  16695. if (match$2(editor, name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) {
  16696. remove$1(editor, name, vars, node);
  16697. } else {
  16698. applyFormat$1(editor, name, vars, node);
  16699. }
  16700. };
  16701. var fromElements = function (elements, scope) {
  16702. var doc = scope || document;
  16703. var fragment = doc.createDocumentFragment();
  16704. each$k(elements, function (element) {
  16705. fragment.appendChild(element.dom);
  16706. });
  16707. return SugarElement.fromDom(fragment);
  16708. };
  16709. var tableModel = function (element, width, rows) {
  16710. return {
  16711. element: element,
  16712. width: width,
  16713. rows: rows
  16714. };
  16715. };
  16716. var tableRow = function (element, cells) {
  16717. return {
  16718. element: element,
  16719. cells: cells
  16720. };
  16721. };
  16722. var cellPosition = function (x, y) {
  16723. return {
  16724. x: x,
  16725. y: y
  16726. };
  16727. };
  16728. var getSpan = function (td, key) {
  16729. var value = parseInt(get$6(td, key), 10);
  16730. return isNaN(value) ? 1 : value;
  16731. };
  16732. var fillout = function (table, x, y, tr, td) {
  16733. var rowspan = getSpan(td, 'rowspan');
  16734. var colspan = getSpan(td, 'colspan');
  16735. var rows = table.rows;
  16736. for (var y2 = y; y2 < y + rowspan; y2++) {
  16737. if (!rows[y2]) {
  16738. rows[y2] = tableRow(deep$1(tr), []);
  16739. }
  16740. for (var x2 = x; x2 < x + colspan; x2++) {
  16741. var cells = rows[y2].cells;
  16742. cells[x2] = y2 === y && x2 === x ? td : shallow(td);
  16743. }
  16744. }
  16745. };
  16746. var cellExists = function (table, x, y) {
  16747. var rows = table.rows;
  16748. var cells = rows[y] ? rows[y].cells : [];
  16749. return !!cells[x];
  16750. };
  16751. var skipCellsX = function (table, x, y) {
  16752. while (cellExists(table, x, y)) {
  16753. x++;
  16754. }
  16755. return x;
  16756. };
  16757. var getWidth = function (rows) {
  16758. return foldl(rows, function (acc, row) {
  16759. return row.cells.length > acc ? row.cells.length : acc;
  16760. }, 0);
  16761. };
  16762. var findElementPos = function (table, element) {
  16763. var rows = table.rows;
  16764. for (var y = 0; y < rows.length; y++) {
  16765. var cells = rows[y].cells;
  16766. for (var x = 0; x < cells.length; x++) {
  16767. if (eq(cells[x], element)) {
  16768. return Optional.some(cellPosition(x, y));
  16769. }
  16770. }
  16771. }
  16772. return Optional.none();
  16773. };
  16774. var extractRows = function (table, sx, sy, ex, ey) {
  16775. var newRows = [];
  16776. var rows = table.rows;
  16777. for (var y = sy; y <= ey; y++) {
  16778. var cells = rows[y].cells;
  16779. var slice = sx < ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
  16780. newRows.push(tableRow(rows[y].element, slice));
  16781. }
  16782. return newRows;
  16783. };
  16784. var subTable = function (table, startPos, endPos) {
  16785. var sx = startPos.x, sy = startPos.y;
  16786. var ex = endPos.x, ey = endPos.y;
  16787. var newRows = sy < ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
  16788. return tableModel(table.element, getWidth(newRows), newRows);
  16789. };
  16790. var createDomTable = function (table, rows) {
  16791. var tableElement = shallow(table.element);
  16792. var tableBody = SugarElement.fromTag('tbody');
  16793. append(tableBody, rows);
  16794. append$1(tableElement, tableBody);
  16795. return tableElement;
  16796. };
  16797. var modelRowsToDomRows = function (table) {
  16798. return map$3(table.rows, function (row) {
  16799. var cells = map$3(row.cells, function (cell) {
  16800. var td = deep$1(cell);
  16801. remove$6(td, 'colspan');
  16802. remove$6(td, 'rowspan');
  16803. return td;
  16804. });
  16805. var tr = shallow(row.element);
  16806. append(tr, cells);
  16807. return tr;
  16808. });
  16809. };
  16810. var fromDom = function (tableElm) {
  16811. var table = tableModel(shallow(tableElm), 0, []);
  16812. each$k(descendants(tableElm, 'tr'), function (tr, y) {
  16813. each$k(descendants(tr, 'td,th'), function (td, x) {
  16814. fillout(table, skipCellsX(table, x, y), y, tr, td);
  16815. });
  16816. });
  16817. return tableModel(table.element, getWidth(table.rows), table.rows);
  16818. };
  16819. var toDom = function (table) {
  16820. return createDomTable(table, modelRowsToDomRows(table));
  16821. };
  16822. var subsection = function (table, startElement, endElement) {
  16823. return findElementPos(table, startElement).bind(function (startPos) {
  16824. return findElementPos(table, endElement).map(function (endPos) {
  16825. return subTable(table, startPos, endPos);
  16826. });
  16827. });
  16828. };
  16829. var findParentListContainer = function (parents) {
  16830. return find$3(parents, function (elm) {
  16831. return name(elm) === 'ul' || name(elm) === 'ol';
  16832. });
  16833. };
  16834. var getFullySelectedListWrappers = function (parents, rng) {
  16835. return find$3(parents, function (elm) {
  16836. return name(elm) === 'li' && hasAllContentsSelected(elm, rng);
  16837. }).fold(constant([]), function (_li) {
  16838. return findParentListContainer(parents).map(function (listCont) {
  16839. var listElm = SugarElement.fromTag(name(listCont));
  16840. var listStyles = filter$3(getAllRaw(listCont), function (_style, name) {
  16841. return startsWith(name, 'list-style');
  16842. });
  16843. setAll(listElm, listStyles);
  16844. return [
  16845. SugarElement.fromTag('li'),
  16846. listElm
  16847. ];
  16848. }).getOr([]);
  16849. });
  16850. };
  16851. var wrap = function (innerElm, elms) {
  16852. var wrapped = foldl(elms, function (acc, elm) {
  16853. append$1(elm, acc);
  16854. return elm;
  16855. }, innerElm);
  16856. return elms.length > 0 ? fromElements([wrapped]) : wrapped;
  16857. };
  16858. var directListWrappers = function (commonAnchorContainer) {
  16859. if (isListItem(commonAnchorContainer)) {
  16860. return parent(commonAnchorContainer).filter(isList).fold(constant([]), function (listElm) {
  16861. return [
  16862. commonAnchorContainer,
  16863. listElm
  16864. ];
  16865. });
  16866. } else {
  16867. return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
  16868. }
  16869. };
  16870. var getWrapElements = function (rootNode, rng) {
  16871. var commonAnchorContainer = SugarElement.fromDom(rng.commonAncestorContainer);
  16872. var parents = parentsAndSelf(commonAnchorContainer, rootNode);
  16873. var wrapElements = filter$4(parents, function (elm) {
  16874. return isInline$1(elm) || isHeading(elm);
  16875. });
  16876. var listWrappers = getFullySelectedListWrappers(parents, rng);
  16877. var allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
  16878. return map$3(allWrappers, shallow);
  16879. };
  16880. var emptyFragment = function () {
  16881. return fromElements([]);
  16882. };
  16883. var getFragmentFromRange = function (rootNode, rng) {
  16884. return wrap(SugarElement.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
  16885. };
  16886. var getParentTable = function (rootElm, cell) {
  16887. return ancestor$2(cell, 'table', curry(eq, rootElm));
  16888. };
  16889. var getTableFragment = function (rootNode, selectedTableCells) {
  16890. return getParentTable(rootNode, selectedTableCells[0]).bind(function (tableElm) {
  16891. var firstCell = selectedTableCells[0];
  16892. var lastCell = selectedTableCells[selectedTableCells.length - 1];
  16893. var fullTableModel = fromDom(tableElm);
  16894. return subsection(fullTableModel, firstCell, lastCell).map(function (sectionedTableModel) {
  16895. return fromElements([toDom(sectionedTableModel)]);
  16896. });
  16897. }).getOrThunk(emptyFragment);
  16898. };
  16899. var getSelectionFragment = function (rootNode, ranges) {
  16900. return ranges.length > 0 && ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
  16901. };
  16902. var read$3 = function (rootNode, ranges) {
  16903. var selectedCells = getCellsFromElementOrRanges(ranges, rootNode);
  16904. return selectedCells.length > 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
  16905. };
  16906. var trimLeadingCollapsibleText = function (text) {
  16907. return text.replace(/^[ \f\n\r\t\v]+/, '');
  16908. };
  16909. var isCollapsibleWhitespace = function (text, index) {
  16910. return index >= 0 && index < text.length && isWhiteSpace(text.charAt(index));
  16911. };
  16912. var getInnerText = function (bin, shouldTrim) {
  16913. var text = trim$2(bin.innerText);
  16914. return shouldTrim ? trimLeadingCollapsibleText(text) : text;
  16915. };
  16916. var getContextNodeName = function (parentBlockOpt) {
  16917. return parentBlockOpt.map(function (block) {
  16918. return block.nodeName;
  16919. }).getOr('div').toLowerCase();
  16920. };
  16921. var getTextContent = function (editor) {
  16922. return Optional.from(editor.selection.getRng()).map(function (rng) {
  16923. var parentBlockOpt = Optional.from(editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock));
  16924. var body = editor.getBody();
  16925. var contextNodeName = getContextNodeName(parentBlockOpt);
  16926. var shouldTrimSpaces = Env.browser.isIE() && contextNodeName !== 'pre';
  16927. var bin = editor.dom.add(body, contextNodeName, {
  16928. 'data-mce-bogus': 'all',
  16929. 'style': 'overflow: hidden; opacity: 0;'
  16930. }, rng.cloneContents());
  16931. var text = getInnerText(bin, shouldTrimSpaces);
  16932. var nonRenderedText = trim$2(bin.textContent);
  16933. editor.dom.remove(bin);
  16934. if (isCollapsibleWhitespace(nonRenderedText, 0) || isCollapsibleWhitespace(nonRenderedText, nonRenderedText.length - 1)) {
  16935. var parentBlock = parentBlockOpt.getOr(body);
  16936. var parentBlockText = getInnerText(parentBlock, shouldTrimSpaces);
  16937. var textIndex = parentBlockText.indexOf(text);
  16938. if (textIndex === -1) {
  16939. return text;
  16940. } else {
  16941. var hasProceedingSpace = isCollapsibleWhitespace(parentBlockText, textIndex - 1);
  16942. var hasTrailingSpace = isCollapsibleWhitespace(parentBlockText, textIndex + text.length);
  16943. return (hasProceedingSpace ? ' ' : '') + text + (hasTrailingSpace ? ' ' : '');
  16944. }
  16945. } else {
  16946. return text;
  16947. }
  16948. }).getOr('');
  16949. };
  16950. var getSerializedContent = function (editor, args) {
  16951. var rng = editor.selection.getRng(), tmpElm = editor.dom.create('body');
  16952. var sel = editor.selection.getSel();
  16953. var ranges = processRanges(editor, getRanges(sel));
  16954. var fragment = args.contextual ? read$3(SugarElement.fromDom(editor.getBody()), ranges).dom : rng.cloneContents();
  16955. if (fragment) {
  16956. tmpElm.appendChild(fragment);
  16957. }
  16958. return editor.selection.serializer.serialize(tmpElm, args);
  16959. };
  16960. var setupArgs$1 = function (args, format) {
  16961. return __assign(__assign({}, args), {
  16962. format: format,
  16963. get: true,
  16964. selection: true
  16965. });
  16966. };
  16967. var getSelectedContentInternal = function (editor, format, args) {
  16968. if (args === void 0) {
  16969. args = {};
  16970. }
  16971. var defaultedArgs = setupArgs$1(args, format);
  16972. var updatedArgs = editor.fire('BeforeGetContent', defaultedArgs);
  16973. if (updatedArgs.isDefaultPrevented()) {
  16974. editor.fire('GetContent', updatedArgs);
  16975. return updatedArgs.content;
  16976. }
  16977. if (updatedArgs.format === 'text') {
  16978. return getTextContent(editor);
  16979. } else {
  16980. updatedArgs.getInner = true;
  16981. var content = getSerializedContent(editor, updatedArgs);
  16982. if (updatedArgs.format === 'tree') {
  16983. return content;
  16984. } else {
  16985. updatedArgs.content = editor.selection.isCollapsed() ? '' : content;
  16986. editor.fire('GetContent', updatedArgs);
  16987. return updatedArgs.content;
  16988. }
  16989. }
  16990. };
  16991. var KEEP = 0, INSERT = 1, DELETE = 2;
  16992. var diff = function (left, right) {
  16993. var size = left.length + right.length + 2;
  16994. var vDown = new Array(size);
  16995. var vUp = new Array(size);
  16996. var snake = function (start, end, diag) {
  16997. return {
  16998. start: start,
  16999. end: end,
  17000. diag: diag
  17001. };
  17002. };
  17003. var buildScript = function (start1, end1, start2, end2, script) {
  17004. var middle = getMiddleSnake(start1, end1, start2, end2);
  17005. if (middle === null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) {
  17006. var i = start1;
  17007. var j = start2;
  17008. while (i < end1 || j < end2) {
  17009. if (i < end1 && j < end2 && left[i] === right[j]) {
  17010. script.push([
  17011. KEEP,
  17012. left[i]
  17013. ]);
  17014. ++i;
  17015. ++j;
  17016. } else {
  17017. if (end1 - start1 > end2 - start2) {
  17018. script.push([
  17019. DELETE,
  17020. left[i]
  17021. ]);
  17022. ++i;
  17023. } else {
  17024. script.push([
  17025. INSERT,
  17026. right[j]
  17027. ]);
  17028. ++j;
  17029. }
  17030. }
  17031. }
  17032. } else {
  17033. buildScript(start1, middle.start, start2, middle.start - middle.diag, script);
  17034. for (var i2 = middle.start; i2 < middle.end; ++i2) {
  17035. script.push([
  17036. KEEP,
  17037. left[i2]
  17038. ]);
  17039. }
  17040. buildScript(middle.end, end1, middle.end - middle.diag, end2, script);
  17041. }
  17042. };
  17043. var buildSnake = function (start, diag, end1, end2) {
  17044. var end = start;
  17045. while (end - diag < end2 && end < end1 && left[end] === right[end - diag]) {
  17046. ++end;
  17047. }
  17048. return snake(start, end, diag);
  17049. };
  17050. var getMiddleSnake = function (start1, end1, start2, end2) {
  17051. var m = end1 - start1;
  17052. var n = end2 - start2;
  17053. if (m === 0 || n === 0) {
  17054. return null;
  17055. }
  17056. var delta = m - n;
  17057. var sum = n + m;
  17058. var offset = (sum % 2 === 0 ? sum : sum + 1) / 2;
  17059. vDown[1 + offset] = start1;
  17060. vUp[1 + offset] = end1 + 1;
  17061. var d, k, i, x, y;
  17062. for (d = 0; d <= offset; ++d) {
  17063. for (k = -d; k <= d; k += 2) {
  17064. i = k + offset;
  17065. if (k === -d || k !== d && vDown[i - 1] < vDown[i + 1]) {
  17066. vDown[i] = vDown[i + 1];
  17067. } else {
  17068. vDown[i] = vDown[i - 1] + 1;
  17069. }
  17070. x = vDown[i];
  17071. y = x - start1 + start2 - k;
  17072. while (x < end1 && y < end2 && left[x] === right[y]) {
  17073. vDown[i] = ++x;
  17074. ++y;
  17075. }
  17076. if (delta % 2 !== 0 && delta - d <= k && k <= delta + d) {
  17077. if (vUp[i - delta] <= vDown[i]) {
  17078. return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2);
  17079. }
  17080. }
  17081. }
  17082. for (k = delta - d; k <= delta + d; k += 2) {
  17083. i = k + offset - delta;
  17084. if (k === delta - d || k !== delta + d && vUp[i + 1] <= vUp[i - 1]) {
  17085. vUp[i] = vUp[i + 1] - 1;
  17086. } else {
  17087. vUp[i] = vUp[i - 1];
  17088. }
  17089. x = vUp[i] - 1;
  17090. y = x - start1 + start2 - k;
  17091. while (x >= start1 && y >= start2 && left[x] === right[y]) {
  17092. vUp[i] = x--;
  17093. y--;
  17094. }
  17095. if (delta % 2 === 0 && -d <= k && k <= d) {
  17096. if (vUp[i] <= vDown[i + delta]) {
  17097. return buildSnake(vUp[i], k + start1 - start2, end1, end2);
  17098. }
  17099. }
  17100. }
  17101. }
  17102. };
  17103. var script = [];
  17104. buildScript(0, left.length, 0, right.length, script);
  17105. return script;
  17106. };
  17107. var getOuterHtml = function (elm) {
  17108. if (isElement$5(elm)) {
  17109. return elm.outerHTML;
  17110. } else if (isText$7(elm)) {
  17111. return Entities.encodeRaw(elm.data, false);
  17112. } else if (isComment(elm)) {
  17113. return '<!--' + elm.data + '-->';
  17114. }
  17115. return '';
  17116. };
  17117. var createFragment = function (html) {
  17118. var node;
  17119. var container = document.createElement('div');
  17120. var frag = document.createDocumentFragment();
  17121. if (html) {
  17122. container.innerHTML = html;
  17123. }
  17124. while (node = container.firstChild) {
  17125. frag.appendChild(node);
  17126. }
  17127. return frag;
  17128. };
  17129. var insertAt = function (elm, html, index) {
  17130. var fragment = createFragment(html);
  17131. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  17132. var target = elm.childNodes[index];
  17133. target.parentNode.insertBefore(fragment, target);
  17134. } else {
  17135. elm.appendChild(fragment);
  17136. }
  17137. };
  17138. var removeAt = function (elm, index) {
  17139. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  17140. var target = elm.childNodes[index];
  17141. target.parentNode.removeChild(target);
  17142. }
  17143. };
  17144. var applyDiff = function (diff, elm) {
  17145. var index = 0;
  17146. each$k(diff, function (action) {
  17147. if (action[0] === KEEP) {
  17148. index++;
  17149. } else if (action[0] === INSERT) {
  17150. insertAt(elm, action[1], index);
  17151. index++;
  17152. } else if (action[0] === DELETE) {
  17153. removeAt(elm, index);
  17154. }
  17155. });
  17156. };
  17157. var read$2 = function (elm) {
  17158. return filter$4(map$3(from(elm.childNodes), getOuterHtml), function (item) {
  17159. return item.length > 0;
  17160. });
  17161. };
  17162. var write = function (fragments, elm) {
  17163. var currentFragments = map$3(from(elm.childNodes), getOuterHtml);
  17164. applyDiff(diff(currentFragments, fragments), elm);
  17165. return elm;
  17166. };
  17167. var lazyTempDocument = cached(function () {
  17168. return document.implementation.createHTMLDocument('undo');
  17169. });
  17170. var hasIframes = function (html) {
  17171. return html.indexOf('</iframe>') !== -1;
  17172. };
  17173. var createFragmentedLevel = function (fragments) {
  17174. return {
  17175. type: 'fragmented',
  17176. fragments: fragments,
  17177. content: '',
  17178. bookmark: null,
  17179. beforeBookmark: null
  17180. };
  17181. };
  17182. var createCompleteLevel = function (content) {
  17183. return {
  17184. type: 'complete',
  17185. fragments: null,
  17186. content: content,
  17187. bookmark: null,
  17188. beforeBookmark: null
  17189. };
  17190. };
  17191. var createFromEditor = function (editor) {
  17192. var fragments = read$2(editor.getBody());
  17193. var trimmedFragments = bind(fragments, function (html) {
  17194. var trimmed = trimInternal(editor.serializer, html);
  17195. return trimmed.length > 0 ? [trimmed] : [];
  17196. });
  17197. var content = trimmedFragments.join('');
  17198. return hasIframes(content) ? createFragmentedLevel(trimmedFragments) : createCompleteLevel(content);
  17199. };
  17200. var applyToEditor = function (editor, level, before) {
  17201. var bookmark = before ? level.beforeBookmark : level.bookmark;
  17202. if (level.type === 'fragmented') {
  17203. write(level.fragments, editor.getBody());
  17204. } else {
  17205. editor.setContent(level.content, {
  17206. format: 'raw',
  17207. no_selection: isNonNullable(bookmark) && isPathBookmark(bookmark) ? !bookmark.isFakeCaret : true
  17208. });
  17209. }
  17210. editor.selection.moveToBookmark(bookmark);
  17211. };
  17212. var getLevelContent = function (level) {
  17213. return level.type === 'fragmented' ? level.fragments.join('') : level.content;
  17214. };
  17215. var getCleanLevelContent = function (level) {
  17216. var elm = SugarElement.fromTag('body', lazyTempDocument());
  17217. set(elm, getLevelContent(level));
  17218. each$k(descendants(elm, '*[data-mce-bogus]'), unwrap);
  17219. return get$3(elm);
  17220. };
  17221. var hasEqualContent = function (level1, level2) {
  17222. return getLevelContent(level1) === getLevelContent(level2);
  17223. };
  17224. var hasEqualCleanedContent = function (level1, level2) {
  17225. return getCleanLevelContent(level1) === getCleanLevelContent(level2);
  17226. };
  17227. var isEq$1 = function (level1, level2) {
  17228. if (!level1 || !level2) {
  17229. return false;
  17230. } else if (hasEqualContent(level1, level2)) {
  17231. return true;
  17232. } else {
  17233. return hasEqualCleanedContent(level1, level2);
  17234. }
  17235. };
  17236. var isUnlocked = function (locks) {
  17237. return locks.get() === 0;
  17238. };
  17239. var setTyping = function (undoManager, typing, locks) {
  17240. if (isUnlocked(locks)) {
  17241. undoManager.typing = typing;
  17242. }
  17243. };
  17244. var endTyping = function (undoManager, locks) {
  17245. if (undoManager.typing) {
  17246. setTyping(undoManager, false, locks);
  17247. undoManager.add();
  17248. }
  17249. };
  17250. var endTypingLevelIgnoreLocks = function (undoManager) {
  17251. if (undoManager.typing) {
  17252. undoManager.typing = false;
  17253. undoManager.add();
  17254. }
  17255. };
  17256. var beforeChange$1 = function (editor, locks, beforeBookmark) {
  17257. if (isUnlocked(locks)) {
  17258. beforeBookmark.set(getUndoBookmark(editor.selection));
  17259. }
  17260. };
  17261. var addUndoLevel$1 = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  17262. var currentLevel = createFromEditor(editor);
  17263. level = level || {};
  17264. level = Tools.extend(level, currentLevel);
  17265. if (isUnlocked(locks) === false || editor.removed) {
  17266. return null;
  17267. }
  17268. var lastLevel = undoManager.data[index.get()];
  17269. if (editor.fire('BeforeAddUndo', {
  17270. level: level,
  17271. lastLevel: lastLevel,
  17272. originalEvent: event
  17273. }).isDefaultPrevented()) {
  17274. return null;
  17275. }
  17276. if (lastLevel && isEq$1(lastLevel, level)) {
  17277. return null;
  17278. }
  17279. if (undoManager.data[index.get()]) {
  17280. beforeBookmark.get().each(function (bm) {
  17281. undoManager.data[index.get()].beforeBookmark = bm;
  17282. });
  17283. }
  17284. var customUndoRedoLevels = getCustomUndoRedoLevels(editor);
  17285. if (customUndoRedoLevels) {
  17286. if (undoManager.data.length > customUndoRedoLevels) {
  17287. for (var i = 0; i < undoManager.data.length - 1; i++) {
  17288. undoManager.data[i] = undoManager.data[i + 1];
  17289. }
  17290. undoManager.data.length--;
  17291. index.set(undoManager.data.length);
  17292. }
  17293. }
  17294. level.bookmark = getUndoBookmark(editor.selection);
  17295. if (index.get() < undoManager.data.length - 1) {
  17296. undoManager.data.length = index.get() + 1;
  17297. }
  17298. undoManager.data.push(level);
  17299. index.set(undoManager.data.length - 1);
  17300. var args = {
  17301. level: level,
  17302. lastLevel: lastLevel,
  17303. originalEvent: event
  17304. };
  17305. if (index.get() > 0) {
  17306. editor.setDirty(true);
  17307. editor.fire('AddUndo', args);
  17308. editor.fire('change', args);
  17309. } else {
  17310. editor.fire('AddUndo', args);
  17311. }
  17312. return level;
  17313. };
  17314. var clear$1 = function (editor, undoManager, index) {
  17315. undoManager.data = [];
  17316. index.set(0);
  17317. undoManager.typing = false;
  17318. editor.fire('ClearUndos');
  17319. };
  17320. var extra$1 = function (editor, undoManager, index, callback1, callback2) {
  17321. if (undoManager.transact(callback1)) {
  17322. var bookmark = undoManager.data[index.get()].bookmark;
  17323. var lastLevel = undoManager.data[index.get() - 1];
  17324. applyToEditor(editor, lastLevel, true);
  17325. if (undoManager.transact(callback2)) {
  17326. undoManager.data[index.get() - 1].beforeBookmark = bookmark;
  17327. }
  17328. }
  17329. };
  17330. var redo$1 = function (editor, index, data) {
  17331. var level;
  17332. if (index.get() < data.length - 1) {
  17333. index.set(index.get() + 1);
  17334. level = data[index.get()];
  17335. applyToEditor(editor, level, false);
  17336. editor.setDirty(true);
  17337. editor.fire('Redo', { level: level });
  17338. }
  17339. return level;
  17340. };
  17341. var undo$1 = function (editor, undoManager, locks, index) {
  17342. var level;
  17343. if (undoManager.typing) {
  17344. undoManager.add();
  17345. undoManager.typing = false;
  17346. setTyping(undoManager, false, locks);
  17347. }
  17348. if (index.get() > 0) {
  17349. index.set(index.get() - 1);
  17350. level = undoManager.data[index.get()];
  17351. applyToEditor(editor, level, true);
  17352. editor.setDirty(true);
  17353. editor.fire('Undo', { level: level });
  17354. }
  17355. return level;
  17356. };
  17357. var reset$1 = function (undoManager) {
  17358. undoManager.clear();
  17359. undoManager.add();
  17360. };
  17361. var hasUndo$1 = function (editor, undoManager, index) {
  17362. return index.get() > 0 || undoManager.typing && undoManager.data[0] && !isEq$1(createFromEditor(editor), undoManager.data[0]);
  17363. };
  17364. var hasRedo$1 = function (undoManager, index) {
  17365. return index.get() < undoManager.data.length - 1 && !undoManager.typing;
  17366. };
  17367. var transact$1 = function (undoManager, locks, callback) {
  17368. endTyping(undoManager, locks);
  17369. undoManager.beforeChange();
  17370. undoManager.ignore(callback);
  17371. return undoManager.add();
  17372. };
  17373. var ignore$1 = function (locks, callback) {
  17374. try {
  17375. locks.set(locks.get() + 1);
  17376. callback();
  17377. } finally {
  17378. locks.set(locks.get() - 1);
  17379. }
  17380. };
  17381. var addVisualInternal = function (editor, elm) {
  17382. var dom = editor.dom;
  17383. var scope = isNonNullable(elm) ? elm : editor.getBody();
  17384. if (isUndefined(editor.hasVisual)) {
  17385. editor.hasVisual = isVisualAidsEnabled(editor);
  17386. }
  17387. each$k(dom.select('table,a', scope), function (matchedElm) {
  17388. switch (matchedElm.nodeName) {
  17389. case 'TABLE':
  17390. var cls = getVisualAidsTableClass(editor);
  17391. var value = dom.getAttrib(matchedElm, 'border');
  17392. if ((!value || value === '0') && editor.hasVisual) {
  17393. dom.addClass(matchedElm, cls);
  17394. } else {
  17395. dom.removeClass(matchedElm, cls);
  17396. }
  17397. break;
  17398. case 'A':
  17399. if (!dom.getAttrib(matchedElm, 'href')) {
  17400. var value_1 = dom.getAttrib(matchedElm, 'name') || matchedElm.id;
  17401. var cls_1 = getVisualAidsAnchorClass(editor);
  17402. if (value_1 && editor.hasVisual) {
  17403. dom.addClass(matchedElm, cls_1);
  17404. } else {
  17405. dom.removeClass(matchedElm, cls_1);
  17406. }
  17407. }
  17408. break;
  17409. }
  17410. });
  17411. editor.fire('VisualAid', {
  17412. element: elm,
  17413. hasVisual: editor.hasVisual
  17414. });
  17415. };
  17416. var makePlainAdaptor = function (editor) {
  17417. return {
  17418. undoManager: {
  17419. beforeChange: function (locks, beforeBookmark) {
  17420. return beforeChange$1(editor, locks, beforeBookmark);
  17421. },
  17422. add: function (undoManager, index, locks, beforeBookmark, level, event) {
  17423. return addUndoLevel$1(editor, undoManager, index, locks, beforeBookmark, level, event);
  17424. },
  17425. undo: function (undoManager, locks, index) {
  17426. return undo$1(editor, undoManager, locks, index);
  17427. },
  17428. redo: function (index, data) {
  17429. return redo$1(editor, index, data);
  17430. },
  17431. clear: function (undoManager, index) {
  17432. return clear$1(editor, undoManager, index);
  17433. },
  17434. reset: function (undoManager) {
  17435. return reset$1(undoManager);
  17436. },
  17437. hasUndo: function (undoManager, index) {
  17438. return hasUndo$1(editor, undoManager, index);
  17439. },
  17440. hasRedo: function (undoManager, index) {
  17441. return hasRedo$1(undoManager, index);
  17442. },
  17443. transact: function (undoManager, locks, callback) {
  17444. return transact$1(undoManager, locks, callback);
  17445. },
  17446. ignore: function (locks, callback) {
  17447. return ignore$1(locks, callback);
  17448. },
  17449. extra: function (undoManager, index, callback1, callback2) {
  17450. return extra$1(editor, undoManager, index, callback1, callback2);
  17451. }
  17452. },
  17453. formatter: {
  17454. match: function (name, vars, node, similar) {
  17455. return match$2(editor, name, vars, node, similar);
  17456. },
  17457. matchAll: function (names, vars) {
  17458. return matchAll(editor, names, vars);
  17459. },
  17460. matchNode: function (node, name, vars, similar) {
  17461. return matchNode(editor, node, name, vars, similar);
  17462. },
  17463. canApply: function (name) {
  17464. return canApply(editor, name);
  17465. },
  17466. closest: function (names) {
  17467. return closest(editor, names);
  17468. },
  17469. apply: function (name, vars, node) {
  17470. return applyFormat$1(editor, name, vars, node);
  17471. },
  17472. remove: function (name, vars, node, similar) {
  17473. return remove$1(editor, name, vars, node, similar);
  17474. },
  17475. toggle: function (name, vars, node) {
  17476. return toggle(editor, name, vars, node);
  17477. },
  17478. formatChanged: function (registeredFormatListeners, formats, callback, similar, vars) {
  17479. return formatChangedInternal(editor, registeredFormatListeners, formats, callback, similar, vars);
  17480. }
  17481. },
  17482. editor: {
  17483. getContent: function (args, format) {
  17484. return getContentInternal(editor, args, format);
  17485. },
  17486. setContent: function (content, args) {
  17487. return setContentInternal(editor, content, args);
  17488. },
  17489. insertContent: function (value, details) {
  17490. return insertHtmlAtCaret(editor, value, details);
  17491. },
  17492. addVisual: function (elm) {
  17493. return addVisualInternal(editor, elm);
  17494. }
  17495. },
  17496. selection: {
  17497. getContent: function (format, args) {
  17498. return getSelectedContentInternal(editor, format, args);
  17499. }
  17500. },
  17501. raw: {
  17502. getModel: function () {
  17503. return Optional.none();
  17504. }
  17505. }
  17506. };
  17507. };
  17508. var makeRtcAdaptor = function (rtcEditor) {
  17509. var defaultVars = function (vars) {
  17510. return isObject(vars) ? vars : {};
  17511. };
  17512. var undoManager = rtcEditor.undoManager, formatter = rtcEditor.formatter, editor = rtcEditor.editor, selection = rtcEditor.selection, raw = rtcEditor.raw;
  17513. return {
  17514. undoManager: {
  17515. beforeChange: undoManager.beforeChange,
  17516. add: undoManager.add,
  17517. undo: undoManager.undo,
  17518. redo: undoManager.redo,
  17519. clear: undoManager.clear,
  17520. reset: undoManager.reset,
  17521. hasUndo: undoManager.hasUndo,
  17522. hasRedo: undoManager.hasRedo,
  17523. transact: function (_undoManager, _locks, fn) {
  17524. return undoManager.transact(fn);
  17525. },
  17526. ignore: function (_locks, callback) {
  17527. return undoManager.ignore(callback);
  17528. },
  17529. extra: function (_undoManager, _index, callback1, callback2) {
  17530. return undoManager.extra(callback1, callback2);
  17531. }
  17532. },
  17533. formatter: {
  17534. match: function (name, vars, _node, similar) {
  17535. return formatter.match(name, defaultVars(vars), similar);
  17536. },
  17537. matchAll: formatter.matchAll,
  17538. matchNode: formatter.matchNode,
  17539. canApply: function (name) {
  17540. return formatter.canApply(name);
  17541. },
  17542. closest: function (names) {
  17543. return formatter.closest(names);
  17544. },
  17545. apply: function (name, vars, _node) {
  17546. return formatter.apply(name, defaultVars(vars));
  17547. },
  17548. remove: function (name, vars, _node, _similar) {
  17549. return formatter.remove(name, defaultVars(vars));
  17550. },
  17551. toggle: function (name, vars, _node) {
  17552. return formatter.toggle(name, defaultVars(vars));
  17553. },
  17554. formatChanged: function (_rfl, formats, callback, similar, vars) {
  17555. return formatter.formatChanged(formats, callback, similar, vars);
  17556. }
  17557. },
  17558. editor: {
  17559. getContent: function (args, _format) {
  17560. return editor.getContent(args);
  17561. },
  17562. setContent: function (content, args) {
  17563. return editor.setContent(content, args);
  17564. },
  17565. insertContent: function (content, _details) {
  17566. return editor.insertContent(content);
  17567. },
  17568. addVisual: editor.addVisual
  17569. },
  17570. selection: {
  17571. getContent: function (_format, args) {
  17572. return selection.getContent(args);
  17573. }
  17574. },
  17575. raw: {
  17576. getModel: function () {
  17577. return Optional.some(raw.getRawModel());
  17578. }
  17579. }
  17580. };
  17581. };
  17582. var makeNoopAdaptor = function () {
  17583. var nul = constant(null);
  17584. var empty = constant('');
  17585. return {
  17586. undoManager: {
  17587. beforeChange: noop,
  17588. add: nul,
  17589. undo: nul,
  17590. redo: nul,
  17591. clear: noop,
  17592. reset: noop,
  17593. hasUndo: never,
  17594. hasRedo: never,
  17595. transact: nul,
  17596. ignore: noop,
  17597. extra: noop
  17598. },
  17599. formatter: {
  17600. match: never,
  17601. matchAll: constant([]),
  17602. matchNode: constant(undefined),
  17603. canApply: never,
  17604. closest: empty,
  17605. apply: noop,
  17606. remove: noop,
  17607. toggle: noop,
  17608. formatChanged: constant({ unbind: noop })
  17609. },
  17610. editor: {
  17611. getContent: empty,
  17612. setContent: empty,
  17613. insertContent: noop,
  17614. addVisual: noop
  17615. },
  17616. selection: { getContent: empty },
  17617. raw: { getModel: constant(Optional.none()) }
  17618. };
  17619. };
  17620. var isRtc = function (editor) {
  17621. return has$2(editor.plugins, 'rtc');
  17622. };
  17623. var getRtcSetup = function (editor) {
  17624. return get$9(editor.plugins, 'rtc').bind(function (rtcPlugin) {
  17625. return Optional.from(rtcPlugin.setup);
  17626. });
  17627. };
  17628. var setup$i = function (editor) {
  17629. var editorCast = editor;
  17630. return getRtcSetup(editor).fold(function () {
  17631. editorCast.rtcInstance = makePlainAdaptor(editor);
  17632. return Optional.none();
  17633. }, function (setup) {
  17634. editorCast.rtcInstance = makeNoopAdaptor();
  17635. return Optional.some(function () {
  17636. return setup().then(function (rtcEditor) {
  17637. editorCast.rtcInstance = makeRtcAdaptor(rtcEditor);
  17638. return rtcEditor.rtc.isRemote;
  17639. });
  17640. });
  17641. });
  17642. };
  17643. var getRtcInstanceWithFallback = function (editor) {
  17644. return editor.rtcInstance ? editor.rtcInstance : makePlainAdaptor(editor);
  17645. };
  17646. var getRtcInstanceWithError = function (editor) {
  17647. var rtcInstance = editor.rtcInstance;
  17648. if (!rtcInstance) {
  17649. throw new Error('Failed to get RTC instance not yet initialized.');
  17650. } else {
  17651. return rtcInstance;
  17652. }
  17653. };
  17654. var beforeChange = function (editor, locks, beforeBookmark) {
  17655. getRtcInstanceWithError(editor).undoManager.beforeChange(locks, beforeBookmark);
  17656. };
  17657. var addUndoLevel = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  17658. return getRtcInstanceWithError(editor).undoManager.add(undoManager, index, locks, beforeBookmark, level, event);
  17659. };
  17660. var undo = function (editor, undoManager, locks, index) {
  17661. return getRtcInstanceWithError(editor).undoManager.undo(undoManager, locks, index);
  17662. };
  17663. var redo = function (editor, index, data) {
  17664. return getRtcInstanceWithError(editor).undoManager.redo(index, data);
  17665. };
  17666. var clear = function (editor, undoManager, index) {
  17667. getRtcInstanceWithError(editor).undoManager.clear(undoManager, index);
  17668. };
  17669. var reset = function (editor, undoManager) {
  17670. getRtcInstanceWithError(editor).undoManager.reset(undoManager);
  17671. };
  17672. var hasUndo = function (editor, undoManager, index) {
  17673. return getRtcInstanceWithError(editor).undoManager.hasUndo(undoManager, index);
  17674. };
  17675. var hasRedo = function (editor, undoManager, index) {
  17676. return getRtcInstanceWithError(editor).undoManager.hasRedo(undoManager, index);
  17677. };
  17678. var transact = function (editor, undoManager, locks, callback) {
  17679. return getRtcInstanceWithError(editor).undoManager.transact(undoManager, locks, callback);
  17680. };
  17681. var ignore = function (editor, locks, callback) {
  17682. getRtcInstanceWithError(editor).undoManager.ignore(locks, callback);
  17683. };
  17684. var extra = function (editor, undoManager, index, callback1, callback2) {
  17685. getRtcInstanceWithError(editor).undoManager.extra(undoManager, index, callback1, callback2);
  17686. };
  17687. var matchFormat = function (editor, name, vars, node, similar) {
  17688. return getRtcInstanceWithError(editor).formatter.match(name, vars, node, similar);
  17689. };
  17690. var matchAllFormats = function (editor, names, vars) {
  17691. return getRtcInstanceWithError(editor).formatter.matchAll(names, vars);
  17692. };
  17693. var matchNodeFormat = function (editor, node, name, vars, similar) {
  17694. return getRtcInstanceWithError(editor).formatter.matchNode(node, name, vars, similar);
  17695. };
  17696. var canApplyFormat = function (editor, name) {
  17697. return getRtcInstanceWithError(editor).formatter.canApply(name);
  17698. };
  17699. var closestFormat = function (editor, names) {
  17700. return getRtcInstanceWithError(editor).formatter.closest(names);
  17701. };
  17702. var applyFormat = function (editor, name, vars, node) {
  17703. getRtcInstanceWithError(editor).formatter.apply(name, vars, node);
  17704. };
  17705. var removeFormat = function (editor, name, vars, node, similar) {
  17706. getRtcInstanceWithError(editor).formatter.remove(name, vars, node, similar);
  17707. };
  17708. var toggleFormat = function (editor, name, vars, node) {
  17709. getRtcInstanceWithError(editor).formatter.toggle(name, vars, node);
  17710. };
  17711. var formatChanged = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  17712. return getRtcInstanceWithError(editor).formatter.formatChanged(registeredFormatListeners, formats, callback, similar, vars);
  17713. };
  17714. var getContent$2 = function (editor, args, format) {
  17715. return getRtcInstanceWithFallback(editor).editor.getContent(args, format);
  17716. };
  17717. var setContent$2 = function (editor, content, args) {
  17718. return getRtcInstanceWithFallback(editor).editor.setContent(content, args);
  17719. };
  17720. var insertContent = function (editor, value, details) {
  17721. return getRtcInstanceWithFallback(editor).editor.insertContent(value, details);
  17722. };
  17723. var getSelectedContent = function (editor, format, args) {
  17724. return getRtcInstanceWithError(editor).selection.getContent(format, args);
  17725. };
  17726. var addVisual$1 = function (editor, elm) {
  17727. return getRtcInstanceWithError(editor).editor.addVisual(elm);
  17728. };
  17729. var getContent$1 = function (editor, args) {
  17730. if (args === void 0) {
  17731. args = {};
  17732. }
  17733. var format = args.format ? args.format : 'html';
  17734. return getSelectedContent(editor, format, args);
  17735. };
  17736. var removeEmpty = function (text) {
  17737. if (text.dom.length === 0) {
  17738. remove$7(text);
  17739. return Optional.none();
  17740. } else {
  17741. return Optional.some(text);
  17742. }
  17743. };
  17744. var walkPastBookmark = function (node, start) {
  17745. return node.filter(function (elm) {
  17746. return BookmarkManager.isBookmarkNode(elm.dom);
  17747. }).bind(start ? nextSibling : prevSibling);
  17748. };
  17749. var merge = function (outer, inner, rng, start) {
  17750. var outerElm = outer.dom;
  17751. var innerElm = inner.dom;
  17752. var oldLength = start ? outerElm.length : innerElm.length;
  17753. if (start) {
  17754. mergeTextNodes(outerElm, innerElm, false, !start);
  17755. rng.setStart(innerElm, oldLength);
  17756. } else {
  17757. mergeTextNodes(innerElm, outerElm, false, !start);
  17758. rng.setEnd(innerElm, oldLength);
  17759. }
  17760. };
  17761. var normalizeTextIfRequired = function (inner, start) {
  17762. parent(inner).each(function (root) {
  17763. var text = inner.dom;
  17764. if (start && needsToBeNbspLeft(root, CaretPosition(text, 0))) {
  17765. normalizeWhitespaceAfter(text, 0);
  17766. } else if (!start && needsToBeNbspRight(root, CaretPosition(text, text.length))) {
  17767. normalizeWhitespaceBefore(text, text.length);
  17768. }
  17769. });
  17770. };
  17771. var mergeAndNormalizeText = function (outerNode, innerNode, rng, start) {
  17772. outerNode.bind(function (outer) {
  17773. var normalizer = start ? normalizeWhitespaceBefore : normalizeWhitespaceAfter;
  17774. normalizer(outer.dom, start ? outer.dom.length : 0);
  17775. return innerNode.filter(isText$8).map(function (inner) {
  17776. return merge(outer, inner, rng, start);
  17777. });
  17778. }).orThunk(function () {
  17779. var innerTextNode = walkPastBookmark(innerNode, start).or(innerNode).filter(isText$8);
  17780. return innerTextNode.map(function (inner) {
  17781. return normalizeTextIfRequired(inner, start);
  17782. });
  17783. });
  17784. };
  17785. var rngSetContent = function (rng, fragment) {
  17786. var firstChild = Optional.from(fragment.firstChild).map(SugarElement.fromDom);
  17787. var lastChild = Optional.from(fragment.lastChild).map(SugarElement.fromDom);
  17788. rng.deleteContents();
  17789. rng.insertNode(fragment);
  17790. var prevText = firstChild.bind(prevSibling).filter(isText$8).bind(removeEmpty);
  17791. var nextText = lastChild.bind(nextSibling).filter(isText$8).bind(removeEmpty);
  17792. mergeAndNormalizeText(prevText, firstChild, rng, true);
  17793. mergeAndNormalizeText(nextText, lastChild, rng, false);
  17794. rng.collapse(false);
  17795. };
  17796. var setupArgs = function (args, content) {
  17797. return __assign(__assign({ format: 'html' }, args), {
  17798. set: true,
  17799. selection: true,
  17800. content: content
  17801. });
  17802. };
  17803. var cleanContent = function (editor, args) {
  17804. if (args.format !== 'raw') {
  17805. var rng = editor.selection.getRng();
  17806. var contextBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
  17807. var contextArgs = contextBlock ? { context: contextBlock.nodeName.toLowerCase() } : {};
  17808. var node = editor.parser.parse(args.content, __assign(__assign({
  17809. isRootContent: true,
  17810. forced_root_block: false
  17811. }, contextArgs), args));
  17812. return HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(node);
  17813. } else {
  17814. return args.content;
  17815. }
  17816. };
  17817. var setContent$1 = function (editor, content, args) {
  17818. if (args === void 0) {
  17819. args = {};
  17820. }
  17821. var defaultedArgs = setupArgs(args, content);
  17822. var updatedArgs = defaultedArgs;
  17823. if (!defaultedArgs.no_events) {
  17824. var eventArgs = editor.fire('BeforeSetContent', defaultedArgs);
  17825. if (eventArgs.isDefaultPrevented()) {
  17826. editor.fire('SetContent', eventArgs);
  17827. return;
  17828. } else {
  17829. updatedArgs = eventArgs;
  17830. }
  17831. }
  17832. updatedArgs.content = cleanContent(editor, updatedArgs);
  17833. var rng = editor.selection.getRng();
  17834. rngSetContent(rng, rng.createContextualFragment(updatedArgs.content));
  17835. editor.selection.setRng(rng);
  17836. scrollRangeIntoView(editor, rng);
  17837. if (!updatedArgs.no_events) {
  17838. editor.fire('SetContent', updatedArgs);
  17839. }
  17840. };
  17841. var deleteFromCallbackMap = function (callbackMap, selector, callback) {
  17842. if (callbackMap && has$2(callbackMap, selector)) {
  17843. var newCallbacks = filter$4(callbackMap[selector], function (cb) {
  17844. return cb !== callback;
  17845. });
  17846. if (newCallbacks.length === 0) {
  17847. delete callbackMap[selector];
  17848. } else {
  17849. callbackMap[selector] = newCallbacks;
  17850. }
  17851. }
  17852. };
  17853. function SelectorChanged (dom, editor) {
  17854. var selectorChangedData;
  17855. var currentSelectors;
  17856. var findMatchingNode = function (selector, nodes) {
  17857. return find$3(nodes, function (node) {
  17858. return dom.is(node, selector);
  17859. });
  17860. };
  17861. var getParents = function (elem) {
  17862. return dom.getParents(elem, null, dom.getRoot());
  17863. };
  17864. return {
  17865. selectorChangedWithUnbind: function (selector, callback) {
  17866. if (!selectorChangedData) {
  17867. selectorChangedData = {};
  17868. currentSelectors = {};
  17869. editor.on('NodeChange', function (e) {
  17870. var node = e.element;
  17871. var parents = getParents(node);
  17872. var matchedSelectors = {};
  17873. Tools.each(selectorChangedData, function (callbacks, selector) {
  17874. findMatchingNode(selector, parents).each(function (node) {
  17875. if (!currentSelectors[selector]) {
  17876. each$k(callbacks, function (callback) {
  17877. callback(true, {
  17878. node: node,
  17879. selector: selector,
  17880. parents: parents
  17881. });
  17882. });
  17883. currentSelectors[selector] = callbacks;
  17884. }
  17885. matchedSelectors[selector] = callbacks;
  17886. });
  17887. });
  17888. Tools.each(currentSelectors, function (callbacks, selector) {
  17889. if (!matchedSelectors[selector]) {
  17890. delete currentSelectors[selector];
  17891. Tools.each(callbacks, function (callback) {
  17892. callback(false, {
  17893. node: node,
  17894. selector: selector,
  17895. parents: parents
  17896. });
  17897. });
  17898. }
  17899. });
  17900. });
  17901. }
  17902. if (!selectorChangedData[selector]) {
  17903. selectorChangedData[selector] = [];
  17904. }
  17905. selectorChangedData[selector].push(callback);
  17906. findMatchingNode(selector, getParents(editor.selection.getStart())).each(function () {
  17907. currentSelectors[selector] = selectorChangedData[selector];
  17908. });
  17909. return {
  17910. unbind: function () {
  17911. deleteFromCallbackMap(selectorChangedData, selector, callback);
  17912. deleteFromCallbackMap(currentSelectors, selector, callback);
  17913. }
  17914. };
  17915. }
  17916. };
  17917. }
  17918. var isNativeIeSelection = function (rng) {
  17919. return !!rng.select;
  17920. };
  17921. var isAttachedToDom = function (node) {
  17922. return !!(node && node.ownerDocument) && contains$1(SugarElement.fromDom(node.ownerDocument), SugarElement.fromDom(node));
  17923. };
  17924. var isValidRange = function (rng) {
  17925. if (!rng) {
  17926. return false;
  17927. } else if (isNativeIeSelection(rng)) {
  17928. return true;
  17929. } else {
  17930. return isAttachedToDom(rng.startContainer) && isAttachedToDom(rng.endContainer);
  17931. }
  17932. };
  17933. var EditorSelection = function (dom, win, serializer, editor) {
  17934. var selectedRange;
  17935. var explicitRange;
  17936. var selectorChangedWithUnbind = SelectorChanged(dom, editor).selectorChangedWithUnbind;
  17937. var setCursorLocation = function (node, offset) {
  17938. var rng = dom.createRng();
  17939. if (isNonNullable(node) && isNonNullable(offset)) {
  17940. rng.setStart(node, offset);
  17941. rng.setEnd(node, offset);
  17942. setRng(rng);
  17943. collapse(false);
  17944. } else {
  17945. moveEndPoint(dom, rng, editor.getBody(), true);
  17946. setRng(rng);
  17947. }
  17948. };
  17949. var getContent = function (args) {
  17950. return getContent$1(editor, args);
  17951. };
  17952. var setContent = function (content, args) {
  17953. return setContent$1(editor, content, args);
  17954. };
  17955. var getStart$1 = function (real) {
  17956. return getStart(editor.getBody(), getRng$1(), real);
  17957. };
  17958. var getEnd$1 = function (real) {
  17959. return getEnd(editor.getBody(), getRng$1(), real);
  17960. };
  17961. var getBookmark = function (type, normalized) {
  17962. return bookmarkManager.getBookmark(type, normalized);
  17963. };
  17964. var moveToBookmark = function (bookmark) {
  17965. return bookmarkManager.moveToBookmark(bookmark);
  17966. };
  17967. var select$1 = function (node, content) {
  17968. select(dom, node, content).each(setRng);
  17969. return node;
  17970. };
  17971. var isCollapsed = function () {
  17972. var rng = getRng$1(), sel = getSel();
  17973. if (!rng || rng.item) {
  17974. return false;
  17975. }
  17976. if (rng.compareEndPoints) {
  17977. return rng.compareEndPoints('StartToEnd', rng) === 0;
  17978. }
  17979. return !sel || rng.collapsed;
  17980. };
  17981. var collapse = function (toStart) {
  17982. var rng = getRng$1();
  17983. rng.collapse(!!toStart);
  17984. setRng(rng);
  17985. };
  17986. var getSel = function () {
  17987. return win.getSelection ? win.getSelection() : win.document.selection;
  17988. };
  17989. var getRng$1 = function () {
  17990. var selection, rng, elm;
  17991. var tryCompareBoundaryPoints = function (how, sourceRange, destinationRange) {
  17992. try {
  17993. return sourceRange.compareBoundaryPoints(how, destinationRange);
  17994. } catch (ex) {
  17995. return -1;
  17996. }
  17997. };
  17998. var doc = win.document;
  17999. if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  18000. var bookmark = getRng(editor);
  18001. if (bookmark.isSome()) {
  18002. return bookmark.map(function (r) {
  18003. return processRanges(editor, [r])[0];
  18004. }).getOr(doc.createRange());
  18005. }
  18006. }
  18007. try {
  18008. if ((selection = getSel()) && !isRestrictedNode(selection.anchorNode)) {
  18009. if (selection.rangeCount > 0) {
  18010. rng = selection.getRangeAt(0);
  18011. } else {
  18012. rng = selection.createRange ? selection.createRange() : doc.createRange();
  18013. }
  18014. rng = processRanges(editor, [rng])[0];
  18015. }
  18016. } catch (ex) {
  18017. }
  18018. if (!rng) {
  18019. rng = doc.createRange ? doc.createRange() : doc.body.createTextRange();
  18020. }
  18021. if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
  18022. elm = dom.getRoot();
  18023. rng.setStart(elm, 0);
  18024. rng.setEnd(elm, 0);
  18025. }
  18026. if (selectedRange && explicitRange) {
  18027. if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 && tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
  18028. rng = explicitRange;
  18029. } else {
  18030. selectedRange = null;
  18031. explicitRange = null;
  18032. }
  18033. }
  18034. return rng;
  18035. };
  18036. var setRng = function (rng, forward) {
  18037. var node;
  18038. if (!isValidRange(rng)) {
  18039. return;
  18040. }
  18041. var ieRange = isNativeIeSelection(rng) ? rng : null;
  18042. if (ieRange) {
  18043. explicitRange = null;
  18044. try {
  18045. ieRange.select();
  18046. } catch (ex) {
  18047. }
  18048. return;
  18049. }
  18050. var sel = getSel();
  18051. var evt = editor.fire('SetSelectionRange', {
  18052. range: rng,
  18053. forward: forward
  18054. });
  18055. rng = evt.range;
  18056. if (sel) {
  18057. explicitRange = rng;
  18058. try {
  18059. sel.removeAllRanges();
  18060. sel.addRange(rng);
  18061. } catch (ex) {
  18062. }
  18063. if (forward === false && sel.extend) {
  18064. sel.collapse(rng.endContainer, rng.endOffset);
  18065. sel.extend(rng.startContainer, rng.startOffset);
  18066. }
  18067. selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
  18068. }
  18069. if (!rng.collapsed && rng.startContainer === rng.endContainer && sel.setBaseAndExtent && !Env.ie) {
  18070. if (rng.endOffset - rng.startOffset < 2) {
  18071. if (rng.startContainer.hasChildNodes()) {
  18072. node = rng.startContainer.childNodes[rng.startOffset];
  18073. if (node && node.tagName === 'IMG') {
  18074. sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
  18075. if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
  18076. sel.setBaseAndExtent(node, 0, node, 1);
  18077. }
  18078. }
  18079. }
  18080. }
  18081. }
  18082. editor.fire('AfterSetSelectionRange', {
  18083. range: rng,
  18084. forward: forward
  18085. });
  18086. };
  18087. var setNode = function (elm) {
  18088. setContent(dom.getOuterHTML(elm));
  18089. return elm;
  18090. };
  18091. var getNode$1 = function () {
  18092. return getNode(editor.getBody(), getRng$1());
  18093. };
  18094. var getSelectedBlocks$1 = function (startElm, endElm) {
  18095. return getSelectedBlocks(dom, getRng$1(), startElm, endElm);
  18096. };
  18097. var isForward = function () {
  18098. var sel = getSel();
  18099. var anchorNode = sel === null || sel === void 0 ? void 0 : sel.anchorNode;
  18100. var focusNode = sel === null || sel === void 0 ? void 0 : sel.focusNode;
  18101. if (!sel || !anchorNode || !focusNode || isRestrictedNode(anchorNode) || isRestrictedNode(focusNode)) {
  18102. return true;
  18103. }
  18104. var anchorRange = dom.createRng();
  18105. anchorRange.setStart(anchorNode, sel.anchorOffset);
  18106. anchorRange.collapse(true);
  18107. var focusRange = dom.createRng();
  18108. focusRange.setStart(focusNode, sel.focusOffset);
  18109. focusRange.collapse(true);
  18110. return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
  18111. };
  18112. var normalize = function () {
  18113. var rng = getRng$1();
  18114. var sel = getSel();
  18115. if (!hasMultipleRanges(sel) && hasAnyRanges(editor)) {
  18116. var normRng = normalize$2(dom, rng);
  18117. normRng.each(function (normRng) {
  18118. setRng(normRng, isForward());
  18119. });
  18120. return normRng.getOr(rng);
  18121. }
  18122. return rng;
  18123. };
  18124. var selectorChanged = function (selector, callback) {
  18125. selectorChangedWithUnbind(selector, callback);
  18126. return exports;
  18127. };
  18128. var getScrollContainer = function () {
  18129. var scrollContainer;
  18130. var node = dom.getRoot();
  18131. while (node && node.nodeName !== 'BODY') {
  18132. if (node.scrollHeight > node.clientHeight) {
  18133. scrollContainer = node;
  18134. break;
  18135. }
  18136. node = node.parentNode;
  18137. }
  18138. return scrollContainer;
  18139. };
  18140. var scrollIntoView = function (elm, alignToTop) {
  18141. if (isNonNullable(elm)) {
  18142. scrollElementIntoView(editor, elm, alignToTop);
  18143. } else {
  18144. scrollRangeIntoView(editor, getRng$1(), alignToTop);
  18145. }
  18146. };
  18147. var placeCaretAt = function (clientX, clientY) {
  18148. return setRng(fromPoint(clientX, clientY, editor.getDoc()));
  18149. };
  18150. var getBoundingClientRect = function () {
  18151. var rng = getRng$1();
  18152. return rng.collapsed ? CaretPosition.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
  18153. };
  18154. var destroy = function () {
  18155. win = selectedRange = explicitRange = null;
  18156. controlSelection.destroy();
  18157. };
  18158. var exports = {
  18159. bookmarkManager: null,
  18160. controlSelection: null,
  18161. dom: dom,
  18162. win: win,
  18163. serializer: serializer,
  18164. editor: editor,
  18165. collapse: collapse,
  18166. setCursorLocation: setCursorLocation,
  18167. getContent: getContent,
  18168. setContent: setContent,
  18169. getBookmark: getBookmark,
  18170. moveToBookmark: moveToBookmark,
  18171. select: select$1,
  18172. isCollapsed: isCollapsed,
  18173. isForward: isForward,
  18174. setNode: setNode,
  18175. getNode: getNode$1,
  18176. getSel: getSel,
  18177. setRng: setRng,
  18178. getRng: getRng$1,
  18179. getStart: getStart$1,
  18180. getEnd: getEnd$1,
  18181. getSelectedBlocks: getSelectedBlocks$1,
  18182. normalize: normalize,
  18183. selectorChanged: selectorChanged,
  18184. selectorChangedWithUnbind: selectorChangedWithUnbind,
  18185. getScrollContainer: getScrollContainer,
  18186. scrollIntoView: scrollIntoView,
  18187. placeCaretAt: placeCaretAt,
  18188. getBoundingClientRect: getBoundingClientRect,
  18189. destroy: destroy
  18190. };
  18191. var bookmarkManager = BookmarkManager(exports);
  18192. var controlSelection = ControlSelection(exports, editor);
  18193. exports.bookmarkManager = bookmarkManager;
  18194. exports.controlSelection = controlSelection;
  18195. return exports;
  18196. };
  18197. var removeAttrs = function (node, names) {
  18198. each$k(names, function (name) {
  18199. node.attr(name, null);
  18200. });
  18201. };
  18202. var addFontToSpansFilter = function (domParser, styles, fontSizes) {
  18203. domParser.addNodeFilter('font', function (nodes) {
  18204. each$k(nodes, function (node) {
  18205. var props = styles.parse(node.attr('style'));
  18206. var color = node.attr('color');
  18207. var face = node.attr('face');
  18208. var size = node.attr('size');
  18209. if (color) {
  18210. props.color = color;
  18211. }
  18212. if (face) {
  18213. props['font-family'] = face;
  18214. }
  18215. if (size) {
  18216. props['font-size'] = fontSizes[parseInt(node.attr('size'), 10) - 1];
  18217. }
  18218. node.name = 'span';
  18219. node.attr('style', styles.serialize(props));
  18220. removeAttrs(node, [
  18221. 'color',
  18222. 'face',
  18223. 'size'
  18224. ]);
  18225. });
  18226. });
  18227. };
  18228. var addStrikeToSpanFilter = function (domParser, styles) {
  18229. domParser.addNodeFilter('strike', function (nodes) {
  18230. each$k(nodes, function (node) {
  18231. var props = styles.parse(node.attr('style'));
  18232. props['text-decoration'] = 'line-through';
  18233. node.name = 'span';
  18234. node.attr('style', styles.serialize(props));
  18235. });
  18236. });
  18237. };
  18238. var addFilters = function (domParser, settings) {
  18239. var styles = Styles();
  18240. if (settings.convert_fonts_to_spans) {
  18241. addFontToSpansFilter(domParser, styles, Tools.explode(settings.font_size_legacy_values));
  18242. }
  18243. addStrikeToSpanFilter(domParser, styles);
  18244. };
  18245. var register$2 = function (domParser, settings) {
  18246. if (settings.inline_styles) {
  18247. addFilters(domParser, settings);
  18248. }
  18249. };
  18250. var blobUriToBlob = function (url) {
  18251. return new promiseObj(function (resolve, reject) {
  18252. var rejectWithError = function () {
  18253. reject('Cannot convert ' + url + ' to Blob. Resource might not exist or is inaccessible.');
  18254. };
  18255. try {
  18256. var xhr_1 = new XMLHttpRequest();
  18257. xhr_1.open('GET', url, true);
  18258. xhr_1.responseType = 'blob';
  18259. xhr_1.onload = function () {
  18260. if (xhr_1.status === 200) {
  18261. resolve(xhr_1.response);
  18262. } else {
  18263. rejectWithError();
  18264. }
  18265. };
  18266. xhr_1.onerror = rejectWithError;
  18267. xhr_1.send();
  18268. } catch (ex) {
  18269. rejectWithError();
  18270. }
  18271. });
  18272. };
  18273. var parseDataUri = function (uri) {
  18274. var type;
  18275. var uriParts = decodeURIComponent(uri).split(',');
  18276. var matches = /data:([^;]+)/.exec(uriParts[0]);
  18277. if (matches) {
  18278. type = matches[1];
  18279. }
  18280. return {
  18281. type: type,
  18282. data: uriParts[1]
  18283. };
  18284. };
  18285. var buildBlob = function (type, data) {
  18286. var str;
  18287. try {
  18288. str = atob(data);
  18289. } catch (e) {
  18290. return Optional.none();
  18291. }
  18292. var arr = new Uint8Array(str.length);
  18293. for (var i = 0; i < arr.length; i++) {
  18294. arr[i] = str.charCodeAt(i);
  18295. }
  18296. return Optional.some(new Blob([arr], { type: type }));
  18297. };
  18298. var dataUriToBlob = function (uri) {
  18299. return new promiseObj(function (resolve) {
  18300. var _a = parseDataUri(uri), type = _a.type, data = _a.data;
  18301. buildBlob(type, data).fold(function () {
  18302. return resolve(new Blob([]));
  18303. }, resolve);
  18304. });
  18305. };
  18306. var uriToBlob = function (url) {
  18307. if (url.indexOf('blob:') === 0) {
  18308. return blobUriToBlob(url);
  18309. }
  18310. if (url.indexOf('data:') === 0) {
  18311. return dataUriToBlob(url);
  18312. }
  18313. return null;
  18314. };
  18315. var blobToDataUri = function (blob) {
  18316. return new promiseObj(function (resolve) {
  18317. var reader = new FileReader();
  18318. reader.onloadend = function () {
  18319. resolve(reader.result);
  18320. };
  18321. reader.readAsDataURL(blob);
  18322. });
  18323. };
  18324. var count$1 = 0;
  18325. var uniqueId = function (prefix) {
  18326. return (prefix || 'blobid') + count$1++;
  18327. };
  18328. var imageToBlobInfo = function (blobCache, img, resolve, reject) {
  18329. var base64, blobInfo;
  18330. if (img.src.indexOf('blob:') === 0) {
  18331. blobInfo = blobCache.getByUri(img.src);
  18332. if (blobInfo) {
  18333. resolve({
  18334. image: img,
  18335. blobInfo: blobInfo
  18336. });
  18337. } else {
  18338. uriToBlob(img.src).then(function (blob) {
  18339. blobToDataUri(blob).then(function (dataUri) {
  18340. base64 = parseDataUri(dataUri).data;
  18341. blobInfo = blobCache.create(uniqueId(), blob, base64);
  18342. blobCache.add(blobInfo);
  18343. resolve({
  18344. image: img,
  18345. blobInfo: blobInfo
  18346. });
  18347. });
  18348. }, function (err) {
  18349. reject(err);
  18350. });
  18351. }
  18352. return;
  18353. }
  18354. var _a = parseDataUri(img.src), data = _a.data, type = _a.type;
  18355. base64 = data;
  18356. blobInfo = blobCache.getByData(base64, type);
  18357. if (blobInfo) {
  18358. resolve({
  18359. image: img,
  18360. blobInfo: blobInfo
  18361. });
  18362. } else {
  18363. uriToBlob(img.src).then(function (blob) {
  18364. blobInfo = blobCache.create(uniqueId(), blob, base64);
  18365. blobCache.add(blobInfo);
  18366. resolve({
  18367. image: img,
  18368. blobInfo: blobInfo
  18369. });
  18370. }, function (err) {
  18371. reject(err);
  18372. });
  18373. }
  18374. };
  18375. var getAllImages = function (elm) {
  18376. return elm ? from(elm.getElementsByTagName('img')) : [];
  18377. };
  18378. var ImageScanner = function (uploadStatus, blobCache) {
  18379. var cachedPromises = {};
  18380. var findAll = function (elm, predicate) {
  18381. if (!predicate) {
  18382. predicate = always;
  18383. }
  18384. var images = filter$4(getAllImages(elm), function (img) {
  18385. var src = img.src;
  18386. if (!Env.fileApi) {
  18387. return false;
  18388. }
  18389. if (img.hasAttribute('data-mce-bogus')) {
  18390. return false;
  18391. }
  18392. if (img.hasAttribute('data-mce-placeholder')) {
  18393. return false;
  18394. }
  18395. if (!src || src === Env.transparentSrc) {
  18396. return false;
  18397. }
  18398. if (src.indexOf('blob:') === 0) {
  18399. return !uploadStatus.isUploaded(src) && predicate(img);
  18400. }
  18401. if (src.indexOf('data:') === 0) {
  18402. return predicate(img);
  18403. }
  18404. return false;
  18405. });
  18406. var promises = map$3(images, function (img) {
  18407. if (cachedPromises[img.src] !== undefined) {
  18408. return new promiseObj(function (resolve) {
  18409. cachedPromises[img.src].then(function (imageInfo) {
  18410. if (typeof imageInfo === 'string') {
  18411. return imageInfo;
  18412. }
  18413. resolve({
  18414. image: img,
  18415. blobInfo: imageInfo.blobInfo
  18416. });
  18417. });
  18418. });
  18419. }
  18420. var newPromise = new promiseObj(function (resolve, reject) {
  18421. imageToBlobInfo(blobCache, img, resolve, reject);
  18422. }).then(function (result) {
  18423. delete cachedPromises[result.image.src];
  18424. return result;
  18425. }).catch(function (error) {
  18426. delete cachedPromises[img.src];
  18427. return error;
  18428. });
  18429. cachedPromises[img.src] = newPromise;
  18430. return newPromise;
  18431. });
  18432. return promiseObj.all(promises);
  18433. };
  18434. return { findAll: findAll };
  18435. };
  18436. var paddEmptyNode = function (settings, args, blockElements, node) {
  18437. var brPreferred = settings.padd_empty_with_br || args.insert;
  18438. if (brPreferred && blockElements[node.name]) {
  18439. node.empty().append(new AstNode('br', 1)).shortEnded = true;
  18440. } else {
  18441. node.empty().append(new AstNode('#text', 3)).value = nbsp;
  18442. }
  18443. };
  18444. var isPaddedWithNbsp = function (node) {
  18445. return hasOnlyChild(node, '#text') && node.firstChild.value === nbsp;
  18446. };
  18447. var hasOnlyChild = function (node, name) {
  18448. return node && node.firstChild && node.firstChild === node.lastChild && node.firstChild.name === name;
  18449. };
  18450. var isPadded = function (schema, node) {
  18451. var rule = schema.getElementRule(node.name);
  18452. return rule && rule.paddEmpty;
  18453. };
  18454. var isEmpty = function (schema, nonEmptyElements, whitespaceElements, node) {
  18455. return node.isEmpty(nonEmptyElements, whitespaceElements, function (node) {
  18456. return isPadded(schema, node);
  18457. });
  18458. };
  18459. var isLineBreakNode = function (node, blockElements) {
  18460. return node && (has$2(blockElements, node.name) || node.name === 'br');
  18461. };
  18462. var isBogusImage = function (img) {
  18463. return isNonNullable(img.attr('data-mce-bogus'));
  18464. };
  18465. var isInternalImageSource = function (img) {
  18466. return img.attr('src') === Env.transparentSrc || isNonNullable(img.attr('data-mce-placeholder'));
  18467. };
  18468. var isValidDataImg = function (img, settings) {
  18469. if (settings.images_dataimg_filter) {
  18470. var imgElem_1 = new Image();
  18471. imgElem_1.src = img.attr('src');
  18472. each$j(img.attributes.map, function (value, key) {
  18473. imgElem_1.setAttribute(key, value);
  18474. });
  18475. return settings.images_dataimg_filter(imgElem_1);
  18476. } else {
  18477. return true;
  18478. }
  18479. };
  18480. var registerBase64ImageFilter = function (parser, settings) {
  18481. var blobCache = settings.blob_cache;
  18482. var processImage = function (img) {
  18483. var inputSrc = img.attr('src');
  18484. if (isInternalImageSource(img) || isBogusImage(img)) {
  18485. return;
  18486. }
  18487. parseDataUri$1(inputSrc).filter(function () {
  18488. return isValidDataImg(img, settings);
  18489. }).bind(function (_a) {
  18490. var type = _a.type, data = _a.data;
  18491. return Optional.from(blobCache.getByData(data, type)).orThunk(function () {
  18492. return buildBlob(type, data).map(function (blob) {
  18493. var blobInfo = blobCache.create(uniqueId(), blob, data);
  18494. blobCache.add(blobInfo);
  18495. return blobInfo;
  18496. });
  18497. });
  18498. }).each(function (blobInfo) {
  18499. img.attr('src', blobInfo.blobUri());
  18500. });
  18501. };
  18502. if (blobCache) {
  18503. parser.addAttributeFilter('src', function (nodes) {
  18504. return each$k(nodes, processImage);
  18505. });
  18506. }
  18507. };
  18508. var register$1 = function (parser, settings) {
  18509. var schema = parser.schema;
  18510. if (settings.remove_trailing_brs) {
  18511. parser.addNodeFilter('br', function (nodes, _, args) {
  18512. var i;
  18513. var l = nodes.length;
  18514. var node;
  18515. var blockElements = Tools.extend({}, schema.getBlockElements());
  18516. var nonEmptyElements = schema.getNonEmptyElements();
  18517. var parent, lastParent, prev, prevName;
  18518. var whiteSpaceElements = schema.getWhiteSpaceElements();
  18519. var elementRule, textNode;
  18520. blockElements.body = 1;
  18521. for (i = 0; i < l; i++) {
  18522. node = nodes[i];
  18523. parent = node.parent;
  18524. if (blockElements[node.parent.name] && node === parent.lastChild) {
  18525. prev = node.prev;
  18526. while (prev) {
  18527. prevName = prev.name;
  18528. if (prevName !== 'span' || prev.attr('data-mce-type') !== 'bookmark') {
  18529. if (prevName === 'br') {
  18530. node = null;
  18531. }
  18532. break;
  18533. }
  18534. prev = prev.prev;
  18535. }
  18536. if (node) {
  18537. node.remove();
  18538. if (isEmpty(schema, nonEmptyElements, whiteSpaceElements, parent)) {
  18539. elementRule = schema.getElementRule(parent.name);
  18540. if (elementRule) {
  18541. if (elementRule.removeEmpty) {
  18542. parent.remove();
  18543. } else if (elementRule.paddEmpty) {
  18544. paddEmptyNode(settings, args, blockElements, parent);
  18545. }
  18546. }
  18547. }
  18548. }
  18549. } else {
  18550. lastParent = node;
  18551. while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) {
  18552. lastParent = parent;
  18553. if (blockElements[parent.name]) {
  18554. break;
  18555. }
  18556. parent = parent.parent;
  18557. }
  18558. if (lastParent === parent && settings.padd_empty_with_br !== true) {
  18559. textNode = new AstNode('#text', 3);
  18560. textNode.value = nbsp;
  18561. node.replace(textNode);
  18562. }
  18563. }
  18564. }
  18565. });
  18566. }
  18567. parser.addAttributeFilter('href', function (nodes) {
  18568. var i = nodes.length;
  18569. var appendRel = function (rel) {
  18570. var parts = rel.split(' ').filter(function (p) {
  18571. return p.length > 0;
  18572. });
  18573. return parts.concat(['noopener']).sort().join(' ');
  18574. };
  18575. var addNoOpener = function (rel) {
  18576. var newRel = rel ? Tools.trim(rel) : '';
  18577. if (!/\b(noopener)\b/g.test(newRel)) {
  18578. return appendRel(newRel);
  18579. } else {
  18580. return newRel;
  18581. }
  18582. };
  18583. if (!settings.allow_unsafe_link_target) {
  18584. while (i--) {
  18585. var node = nodes[i];
  18586. if (node.name === 'a' && node.attr('target') === '_blank') {
  18587. node.attr('rel', addNoOpener(node.attr('rel')));
  18588. }
  18589. }
  18590. }
  18591. });
  18592. if (!settings.allow_html_in_named_anchor) {
  18593. parser.addAttributeFilter('id,name', function (nodes) {
  18594. var i = nodes.length, sibling, prevSibling, parent, node;
  18595. while (i--) {
  18596. node = nodes[i];
  18597. if (node.name === 'a' && node.firstChild && !node.attr('href')) {
  18598. parent = node.parent;
  18599. sibling = node.lastChild;
  18600. do {
  18601. prevSibling = sibling.prev;
  18602. parent.insert(sibling, node);
  18603. sibling = prevSibling;
  18604. } while (sibling);
  18605. }
  18606. }
  18607. });
  18608. }
  18609. if (settings.fix_list_elements) {
  18610. parser.addNodeFilter('ul,ol', function (nodes) {
  18611. var i = nodes.length, node, parentNode;
  18612. while (i--) {
  18613. node = nodes[i];
  18614. parentNode = node.parent;
  18615. if (parentNode.name === 'ul' || parentNode.name === 'ol') {
  18616. if (node.prev && node.prev.name === 'li') {
  18617. node.prev.append(node);
  18618. } else {
  18619. var li = new AstNode('li', 1);
  18620. li.attr('style', 'list-style-type: none');
  18621. node.wrap(li);
  18622. }
  18623. }
  18624. }
  18625. });
  18626. }
  18627. if (settings.validate && schema.getValidClasses()) {
  18628. parser.addAttributeFilter('class', function (nodes) {
  18629. var validClasses = schema.getValidClasses();
  18630. var i = nodes.length;
  18631. while (i--) {
  18632. var node = nodes[i];
  18633. var classList = node.attr('class').split(' ');
  18634. var classValue = '';
  18635. for (var ci = 0; ci < classList.length; ci++) {
  18636. var className = classList[ci];
  18637. var valid = false;
  18638. var validClassesMap = validClasses['*'];
  18639. if (validClassesMap && validClassesMap[className]) {
  18640. valid = true;
  18641. }
  18642. validClassesMap = validClasses[node.name];
  18643. if (!valid && validClassesMap && validClassesMap[className]) {
  18644. valid = true;
  18645. }
  18646. if (valid) {
  18647. if (classValue) {
  18648. classValue += ' ';
  18649. }
  18650. classValue += className;
  18651. }
  18652. }
  18653. if (!classValue.length) {
  18654. classValue = null;
  18655. }
  18656. node.attr('class', classValue);
  18657. }
  18658. });
  18659. }
  18660. registerBase64ImageFilter(parser, settings);
  18661. };
  18662. var makeMap = Tools.makeMap, each$6 = Tools.each, explode$2 = Tools.explode, extend$4 = Tools.extend;
  18663. var DomParser = function (settings, schema) {
  18664. if (schema === void 0) {
  18665. schema = Schema();
  18666. }
  18667. var nodeFilters = {};
  18668. var attributeFilters = [];
  18669. var matchedNodes = {};
  18670. var matchedAttributes = {};
  18671. settings = settings || {};
  18672. settings.validate = 'validate' in settings ? settings.validate : true;
  18673. settings.root_name = settings.root_name || 'body';
  18674. var fixInvalidChildren = function (nodes) {
  18675. var nonSplitableElements = makeMap('tr,td,th,tbody,thead,tfoot,table');
  18676. var nonEmptyElements = schema.getNonEmptyElements();
  18677. var whitespaceElements = schema.getWhiteSpaceElements();
  18678. var textBlockElements = schema.getTextBlockElements();
  18679. var specialElements = schema.getSpecialElements();
  18680. var removeOrUnwrapInvalidNode = function (node, originalNodeParent) {
  18681. if (originalNodeParent === void 0) {
  18682. originalNodeParent = node.parent;
  18683. }
  18684. if (specialElements[node.name]) {
  18685. node.empty().remove();
  18686. } else {
  18687. var children = node.children();
  18688. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  18689. var childNode = children_1[_i];
  18690. if (!schema.isValidChild(originalNodeParent.name, childNode.name)) {
  18691. removeOrUnwrapInvalidNode(childNode, originalNodeParent);
  18692. }
  18693. }
  18694. node.unwrap();
  18695. }
  18696. };
  18697. for (var ni = 0; ni < nodes.length; ni++) {
  18698. var node = nodes[ni];
  18699. var parent_1 = void 0, newParent = void 0, tempNode = void 0;
  18700. if (!node.parent || node.fixed) {
  18701. continue;
  18702. }
  18703. if (textBlockElements[node.name] && node.parent.name === 'li') {
  18704. var sibling = node.next;
  18705. while (sibling) {
  18706. if (textBlockElements[sibling.name]) {
  18707. sibling.name = 'li';
  18708. sibling.fixed = true;
  18709. node.parent.insert(sibling, node.parent);
  18710. } else {
  18711. break;
  18712. }
  18713. sibling = sibling.next;
  18714. }
  18715. node.unwrap();
  18716. continue;
  18717. }
  18718. var parents = [node];
  18719. for (parent_1 = node.parent; parent_1 && !schema.isValidChild(parent_1.name, node.name) && !nonSplitableElements[parent_1.name]; parent_1 = parent_1.parent) {
  18720. parents.push(parent_1);
  18721. }
  18722. if (parent_1 && parents.length > 1) {
  18723. if (schema.isValidChild(parent_1.name, node.name)) {
  18724. parents.reverse();
  18725. newParent = filterNode(parents[0].clone());
  18726. var currentNode = newParent;
  18727. for (var i = 0; i < parents.length - 1; i++) {
  18728. if (schema.isValidChild(currentNode.name, parents[i].name)) {
  18729. tempNode = filterNode(parents[i].clone());
  18730. currentNode.append(tempNode);
  18731. } else {
  18732. tempNode = currentNode;
  18733. }
  18734. for (var childNode = parents[i].firstChild; childNode && childNode !== parents[i + 1];) {
  18735. var nextNode = childNode.next;
  18736. tempNode.append(childNode);
  18737. childNode = nextNode;
  18738. }
  18739. currentNode = tempNode;
  18740. }
  18741. if (!isEmpty(schema, nonEmptyElements, whitespaceElements, newParent)) {
  18742. parent_1.insert(newParent, parents[0], true);
  18743. parent_1.insert(node, newParent);
  18744. } else {
  18745. parent_1.insert(node, parents[0], true);
  18746. }
  18747. parent_1 = parents[0];
  18748. if (isEmpty(schema, nonEmptyElements, whitespaceElements, parent_1) || hasOnlyChild(parent_1, 'br')) {
  18749. parent_1.empty().remove();
  18750. }
  18751. } else {
  18752. removeOrUnwrapInvalidNode(node);
  18753. }
  18754. } else if (node.parent) {
  18755. if (node.name === 'li') {
  18756. var sibling = node.prev;
  18757. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  18758. sibling.append(node);
  18759. continue;
  18760. }
  18761. sibling = node.next;
  18762. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  18763. sibling.insert(node, sibling.firstChild, true);
  18764. continue;
  18765. }
  18766. node.wrap(filterNode(new AstNode('ul', 1)));
  18767. continue;
  18768. }
  18769. if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
  18770. node.wrap(filterNode(new AstNode('div', 1)));
  18771. } else {
  18772. removeOrUnwrapInvalidNode(node);
  18773. }
  18774. }
  18775. }
  18776. };
  18777. var filterNode = function (node) {
  18778. var name = node.name;
  18779. if (name in nodeFilters) {
  18780. var list = matchedNodes[name];
  18781. if (list) {
  18782. list.push(node);
  18783. } else {
  18784. matchedNodes[name] = [node];
  18785. }
  18786. }
  18787. var i = attributeFilters.length;
  18788. while (i--) {
  18789. var attrName = attributeFilters[i].name;
  18790. if (attrName in node.attributes.map) {
  18791. var list = matchedAttributes[attrName];
  18792. if (list) {
  18793. list.push(node);
  18794. } else {
  18795. matchedAttributes[attrName] = [node];
  18796. }
  18797. }
  18798. }
  18799. return node;
  18800. };
  18801. var addNodeFilter = function (name, callback) {
  18802. each$6(explode$2(name), function (name) {
  18803. var list = nodeFilters[name];
  18804. if (!list) {
  18805. nodeFilters[name] = list = [];
  18806. }
  18807. list.push(callback);
  18808. });
  18809. };
  18810. var getNodeFilters = function () {
  18811. var out = [];
  18812. for (var name_1 in nodeFilters) {
  18813. if (has$2(nodeFilters, name_1)) {
  18814. out.push({
  18815. name: name_1,
  18816. callbacks: nodeFilters[name_1]
  18817. });
  18818. }
  18819. }
  18820. return out;
  18821. };
  18822. var addAttributeFilter = function (name, callback) {
  18823. each$6(explode$2(name), function (name) {
  18824. var i;
  18825. for (i = 0; i < attributeFilters.length; i++) {
  18826. if (attributeFilters[i].name === name) {
  18827. attributeFilters[i].callbacks.push(callback);
  18828. return;
  18829. }
  18830. }
  18831. attributeFilters.push({
  18832. name: name,
  18833. callbacks: [callback]
  18834. });
  18835. });
  18836. };
  18837. var getAttributeFilters = function () {
  18838. return [].concat(attributeFilters);
  18839. };
  18840. var parse = function (html, args) {
  18841. var nodes, i, l, fi, fl, list, name;
  18842. var invalidChildren = [];
  18843. var node;
  18844. var getRootBlockName = function (name) {
  18845. if (name === false) {
  18846. return '';
  18847. } else if (name === true) {
  18848. return 'p';
  18849. } else {
  18850. return name;
  18851. }
  18852. };
  18853. args = args || {};
  18854. matchedNodes = {};
  18855. matchedAttributes = {};
  18856. var blockElements = extend$4(makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  18857. var nonEmptyElements = schema.getNonEmptyElements();
  18858. var children = schema.children;
  18859. var validate = settings.validate;
  18860. var forcedRootBlockName = 'forced_root_block' in args ? args.forced_root_block : settings.forced_root_block;
  18861. var rootBlockName = getRootBlockName(forcedRootBlockName);
  18862. var whiteSpaceElements = schema.getWhiteSpaceElements();
  18863. var startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  18864. var endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  18865. var allWhiteSpaceRegExp = /[ \t\r\n]+/g;
  18866. var isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/;
  18867. var isInWhiteSpacePreservedElement = has$2(whiteSpaceElements, args.context) || has$2(whiteSpaceElements, settings.root_name);
  18868. var addRootBlocks = function () {
  18869. var node = rootNode.firstChild, rootBlockNode = null;
  18870. var trim = function (rootBlock) {
  18871. if (rootBlock) {
  18872. node = rootBlock.firstChild;
  18873. if (node && node.type === 3) {
  18874. node.value = node.value.replace(startWhiteSpaceRegExp, '');
  18875. }
  18876. node = rootBlock.lastChild;
  18877. if (node && node.type === 3) {
  18878. node.value = node.value.replace(endWhiteSpaceRegExp, '');
  18879. }
  18880. }
  18881. };
  18882. if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
  18883. return;
  18884. }
  18885. while (node) {
  18886. var next = node.next;
  18887. if (node.type === 3 || node.type === 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type')) {
  18888. if (!rootBlockNode) {
  18889. rootBlockNode = createNode(rootBlockName, 1);
  18890. rootBlockNode.attr(settings.forced_root_block_attrs);
  18891. rootNode.insert(rootBlockNode, node);
  18892. rootBlockNode.append(node);
  18893. } else {
  18894. rootBlockNode.append(node);
  18895. }
  18896. } else {
  18897. trim(rootBlockNode);
  18898. rootBlockNode = null;
  18899. }
  18900. node = next;
  18901. }
  18902. trim(rootBlockNode);
  18903. };
  18904. var createNode = function (name, type) {
  18905. var node = new AstNode(name, type);
  18906. var list;
  18907. if (name in nodeFilters) {
  18908. list = matchedNodes[name];
  18909. if (list) {
  18910. list.push(node);
  18911. } else {
  18912. matchedNodes[name] = [node];
  18913. }
  18914. }
  18915. return node;
  18916. };
  18917. var removeWhitespaceBefore = function (node) {
  18918. var blockElements = schema.getBlockElements();
  18919. for (var textNode = node.prev; textNode && textNode.type === 3;) {
  18920. var textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
  18921. if (textVal.length > 0) {
  18922. textNode.value = textVal;
  18923. return;
  18924. }
  18925. var textNodeNext = textNode.next;
  18926. if (textNodeNext) {
  18927. if (textNodeNext.type === 3 && textNodeNext.value.length) {
  18928. textNode = textNode.prev;
  18929. continue;
  18930. }
  18931. if (!blockElements[textNodeNext.name] && textNodeNext.name !== 'script' && textNodeNext.name !== 'style') {
  18932. textNode = textNode.prev;
  18933. continue;
  18934. }
  18935. }
  18936. var sibling = textNode.prev;
  18937. textNode.remove();
  18938. textNode = sibling;
  18939. }
  18940. };
  18941. var cloneAndExcludeBlocks = function (input) {
  18942. var output = {};
  18943. for (var name_2 in input) {
  18944. if (name_2 !== 'li' && name_2 !== 'p') {
  18945. output[name_2] = input[name_2];
  18946. }
  18947. }
  18948. return output;
  18949. };
  18950. var parser = SaxParser({
  18951. validate: validate,
  18952. document: settings.document,
  18953. allow_html_data_urls: settings.allow_html_data_urls,
  18954. allow_svg_data_urls: settings.allow_svg_data_urls,
  18955. allow_script_urls: settings.allow_script_urls,
  18956. allow_conditional_comments: settings.allow_conditional_comments,
  18957. preserve_cdata: settings.preserve_cdata,
  18958. self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()),
  18959. cdata: function (text) {
  18960. node.append(createNode('#cdata', 4)).value = text;
  18961. },
  18962. text: function (text, raw) {
  18963. var textNode;
  18964. if (!isInWhiteSpacePreservedElement) {
  18965. text = text.replace(allWhiteSpaceRegExp, ' ');
  18966. if (isLineBreakNode(node.lastChild, blockElements)) {
  18967. text = text.replace(startWhiteSpaceRegExp, '');
  18968. }
  18969. }
  18970. if (text.length !== 0) {
  18971. textNode = createNode('#text', 3);
  18972. textNode.raw = !!raw;
  18973. node.append(textNode).value = text;
  18974. }
  18975. },
  18976. comment: function (text) {
  18977. node.append(createNode('#comment', 8)).value = text;
  18978. },
  18979. pi: function (name, text) {
  18980. node.append(createNode(name, 7)).value = text;
  18981. removeWhitespaceBefore(node);
  18982. },
  18983. doctype: function (text) {
  18984. var newNode = node.append(createNode('#doctype', 10));
  18985. newNode.value = text;
  18986. removeWhitespaceBefore(node);
  18987. },
  18988. start: function (name, attrs, empty) {
  18989. var elementRule = validate ? schema.getElementRule(name) : {};
  18990. if (elementRule) {
  18991. var newNode = createNode(elementRule.outputName || name, 1);
  18992. newNode.attributes = attrs;
  18993. newNode.shortEnded = empty;
  18994. node.append(newNode);
  18995. var parent_2 = children[node.name];
  18996. if (parent_2 && children[newNode.name] && !parent_2[newNode.name]) {
  18997. invalidChildren.push(newNode);
  18998. }
  18999. var attrFiltersLen = attributeFilters.length;
  19000. while (attrFiltersLen--) {
  19001. var attrName = attributeFilters[attrFiltersLen].name;
  19002. if (attrName in attrs.map) {
  19003. list = matchedAttributes[attrName];
  19004. if (list) {
  19005. list.push(newNode);
  19006. } else {
  19007. matchedAttributes[attrName] = [newNode];
  19008. }
  19009. }
  19010. }
  19011. if (blockElements[name]) {
  19012. removeWhitespaceBefore(newNode);
  19013. }
  19014. if (!empty) {
  19015. node = newNode;
  19016. }
  19017. if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  19018. isInWhiteSpacePreservedElement = true;
  19019. }
  19020. }
  19021. },
  19022. end: function (name) {
  19023. var textNode, text, sibling, tempNode;
  19024. var elementRule = validate ? schema.getElementRule(name) : {};
  19025. if (elementRule) {
  19026. if (blockElements[name]) {
  19027. if (!isInWhiteSpacePreservedElement) {
  19028. textNode = node.firstChild;
  19029. if (textNode && textNode.type === 3) {
  19030. text = textNode.value.replace(startWhiteSpaceRegExp, '');
  19031. if (text.length > 0) {
  19032. textNode.value = text;
  19033. textNode = textNode.next;
  19034. } else {
  19035. sibling = textNode.next;
  19036. textNode.remove();
  19037. textNode = sibling;
  19038. while (textNode && textNode.type === 3) {
  19039. text = textNode.value;
  19040. sibling = textNode.next;
  19041. if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  19042. textNode.remove();
  19043. textNode = sibling;
  19044. }
  19045. textNode = sibling;
  19046. }
  19047. }
  19048. }
  19049. textNode = node.lastChild;
  19050. if (textNode && textNode.type === 3) {
  19051. text = textNode.value.replace(endWhiteSpaceRegExp, '');
  19052. if (text.length > 0) {
  19053. textNode.value = text;
  19054. textNode = textNode.prev;
  19055. } else {
  19056. sibling = textNode.prev;
  19057. textNode.remove();
  19058. textNode = sibling;
  19059. while (textNode && textNode.type === 3) {
  19060. text = textNode.value;
  19061. sibling = textNode.prev;
  19062. if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  19063. textNode.remove();
  19064. textNode = sibling;
  19065. }
  19066. textNode = sibling;
  19067. }
  19068. }
  19069. }
  19070. }
  19071. }
  19072. if (isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  19073. isInWhiteSpacePreservedElement = false;
  19074. }
  19075. if (elementRule.removeEmpty && isEmpty(schema, nonEmptyElements, whiteSpaceElements, node)) {
  19076. tempNode = node.parent;
  19077. if (blockElements[node.name]) {
  19078. node.empty().remove();
  19079. } else {
  19080. node.unwrap();
  19081. }
  19082. node = tempNode;
  19083. return;
  19084. }
  19085. if (elementRule.paddEmpty && (isPaddedWithNbsp(node) || isEmpty(schema, nonEmptyElements, whiteSpaceElements, node))) {
  19086. paddEmptyNode(settings, args, blockElements, node);
  19087. }
  19088. node = node.parent;
  19089. }
  19090. }
  19091. }, schema);
  19092. var rootNode = node = new AstNode(args.context || settings.root_name, 11);
  19093. parser.parse(html, args.format);
  19094. if (validate && invalidChildren.length) {
  19095. if (!args.context) {
  19096. fixInvalidChildren(invalidChildren);
  19097. } else {
  19098. args.invalid = true;
  19099. }
  19100. }
  19101. if (rootBlockName && (rootNode.name === 'body' || args.isRootContent)) {
  19102. addRootBlocks();
  19103. }
  19104. if (!args.invalid) {
  19105. for (name in matchedNodes) {
  19106. if (!has$2(matchedNodes, name)) {
  19107. continue;
  19108. }
  19109. list = nodeFilters[name];
  19110. nodes = matchedNodes[name];
  19111. fi = nodes.length;
  19112. while (fi--) {
  19113. if (!nodes[fi].parent) {
  19114. nodes.splice(fi, 1);
  19115. }
  19116. }
  19117. for (i = 0, l = list.length; i < l; i++) {
  19118. list[i](nodes, name, args);
  19119. }
  19120. }
  19121. for (i = 0, l = attributeFilters.length; i < l; i++) {
  19122. list = attributeFilters[i];
  19123. if (list.name in matchedAttributes) {
  19124. nodes = matchedAttributes[list.name];
  19125. fi = nodes.length;
  19126. while (fi--) {
  19127. if (!nodes[fi].parent) {
  19128. nodes.splice(fi, 1);
  19129. }
  19130. }
  19131. for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) {
  19132. list.callbacks[fi](nodes, list.name, args);
  19133. }
  19134. }
  19135. }
  19136. }
  19137. return rootNode;
  19138. };
  19139. var exports = {
  19140. schema: schema,
  19141. addAttributeFilter: addAttributeFilter,
  19142. getAttributeFilters: getAttributeFilters,
  19143. addNodeFilter: addNodeFilter,
  19144. getNodeFilters: getNodeFilters,
  19145. filterNode: filterNode,
  19146. parse: parse
  19147. };
  19148. register$1(exports, settings);
  19149. register$2(exports, settings);
  19150. return exports;
  19151. };
  19152. var register = function (htmlParser, settings, dom) {
  19153. htmlParser.addAttributeFilter('data-mce-tabindex', function (nodes, name) {
  19154. var i = nodes.length;
  19155. while (i--) {
  19156. var node = nodes[i];
  19157. node.attr('tabindex', node.attr('data-mce-tabindex'));
  19158. node.attr(name, null);
  19159. }
  19160. });
  19161. htmlParser.addAttributeFilter('src,href,style', function (nodes, name) {
  19162. var internalName = 'data-mce-' + name;
  19163. var urlConverter = settings.url_converter;
  19164. var urlConverterScope = settings.url_converter_scope;
  19165. var i = nodes.length;
  19166. while (i--) {
  19167. var node = nodes[i];
  19168. var value = node.attr(internalName);
  19169. if (value !== undefined) {
  19170. node.attr(name, value.length > 0 ? value : null);
  19171. node.attr(internalName, null);
  19172. } else {
  19173. value = node.attr(name);
  19174. if (name === 'style') {
  19175. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  19176. } else if (urlConverter) {
  19177. value = urlConverter.call(urlConverterScope, value, name, node.name);
  19178. }
  19179. node.attr(name, value.length > 0 ? value : null);
  19180. }
  19181. }
  19182. });
  19183. htmlParser.addAttributeFilter('class', function (nodes) {
  19184. var i = nodes.length;
  19185. while (i--) {
  19186. var node = nodes[i];
  19187. var value = node.attr('class');
  19188. if (value) {
  19189. value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
  19190. node.attr('class', value.length > 0 ? value : null);
  19191. }
  19192. }
  19193. });
  19194. htmlParser.addAttributeFilter('data-mce-type', function (nodes, name, args) {
  19195. var i = nodes.length;
  19196. while (i--) {
  19197. var node = nodes[i];
  19198. if (node.attr('data-mce-type') === 'bookmark' && !args.cleanup) {
  19199. var hasChildren = Optional.from(node.firstChild).exists(function (firstChild) {
  19200. return !isZwsp(firstChild.value);
  19201. });
  19202. if (hasChildren) {
  19203. node.unwrap();
  19204. } else {
  19205. node.remove();
  19206. }
  19207. }
  19208. }
  19209. });
  19210. htmlParser.addNodeFilter('noscript', function (nodes) {
  19211. var i = nodes.length;
  19212. while (i--) {
  19213. var node = nodes[i].firstChild;
  19214. if (node) {
  19215. node.value = Entities.decode(node.value);
  19216. }
  19217. }
  19218. });
  19219. htmlParser.addNodeFilter('script,style', function (nodes, name) {
  19220. var trim = function (value) {
  19221. 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, '');
  19222. };
  19223. var i = nodes.length;
  19224. while (i--) {
  19225. var node = nodes[i];
  19226. var value = node.firstChild ? node.firstChild.value : '';
  19227. if (name === 'script') {
  19228. var type = node.attr('type');
  19229. if (type) {
  19230. node.attr('type', type === 'mce-no/type' ? null : type.replace(/^mce\-/, ''));
  19231. }
  19232. if (settings.element_format === 'xhtml' && value.length > 0) {
  19233. node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
  19234. }
  19235. } else {
  19236. if (settings.element_format === 'xhtml' && value.length > 0) {
  19237. node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
  19238. }
  19239. }
  19240. }
  19241. });
  19242. htmlParser.addNodeFilter('#comment', function (nodes) {
  19243. var i = nodes.length;
  19244. while (i--) {
  19245. var node = nodes[i];
  19246. if (settings.preserve_cdata && node.value.indexOf('[CDATA[') === 0) {
  19247. node.name = '#cdata';
  19248. node.type = 4;
  19249. node.value = dom.decode(node.value.replace(/^\[CDATA\[|\]\]$/g, ''));
  19250. } else if (node.value.indexOf('mce:protected ') === 0) {
  19251. node.name = '#text';
  19252. node.type = 3;
  19253. node.raw = true;
  19254. node.value = unescape(node.value).substr(14);
  19255. }
  19256. }
  19257. });
  19258. htmlParser.addNodeFilter('xml:namespace,input', function (nodes, name) {
  19259. var i = nodes.length;
  19260. while (i--) {
  19261. var node = nodes[i];
  19262. if (node.type === 7) {
  19263. node.remove();
  19264. } else if (node.type === 1) {
  19265. if (name === 'input' && !node.attr('type')) {
  19266. node.attr('type', 'text');
  19267. }
  19268. }
  19269. }
  19270. });
  19271. htmlParser.addAttributeFilter('data-mce-type', function (nodes) {
  19272. each$k(nodes, function (node) {
  19273. if (node.attr('data-mce-type') === 'format-caret') {
  19274. if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
  19275. node.remove();
  19276. } else {
  19277. node.unwrap();
  19278. }
  19279. }
  19280. });
  19281. });
  19282. 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) {
  19283. var i = nodes.length;
  19284. while (i--) {
  19285. nodes[i].attr(name, null);
  19286. }
  19287. });
  19288. };
  19289. var trimTrailingBr = function (rootNode) {
  19290. var isBr = function (node) {
  19291. return node && node.name === 'br';
  19292. };
  19293. var brNode1 = rootNode.lastChild;
  19294. if (isBr(brNode1)) {
  19295. var brNode2 = brNode1.prev;
  19296. if (isBr(brNode2)) {
  19297. brNode1.remove();
  19298. brNode2.remove();
  19299. }
  19300. }
  19301. };
  19302. var preProcess = function (editor, node, args) {
  19303. var oldDoc;
  19304. var dom = editor.dom;
  19305. var clonedNode = node.cloneNode(true);
  19306. var impl = document.implementation;
  19307. if (impl.createHTMLDocument) {
  19308. var doc_1 = impl.createHTMLDocument('');
  19309. Tools.each(clonedNode.nodeName === 'BODY' ? clonedNode.childNodes : [clonedNode], function (node) {
  19310. doc_1.body.appendChild(doc_1.importNode(node, true));
  19311. });
  19312. if (clonedNode.nodeName !== 'BODY') {
  19313. clonedNode = doc_1.body.firstChild;
  19314. } else {
  19315. clonedNode = doc_1.body;
  19316. }
  19317. oldDoc = dom.doc;
  19318. dom.doc = doc_1;
  19319. }
  19320. firePreProcess(editor, __assign(__assign({}, args), { node: clonedNode }));
  19321. if (oldDoc) {
  19322. dom.doc = oldDoc;
  19323. }
  19324. return clonedNode;
  19325. };
  19326. var shouldFireEvent = function (editor, args) {
  19327. return editor && editor.hasEventListeners('PreProcess') && !args.no_events;
  19328. };
  19329. var process = function (editor, node, args) {
  19330. return shouldFireEvent(editor, args) ? preProcess(editor, node, args) : node;
  19331. };
  19332. var addTempAttr = function (htmlParser, tempAttrs, name) {
  19333. if (Tools.inArray(tempAttrs, name) === -1) {
  19334. htmlParser.addAttributeFilter(name, function (nodes, name) {
  19335. var i = nodes.length;
  19336. while (i--) {
  19337. nodes[i].attr(name, null);
  19338. }
  19339. });
  19340. tempAttrs.push(name);
  19341. }
  19342. };
  19343. var postProcess = function (editor, args, content) {
  19344. if (!args.no_events && editor) {
  19345. var outArgs = firePostProcess(editor, __assign(__assign({}, args), { content: content }));
  19346. return outArgs.content;
  19347. } else {
  19348. return content;
  19349. }
  19350. };
  19351. var getHtmlFromNode = function (dom, node, args) {
  19352. var html = trim$2(args.getInner ? node.innerHTML : dom.getOuterHTML(node));
  19353. return args.selection || isWsPreserveElement(SugarElement.fromDom(node)) ? html : Tools.trim(html);
  19354. };
  19355. var parseHtml = function (htmlParser, html, args) {
  19356. var parserArgs = args.selection ? __assign({ forced_root_block: false }, args) : args;
  19357. var rootNode = htmlParser.parse(html, parserArgs);
  19358. trimTrailingBr(rootNode);
  19359. return rootNode;
  19360. };
  19361. var serializeNode = function (settings, schema, node) {
  19362. var htmlSerializer = HtmlSerializer(settings, schema);
  19363. return htmlSerializer.serialize(node);
  19364. };
  19365. var toHtml = function (editor, settings, schema, rootNode, args) {
  19366. var content = serializeNode(settings, schema, rootNode);
  19367. return postProcess(editor, args, content);
  19368. };
  19369. var DomSerializerImpl = function (settings, editor) {
  19370. var tempAttrs = ['data-mce-selected'];
  19371. var dom = editor && editor.dom ? editor.dom : DOMUtils.DOM;
  19372. var schema = editor && editor.schema ? editor.schema : Schema(settings);
  19373. settings.entity_encoding = settings.entity_encoding || 'named';
  19374. settings.remove_trailing_brs = 'remove_trailing_brs' in settings ? settings.remove_trailing_brs : true;
  19375. var htmlParser = DomParser(settings, schema);
  19376. register(htmlParser, settings, dom);
  19377. var serialize = function (node, parserArgs) {
  19378. if (parserArgs === void 0) {
  19379. parserArgs = {};
  19380. }
  19381. var args = __assign({ format: 'html' }, parserArgs);
  19382. var targetNode = process(editor, node, args);
  19383. var html = getHtmlFromNode(dom, targetNode, args);
  19384. var rootNode = parseHtml(htmlParser, html, args);
  19385. return args.format === 'tree' ? rootNode : toHtml(editor, settings, schema, rootNode, args);
  19386. };
  19387. return {
  19388. schema: schema,
  19389. addNodeFilter: htmlParser.addNodeFilter,
  19390. addAttributeFilter: htmlParser.addAttributeFilter,
  19391. serialize: serialize,
  19392. addRules: schema.addValidElements,
  19393. setRules: schema.setValidElements,
  19394. addTempAttr: curry(addTempAttr, htmlParser, tempAttrs),
  19395. getTempAttrs: constant(tempAttrs),
  19396. getNodeFilters: htmlParser.getNodeFilters,
  19397. getAttributeFilters: htmlParser.getAttributeFilters
  19398. };
  19399. };
  19400. var DomSerializer = function (settings, editor) {
  19401. var domSerializer = DomSerializerImpl(settings, editor);
  19402. return {
  19403. schema: domSerializer.schema,
  19404. addNodeFilter: domSerializer.addNodeFilter,
  19405. addAttributeFilter: domSerializer.addAttributeFilter,
  19406. serialize: domSerializer.serialize,
  19407. addRules: domSerializer.addRules,
  19408. setRules: domSerializer.setRules,
  19409. addTempAttr: domSerializer.addTempAttr,
  19410. getTempAttrs: domSerializer.getTempAttrs,
  19411. getNodeFilters: domSerializer.getNodeFilters,
  19412. getAttributeFilters: domSerializer.getAttributeFilters
  19413. };
  19414. };
  19415. var defaultFormat = 'html';
  19416. var getContent = function (editor, args) {
  19417. if (args === void 0) {
  19418. args = {};
  19419. }
  19420. var format = args.format ? args.format : defaultFormat;
  19421. return getContent$2(editor, args, format);
  19422. };
  19423. var setContent = function (editor, content, args) {
  19424. if (args === void 0) {
  19425. args = {};
  19426. }
  19427. return setContent$2(editor, content, args);
  19428. };
  19429. var DOM$7 = DOMUtils.DOM;
  19430. var restoreOriginalStyles = function (editor) {
  19431. DOM$7.setStyle(editor.id, 'display', editor.orgDisplay);
  19432. };
  19433. var safeDestroy = function (x) {
  19434. return Optional.from(x).each(function (x) {
  19435. return x.destroy();
  19436. });
  19437. };
  19438. var clearDomReferences = function (editor) {
  19439. editor.contentAreaContainer = editor.formElement = editor.container = editor.editorContainer = null;
  19440. editor.bodyElement = editor.contentDocument = editor.contentWindow = null;
  19441. editor.iframeElement = editor.targetElm = null;
  19442. if (editor.selection) {
  19443. editor.selection = editor.selection.win = editor.selection.dom = editor.selection.dom.doc = null;
  19444. }
  19445. };
  19446. var restoreForm = function (editor) {
  19447. var form = editor.formElement;
  19448. if (form) {
  19449. if (form._mceOldSubmit) {
  19450. form.submit = form._mceOldSubmit;
  19451. form._mceOldSubmit = null;
  19452. }
  19453. DOM$7.unbind(form, 'submit reset', editor.formEventDelegate);
  19454. }
  19455. };
  19456. var remove = function (editor) {
  19457. if (!editor.removed) {
  19458. var _selectionOverrides = editor._selectionOverrides, editorUpload = editor.editorUpload;
  19459. var body = editor.getBody();
  19460. var element = editor.getElement();
  19461. if (body) {
  19462. editor.save({ is_removing: true });
  19463. }
  19464. editor.removed = true;
  19465. editor.unbindAllNativeEvents();
  19466. if (editor.hasHiddenInput && element) {
  19467. DOM$7.remove(element.nextSibling);
  19468. }
  19469. fireRemove(editor);
  19470. editor.editorManager.remove(editor);
  19471. if (!editor.inline && body) {
  19472. restoreOriginalStyles(editor);
  19473. }
  19474. fireDetach(editor);
  19475. DOM$7.remove(editor.getContainer());
  19476. safeDestroy(_selectionOverrides);
  19477. safeDestroy(editorUpload);
  19478. editor.destroy();
  19479. }
  19480. };
  19481. var destroy = function (editor, automatic) {
  19482. var selection = editor.selection, dom = editor.dom;
  19483. if (editor.destroyed) {
  19484. return;
  19485. }
  19486. if (!automatic && !editor.removed) {
  19487. editor.remove();
  19488. return;
  19489. }
  19490. if (!automatic) {
  19491. editor.editorManager.off('beforeunload', editor._beforeUnload);
  19492. if (editor.theme && editor.theme.destroy) {
  19493. editor.theme.destroy();
  19494. }
  19495. safeDestroy(selection);
  19496. safeDestroy(dom);
  19497. }
  19498. restoreForm(editor);
  19499. clearDomReferences(editor);
  19500. editor.destroyed = true;
  19501. };
  19502. var deep = function (old, nu) {
  19503. var bothObjects = isObject(old) && isObject(nu);
  19504. return bothObjects ? deepMerge(old, nu) : nu;
  19505. };
  19506. var baseMerge = function (merger) {
  19507. return function () {
  19508. var objects = [];
  19509. for (var _i = 0; _i < arguments.length; _i++) {
  19510. objects[_i] = arguments[_i];
  19511. }
  19512. if (objects.length === 0) {
  19513. throw new Error('Can\'t merge zero objects');
  19514. }
  19515. var ret = {};
  19516. for (var j = 0; j < objects.length; j++) {
  19517. var curObject = objects[j];
  19518. for (var key in curObject) {
  19519. if (has$2(curObject, key)) {
  19520. ret[key] = merger(ret[key], curObject[key]);
  19521. }
  19522. }
  19523. }
  19524. return ret;
  19525. };
  19526. };
  19527. var deepMerge = baseMerge(deep);
  19528. var deprecatedSettings = ('autoresize_on_init,content_editable_state,convert_fonts_to_spans,inline_styles,padd_empty_with_br,block_elements,' + 'boolean_attributes,editor_deselector,editor_selector,elements,file_browser_callback_types,filepicker_validator_handler,' + 'force_hex_style_colors,force_p_newlines,gecko_spellcheck,images_dataimg_filter,media_scripts,mode,move_caret_before_on_enter_elements,' + 'non_empty_elements,self_closing_elements,short_ended_elements,special,spellchecker_select_languages,spellchecker_whitelist,' + 'tab_focus,table_responsive_width,text_block_elements,text_inline_elements,toolbar_drawer,types,validate,whitespace_elements,' + 'paste_word_valid_elements,paste_retain_style_properties,paste_convert_word_fake_lists').split(',');
  19529. var deprecatedPlugins = 'bbcode,colorpicker,contextmenu,fullpage,legacyoutput,spellchecker,textcolor'.split(',');
  19530. var movedToPremiumPlugins = 'imagetools,toc'.split(',');
  19531. var getDeprecatedSettings = function (settings) {
  19532. var settingNames = filter$4(deprecatedSettings, function (setting) {
  19533. return has$2(settings, setting);
  19534. });
  19535. var forcedRootBlock = settings.forced_root_block;
  19536. if (forcedRootBlock === false || forcedRootBlock === '') {
  19537. settingNames.push('forced_root_block (false only)');
  19538. }
  19539. return sort(settingNames);
  19540. };
  19541. var getDeprecatedPlugins = function (settings) {
  19542. var plugins = Tools.makeMap(settings.plugins, ' ');
  19543. var hasPlugin = function (plugin) {
  19544. return has$2(plugins, plugin);
  19545. };
  19546. var pluginNames = __spreadArray(__spreadArray([], filter$4(deprecatedPlugins, hasPlugin), true), bind(movedToPremiumPlugins, function (plugin) {
  19547. return hasPlugin(plugin) ? [plugin + ' (moving to premium)'] : [];
  19548. }), true);
  19549. return sort(pluginNames);
  19550. };
  19551. var logDeprecationsWarning = function (rawSettings, finalSettings) {
  19552. var deprecatedSettings = getDeprecatedSettings(rawSettings);
  19553. var deprecatedPlugins = getDeprecatedPlugins(finalSettings);
  19554. var hasDeprecatedPlugins = deprecatedPlugins.length > 0;
  19555. var hasDeprecatedSettings = deprecatedSettings.length > 0;
  19556. var isLegacyMobileTheme = finalSettings.theme === 'mobile';
  19557. if (hasDeprecatedPlugins || hasDeprecatedSettings || isLegacyMobileTheme) {
  19558. var listJoiner = '\n- ';
  19559. var themesMessage = isLegacyMobileTheme ? '\n\nThemes:' + listJoiner + 'mobile' : '';
  19560. var pluginsMessage = hasDeprecatedPlugins ? '\n\nPlugins:' + listJoiner + deprecatedPlugins.join(listJoiner) : '';
  19561. var settingsMessage = hasDeprecatedSettings ? '\n\nSettings:' + listJoiner + deprecatedSettings.join(listJoiner) : '';
  19562. console.warn('The following deprecated features are currently enabled, these will be removed in TinyMCE 6.0. ' + 'See https://www.tiny.cloud/docs/release-notes/6.0-upcoming-changes/ for more information.' + themesMessage + pluginsMessage + settingsMessage);
  19563. }
  19564. };
  19565. var sectionResult = function (sections, settings) {
  19566. return {
  19567. sections: constant(sections),
  19568. settings: constant(settings)
  19569. };
  19570. };
  19571. var deviceDetection = detect().deviceType;
  19572. var isTouch = deviceDetection.isTouch();
  19573. var isPhone = deviceDetection.isPhone();
  19574. var isTablet = deviceDetection.isTablet();
  19575. var legacyMobilePlugins = [
  19576. 'lists',
  19577. 'autolink',
  19578. 'autosave'
  19579. ];
  19580. var defaultTouchSettings = {
  19581. table_grid: false,
  19582. object_resizing: false,
  19583. resize: false
  19584. };
  19585. var normalizePlugins = function (plugins) {
  19586. var pluginNames = isArray$1(plugins) ? plugins.join(' ') : plugins;
  19587. var trimmedPlugins = map$3(isString$1(pluginNames) ? pluginNames.split(' ') : [], trim$4);
  19588. return filter$4(trimmedPlugins, function (item) {
  19589. return item.length > 0;
  19590. });
  19591. };
  19592. var filterLegacyMobilePlugins = function (plugins) {
  19593. return filter$4(plugins, curry(contains$3, legacyMobilePlugins));
  19594. };
  19595. var extractSections = function (keys, settings) {
  19596. var result = bifilter(settings, function (value, key) {
  19597. return contains$3(keys, key);
  19598. });
  19599. return sectionResult(result.t, result.f);
  19600. };
  19601. var getSection = function (sectionResult, name, defaults) {
  19602. if (defaults === void 0) {
  19603. defaults = {};
  19604. }
  19605. var sections = sectionResult.sections();
  19606. var sectionSettings = get$9(sections, name).getOr({});
  19607. return Tools.extend({}, defaults, sectionSettings);
  19608. };
  19609. var hasSection = function (sectionResult, name) {
  19610. return has$2(sectionResult.sections(), name);
  19611. };
  19612. var isSectionTheme = function (sectionResult, name, theme) {
  19613. var section = sectionResult.sections();
  19614. return hasSection(sectionResult, name) && section[name].theme === theme;
  19615. };
  19616. var getSectionConfig = function (sectionResult, name) {
  19617. return hasSection(sectionResult, name) ? sectionResult.sections()[name] : {};
  19618. };
  19619. var getToolbarMode = function (settings, defaultVal) {
  19620. return get$9(settings, 'toolbar_mode').orThunk(function () {
  19621. return get$9(settings, 'toolbar_drawer').map(function (val) {
  19622. return val === false ? 'wrap' : val;
  19623. });
  19624. }).getOr(defaultVal);
  19625. };
  19626. var getDefaultSettings = function (settings, id, documentBaseUrl, isTouch, editor) {
  19627. var baseDefaults = {
  19628. id: id,
  19629. theme: 'silver',
  19630. toolbar_mode: getToolbarMode(settings, 'floating'),
  19631. plugins: '',
  19632. document_base_url: documentBaseUrl,
  19633. add_form_submit_trigger: true,
  19634. submit_patch: true,
  19635. add_unload_trigger: true,
  19636. convert_urls: true,
  19637. relative_urls: true,
  19638. remove_script_host: true,
  19639. object_resizing: true,
  19640. doctype: '<!DOCTYPE html>',
  19641. visual: true,
  19642. font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%',
  19643. forced_root_block: 'p',
  19644. hidden_input: true,
  19645. inline_styles: true,
  19646. convert_fonts_to_spans: true,
  19647. indent: true,
  19648. 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',
  19649. 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',
  19650. entity_encoding: 'named',
  19651. url_converter: editor.convertURL,
  19652. url_converter_scope: editor
  19653. };
  19654. return __assign(__assign({}, baseDefaults), isTouch ? defaultTouchSettings : {});
  19655. };
  19656. var getDefaultMobileSettings = function (mobileSettings, isPhone) {
  19657. var defaultMobileSettings = {
  19658. resize: false,
  19659. toolbar_mode: getToolbarMode(mobileSettings, 'scrolling'),
  19660. toolbar_sticky: false
  19661. };
  19662. var defaultPhoneSettings = { menubar: false };
  19663. return __assign(__assign(__assign({}, defaultTouchSettings), defaultMobileSettings), isPhone ? defaultPhoneSettings : {});
  19664. };
  19665. var getExternalPlugins = function (overrideSettings, settings) {
  19666. var userDefinedExternalPlugins = settings.external_plugins ? settings.external_plugins : {};
  19667. if (overrideSettings && overrideSettings.external_plugins) {
  19668. return Tools.extend({}, overrideSettings.external_plugins, userDefinedExternalPlugins);
  19669. } else {
  19670. return userDefinedExternalPlugins;
  19671. }
  19672. };
  19673. var combinePlugins = function (forcedPlugins, plugins) {
  19674. return [].concat(normalizePlugins(forcedPlugins)).concat(normalizePlugins(plugins));
  19675. };
  19676. var getPlatformPlugins = function (isMobileDevice, sectionResult, desktopPlugins, mobilePlugins) {
  19677. if (isMobileDevice && isSectionTheme(sectionResult, 'mobile', 'mobile')) {
  19678. return filterLegacyMobilePlugins(mobilePlugins);
  19679. } else if (isMobileDevice && hasSection(sectionResult, 'mobile')) {
  19680. return mobilePlugins;
  19681. } else {
  19682. return desktopPlugins;
  19683. }
  19684. };
  19685. var processPlugins = function (isMobileDevice, sectionResult, defaultOverrideSettings, settings) {
  19686. var forcedPlugins = normalizePlugins(defaultOverrideSettings.forced_plugins);
  19687. var desktopPlugins = normalizePlugins(settings.plugins);
  19688. var mobileConfig = getSectionConfig(sectionResult, 'mobile');
  19689. var mobilePlugins = mobileConfig.plugins ? normalizePlugins(mobileConfig.plugins) : desktopPlugins;
  19690. var platformPlugins = getPlatformPlugins(isMobileDevice, sectionResult, desktopPlugins, mobilePlugins);
  19691. var combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
  19692. if (Env.browser.isIE() && contains$3(combinedPlugins, 'rtc')) {
  19693. throw new Error('RTC plugin is not supported on IE 11.');
  19694. }
  19695. return Tools.extend(settings, { plugins: combinedPlugins.join(' ') });
  19696. };
  19697. var isOnMobile = function (isMobileDevice, sectionResult) {
  19698. return isMobileDevice && hasSection(sectionResult, 'mobile');
  19699. };
  19700. var combineSettings = function (isMobileDevice, isPhone, defaultSettings, defaultOverrideSettings, settings) {
  19701. var defaultDeviceSettings = isMobileDevice ? { mobile: getDefaultMobileSettings(settings.mobile || {}, isPhone) } : {};
  19702. var sectionResult = extractSections(['mobile'], deepMerge(defaultDeviceSettings, settings));
  19703. var extendedSettings = Tools.extend(defaultSettings, defaultOverrideSettings, sectionResult.settings(), isOnMobile(isMobileDevice, sectionResult) ? getSection(sectionResult, 'mobile') : {}, {
  19704. validate: true,
  19705. external_plugins: getExternalPlugins(defaultOverrideSettings, sectionResult.settings())
  19706. });
  19707. return processPlugins(isMobileDevice, sectionResult, defaultOverrideSettings, extendedSettings);
  19708. };
  19709. var getEditorSettings = function (editor, id, documentBaseUrl, defaultOverrideSettings, settings) {
  19710. var defaultSettings = getDefaultSettings(settings, id, documentBaseUrl, isTouch, editor);
  19711. var finalSettings = combineSettings(isPhone || isTablet, isPhone, defaultSettings, defaultOverrideSettings, settings);
  19712. if (finalSettings.deprecation_warnings !== false) {
  19713. logDeprecationsWarning(settings, finalSettings);
  19714. }
  19715. return finalSettings;
  19716. };
  19717. var getFiltered = function (predicate, editor, name) {
  19718. return Optional.from(editor.settings[name]).filter(predicate);
  19719. };
  19720. var getParamObject = function (value) {
  19721. var output = {};
  19722. if (typeof value === 'string') {
  19723. each$k(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function (val) {
  19724. var arr = val.split('=');
  19725. if (arr.length > 1) {
  19726. output[Tools.trim(arr[0])] = Tools.trim(arr[1]);
  19727. } else {
  19728. output[Tools.trim(arr[0])] = Tools.trim(arr[0]);
  19729. }
  19730. });
  19731. } else {
  19732. output = value;
  19733. }
  19734. return output;
  19735. };
  19736. var isArrayOf = function (p) {
  19737. return function (a) {
  19738. return isArray$1(a) && forall(a, p);
  19739. };
  19740. };
  19741. var getParam = function (editor, name, defaultVal, type) {
  19742. var value = name in editor.settings ? editor.settings[name] : defaultVal;
  19743. if (type === 'hash') {
  19744. return getParamObject(value);
  19745. } else if (type === 'string') {
  19746. return getFiltered(isString$1, editor, name).getOr(defaultVal);
  19747. } else if (type === 'number') {
  19748. return getFiltered(isNumber, editor, name).getOr(defaultVal);
  19749. } else if (type === 'boolean') {
  19750. return getFiltered(isBoolean, editor, name).getOr(defaultVal);
  19751. } else if (type === 'object') {
  19752. return getFiltered(isObject, editor, name).getOr(defaultVal);
  19753. } else if (type === 'array') {
  19754. return getFiltered(isArray$1, editor, name).getOr(defaultVal);
  19755. } else if (type === 'string[]') {
  19756. return getFiltered(isArrayOf(isString$1), editor, name).getOr(defaultVal);
  19757. } else if (type === 'function') {
  19758. return getFiltered(isFunction, editor, name).getOr(defaultVal);
  19759. } else {
  19760. return value;
  19761. }
  19762. };
  19763. var CreateIconManager = function () {
  19764. var lookup = {};
  19765. var add = function (id, iconPack) {
  19766. lookup[id] = iconPack;
  19767. };
  19768. var get = function (id) {
  19769. if (lookup[id]) {
  19770. return lookup[id];
  19771. }
  19772. return { icons: {} };
  19773. };
  19774. var has = function (id) {
  19775. return has$2(lookup, id);
  19776. };
  19777. return {
  19778. add: add,
  19779. get: get,
  19780. has: has
  19781. };
  19782. };
  19783. var IconManager = CreateIconManager();
  19784. var getProp = function (propName, elm) {
  19785. var rawElm = elm.dom;
  19786. return rawElm[propName];
  19787. };
  19788. var getComputedSizeProp = function (propName, elm) {
  19789. return parseInt(get$5(elm, propName), 10);
  19790. };
  19791. var getClientWidth = curry(getProp, 'clientWidth');
  19792. var getClientHeight = curry(getProp, 'clientHeight');
  19793. var getMarginTop = curry(getComputedSizeProp, 'margin-top');
  19794. var getMarginLeft = curry(getComputedSizeProp, 'margin-left');
  19795. var getBoundingClientRect = function (elm) {
  19796. return elm.dom.getBoundingClientRect();
  19797. };
  19798. var isInsideElementContentArea = function (bodyElm, clientX, clientY) {
  19799. var clientWidth = getClientWidth(bodyElm);
  19800. var clientHeight = getClientHeight(bodyElm);
  19801. return clientX >= 0 && clientY >= 0 && clientX <= clientWidth && clientY <= clientHeight;
  19802. };
  19803. var transpose = function (inline, elm, clientX, clientY) {
  19804. var clientRect = getBoundingClientRect(elm);
  19805. var deltaX = inline ? clientRect.left + elm.dom.clientLeft + getMarginLeft(elm) : 0;
  19806. var deltaY = inline ? clientRect.top + elm.dom.clientTop + getMarginTop(elm) : 0;
  19807. var x = clientX - deltaX;
  19808. var y = clientY - deltaY;
  19809. return {
  19810. x: x,
  19811. y: y
  19812. };
  19813. };
  19814. var isXYInContentArea = function (editor, clientX, clientY) {
  19815. var bodyElm = SugarElement.fromDom(editor.getBody());
  19816. var targetElm = editor.inline ? bodyElm : documentElement(bodyElm);
  19817. var transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
  19818. return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
  19819. };
  19820. var fromDomSafe = function (node) {
  19821. return Optional.from(node).map(SugarElement.fromDom);
  19822. };
  19823. var isEditorAttachedToDom = function (editor) {
  19824. var rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
  19825. return fromDomSafe(rawContainer).map(inBody).getOr(false);
  19826. };
  19827. var NotificationManagerImpl = function () {
  19828. var unimplemented = function () {
  19829. throw new Error('Theme did not provide a NotificationManager implementation.');
  19830. };
  19831. return {
  19832. open: unimplemented,
  19833. close: unimplemented,
  19834. reposition: unimplemented,
  19835. getArgs: unimplemented
  19836. };
  19837. };
  19838. var NotificationManager = function (editor) {
  19839. var notifications = [];
  19840. var getImplementation = function () {
  19841. var theme = editor.theme;
  19842. return theme && theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
  19843. };
  19844. var getTopNotification = function () {
  19845. return Optional.from(notifications[0]);
  19846. };
  19847. var isEqual = function (a, b) {
  19848. return a.type === b.type && a.text === b.text && !a.progressBar && !a.timeout && !b.progressBar && !b.timeout;
  19849. };
  19850. var reposition = function () {
  19851. if (notifications.length > 0) {
  19852. getImplementation().reposition(notifications);
  19853. }
  19854. };
  19855. var addNotification = function (notification) {
  19856. notifications.push(notification);
  19857. };
  19858. var closeNotification = function (notification) {
  19859. findIndex$2(notifications, function (otherNotification) {
  19860. return otherNotification === notification;
  19861. }).each(function (index) {
  19862. notifications.splice(index, 1);
  19863. });
  19864. };
  19865. var open = function (spec, fireEvent) {
  19866. if (fireEvent === void 0) {
  19867. fireEvent = true;
  19868. }
  19869. if (editor.removed || !isEditorAttachedToDom(editor)) {
  19870. return;
  19871. }
  19872. if (fireEvent) {
  19873. editor.fire('BeforeOpenNotification', { notification: spec });
  19874. }
  19875. return find$3(notifications, function (notification) {
  19876. return isEqual(getImplementation().getArgs(notification), spec);
  19877. }).getOrThunk(function () {
  19878. editor.editorManager.setActive(editor);
  19879. var notification = getImplementation().open(spec, function () {
  19880. closeNotification(notification);
  19881. reposition();
  19882. getTopNotification().fold(function () {
  19883. return editor.focus();
  19884. }, function (top) {
  19885. return focus$1(SugarElement.fromDom(top.getEl()));
  19886. });
  19887. });
  19888. addNotification(notification);
  19889. reposition();
  19890. editor.fire('OpenNotification', { notification: __assign({}, notification) });
  19891. return notification;
  19892. });
  19893. };
  19894. var close = function () {
  19895. getTopNotification().each(function (notification) {
  19896. getImplementation().close(notification);
  19897. closeNotification(notification);
  19898. reposition();
  19899. });
  19900. };
  19901. var getNotifications = constant(notifications);
  19902. var registerEvents = function (editor) {
  19903. editor.on('SkinLoaded', function () {
  19904. var serviceMessage = getServiceMessage(editor);
  19905. if (serviceMessage) {
  19906. open({
  19907. text: serviceMessage,
  19908. type: 'warning',
  19909. timeout: 0
  19910. }, false);
  19911. }
  19912. reposition();
  19913. });
  19914. editor.on('show ResizeEditor ResizeWindow NodeChange', function () {
  19915. Delay.requestAnimationFrame(reposition);
  19916. });
  19917. editor.on('remove', function () {
  19918. each$k(notifications.slice(), function (notification) {
  19919. getImplementation().close(notification);
  19920. });
  19921. });
  19922. };
  19923. registerEvents(editor);
  19924. return {
  19925. open: open,
  19926. close: close,
  19927. getNotifications: getNotifications
  19928. };
  19929. };
  19930. var PluginManager = AddOnManager.PluginManager;
  19931. var ThemeManager = AddOnManager.ThemeManager;
  19932. function WindowManagerImpl () {
  19933. var unimplemented = function () {
  19934. throw new Error('Theme did not provide a WindowManager implementation.');
  19935. };
  19936. return {
  19937. open: unimplemented,
  19938. openUrl: unimplemented,
  19939. alert: unimplemented,
  19940. confirm: unimplemented,
  19941. close: unimplemented,
  19942. getParams: unimplemented,
  19943. setParams: unimplemented
  19944. };
  19945. }
  19946. var WindowManager = function (editor) {
  19947. var dialogs = [];
  19948. var getImplementation = function () {
  19949. var theme = editor.theme;
  19950. return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
  19951. };
  19952. var funcBind = function (scope, f) {
  19953. return function () {
  19954. var args = [];
  19955. for (var _i = 0; _i < arguments.length; _i++) {
  19956. args[_i] = arguments[_i];
  19957. }
  19958. return f ? f.apply(scope, args) : undefined;
  19959. };
  19960. };
  19961. var fireOpenEvent = function (dialog) {
  19962. editor.fire('OpenWindow', { dialog: dialog });
  19963. };
  19964. var fireCloseEvent = function (dialog) {
  19965. editor.fire('CloseWindow', { dialog: dialog });
  19966. };
  19967. var addDialog = function (dialog) {
  19968. dialogs.push(dialog);
  19969. fireOpenEvent(dialog);
  19970. };
  19971. var closeDialog = function (dialog) {
  19972. fireCloseEvent(dialog);
  19973. dialogs = filter$4(dialogs, function (otherDialog) {
  19974. return otherDialog !== dialog;
  19975. });
  19976. if (dialogs.length === 0) {
  19977. editor.focus();
  19978. }
  19979. };
  19980. var getTopDialog = function () {
  19981. return Optional.from(dialogs[dialogs.length - 1]);
  19982. };
  19983. var storeSelectionAndOpenDialog = function (openDialog) {
  19984. editor.editorManager.setActive(editor);
  19985. store(editor);
  19986. var dialog = openDialog();
  19987. addDialog(dialog);
  19988. return dialog;
  19989. };
  19990. var open = function (args, params) {
  19991. return storeSelectionAndOpenDialog(function () {
  19992. return getImplementation().open(args, params, closeDialog);
  19993. });
  19994. };
  19995. var openUrl = function (args) {
  19996. return storeSelectionAndOpenDialog(function () {
  19997. return getImplementation().openUrl(args, closeDialog);
  19998. });
  19999. };
  20000. var alert = function (message, callback, scope) {
  20001. var windowManagerImpl = getImplementation();
  20002. windowManagerImpl.alert(message, funcBind(scope ? scope : windowManagerImpl, callback));
  20003. };
  20004. var confirm = function (message, callback, scope) {
  20005. var windowManagerImpl = getImplementation();
  20006. windowManagerImpl.confirm(message, funcBind(scope ? scope : windowManagerImpl, callback));
  20007. };
  20008. var close = function () {
  20009. getTopDialog().each(function (dialog) {
  20010. getImplementation().close(dialog);
  20011. closeDialog(dialog);
  20012. });
  20013. };
  20014. editor.on('remove', function () {
  20015. each$k(dialogs, function (dialog) {
  20016. getImplementation().close(dialog);
  20017. });
  20018. });
  20019. return {
  20020. open: open,
  20021. openUrl: openUrl,
  20022. alert: alert,
  20023. confirm: confirm,
  20024. close: close
  20025. };
  20026. };
  20027. var displayNotification = function (editor, message) {
  20028. editor.notificationManager.open({
  20029. type: 'error',
  20030. text: message
  20031. });
  20032. };
  20033. var displayError = function (editor, message) {
  20034. if (editor._skinLoaded) {
  20035. displayNotification(editor, message);
  20036. } else {
  20037. editor.on('SkinLoaded', function () {
  20038. displayNotification(editor, message);
  20039. });
  20040. }
  20041. };
  20042. var uploadError = function (editor, message) {
  20043. displayError(editor, I18n.translate([
  20044. 'Failed to upload image: {0}',
  20045. message
  20046. ]));
  20047. };
  20048. var logError = function (editor, errorType, msg) {
  20049. fireError(editor, errorType, { message: msg });
  20050. console.error(msg);
  20051. };
  20052. var createLoadError = function (type, url, name) {
  20053. return name ? 'Failed to load ' + type + ': ' + name + ' from url ' + url : 'Failed to load ' + type + ' url: ' + url;
  20054. };
  20055. var pluginLoadError = function (editor, url, name) {
  20056. logError(editor, 'PluginLoadError', createLoadError('plugin', url, name));
  20057. };
  20058. var iconsLoadError = function (editor, url, name) {
  20059. logError(editor, 'IconsLoadError', createLoadError('icons', url, name));
  20060. };
  20061. var languageLoadError = function (editor, url, name) {
  20062. logError(editor, 'LanguageLoadError', createLoadError('language', url, name));
  20063. };
  20064. var pluginInitError = function (editor, name, err) {
  20065. var message = I18n.translate([
  20066. 'Failed to initialize plugin: {0}',
  20067. name
  20068. ]);
  20069. fireError(editor, 'PluginLoadError', { message: message });
  20070. initError(message, err);
  20071. displayError(editor, message);
  20072. };
  20073. var initError = function (message) {
  20074. var x = [];
  20075. for (var _i = 1; _i < arguments.length; _i++) {
  20076. x[_i - 1] = arguments[_i];
  20077. }
  20078. var console = window.console;
  20079. if (console) {
  20080. if (console.error) {
  20081. console.error.apply(console, __spreadArray([message], x, false));
  20082. } else {
  20083. console.log.apply(console, __spreadArray([message], x, false));
  20084. }
  20085. }
  20086. };
  20087. var isContentCssSkinName = function (url) {
  20088. return /^[a-z0-9\-]+$/i.test(url);
  20089. };
  20090. var getContentCssUrls = function (editor) {
  20091. return transformToUrls(editor, getContentCss(editor));
  20092. };
  20093. var getFontCssUrls = function (editor) {
  20094. return transformToUrls(editor, getFontCss(editor));
  20095. };
  20096. var transformToUrls = function (editor, cssLinks) {
  20097. var skinUrl = editor.editorManager.baseURL + '/skins/content';
  20098. var suffix = editor.editorManager.suffix;
  20099. var contentCssFile = 'content' + suffix + '.css';
  20100. var inline = editor.inline === true;
  20101. return map$3(cssLinks, function (url) {
  20102. if (isContentCssSkinName(url) && !inline) {
  20103. return skinUrl + '/' + url + '/' + contentCssFile;
  20104. } else {
  20105. return editor.documentBaseURI.toAbsolute(url);
  20106. }
  20107. });
  20108. };
  20109. var appendContentCssFromSettings = function (editor) {
  20110. editor.contentCSS = editor.contentCSS.concat(getContentCssUrls(editor), getFontCssUrls(editor));
  20111. };
  20112. var UploadStatus = function () {
  20113. var PENDING = 1, UPLOADED = 2;
  20114. var blobUriStatuses = {};
  20115. var createStatus = function (status, resultUri) {
  20116. return {
  20117. status: status,
  20118. resultUri: resultUri
  20119. };
  20120. };
  20121. var hasBlobUri = function (blobUri) {
  20122. return blobUri in blobUriStatuses;
  20123. };
  20124. var getResultUri = function (blobUri) {
  20125. var result = blobUriStatuses[blobUri];
  20126. return result ? result.resultUri : null;
  20127. };
  20128. var isPending = function (blobUri) {
  20129. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
  20130. };
  20131. var isUploaded = function (blobUri) {
  20132. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
  20133. };
  20134. var markPending = function (blobUri) {
  20135. blobUriStatuses[blobUri] = createStatus(PENDING, null);
  20136. };
  20137. var markUploaded = function (blobUri, resultUri) {
  20138. blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
  20139. };
  20140. var removeFailed = function (blobUri) {
  20141. delete blobUriStatuses[blobUri];
  20142. };
  20143. var destroy = function () {
  20144. blobUriStatuses = {};
  20145. };
  20146. return {
  20147. hasBlobUri: hasBlobUri,
  20148. getResultUri: getResultUri,
  20149. isPending: isPending,
  20150. isUploaded: isUploaded,
  20151. markPending: markPending,
  20152. markUploaded: markUploaded,
  20153. removeFailed: removeFailed,
  20154. destroy: destroy
  20155. };
  20156. };
  20157. var count = 0;
  20158. var seed = function () {
  20159. var rnd = function () {
  20160. return Math.round(Math.random() * 4294967295).toString(36);
  20161. };
  20162. var now = new Date().getTime();
  20163. return 's' + now.toString(36) + rnd() + rnd() + rnd();
  20164. };
  20165. var uuid = function (prefix) {
  20166. return prefix + count++ + seed();
  20167. };
  20168. var BlobCache = function () {
  20169. var cache = [];
  20170. var mimeToExt = function (mime) {
  20171. var mimes = {
  20172. 'image/jpeg': 'jpg',
  20173. 'image/jpg': 'jpg',
  20174. 'image/gif': 'gif',
  20175. 'image/png': 'png',
  20176. 'image/apng': 'apng',
  20177. 'image/avif': 'avif',
  20178. 'image/svg+xml': 'svg',
  20179. 'image/webp': 'webp',
  20180. 'image/bmp': 'bmp',
  20181. 'image/tiff': 'tiff'
  20182. };
  20183. return mimes[mime.toLowerCase()] || 'dat';
  20184. };
  20185. var create = function (o, blob, base64, name, filename) {
  20186. if (isString$1(o)) {
  20187. var id = o;
  20188. return toBlobInfo({
  20189. id: id,
  20190. name: name,
  20191. filename: filename,
  20192. blob: blob,
  20193. base64: base64
  20194. });
  20195. } else if (isObject(o)) {
  20196. return toBlobInfo(o);
  20197. } else {
  20198. throw new Error('Unknown input type');
  20199. }
  20200. };
  20201. var toBlobInfo = function (o) {
  20202. if (!o.blob || !o.base64) {
  20203. throw new Error('blob and base64 representations of the image are required for BlobInfo to be created');
  20204. }
  20205. var id = o.id || uuid('blobid');
  20206. var name = o.name || id;
  20207. var blob = o.blob;
  20208. return {
  20209. id: constant(id),
  20210. name: constant(name),
  20211. filename: constant(o.filename || name + '.' + mimeToExt(blob.type)),
  20212. blob: constant(blob),
  20213. base64: constant(o.base64),
  20214. blobUri: constant(o.blobUri || URL.createObjectURL(blob)),
  20215. uri: constant(o.uri)
  20216. };
  20217. };
  20218. var add = function (blobInfo) {
  20219. if (!get(blobInfo.id())) {
  20220. cache.push(blobInfo);
  20221. }
  20222. };
  20223. var findFirst = function (predicate) {
  20224. return find$3(cache, predicate).getOrUndefined();
  20225. };
  20226. var get = function (id) {
  20227. return findFirst(function (cachedBlobInfo) {
  20228. return cachedBlobInfo.id() === id;
  20229. });
  20230. };
  20231. var getByUri = function (blobUri) {
  20232. return findFirst(function (blobInfo) {
  20233. return blobInfo.blobUri() === blobUri;
  20234. });
  20235. };
  20236. var getByData = function (base64, type) {
  20237. return findFirst(function (blobInfo) {
  20238. return blobInfo.base64() === base64 && blobInfo.blob().type === type;
  20239. });
  20240. };
  20241. var removeByUri = function (blobUri) {
  20242. cache = filter$4(cache, function (blobInfo) {
  20243. if (blobInfo.blobUri() === blobUri) {
  20244. URL.revokeObjectURL(blobInfo.blobUri());
  20245. return false;
  20246. }
  20247. return true;
  20248. });
  20249. };
  20250. var destroy = function () {
  20251. each$k(cache, function (cachedBlobInfo) {
  20252. URL.revokeObjectURL(cachedBlobInfo.blobUri());
  20253. });
  20254. cache = [];
  20255. };
  20256. return {
  20257. create: create,
  20258. add: add,
  20259. get: get,
  20260. getByUri: getByUri,
  20261. getByData: getByData,
  20262. findFirst: findFirst,
  20263. removeByUri: removeByUri,
  20264. destroy: destroy
  20265. };
  20266. };
  20267. var Uploader = function (uploadStatus, settings) {
  20268. var pendingPromises = {};
  20269. var pathJoin = function (path1, path2) {
  20270. if (path1) {
  20271. return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
  20272. }
  20273. return path2;
  20274. };
  20275. var defaultHandler = function (blobInfo, success, failure, progress) {
  20276. var xhr = new XMLHttpRequest();
  20277. xhr.open('POST', settings.url);
  20278. xhr.withCredentials = settings.credentials;
  20279. xhr.upload.onprogress = function (e) {
  20280. progress(e.loaded / e.total * 100);
  20281. };
  20282. xhr.onerror = function () {
  20283. failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  20284. };
  20285. xhr.onload = function () {
  20286. if (xhr.status < 200 || xhr.status >= 300) {
  20287. failure('HTTP Error: ' + xhr.status);
  20288. return;
  20289. }
  20290. var json = JSON.parse(xhr.responseText);
  20291. if (!json || typeof json.location !== 'string') {
  20292. failure('Invalid JSON: ' + xhr.responseText);
  20293. return;
  20294. }
  20295. success(pathJoin(settings.basePath, json.location));
  20296. };
  20297. var formData = new FormData();
  20298. formData.append('file', blobInfo.blob(), blobInfo.filename());
  20299. xhr.send(formData);
  20300. };
  20301. var noUpload = function () {
  20302. return new promiseObj(function (resolve) {
  20303. resolve([]);
  20304. });
  20305. };
  20306. var handlerSuccess = function (blobInfo, url) {
  20307. return {
  20308. url: url,
  20309. blobInfo: blobInfo,
  20310. status: true
  20311. };
  20312. };
  20313. var handlerFailure = function (blobInfo, message, options) {
  20314. return {
  20315. url: '',
  20316. blobInfo: blobInfo,
  20317. status: false,
  20318. error: {
  20319. message: message,
  20320. options: options
  20321. }
  20322. };
  20323. };
  20324. var resolvePending = function (blobUri, result) {
  20325. Tools.each(pendingPromises[blobUri], function (resolve) {
  20326. resolve(result);
  20327. });
  20328. delete pendingPromises[blobUri];
  20329. };
  20330. var uploadBlobInfo = function (blobInfo, handler, openNotification) {
  20331. uploadStatus.markPending(blobInfo.blobUri());
  20332. return new promiseObj(function (resolve) {
  20333. var notification, progress;
  20334. try {
  20335. var closeNotification_1 = function () {
  20336. if (notification) {
  20337. notification.close();
  20338. progress = noop;
  20339. }
  20340. };
  20341. var success = function (url) {
  20342. closeNotification_1();
  20343. uploadStatus.markUploaded(blobInfo.blobUri(), url);
  20344. resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
  20345. resolve(handlerSuccess(blobInfo, url));
  20346. };
  20347. var failure = function (error, options) {
  20348. var failureOptions = options ? options : {};
  20349. closeNotification_1();
  20350. uploadStatus.removeFailed(blobInfo.blobUri());
  20351. resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error, failureOptions));
  20352. resolve(handlerFailure(blobInfo, error, failureOptions));
  20353. };
  20354. progress = function (percent) {
  20355. if (percent < 0 || percent > 100) {
  20356. return;
  20357. }
  20358. Optional.from(notification).orThunk(function () {
  20359. return Optional.from(openNotification).map(apply);
  20360. }).each(function (n) {
  20361. notification = n;
  20362. n.progressBar.value(percent);
  20363. });
  20364. };
  20365. handler(blobInfo, success, failure, progress);
  20366. } catch (ex) {
  20367. resolve(handlerFailure(blobInfo, ex.message, {}));
  20368. }
  20369. });
  20370. };
  20371. var isDefaultHandler = function (handler) {
  20372. return handler === defaultHandler;
  20373. };
  20374. var pendingUploadBlobInfo = function (blobInfo) {
  20375. var blobUri = blobInfo.blobUri();
  20376. return new promiseObj(function (resolve) {
  20377. pendingPromises[blobUri] = pendingPromises[blobUri] || [];
  20378. pendingPromises[blobUri].push(resolve);
  20379. });
  20380. };
  20381. var uploadBlobs = function (blobInfos, openNotification) {
  20382. blobInfos = Tools.grep(blobInfos, function (blobInfo) {
  20383. return !uploadStatus.isUploaded(blobInfo.blobUri());
  20384. });
  20385. return promiseObj.all(Tools.map(blobInfos, function (blobInfo) {
  20386. return uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification);
  20387. }));
  20388. };
  20389. var upload = function (blobInfos, openNotification) {
  20390. return !settings.url && isDefaultHandler(settings.handler) ? noUpload() : uploadBlobs(blobInfos, openNotification);
  20391. };
  20392. if (isFunction(settings.handler) === false) {
  20393. settings.handler = defaultHandler;
  20394. }
  20395. return { upload: upload };
  20396. };
  20397. var openNotification = function (editor) {
  20398. return function () {
  20399. return editor.notificationManager.open({
  20400. text: editor.translate('Image uploading...'),
  20401. type: 'info',
  20402. timeout: -1,
  20403. progressBar: true
  20404. });
  20405. };
  20406. };
  20407. var createUploader = function (editor, uploadStatus) {
  20408. return Uploader(uploadStatus, {
  20409. url: getImageUploadUrl(editor),
  20410. basePath: getImageUploadBasePath(editor),
  20411. credentials: getImagesUploadCredentials(editor),
  20412. handler: getImagesUploadHandler(editor)
  20413. });
  20414. };
  20415. var ImageUploader = function (editor) {
  20416. var uploadStatus = UploadStatus();
  20417. var uploader = createUploader(editor, uploadStatus);
  20418. return {
  20419. upload: function (blobInfos, showNotification) {
  20420. if (showNotification === void 0) {
  20421. showNotification = true;
  20422. }
  20423. return uploader.upload(blobInfos, showNotification ? openNotification(editor) : undefined);
  20424. }
  20425. };
  20426. };
  20427. var UploadChangeHandler = function (editor) {
  20428. var lastChangedLevel = Cell(null);
  20429. editor.on('change AddUndo', function (e) {
  20430. lastChangedLevel.set(__assign({}, e.level));
  20431. });
  20432. var fireIfChanged = function () {
  20433. var data = editor.undoManager.data;
  20434. last$2(data).filter(function (level) {
  20435. return !isEq$1(lastChangedLevel.get(), level);
  20436. }).each(function (level) {
  20437. editor.setDirty(true);
  20438. editor.fire('change', {
  20439. level: level,
  20440. lastLevel: get$a(data, data.length - 2).getOrNull()
  20441. });
  20442. });
  20443. };
  20444. return { fireIfChanged: fireIfChanged };
  20445. };
  20446. var EditorUpload = function (editor) {
  20447. var blobCache = BlobCache();
  20448. var uploader, imageScanner;
  20449. var uploadStatus = UploadStatus();
  20450. var urlFilters = [];
  20451. var changeHandler = UploadChangeHandler(editor);
  20452. var aliveGuard = function (callback) {
  20453. return function (result) {
  20454. if (editor.selection) {
  20455. return callback(result);
  20456. }
  20457. return [];
  20458. };
  20459. };
  20460. var cacheInvalidator = function (url) {
  20461. return url + (url.indexOf('?') === -1 ? '?' : '&') + new Date().getTime();
  20462. };
  20463. var replaceString = function (content, search, replace) {
  20464. var index = 0;
  20465. do {
  20466. index = content.indexOf(search, index);
  20467. if (index !== -1) {
  20468. content = content.substring(0, index) + replace + content.substr(index + search.length);
  20469. index += replace.length - search.length + 1;
  20470. }
  20471. } while (index !== -1);
  20472. return content;
  20473. };
  20474. var replaceImageUrl = function (content, targetUrl, replacementUrl) {
  20475. var replacementString = 'src="' + replacementUrl + '"' + (replacementUrl === Env.transparentSrc ? ' data-mce-placeholder="1"' : '');
  20476. content = replaceString(content, 'src="' + targetUrl + '"', replacementString);
  20477. content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
  20478. return content;
  20479. };
  20480. var replaceUrlInUndoStack = function (targetUrl, replacementUrl) {
  20481. each$k(editor.undoManager.data, function (level) {
  20482. if (level.type === 'fragmented') {
  20483. level.fragments = map$3(level.fragments, function (fragment) {
  20484. return replaceImageUrl(fragment, targetUrl, replacementUrl);
  20485. });
  20486. } else {
  20487. level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
  20488. }
  20489. });
  20490. };
  20491. var replaceImageUriInView = function (image, resultUri) {
  20492. var src = editor.convertURL(resultUri, 'src');
  20493. replaceUrlInUndoStack(image.src, resultUri);
  20494. editor.$(image).attr({
  20495. 'src': shouldReuseFileName(editor) ? cacheInvalidator(resultUri) : resultUri,
  20496. 'data-mce-src': src
  20497. });
  20498. };
  20499. var uploadImages = function (callback) {
  20500. if (!uploader) {
  20501. uploader = createUploader(editor, uploadStatus);
  20502. }
  20503. return scanForImages().then(aliveGuard(function (imageInfos) {
  20504. var blobInfos = map$3(imageInfos, function (imageInfo) {
  20505. return imageInfo.blobInfo;
  20506. });
  20507. return uploader.upload(blobInfos, openNotification(editor)).then(aliveGuard(function (result) {
  20508. var imagesToRemove = [];
  20509. var filteredResult = map$3(result, function (uploadInfo, index) {
  20510. var blobInfo = imageInfos[index].blobInfo;
  20511. var image = imageInfos[index].image;
  20512. if (uploadInfo.status && shouldReplaceBlobUris(editor)) {
  20513. blobCache.removeByUri(image.src);
  20514. if (isRtc(editor)) ; else {
  20515. replaceImageUriInView(image, uploadInfo.url);
  20516. }
  20517. } else if (uploadInfo.error) {
  20518. if (uploadInfo.error.options.remove) {
  20519. replaceUrlInUndoStack(image.getAttribute('src'), Env.transparentSrc);
  20520. imagesToRemove.push(image);
  20521. }
  20522. uploadError(editor, uploadInfo.error.message);
  20523. }
  20524. return {
  20525. element: image,
  20526. status: uploadInfo.status,
  20527. uploadUri: uploadInfo.url,
  20528. blobInfo: blobInfo
  20529. };
  20530. });
  20531. if (filteredResult.length > 0) {
  20532. changeHandler.fireIfChanged();
  20533. }
  20534. if (imagesToRemove.length > 0) {
  20535. if (isRtc(editor)) {
  20536. console.error('Removing images on failed uploads is currently unsupported for RTC');
  20537. } else {
  20538. editor.undoManager.transact(function () {
  20539. each$k(imagesToRemove, function (element) {
  20540. editor.dom.remove(element);
  20541. blobCache.removeByUri(element.src);
  20542. });
  20543. });
  20544. }
  20545. }
  20546. if (callback) {
  20547. callback(filteredResult);
  20548. }
  20549. return filteredResult;
  20550. }));
  20551. }));
  20552. };
  20553. var uploadImagesAuto = function (callback) {
  20554. if (isAutomaticUploadsEnabled(editor)) {
  20555. return uploadImages(callback);
  20556. }
  20557. };
  20558. var isValidDataUriImage = function (imgElm) {
  20559. if (forall(urlFilters, function (filter) {
  20560. return filter(imgElm);
  20561. }) === false) {
  20562. return false;
  20563. }
  20564. if (imgElm.getAttribute('src').indexOf('data:') === 0) {
  20565. var dataImgFilter = getImagesDataImgFilter(editor);
  20566. return dataImgFilter(imgElm);
  20567. }
  20568. return true;
  20569. };
  20570. var addFilter = function (filter) {
  20571. urlFilters.push(filter);
  20572. };
  20573. var scanForImages = function () {
  20574. if (!imageScanner) {
  20575. imageScanner = ImageScanner(uploadStatus, blobCache);
  20576. }
  20577. return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(function (result) {
  20578. result = filter$4(result, function (resultItem) {
  20579. if (typeof resultItem === 'string') {
  20580. displayError(editor, resultItem);
  20581. return false;
  20582. }
  20583. return true;
  20584. });
  20585. if (isRtc(editor)) ; else {
  20586. each$k(result, function (resultItem) {
  20587. replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
  20588. resultItem.image.src = resultItem.blobInfo.blobUri();
  20589. resultItem.image.removeAttribute('data-mce-src');
  20590. });
  20591. }
  20592. return result;
  20593. }));
  20594. };
  20595. var destroy = function () {
  20596. blobCache.destroy();
  20597. uploadStatus.destroy();
  20598. imageScanner = uploader = null;
  20599. };
  20600. var replaceBlobUris = function (content) {
  20601. return content.replace(/src="(blob:[^"]+)"/g, function (match, blobUri) {
  20602. var resultUri = uploadStatus.getResultUri(blobUri);
  20603. if (resultUri) {
  20604. return 'src="' + resultUri + '"';
  20605. }
  20606. var blobInfo = blobCache.getByUri(blobUri);
  20607. if (!blobInfo) {
  20608. blobInfo = foldl(editor.editorManager.get(), function (result, editor) {
  20609. return result || editor.editorUpload && editor.editorUpload.blobCache.getByUri(blobUri);
  20610. }, null);
  20611. }
  20612. if (blobInfo) {
  20613. var blob = blobInfo.blob();
  20614. return 'src="data:' + blob.type + ';base64,' + blobInfo.base64() + '"';
  20615. }
  20616. return match;
  20617. });
  20618. };
  20619. editor.on('SetContent', function () {
  20620. if (isAutomaticUploadsEnabled(editor)) {
  20621. uploadImagesAuto();
  20622. } else {
  20623. scanForImages();
  20624. }
  20625. });
  20626. editor.on('RawSaveContent', function (e) {
  20627. e.content = replaceBlobUris(e.content);
  20628. });
  20629. editor.on('GetContent', function (e) {
  20630. if (e.source_view || e.format === 'raw' || e.format === 'tree') {
  20631. return;
  20632. }
  20633. e.content = replaceBlobUris(e.content);
  20634. });
  20635. editor.on('PostRender', function () {
  20636. editor.parser.addNodeFilter('img', function (images) {
  20637. each$k(images, function (img) {
  20638. var src = img.attr('src');
  20639. if (blobCache.getByUri(src)) {
  20640. return;
  20641. }
  20642. var resultUri = uploadStatus.getResultUri(src);
  20643. if (resultUri) {
  20644. img.attr('src', resultUri);
  20645. }
  20646. });
  20647. });
  20648. });
  20649. return {
  20650. blobCache: blobCache,
  20651. addFilter: addFilter,
  20652. uploadImages: uploadImages,
  20653. uploadImagesAuto: uploadImagesAuto,
  20654. scanForImages: scanForImages,
  20655. destroy: destroy
  20656. };
  20657. };
  20658. var get = function (dom) {
  20659. var formats = {
  20660. valigntop: [{
  20661. selector: 'td,th',
  20662. styles: { verticalAlign: 'top' }
  20663. }],
  20664. valignmiddle: [{
  20665. selector: 'td,th',
  20666. styles: { verticalAlign: 'middle' }
  20667. }],
  20668. valignbottom: [{
  20669. selector: 'td,th',
  20670. styles: { verticalAlign: 'bottom' }
  20671. }],
  20672. alignleft: [
  20673. {
  20674. selector: 'figure.image',
  20675. collapsed: false,
  20676. classes: 'align-left',
  20677. ceFalseOverride: true,
  20678. preview: 'font-family font-size'
  20679. },
  20680. {
  20681. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20682. styles: { textAlign: 'left' },
  20683. inherit: false,
  20684. preview: false,
  20685. defaultBlock: 'div'
  20686. },
  20687. {
  20688. selector: 'img,table,audio,video',
  20689. collapsed: false,
  20690. styles: { float: 'left' },
  20691. preview: 'font-family font-size'
  20692. }
  20693. ],
  20694. aligncenter: [
  20695. {
  20696. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20697. styles: { textAlign: 'center' },
  20698. inherit: false,
  20699. preview: 'font-family font-size',
  20700. defaultBlock: 'div'
  20701. },
  20702. {
  20703. selector: 'figure.image',
  20704. collapsed: false,
  20705. classes: 'align-center',
  20706. ceFalseOverride: true,
  20707. preview: 'font-family font-size'
  20708. },
  20709. {
  20710. selector: 'img,audio,video',
  20711. collapsed: false,
  20712. styles: {
  20713. display: 'block',
  20714. marginLeft: 'auto',
  20715. marginRight: 'auto'
  20716. },
  20717. preview: false
  20718. },
  20719. {
  20720. selector: 'table',
  20721. collapsed: false,
  20722. styles: {
  20723. marginLeft: 'auto',
  20724. marginRight: 'auto'
  20725. },
  20726. preview: 'font-family font-size'
  20727. }
  20728. ],
  20729. alignright: [
  20730. {
  20731. selector: 'figure.image',
  20732. collapsed: false,
  20733. classes: 'align-right',
  20734. ceFalseOverride: true,
  20735. preview: 'font-family font-size'
  20736. },
  20737. {
  20738. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20739. styles: { textAlign: 'right' },
  20740. inherit: false,
  20741. preview: 'font-family font-size',
  20742. defaultBlock: 'div'
  20743. },
  20744. {
  20745. selector: 'img,table,audio,video',
  20746. collapsed: false,
  20747. styles: { float: 'right' },
  20748. preview: 'font-family font-size'
  20749. }
  20750. ],
  20751. alignjustify: [{
  20752. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20753. styles: { textAlign: 'justify' },
  20754. inherit: false,
  20755. defaultBlock: 'div',
  20756. preview: 'font-family font-size'
  20757. }],
  20758. bold: [
  20759. {
  20760. inline: 'strong',
  20761. remove: 'all',
  20762. preserve_attributes: [
  20763. 'class',
  20764. 'style'
  20765. ]
  20766. },
  20767. {
  20768. inline: 'span',
  20769. styles: { fontWeight: 'bold' }
  20770. },
  20771. {
  20772. inline: 'b',
  20773. remove: 'all',
  20774. preserve_attributes: [
  20775. 'class',
  20776. 'style'
  20777. ]
  20778. }
  20779. ],
  20780. italic: [
  20781. {
  20782. inline: 'em',
  20783. remove: 'all',
  20784. preserve_attributes: [
  20785. 'class',
  20786. 'style'
  20787. ]
  20788. },
  20789. {
  20790. inline: 'span',
  20791. styles: { fontStyle: 'italic' }
  20792. },
  20793. {
  20794. inline: 'i',
  20795. remove: 'all',
  20796. preserve_attributes: [
  20797. 'class',
  20798. 'style'
  20799. ]
  20800. }
  20801. ],
  20802. underline: [
  20803. {
  20804. inline: 'span',
  20805. styles: { textDecoration: 'underline' },
  20806. exact: true
  20807. },
  20808. {
  20809. inline: 'u',
  20810. remove: 'all',
  20811. preserve_attributes: [
  20812. 'class',
  20813. 'style'
  20814. ]
  20815. }
  20816. ],
  20817. strikethrough: [
  20818. {
  20819. inline: 'span',
  20820. styles: { textDecoration: 'line-through' },
  20821. exact: true
  20822. },
  20823. {
  20824. inline: 'strike',
  20825. remove: 'all',
  20826. preserve_attributes: [
  20827. 'class',
  20828. 'style'
  20829. ]
  20830. },
  20831. {
  20832. inline: 's',
  20833. remove: 'all',
  20834. preserve_attributes: [
  20835. 'class',
  20836. 'style'
  20837. ]
  20838. }
  20839. ],
  20840. forecolor: {
  20841. inline: 'span',
  20842. styles: { color: '%value' },
  20843. links: true,
  20844. remove_similar: true,
  20845. clear_child_styles: true
  20846. },
  20847. hilitecolor: {
  20848. inline: 'span',
  20849. styles: { backgroundColor: '%value' },
  20850. links: true,
  20851. remove_similar: true,
  20852. clear_child_styles: true
  20853. },
  20854. fontname: {
  20855. inline: 'span',
  20856. toggle: false,
  20857. styles: { fontFamily: '%value' },
  20858. clear_child_styles: true
  20859. },
  20860. fontsize: {
  20861. inline: 'span',
  20862. toggle: false,
  20863. styles: { fontSize: '%value' },
  20864. clear_child_styles: true
  20865. },
  20866. lineheight: {
  20867. selector: 'h1,h2,h3,h4,h5,h6,p,li,td,th,div',
  20868. defaultBlock: 'p',
  20869. styles: { lineHeight: '%value' }
  20870. },
  20871. fontsize_class: {
  20872. inline: 'span',
  20873. attributes: { class: '%value' }
  20874. },
  20875. blockquote: {
  20876. block: 'blockquote',
  20877. wrapper: true,
  20878. remove: 'all'
  20879. },
  20880. subscript: { inline: 'sub' },
  20881. superscript: { inline: 'sup' },
  20882. code: { inline: 'code' },
  20883. link: {
  20884. inline: 'a',
  20885. selector: 'a',
  20886. remove: 'all',
  20887. split: true,
  20888. deep: true,
  20889. onmatch: function (node, _fmt, _itemName) {
  20890. return isElement$5(node) && node.hasAttribute('href');
  20891. },
  20892. onformat: function (elm, _fmt, vars) {
  20893. Tools.each(vars, function (value, key) {
  20894. dom.setAttrib(elm, key, value);
  20895. });
  20896. }
  20897. },
  20898. lang: {
  20899. inline: 'span',
  20900. clear_child_styles: true,
  20901. remove_similar: true,
  20902. attributes: {
  20903. 'lang': '%value',
  20904. 'data-mce-lang': function (vars) {
  20905. var _a;
  20906. return (_a = vars === null || vars === void 0 ? void 0 : vars.customValue) !== null && _a !== void 0 ? _a : null;
  20907. }
  20908. }
  20909. },
  20910. removeformat: [
  20911. {
  20912. selector: 'b,strong,em,i,font,u,strike,s,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins,small',
  20913. remove: 'all',
  20914. split: true,
  20915. expand: false,
  20916. block_expand: true,
  20917. deep: true
  20918. },
  20919. {
  20920. selector: 'span',
  20921. attributes: [
  20922. 'style',
  20923. 'class'
  20924. ],
  20925. remove: 'empty',
  20926. split: true,
  20927. expand: false,
  20928. deep: true
  20929. },
  20930. {
  20931. selector: '*',
  20932. attributes: [
  20933. 'style',
  20934. 'class'
  20935. ],
  20936. split: false,
  20937. expand: false,
  20938. deep: true
  20939. }
  20940. ]
  20941. };
  20942. Tools.each('p h1 h2 h3 h4 h5 h6 div address pre dt dd samp'.split(/\s/), function (name) {
  20943. formats[name] = {
  20944. block: name,
  20945. remove: 'all'
  20946. };
  20947. });
  20948. return formats;
  20949. };
  20950. var FormatRegistry = function (editor) {
  20951. var formats = {};
  20952. var get$1 = function (name) {
  20953. return isNonNullable(name) ? formats[name] : formats;
  20954. };
  20955. var has = function (name) {
  20956. return has$2(formats, name);
  20957. };
  20958. var register = function (name, format) {
  20959. if (name) {
  20960. if (!isString$1(name)) {
  20961. each$j(name, function (format, name) {
  20962. register(name, format);
  20963. });
  20964. } else {
  20965. if (!isArray$1(format)) {
  20966. format = [format];
  20967. }
  20968. each$k(format, function (format) {
  20969. if (isUndefined(format.deep)) {
  20970. format.deep = !isSelectorFormat(format);
  20971. }
  20972. if (isUndefined(format.split)) {
  20973. format.split = !isSelectorFormat(format) || isInlineFormat(format);
  20974. }
  20975. if (isUndefined(format.remove) && isSelectorFormat(format) && !isInlineFormat(format)) {
  20976. format.remove = 'none';
  20977. }
  20978. if (isSelectorFormat(format) && isInlineFormat(format)) {
  20979. format.mixed = true;
  20980. format.block_expand = true;
  20981. }
  20982. if (isString$1(format.classes)) {
  20983. format.classes = format.classes.split(/\s+/);
  20984. }
  20985. });
  20986. formats[name] = format;
  20987. }
  20988. }
  20989. };
  20990. var unregister = function (name) {
  20991. if (name && formats[name]) {
  20992. delete formats[name];
  20993. }
  20994. return formats;
  20995. };
  20996. register(get(editor.dom));
  20997. register(getFormats(editor));
  20998. return {
  20999. get: get$1,
  21000. has: has,
  21001. register: register,
  21002. unregister: unregister
  21003. };
  21004. };
  21005. var each$5 = Tools.each;
  21006. var dom = DOMUtils.DOM;
  21007. var parsedSelectorToHtml = function (ancestry, editor) {
  21008. var elm, item, fragment;
  21009. var schema = editor && editor.schema || Schema({});
  21010. var decorate = function (elm, item) {
  21011. if (item.classes.length) {
  21012. dom.addClass(elm, item.classes.join(' '));
  21013. }
  21014. dom.setAttribs(elm, item.attrs);
  21015. };
  21016. var createElement = function (sItem) {
  21017. item = typeof sItem === 'string' ? {
  21018. name: sItem,
  21019. classes: [],
  21020. attrs: {}
  21021. } : sItem;
  21022. var elm = dom.create(item.name);
  21023. decorate(elm, item);
  21024. return elm;
  21025. };
  21026. var getRequiredParent = function (elm, candidate) {
  21027. var name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm;
  21028. var elmRule = schema.getElementRule(name);
  21029. var parentsRequired = elmRule && elmRule.parentsRequired;
  21030. if (parentsRequired && parentsRequired.length) {
  21031. return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
  21032. } else {
  21033. return false;
  21034. }
  21035. };
  21036. var wrapInHtml = function (elm, ancestry, siblings) {
  21037. var parent, parentCandidate;
  21038. var ancestor = ancestry.length > 0 && ancestry[0];
  21039. var ancestorName = ancestor && ancestor.name;
  21040. var parentRequired = getRequiredParent(elm, ancestorName);
  21041. if (parentRequired) {
  21042. if (ancestorName === parentRequired) {
  21043. parentCandidate = ancestry[0];
  21044. ancestry = ancestry.slice(1);
  21045. } else {
  21046. parentCandidate = parentRequired;
  21047. }
  21048. } else if (ancestor) {
  21049. parentCandidate = ancestry[0];
  21050. ancestry = ancestry.slice(1);
  21051. } else if (!siblings) {
  21052. return elm;
  21053. }
  21054. if (parentCandidate) {
  21055. parent = createElement(parentCandidate);
  21056. parent.appendChild(elm);
  21057. }
  21058. if (siblings) {
  21059. if (!parent) {
  21060. parent = dom.create('div');
  21061. parent.appendChild(elm);
  21062. }
  21063. Tools.each(siblings, function (sibling) {
  21064. var siblingElm = createElement(sibling);
  21065. parent.insertBefore(siblingElm, elm);
  21066. });
  21067. }
  21068. return wrapInHtml(parent, ancestry, parentCandidate && parentCandidate.siblings);
  21069. };
  21070. if (ancestry && ancestry.length) {
  21071. item = ancestry[0];
  21072. elm = createElement(item);
  21073. fragment = dom.create('div');
  21074. fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
  21075. return fragment;
  21076. } else {
  21077. return '';
  21078. }
  21079. };
  21080. var parseSelectorItem = function (item) {
  21081. var tagName;
  21082. var obj = {
  21083. classes: [],
  21084. attrs: {}
  21085. };
  21086. item = obj.selector = Tools.trim(item);
  21087. if (item !== '*') {
  21088. tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function ($0, $1, $2, $3, $4) {
  21089. switch ($1) {
  21090. case '#':
  21091. obj.attrs.id = $2;
  21092. break;
  21093. case '.':
  21094. obj.classes.push($2);
  21095. break;
  21096. case ':':
  21097. if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
  21098. obj.attrs[$2] = $2;
  21099. }
  21100. break;
  21101. }
  21102. if ($3 === '[') {
  21103. var m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
  21104. if (m) {
  21105. obj.attrs[m[1]] = m[2];
  21106. }
  21107. }
  21108. return '';
  21109. });
  21110. }
  21111. obj.name = tagName || 'div';
  21112. return obj;
  21113. };
  21114. var parseSelector = function (selector) {
  21115. if (!selector || typeof selector !== 'string') {
  21116. return [];
  21117. }
  21118. selector = selector.split(/\s*,\s*/)[0];
  21119. selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1');
  21120. return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), function (item) {
  21121. var siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
  21122. var obj = siblings.pop();
  21123. if (siblings.length) {
  21124. obj.siblings = siblings;
  21125. }
  21126. return obj;
  21127. }).reverse();
  21128. };
  21129. var getCssText = function (editor, format) {
  21130. var name, previewFrag;
  21131. var previewCss = '', parentFontSize;
  21132. var previewStyles = getPreviewStyles(editor);
  21133. if (previewStyles === '') {
  21134. return '';
  21135. }
  21136. var removeVars = function (val) {
  21137. return val.replace(/%(\w+)/g, '');
  21138. };
  21139. if (typeof format === 'string') {
  21140. format = editor.formatter.get(format);
  21141. if (!format) {
  21142. return;
  21143. }
  21144. format = format[0];
  21145. }
  21146. if ('preview' in format) {
  21147. var previewOpt = get$9(format, 'preview');
  21148. if (is$1(previewOpt, false)) {
  21149. return '';
  21150. } else {
  21151. previewStyles = previewOpt.getOr(previewStyles);
  21152. }
  21153. }
  21154. name = format.block || format.inline || 'span';
  21155. var items = parseSelector(format.selector);
  21156. if (items.length) {
  21157. if (!items[0].name) {
  21158. items[0].name = name;
  21159. }
  21160. name = format.selector;
  21161. previewFrag = parsedSelectorToHtml(items, editor);
  21162. } else {
  21163. previewFrag = parsedSelectorToHtml([name], editor);
  21164. }
  21165. var previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;
  21166. each$5(format.styles, function (value, name) {
  21167. var newValue = removeVars(value);
  21168. if (newValue) {
  21169. dom.setStyle(previewElm, name, newValue);
  21170. }
  21171. });
  21172. each$5(format.attributes, function (value, name) {
  21173. var newValue = removeVars(value);
  21174. if (newValue) {
  21175. dom.setAttrib(previewElm, name, newValue);
  21176. }
  21177. });
  21178. each$5(format.classes, function (value) {
  21179. var newValue = removeVars(value);
  21180. if (!dom.hasClass(previewElm, newValue)) {
  21181. dom.addClass(previewElm, newValue);
  21182. }
  21183. });
  21184. editor.fire('PreviewFormats');
  21185. dom.setStyles(previewFrag, {
  21186. position: 'absolute',
  21187. left: -65535
  21188. });
  21189. editor.getBody().appendChild(previewFrag);
  21190. parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
  21191. parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
  21192. each$5(previewStyles.split(' '), function (name) {
  21193. var value = dom.getStyle(previewElm, name, true);
  21194. if (name === 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
  21195. value = dom.getStyle(editor.getBody(), name, true);
  21196. if (dom.toHex(value).toLowerCase() === '#ffffff') {
  21197. return;
  21198. }
  21199. }
  21200. if (name === 'color') {
  21201. if (dom.toHex(value).toLowerCase() === '#000000') {
  21202. return;
  21203. }
  21204. }
  21205. if (name === 'font-size') {
  21206. if (/em|%$/.test(value)) {
  21207. if (parentFontSize === 0) {
  21208. return;
  21209. }
  21210. var numValue = parseFloat(value) / (/%$/.test(value) ? 100 : 1);
  21211. value = numValue * parentFontSize + 'px';
  21212. }
  21213. }
  21214. if (name === 'border' && value) {
  21215. previewCss += 'padding:0 2px;';
  21216. }
  21217. previewCss += name + ':' + value + ';';
  21218. });
  21219. editor.fire('AfterPreviewFormats');
  21220. dom.remove(previewFrag);
  21221. return previewCss;
  21222. };
  21223. var setup$h = function (editor) {
  21224. editor.addShortcut('meta+b', '', 'Bold');
  21225. editor.addShortcut('meta+i', '', 'Italic');
  21226. editor.addShortcut('meta+u', '', 'Underline');
  21227. for (var i = 1; i <= 6; i++) {
  21228. editor.addShortcut('access+' + i, '', [
  21229. 'FormatBlock',
  21230. false,
  21231. 'h' + i
  21232. ]);
  21233. }
  21234. editor.addShortcut('access+7', '', [
  21235. 'FormatBlock',
  21236. false,
  21237. 'p'
  21238. ]);
  21239. editor.addShortcut('access+8', '', [
  21240. 'FormatBlock',
  21241. false,
  21242. 'div'
  21243. ]);
  21244. editor.addShortcut('access+9', '', [
  21245. 'FormatBlock',
  21246. false,
  21247. 'address'
  21248. ]);
  21249. };
  21250. var Formatter = function (editor) {
  21251. var formats = FormatRegistry(editor);
  21252. var formatChangeState = Cell(null);
  21253. setup$h(editor);
  21254. setup$k(editor);
  21255. return {
  21256. get: formats.get,
  21257. has: formats.has,
  21258. register: formats.register,
  21259. unregister: formats.unregister,
  21260. apply: function (name, vars, node) {
  21261. applyFormat(editor, name, vars, node);
  21262. },
  21263. remove: function (name, vars, node, similar) {
  21264. removeFormat(editor, name, vars, node, similar);
  21265. },
  21266. toggle: function (name, vars, node) {
  21267. toggleFormat(editor, name, vars, node);
  21268. },
  21269. match: function (name, vars, node, similar) {
  21270. return matchFormat(editor, name, vars, node, similar);
  21271. },
  21272. closest: function (names) {
  21273. return closestFormat(editor, names);
  21274. },
  21275. matchAll: function (names, vars) {
  21276. return matchAllFormats(editor, names, vars);
  21277. },
  21278. matchNode: function (node, name, vars, similar) {
  21279. return matchNodeFormat(editor, node, name, vars, similar);
  21280. },
  21281. canApply: function (name) {
  21282. return canApplyFormat(editor, name);
  21283. },
  21284. formatChanged: function (formats, callback, similar, vars) {
  21285. return formatChanged(editor, formatChangeState, formats, callback, similar, vars);
  21286. },
  21287. getCssText: curry(getCssText, editor)
  21288. };
  21289. };
  21290. var shouldIgnoreCommand = function (cmd) {
  21291. switch (cmd.toLowerCase()) {
  21292. case 'undo':
  21293. case 'redo':
  21294. case 'mcerepaint':
  21295. case 'mcefocus':
  21296. return true;
  21297. default:
  21298. return false;
  21299. }
  21300. };
  21301. var registerEvents = function (editor, undoManager, locks) {
  21302. var isFirstTypedCharacter = Cell(false);
  21303. var addNonTypingUndoLevel = function (e) {
  21304. setTyping(undoManager, false, locks);
  21305. undoManager.add({}, e);
  21306. };
  21307. editor.on('init', function () {
  21308. undoManager.add();
  21309. });
  21310. editor.on('BeforeExecCommand', function (e) {
  21311. var cmd = e.command;
  21312. if (!shouldIgnoreCommand(cmd)) {
  21313. endTyping(undoManager, locks);
  21314. undoManager.beforeChange();
  21315. }
  21316. });
  21317. editor.on('ExecCommand', function (e) {
  21318. var cmd = e.command;
  21319. if (!shouldIgnoreCommand(cmd)) {
  21320. addNonTypingUndoLevel(e);
  21321. }
  21322. });
  21323. editor.on('ObjectResizeStart cut', function () {
  21324. undoManager.beforeChange();
  21325. });
  21326. editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
  21327. editor.on('dragend', addNonTypingUndoLevel);
  21328. editor.on('keyup', function (e) {
  21329. var keyCode = e.keyCode;
  21330. if (e.isDefaultPrevented()) {
  21331. return;
  21332. }
  21333. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45 || e.ctrlKey) {
  21334. addNonTypingUndoLevel();
  21335. editor.nodeChanged();
  21336. }
  21337. if (keyCode === 46 || keyCode === 8) {
  21338. editor.nodeChanged();
  21339. }
  21340. if (isFirstTypedCharacter.get() && undoManager.typing && isEq$1(createFromEditor(editor), undoManager.data[0]) === false) {
  21341. if (editor.isDirty() === false) {
  21342. editor.setDirty(true);
  21343. editor.fire('change', {
  21344. level: undoManager.data[0],
  21345. lastLevel: null
  21346. });
  21347. }
  21348. editor.fire('TypingUndo');
  21349. isFirstTypedCharacter.set(false);
  21350. editor.nodeChanged();
  21351. }
  21352. });
  21353. editor.on('keydown', function (e) {
  21354. var keyCode = e.keyCode;
  21355. if (e.isDefaultPrevented()) {
  21356. return;
  21357. }
  21358. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45) {
  21359. if (undoManager.typing) {
  21360. addNonTypingUndoLevel(e);
  21361. }
  21362. return;
  21363. }
  21364. var modKey = e.ctrlKey && !e.altKey || e.metaKey;
  21365. if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !undoManager.typing && !modKey) {
  21366. undoManager.beforeChange();
  21367. setTyping(undoManager, true, locks);
  21368. undoManager.add({}, e);
  21369. isFirstTypedCharacter.set(true);
  21370. }
  21371. });
  21372. editor.on('mousedown', function (e) {
  21373. if (undoManager.typing) {
  21374. addNonTypingUndoLevel(e);
  21375. }
  21376. });
  21377. var isInsertReplacementText = function (event) {
  21378. return event.inputType === 'insertReplacementText';
  21379. };
  21380. var isInsertTextDataNull = function (event) {
  21381. return event.inputType === 'insertText' && event.data === null;
  21382. };
  21383. var isInsertFromPasteOrDrop = function (event) {
  21384. return event.inputType === 'insertFromPaste' || event.inputType === 'insertFromDrop';
  21385. };
  21386. editor.on('input', function (e) {
  21387. if (e.inputType && (isInsertReplacementText(e) || isInsertTextDataNull(e) || isInsertFromPasteOrDrop(e))) {
  21388. addNonTypingUndoLevel(e);
  21389. }
  21390. });
  21391. editor.on('AddUndo Undo Redo ClearUndos', function (e) {
  21392. if (!e.isDefaultPrevented()) {
  21393. editor.nodeChanged();
  21394. }
  21395. });
  21396. };
  21397. var addKeyboardShortcuts = function (editor) {
  21398. editor.addShortcut('meta+z', '', 'Undo');
  21399. editor.addShortcut('meta+y,meta+shift+z', '', 'Redo');
  21400. };
  21401. var UndoManager = function (editor) {
  21402. var beforeBookmark = value();
  21403. var locks = Cell(0);
  21404. var index = Cell(0);
  21405. var undoManager = {
  21406. data: [],
  21407. typing: false,
  21408. beforeChange: function () {
  21409. beforeChange(editor, locks, beforeBookmark);
  21410. },
  21411. add: function (level, event) {
  21412. return addUndoLevel(editor, undoManager, index, locks, beforeBookmark, level, event);
  21413. },
  21414. undo: function () {
  21415. return undo(editor, undoManager, locks, index);
  21416. },
  21417. redo: function () {
  21418. return redo(editor, index, undoManager.data);
  21419. },
  21420. clear: function () {
  21421. clear(editor, undoManager, index);
  21422. },
  21423. reset: function () {
  21424. reset(editor, undoManager);
  21425. },
  21426. hasUndo: function () {
  21427. return hasUndo(editor, undoManager, index);
  21428. },
  21429. hasRedo: function () {
  21430. return hasRedo(editor, undoManager, index);
  21431. },
  21432. transact: function (callback) {
  21433. return transact(editor, undoManager, locks, callback);
  21434. },
  21435. ignore: function (callback) {
  21436. ignore(editor, locks, callback);
  21437. },
  21438. extra: function (callback1, callback2) {
  21439. extra(editor, undoManager, index, callback1, callback2);
  21440. }
  21441. };
  21442. if (!isRtc(editor)) {
  21443. registerEvents(editor, undoManager, locks);
  21444. }
  21445. addKeyboardShortcuts(editor);
  21446. return undoManager;
  21447. };
  21448. var nonTypingKeycodes = [
  21449. 9,
  21450. 27,
  21451. VK.HOME,
  21452. VK.END,
  21453. 19,
  21454. 20,
  21455. 44,
  21456. 144,
  21457. 145,
  21458. 33,
  21459. 34,
  21460. 45,
  21461. 16,
  21462. 17,
  21463. 18,
  21464. 91,
  21465. 92,
  21466. 93,
  21467. VK.DOWN,
  21468. VK.UP,
  21469. VK.LEFT,
  21470. VK.RIGHT
  21471. ].concat(Env.browser.isFirefox() ? [224] : []);
  21472. var placeholderAttr = 'data-mce-placeholder';
  21473. var isKeyboardEvent = function (e) {
  21474. return e.type === 'keydown' || e.type === 'keyup';
  21475. };
  21476. var isDeleteEvent = function (e) {
  21477. var keyCode = e.keyCode;
  21478. return keyCode === VK.BACKSPACE || keyCode === VK.DELETE;
  21479. };
  21480. var isNonTypingKeyboardEvent = function (e) {
  21481. if (isKeyboardEvent(e)) {
  21482. var keyCode = e.keyCode;
  21483. return !isDeleteEvent(e) && (VK.metaKeyPressed(e) || e.altKey || keyCode >= 112 && keyCode <= 123 || contains$3(nonTypingKeycodes, keyCode));
  21484. } else {
  21485. return false;
  21486. }
  21487. };
  21488. var isTypingKeyboardEvent = function (e) {
  21489. return isKeyboardEvent(e) && !(isDeleteEvent(e) || e.type === 'keyup' && e.keyCode === 229);
  21490. };
  21491. var isVisuallyEmpty = function (dom, rootElm, forcedRootBlock) {
  21492. if (isEmpty$2(SugarElement.fromDom(rootElm), false)) {
  21493. var isForcedRootBlockFalse = forcedRootBlock === '';
  21494. var firstElement = rootElm.firstElementChild;
  21495. if (!firstElement) {
  21496. return true;
  21497. } else if (dom.getStyle(rootElm.firstElementChild, 'padding-left') || dom.getStyle(rootElm.firstElementChild, 'padding-right')) {
  21498. return false;
  21499. } else {
  21500. return isForcedRootBlockFalse ? !dom.isBlock(firstElement) : forcedRootBlock === firstElement.nodeName.toLowerCase();
  21501. }
  21502. } else {
  21503. return false;
  21504. }
  21505. };
  21506. var setup$g = function (editor) {
  21507. var dom = editor.dom;
  21508. var rootBlock = getForcedRootBlock(editor);
  21509. var placeholder = getPlaceholder(editor);
  21510. var updatePlaceholder = function (e, initial) {
  21511. if (isNonTypingKeyboardEvent(e)) {
  21512. return;
  21513. }
  21514. var body = editor.getBody();
  21515. var showPlaceholder = isTypingKeyboardEvent(e) ? false : isVisuallyEmpty(dom, body, rootBlock);
  21516. var isPlaceholderShown = dom.getAttrib(body, placeholderAttr) !== '';
  21517. if (isPlaceholderShown !== showPlaceholder || initial) {
  21518. dom.setAttrib(body, placeholderAttr, showPlaceholder ? placeholder : null);
  21519. dom.setAttrib(body, 'aria-placeholder', showPlaceholder ? placeholder : null);
  21520. firePlaceholderToggle(editor, showPlaceholder);
  21521. editor.on(showPlaceholder ? 'keydown' : 'keyup', updatePlaceholder);
  21522. editor.off(showPlaceholder ? 'keyup' : 'keydown', updatePlaceholder);
  21523. }
  21524. };
  21525. if (placeholder) {
  21526. editor.on('init', function (e) {
  21527. updatePlaceholder(e, true);
  21528. editor.on('change SetContent ExecCommand', updatePlaceholder);
  21529. editor.on('paste', function (e) {
  21530. return Delay.setEditorTimeout(editor, function () {
  21531. return updatePlaceholder(e);
  21532. });
  21533. });
  21534. });
  21535. }
  21536. };
  21537. var strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
  21538. var hasStrongRtl = function (text) {
  21539. return strongRtl.test(text);
  21540. };
  21541. var isInlineTarget = function (editor, elm) {
  21542. return is$2(SugarElement.fromDom(elm), getInlineBoundarySelector(editor));
  21543. };
  21544. var isRtl = function (element) {
  21545. return DOMUtils.DOM.getStyle(element, 'direction', true) === 'rtl' || hasStrongRtl(element.textContent);
  21546. };
  21547. var findInlineParents = function (isInlineTarget, rootNode, pos) {
  21548. return filter$4(DOMUtils.DOM.getParents(pos.container(), '*', rootNode), isInlineTarget);
  21549. };
  21550. var findRootInline = function (isInlineTarget, rootNode, pos) {
  21551. var parents = findInlineParents(isInlineTarget, rootNode, pos);
  21552. return Optional.from(parents[parents.length - 1]);
  21553. };
  21554. var hasSameParentBlock = function (rootNode, node1, node2) {
  21555. var block1 = getParentBlock$2(node1, rootNode);
  21556. var block2 = getParentBlock$2(node2, rootNode);
  21557. return block1 && block1 === block2;
  21558. };
  21559. var isAtZwsp = function (pos) {
  21560. return isBeforeInline(pos) || isAfterInline(pos);
  21561. };
  21562. var normalizePosition = function (forward, pos) {
  21563. if (!pos) {
  21564. return pos;
  21565. }
  21566. var container = pos.container(), offset = pos.offset();
  21567. if (forward) {
  21568. if (isCaretContainerInline(container)) {
  21569. if (isText$7(container.nextSibling)) {
  21570. return CaretPosition(container.nextSibling, 0);
  21571. } else {
  21572. return CaretPosition.after(container);
  21573. }
  21574. } else {
  21575. return isBeforeInline(pos) ? CaretPosition(container, offset + 1) : pos;
  21576. }
  21577. } else {
  21578. if (isCaretContainerInline(container)) {
  21579. if (isText$7(container.previousSibling)) {
  21580. return CaretPosition(container.previousSibling, container.previousSibling.data.length);
  21581. } else {
  21582. return CaretPosition.before(container);
  21583. }
  21584. } else {
  21585. return isAfterInline(pos) ? CaretPosition(container, offset - 1) : pos;
  21586. }
  21587. }
  21588. };
  21589. var normalizeForwards = curry(normalizePosition, true);
  21590. var normalizeBackwards = curry(normalizePosition, false);
  21591. var isBeforeRoot = function (rootNode) {
  21592. return function (elm) {
  21593. return eq(rootNode, SugarElement.fromDom(elm.dom.parentNode));
  21594. };
  21595. };
  21596. var isTextBlockOrListItem = function (element) {
  21597. return isTextBlock$2(element) || isListItem(element);
  21598. };
  21599. var getParentBlock$1 = function (rootNode, elm) {
  21600. if (contains$1(rootNode, elm)) {
  21601. return closest$3(elm, isTextBlockOrListItem, isBeforeRoot(rootNode));
  21602. } else {
  21603. return Optional.none();
  21604. }
  21605. };
  21606. var placeCaretInEmptyBody = function (editor) {
  21607. var body = editor.getBody();
  21608. var node = body.firstChild && editor.dom.isBlock(body.firstChild) ? body.firstChild : body;
  21609. editor.selection.setCursorLocation(node, 0);
  21610. };
  21611. var paddEmptyBody = function (editor) {
  21612. if (editor.dom.isEmpty(editor.getBody())) {
  21613. editor.setContent('');
  21614. placeCaretInEmptyBody(editor);
  21615. }
  21616. };
  21617. var willDeleteLastPositionInElement = function (forward, fromPos, elm) {
  21618. return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  21619. var normalizedFirstPos = normalizePosition(true, firstPos);
  21620. var normalizedLastPos = normalizePosition(false, lastPos);
  21621. var normalizedFromPos = normalizePosition(false, fromPos);
  21622. if (forward) {
  21623. return nextPosition(elm, normalizedFromPos).exists(function (nextPos) {
  21624. return nextPos.isEqual(normalizedLastPos) && fromPos.isEqual(normalizedFirstPos);
  21625. });
  21626. } else {
  21627. return prevPosition(elm, normalizedFromPos).exists(function (prevPos) {
  21628. return prevPos.isEqual(normalizedFirstPos) && fromPos.isEqual(normalizedLastPos);
  21629. });
  21630. }
  21631. }).getOr(true);
  21632. };
  21633. var blockPosition = function (block, position) {
  21634. return {
  21635. block: block,
  21636. position: position
  21637. };
  21638. };
  21639. var blockBoundary = function (from, to) {
  21640. return {
  21641. from: from,
  21642. to: to
  21643. };
  21644. };
  21645. var getBlockPosition = function (rootNode, pos) {
  21646. var rootElm = SugarElement.fromDom(rootNode);
  21647. var containerElm = SugarElement.fromDom(pos.container());
  21648. return getParentBlock$1(rootElm, containerElm).map(function (block) {
  21649. return blockPosition(block, pos);
  21650. });
  21651. };
  21652. var isDifferentBlocks = function (blockBoundary) {
  21653. return eq(blockBoundary.from.block, blockBoundary.to.block) === false;
  21654. };
  21655. var hasSameParent = function (blockBoundary) {
  21656. return parent(blockBoundary.from.block).bind(function (parent1) {
  21657. return parent(blockBoundary.to.block).filter(function (parent2) {
  21658. return eq(parent1, parent2);
  21659. });
  21660. }).isSome();
  21661. };
  21662. var isEditable$1 = function (blockBoundary) {
  21663. return isContentEditableFalse$b(blockBoundary.from.block.dom) === false && isContentEditableFalse$b(blockBoundary.to.block.dom) === false;
  21664. };
  21665. var skipLastBr = function (rootNode, forward, blockPosition) {
  21666. if (isBr$5(blockPosition.position.getNode()) && isEmpty$2(blockPosition.block) === false) {
  21667. return positionIn(false, blockPosition.block.dom).bind(function (lastPositionInBlock) {
  21668. if (lastPositionInBlock.isEqual(blockPosition.position)) {
  21669. return fromPosition(forward, rootNode, lastPositionInBlock).bind(function (to) {
  21670. return getBlockPosition(rootNode, to);
  21671. });
  21672. } else {
  21673. return Optional.some(blockPosition);
  21674. }
  21675. }).getOr(blockPosition);
  21676. } else {
  21677. return blockPosition;
  21678. }
  21679. };
  21680. var readFromRange = function (rootNode, forward, rng) {
  21681. var fromBlockPos = getBlockPosition(rootNode, CaretPosition.fromRangeStart(rng));
  21682. var toBlockPos = fromBlockPos.bind(function (blockPos) {
  21683. return fromPosition(forward, rootNode, blockPos.position).bind(function (to) {
  21684. return getBlockPosition(rootNode, to).map(function (blockPos) {
  21685. return skipLastBr(rootNode, forward, blockPos);
  21686. });
  21687. });
  21688. });
  21689. return lift2(fromBlockPos, toBlockPos, blockBoundary).filter(function (blockBoundary) {
  21690. return isDifferentBlocks(blockBoundary) && hasSameParent(blockBoundary) && isEditable$1(blockBoundary);
  21691. });
  21692. };
  21693. var read$1 = function (rootNode, forward, rng) {
  21694. return rng.collapsed ? readFromRange(rootNode, forward, rng) : Optional.none();
  21695. };
  21696. var getChildrenUntilBlockBoundary = function (block) {
  21697. var children$1 = children(block);
  21698. return findIndex$2(children$1, isBlock$2).fold(constant(children$1), function (index) {
  21699. return children$1.slice(0, index);
  21700. });
  21701. };
  21702. var extractChildren = function (block) {
  21703. var children = getChildrenUntilBlockBoundary(block);
  21704. each$k(children, remove$7);
  21705. return children;
  21706. };
  21707. var removeEmptyRoot = function (rootNode, block) {
  21708. var parents = parentsAndSelf(block, rootNode);
  21709. return find$3(parents.reverse(), function (element) {
  21710. return isEmpty$2(element);
  21711. }).each(remove$7);
  21712. };
  21713. var isEmptyBefore = function (el) {
  21714. return filter$4(prevSiblings(el), function (el) {
  21715. return !isEmpty$2(el);
  21716. }).length === 0;
  21717. };
  21718. var nestedBlockMerge = function (rootNode, fromBlock, toBlock, insertionPoint) {
  21719. if (isEmpty$2(toBlock)) {
  21720. fillWithPaddingBr(toBlock);
  21721. return firstPositionIn(toBlock.dom);
  21722. }
  21723. if (isEmptyBefore(insertionPoint) && isEmpty$2(fromBlock)) {
  21724. before$4(insertionPoint, SugarElement.fromTag('br'));
  21725. }
  21726. var position = prevPosition(toBlock.dom, CaretPosition.before(insertionPoint.dom));
  21727. each$k(extractChildren(fromBlock), function (child) {
  21728. before$4(insertionPoint, child);
  21729. });
  21730. removeEmptyRoot(rootNode, fromBlock);
  21731. return position;
  21732. };
  21733. var sidelongBlockMerge = function (rootNode, fromBlock, toBlock) {
  21734. if (isEmpty$2(toBlock)) {
  21735. remove$7(toBlock);
  21736. if (isEmpty$2(fromBlock)) {
  21737. fillWithPaddingBr(fromBlock);
  21738. }
  21739. return firstPositionIn(fromBlock.dom);
  21740. }
  21741. var position = lastPositionIn(toBlock.dom);
  21742. each$k(extractChildren(fromBlock), function (child) {
  21743. append$1(toBlock, child);
  21744. });
  21745. removeEmptyRoot(rootNode, fromBlock);
  21746. return position;
  21747. };
  21748. var findInsertionPoint = function (toBlock, block) {
  21749. var parentsAndSelf$1 = parentsAndSelf(block, toBlock);
  21750. return Optional.from(parentsAndSelf$1[parentsAndSelf$1.length - 1]);
  21751. };
  21752. var getInsertionPoint = function (fromBlock, toBlock) {
  21753. return contains$1(toBlock, fromBlock) ? findInsertionPoint(toBlock, fromBlock) : Optional.none();
  21754. };
  21755. var trimBr = function (first, block) {
  21756. positionIn(first, block.dom).map(function (position) {
  21757. return position.getNode();
  21758. }).map(SugarElement.fromDom).filter(isBr$4).each(remove$7);
  21759. };
  21760. var mergeBlockInto = function (rootNode, fromBlock, toBlock) {
  21761. trimBr(true, fromBlock);
  21762. trimBr(false, toBlock);
  21763. return getInsertionPoint(fromBlock, toBlock).fold(curry(sidelongBlockMerge, rootNode, fromBlock, toBlock), curry(nestedBlockMerge, rootNode, fromBlock, toBlock));
  21764. };
  21765. var mergeBlocks = function (rootNode, forward, block1, block2) {
  21766. return forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
  21767. };
  21768. var backspaceDelete$8 = function (editor, forward) {
  21769. var rootNode = SugarElement.fromDom(editor.getBody());
  21770. var position = read$1(rootNode.dom, forward, editor.selection.getRng()).bind(function (blockBoundary) {
  21771. return mergeBlocks(rootNode, forward, blockBoundary.from.block, blockBoundary.to.block);
  21772. });
  21773. position.each(function (pos) {
  21774. editor.selection.setRng(pos.toRange());
  21775. });
  21776. return position.isSome();
  21777. };
  21778. var deleteRangeMergeBlocks = function (rootNode, selection) {
  21779. var rng = selection.getRng();
  21780. return lift2(getParentBlock$1(rootNode, SugarElement.fromDom(rng.startContainer)), getParentBlock$1(rootNode, SugarElement.fromDom(rng.endContainer)), function (block1, block2) {
  21781. if (eq(block1, block2) === false) {
  21782. rng.deleteContents();
  21783. mergeBlocks(rootNode, true, block1, block2).each(function (pos) {
  21784. selection.setRng(pos.toRange());
  21785. });
  21786. return true;
  21787. } else {
  21788. return false;
  21789. }
  21790. }).getOr(false);
  21791. };
  21792. var isRawNodeInTable = function (root, rawNode) {
  21793. var node = SugarElement.fromDom(rawNode);
  21794. var isRoot = curry(eq, root);
  21795. return ancestor$3(node, isTableCell$4, isRoot).isSome();
  21796. };
  21797. var isSelectionInTable = function (root, rng) {
  21798. return isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
  21799. };
  21800. var isEverythingSelected = function (root, rng) {
  21801. var noPrevious = prevPosition(root.dom, CaretPosition.fromRangeStart(rng)).isNone();
  21802. var noNext = nextPosition(root.dom, CaretPosition.fromRangeEnd(rng)).isNone();
  21803. return !isSelectionInTable(root, rng) && noPrevious && noNext;
  21804. };
  21805. var emptyEditor = function (editor) {
  21806. editor.setContent('');
  21807. editor.selection.setCursorLocation();
  21808. return true;
  21809. };
  21810. var deleteRange$1 = function (editor) {
  21811. var rootNode = SugarElement.fromDom(editor.getBody());
  21812. var rng = editor.selection.getRng();
  21813. return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
  21814. };
  21815. var backspaceDelete$7 = function (editor, _forward) {
  21816. return editor.selection.isCollapsed() ? false : deleteRange$1(editor);
  21817. };
  21818. var isContentEditableTrue$2 = isContentEditableTrue$4;
  21819. var isContentEditableFalse$4 = isContentEditableFalse$b;
  21820. var showCaret = function (direction, editor, node, before, scrollIntoView) {
  21821. return Optional.from(editor._selectionOverrides.showCaret(direction, node, before, scrollIntoView));
  21822. };
  21823. var getNodeRange = function (node) {
  21824. var rng = node.ownerDocument.createRange();
  21825. rng.selectNode(node);
  21826. return rng;
  21827. };
  21828. var selectNode = function (editor, node) {
  21829. var e = editor.fire('BeforeObjectSelected', { target: node });
  21830. if (e.isDefaultPrevented()) {
  21831. return Optional.none();
  21832. }
  21833. return Optional.some(getNodeRange(node));
  21834. };
  21835. var renderCaretAtRange = function (editor, range, scrollIntoView) {
  21836. var normalizedRange = normalizeRange(1, editor.getBody(), range);
  21837. var caretPosition = CaretPosition.fromRangeStart(normalizedRange);
  21838. var caretPositionNode = caretPosition.getNode();
  21839. if (isInlineFakeCaretTarget(caretPositionNode)) {
  21840. return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
  21841. }
  21842. var caretPositionBeforeNode = caretPosition.getNode(true);
  21843. if (isInlineFakeCaretTarget(caretPositionBeforeNode)) {
  21844. return showCaret(1, editor, caretPositionBeforeNode, false, false);
  21845. }
  21846. var ceRoot = editor.dom.getParent(caretPosition.getNode(), function (node) {
  21847. return isContentEditableFalse$4(node) || isContentEditableTrue$2(node);
  21848. });
  21849. if (isInlineFakeCaretTarget(ceRoot)) {
  21850. return showCaret(1, editor, ceRoot, false, scrollIntoView);
  21851. }
  21852. return Optional.none();
  21853. };
  21854. var renderRangeCaret = function (editor, range, scrollIntoView) {
  21855. return range.collapsed ? renderCaretAtRange(editor, range, scrollIntoView).getOr(range) : range;
  21856. };
  21857. var isBeforeBoundary = function (pos) {
  21858. return isBeforeContentEditableFalse(pos) || isBeforeMedia(pos);
  21859. };
  21860. var isAfterBoundary = function (pos) {
  21861. return isAfterContentEditableFalse(pos) || isAfterMedia(pos);
  21862. };
  21863. var trimEmptyTextNode = function (dom, node) {
  21864. if (isText$7(node) && node.data.length === 0) {
  21865. dom.remove(node);
  21866. }
  21867. };
  21868. var deleteContentAndShowCaret = function (editor, range, node, direction, forward, peekCaretPosition) {
  21869. showCaret(direction, editor, peekCaretPosition.getNode(!forward), forward, true).each(function (caretRange) {
  21870. if (range.collapsed) {
  21871. var deleteRange = range.cloneRange();
  21872. if (forward) {
  21873. deleteRange.setEnd(caretRange.startContainer, caretRange.startOffset);
  21874. } else {
  21875. deleteRange.setStart(caretRange.endContainer, caretRange.endOffset);
  21876. }
  21877. deleteRange.deleteContents();
  21878. } else {
  21879. range.deleteContents();
  21880. }
  21881. editor.selection.setRng(caretRange);
  21882. });
  21883. trimEmptyTextNode(editor.dom, node);
  21884. return true;
  21885. };
  21886. var deleteBoundaryText = function (editor, forward) {
  21887. var range = editor.selection.getRng();
  21888. if (!isText$7(range.commonAncestorContainer)) {
  21889. return false;
  21890. }
  21891. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  21892. var caretWalker = CaretWalker(editor.getBody());
  21893. var getNextPosFn = curry(getVisualCaretPosition, forward ? caretWalker.next : caretWalker.prev);
  21894. var isBeforeFn = forward ? isBeforeBoundary : isAfterBoundary;
  21895. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  21896. var nextCaretPosition = normalizePosition(forward, getNextPosFn(caretPosition));
  21897. if (!nextCaretPosition || !isMoveInsideSameBlock(caretPosition, nextCaretPosition)) {
  21898. return false;
  21899. } else if (isBeforeFn(nextCaretPosition)) {
  21900. return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, nextCaretPosition);
  21901. }
  21902. var peekCaretPosition = getNextPosFn(nextCaretPosition);
  21903. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  21904. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  21905. return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, peekCaretPosition);
  21906. }
  21907. }
  21908. return false;
  21909. };
  21910. var backspaceDelete$6 = function (editor, forward) {
  21911. return deleteBoundaryText(editor, forward);
  21912. };
  21913. var isCompoundElement = function (node) {
  21914. return isTableCell$4(SugarElement.fromDom(node)) || isListItem(SugarElement.fromDom(node));
  21915. };
  21916. var DeleteAction = Adt.generate([
  21917. { remove: ['element'] },
  21918. { moveToElement: ['element'] },
  21919. { moveToPosition: ['position'] }
  21920. ]);
  21921. var isAtContentEditableBlockCaret = function (forward, from) {
  21922. var elm = from.getNode(forward === false);
  21923. var caretLocation = forward ? 'after' : 'before';
  21924. return isElement$5(elm) && elm.getAttribute('data-mce-caret') === caretLocation;
  21925. };
  21926. var isDeleteFromCefDifferentBlocks = function (root, forward, from, to) {
  21927. var inSameBlock = function (elm) {
  21928. return isInline$1(SugarElement.fromDom(elm)) && !isInSameBlock(from, to, root);
  21929. };
  21930. return getRelativeCefElm(!forward, from).fold(function () {
  21931. return getRelativeCefElm(forward, to).fold(never, inSameBlock);
  21932. }, inSameBlock);
  21933. };
  21934. var deleteEmptyBlockOrMoveToCef = function (root, forward, from, to) {
  21935. var toCefElm = to.getNode(forward === false);
  21936. return getParentBlock$1(SugarElement.fromDom(root), SugarElement.fromDom(from.getNode())).map(function (blockElm) {
  21937. return isEmpty$2(blockElm) ? DeleteAction.remove(blockElm.dom) : DeleteAction.moveToElement(toCefElm);
  21938. }).orThunk(function () {
  21939. return Optional.some(DeleteAction.moveToElement(toCefElm));
  21940. });
  21941. };
  21942. var findCefPosition = function (root, forward, from) {
  21943. return fromPosition(forward, root, from).bind(function (to) {
  21944. if (isCompoundElement(to.getNode())) {
  21945. return Optional.none();
  21946. } else if (isDeleteFromCefDifferentBlocks(root, forward, from, to)) {
  21947. return Optional.none();
  21948. } else if (forward && isContentEditableFalse$b(to.getNode())) {
  21949. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  21950. } else if (forward === false && isContentEditableFalse$b(to.getNode(true))) {
  21951. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  21952. } else if (forward && isAfterContentEditableFalse(from)) {
  21953. return Optional.some(DeleteAction.moveToPosition(to));
  21954. } else if (forward === false && isBeforeContentEditableFalse(from)) {
  21955. return Optional.some(DeleteAction.moveToPosition(to));
  21956. } else {
  21957. return Optional.none();
  21958. }
  21959. });
  21960. };
  21961. var getContentEditableBlockAction = function (forward, elm) {
  21962. if (forward && isContentEditableFalse$b(elm.nextSibling)) {
  21963. return Optional.some(DeleteAction.moveToElement(elm.nextSibling));
  21964. } else if (forward === false && isContentEditableFalse$b(elm.previousSibling)) {
  21965. return Optional.some(DeleteAction.moveToElement(elm.previousSibling));
  21966. } else {
  21967. return Optional.none();
  21968. }
  21969. };
  21970. var skipMoveToActionFromInlineCefToContent = function (root, from, deleteAction) {
  21971. return deleteAction.fold(function (elm) {
  21972. return Optional.some(DeleteAction.remove(elm));
  21973. }, function (elm) {
  21974. return Optional.some(DeleteAction.moveToElement(elm));
  21975. }, function (to) {
  21976. if (isInSameBlock(from, to, root)) {
  21977. return Optional.none();
  21978. } else {
  21979. return Optional.some(DeleteAction.moveToPosition(to));
  21980. }
  21981. });
  21982. };
  21983. var getContentEditableAction = function (root, forward, from) {
  21984. if (isAtContentEditableBlockCaret(forward, from)) {
  21985. return getContentEditableBlockAction(forward, from.getNode(forward === false)).fold(function () {
  21986. return findCefPosition(root, forward, from);
  21987. }, Optional.some);
  21988. } else {
  21989. return findCefPosition(root, forward, from).bind(function (deleteAction) {
  21990. return skipMoveToActionFromInlineCefToContent(root, from, deleteAction);
  21991. });
  21992. }
  21993. };
  21994. var read = function (root, forward, rng) {
  21995. var normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
  21996. var from = CaretPosition.fromRangeStart(normalizedRange);
  21997. var rootElement = SugarElement.fromDom(root);
  21998. if (forward === false && isAfterContentEditableFalse(from)) {
  21999. return Optional.some(DeleteAction.remove(from.getNode(true)));
  22000. } else if (forward && isBeforeContentEditableFalse(from)) {
  22001. return Optional.some(DeleteAction.remove(from.getNode()));
  22002. } else if (forward === false && isBeforeContentEditableFalse(from) && isAfterBr(rootElement, from)) {
  22003. return findPreviousBr(rootElement, from).map(function (br) {
  22004. return DeleteAction.remove(br.getNode());
  22005. });
  22006. } else if (forward && isAfterContentEditableFalse(from) && isBeforeBr$1(rootElement, from)) {
  22007. return findNextBr(rootElement, from).map(function (br) {
  22008. return DeleteAction.remove(br.getNode());
  22009. });
  22010. } else {
  22011. return getContentEditableAction(root, forward, from);
  22012. }
  22013. };
  22014. var deleteElement$1 = function (editor, forward) {
  22015. return function (element) {
  22016. editor._selectionOverrides.hideFakeCaret();
  22017. deleteElement$2(editor, forward, SugarElement.fromDom(element));
  22018. return true;
  22019. };
  22020. };
  22021. var moveToElement = function (editor, forward) {
  22022. return function (element) {
  22023. var pos = forward ? CaretPosition.before(element) : CaretPosition.after(element);
  22024. editor.selection.setRng(pos.toRange());
  22025. return true;
  22026. };
  22027. };
  22028. var moveToPosition = function (editor) {
  22029. return function (pos) {
  22030. editor.selection.setRng(pos.toRange());
  22031. return true;
  22032. };
  22033. };
  22034. var getAncestorCe = function (editor, node) {
  22035. return Optional.from(getContentEditableRoot$1(editor.getBody(), node));
  22036. };
  22037. var backspaceDeleteCaret = function (editor, forward) {
  22038. var selectedNode = editor.selection.getNode();
  22039. return getAncestorCe(editor, selectedNode).filter(isContentEditableFalse$b).fold(function () {
  22040. return read(editor.getBody(), forward, editor.selection.getRng()).exists(function (deleteAction) {
  22041. return deleteAction.fold(deleteElement$1(editor, forward), moveToElement(editor, forward), moveToPosition(editor));
  22042. });
  22043. }, always);
  22044. };
  22045. var deleteOffscreenSelection = function (rootElement) {
  22046. each$k(descendants(rootElement, '.mce-offscreen-selection'), remove$7);
  22047. };
  22048. var backspaceDeleteRange = function (editor, forward) {
  22049. var selectedNode = editor.selection.getNode();
  22050. if (isContentEditableFalse$b(selectedNode) && !isTableCell$5(selectedNode)) {
  22051. var hasCefAncestor = getAncestorCe(editor, selectedNode.parentNode).filter(isContentEditableFalse$b);
  22052. return hasCefAncestor.fold(function () {
  22053. deleteOffscreenSelection(SugarElement.fromDom(editor.getBody()));
  22054. deleteElement$2(editor, forward, SugarElement.fromDom(editor.selection.getNode()));
  22055. paddEmptyBody(editor);
  22056. return true;
  22057. }, always);
  22058. }
  22059. return false;
  22060. };
  22061. var paddEmptyElement = function (editor) {
  22062. var dom = editor.dom, selection = editor.selection;
  22063. var ceRoot = getContentEditableRoot$1(editor.getBody(), selection.getNode());
  22064. if (isContentEditableTrue$4(ceRoot) && dom.isBlock(ceRoot) && dom.isEmpty(ceRoot)) {
  22065. var br = dom.create('br', { 'data-mce-bogus': '1' });
  22066. dom.setHTML(ceRoot, '');
  22067. ceRoot.appendChild(br);
  22068. selection.setRng(CaretPosition.before(br).toRange());
  22069. }
  22070. return true;
  22071. };
  22072. var backspaceDelete$5 = function (editor, forward) {
  22073. if (editor.selection.isCollapsed()) {
  22074. return backspaceDeleteCaret(editor, forward);
  22075. } else {
  22076. return backspaceDeleteRange(editor, forward);
  22077. }
  22078. };
  22079. var deleteCaret$2 = function (editor, forward) {
  22080. var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22081. return fromPosition(forward, editor.getBody(), fromPos).filter(function (pos) {
  22082. return forward ? isBeforeImageBlock(pos) : isAfterImageBlock(pos);
  22083. }).bind(function (pos) {
  22084. return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, pos));
  22085. }).exists(function (elm) {
  22086. editor.selection.select(elm);
  22087. return true;
  22088. });
  22089. };
  22090. var backspaceDelete$4 = function (editor, forward) {
  22091. return editor.selection.isCollapsed() ? deleteCaret$2(editor, forward) : false;
  22092. };
  22093. var isText = isText$7;
  22094. var startsWithCaretContainer = function (node) {
  22095. return isText(node) && node.data[0] === ZWSP$1;
  22096. };
  22097. var endsWithCaretContainer = function (node) {
  22098. return isText(node) && node.data[node.data.length - 1] === ZWSP$1;
  22099. };
  22100. var createZwsp = function (node) {
  22101. return node.ownerDocument.createTextNode(ZWSP$1);
  22102. };
  22103. var insertBefore = function (node) {
  22104. if (isText(node.previousSibling)) {
  22105. if (endsWithCaretContainer(node.previousSibling)) {
  22106. return node.previousSibling;
  22107. } else {
  22108. node.previousSibling.appendData(ZWSP$1);
  22109. return node.previousSibling;
  22110. }
  22111. } else if (isText(node)) {
  22112. if (startsWithCaretContainer(node)) {
  22113. return node;
  22114. } else {
  22115. node.insertData(0, ZWSP$1);
  22116. return node;
  22117. }
  22118. } else {
  22119. var newNode = createZwsp(node);
  22120. node.parentNode.insertBefore(newNode, node);
  22121. return newNode;
  22122. }
  22123. };
  22124. var insertAfter = function (node) {
  22125. if (isText(node.nextSibling)) {
  22126. if (startsWithCaretContainer(node.nextSibling)) {
  22127. return node.nextSibling;
  22128. } else {
  22129. node.nextSibling.insertData(0, ZWSP$1);
  22130. return node.nextSibling;
  22131. }
  22132. } else if (isText(node)) {
  22133. if (endsWithCaretContainer(node)) {
  22134. return node;
  22135. } else {
  22136. node.appendData(ZWSP$1);
  22137. return node;
  22138. }
  22139. } else {
  22140. var newNode = createZwsp(node);
  22141. if (node.nextSibling) {
  22142. node.parentNode.insertBefore(newNode, node.nextSibling);
  22143. } else {
  22144. node.parentNode.appendChild(newNode);
  22145. }
  22146. return newNode;
  22147. }
  22148. };
  22149. var insertInline = function (before, node) {
  22150. return before ? insertBefore(node) : insertAfter(node);
  22151. };
  22152. var insertInlineBefore = curry(insertInline, true);
  22153. var insertInlineAfter = curry(insertInline, false);
  22154. var insertInlinePos = function (pos, before) {
  22155. if (isText$7(pos.container())) {
  22156. return insertInline(before, pos.container());
  22157. } else {
  22158. return insertInline(before, pos.getNode());
  22159. }
  22160. };
  22161. var isPosCaretContainer = function (pos, caret) {
  22162. var caretNode = caret.get();
  22163. return caretNode && pos.container() === caretNode && isCaretContainerInline(caretNode);
  22164. };
  22165. var renderCaret = function (caret, location) {
  22166. return location.fold(function (element) {
  22167. remove$2(caret.get());
  22168. var text = insertInlineBefore(element);
  22169. caret.set(text);
  22170. return Optional.some(CaretPosition(text, text.length - 1));
  22171. }, function (element) {
  22172. return firstPositionIn(element).map(function (pos) {
  22173. if (!isPosCaretContainer(pos, caret)) {
  22174. remove$2(caret.get());
  22175. var text = insertInlinePos(pos, true);
  22176. caret.set(text);
  22177. return CaretPosition(text, 1);
  22178. } else {
  22179. return CaretPosition(caret.get(), 1);
  22180. }
  22181. });
  22182. }, function (element) {
  22183. return lastPositionIn(element).map(function (pos) {
  22184. if (!isPosCaretContainer(pos, caret)) {
  22185. remove$2(caret.get());
  22186. var text = insertInlinePos(pos, false);
  22187. caret.set(text);
  22188. return CaretPosition(text, text.length - 1);
  22189. } else {
  22190. return CaretPosition(caret.get(), caret.get().length - 1);
  22191. }
  22192. });
  22193. }, function (element) {
  22194. remove$2(caret.get());
  22195. var text = insertInlineAfter(element);
  22196. caret.set(text);
  22197. return Optional.some(CaretPosition(text, 1));
  22198. });
  22199. };
  22200. var evaluateUntil = function (fns, args) {
  22201. for (var i = 0; i < fns.length; i++) {
  22202. var result = fns[i].apply(null, args);
  22203. if (result.isSome()) {
  22204. return result;
  22205. }
  22206. }
  22207. return Optional.none();
  22208. };
  22209. var Location = Adt.generate([
  22210. { before: ['element'] },
  22211. { start: ['element'] },
  22212. { end: ['element'] },
  22213. { after: ['element'] }
  22214. ]);
  22215. var rescope$1 = function (rootNode, node) {
  22216. var parentBlock = getParentBlock$2(node, rootNode);
  22217. return parentBlock ? parentBlock : rootNode;
  22218. };
  22219. var before = function (isInlineTarget, rootNode, pos) {
  22220. var nPos = normalizeForwards(pos);
  22221. var scope = rescope$1(rootNode, nPos.container());
  22222. return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  22223. return nextPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  22224. return Location.before(inline);
  22225. });
  22226. }, Optional.none);
  22227. };
  22228. var isNotInsideFormatCaretContainer = function (rootNode, elm) {
  22229. return getParentCaretContainer(rootNode, elm) === null;
  22230. };
  22231. var findInsideRootInline = function (isInlineTarget, rootNode, pos) {
  22232. return findRootInline(isInlineTarget, rootNode, pos).filter(curry(isNotInsideFormatCaretContainer, rootNode));
  22233. };
  22234. var start$1 = function (isInlineTarget, rootNode, pos) {
  22235. var nPos = normalizeBackwards(pos);
  22236. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  22237. var prevPos = prevPosition(inline, nPos);
  22238. return prevPos.isNone() ? Optional.some(Location.start(inline)) : Optional.none();
  22239. });
  22240. };
  22241. var end = function (isInlineTarget, rootNode, pos) {
  22242. var nPos = normalizeForwards(pos);
  22243. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  22244. var nextPos = nextPosition(inline, nPos);
  22245. return nextPos.isNone() ? Optional.some(Location.end(inline)) : Optional.none();
  22246. });
  22247. };
  22248. var after = function (isInlineTarget, rootNode, pos) {
  22249. var nPos = normalizeBackwards(pos);
  22250. var scope = rescope$1(rootNode, nPos.container());
  22251. return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  22252. return prevPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  22253. return Location.after(inline);
  22254. });
  22255. }, Optional.none);
  22256. };
  22257. var isValidLocation = function (location) {
  22258. return isRtl(getElement(location)) === false;
  22259. };
  22260. var readLocation = function (isInlineTarget, rootNode, pos) {
  22261. var location = evaluateUntil([
  22262. before,
  22263. start$1,
  22264. end,
  22265. after
  22266. ], [
  22267. isInlineTarget,
  22268. rootNode,
  22269. pos
  22270. ]);
  22271. return location.filter(isValidLocation);
  22272. };
  22273. var getElement = function (location) {
  22274. return location.fold(identity, identity, identity, identity);
  22275. };
  22276. var getName = function (location) {
  22277. return location.fold(constant('before'), constant('start'), constant('end'), constant('after'));
  22278. };
  22279. var outside = function (location) {
  22280. return location.fold(Location.before, Location.before, Location.after, Location.after);
  22281. };
  22282. var inside = function (location) {
  22283. return location.fold(Location.start, Location.start, Location.end, Location.end);
  22284. };
  22285. var isEq = function (location1, location2) {
  22286. return getName(location1) === getName(location2) && getElement(location1) === getElement(location2);
  22287. };
  22288. var betweenInlines = function (forward, isInlineTarget, rootNode, from, to, location) {
  22289. return lift2(findRootInline(isInlineTarget, rootNode, from), findRootInline(isInlineTarget, rootNode, to), function (fromInline, toInline) {
  22290. if (fromInline !== toInline && hasSameParentBlock(rootNode, fromInline, toInline)) {
  22291. return Location.after(forward ? fromInline : toInline);
  22292. } else {
  22293. return location;
  22294. }
  22295. }).getOr(location);
  22296. };
  22297. var skipNoMovement = function (fromLocation, toLocation) {
  22298. return fromLocation.fold(always, function (fromLocation) {
  22299. return !isEq(fromLocation, toLocation);
  22300. });
  22301. };
  22302. var findLocationTraverse = function (forward, isInlineTarget, rootNode, fromLocation, pos) {
  22303. var from = normalizePosition(forward, pos);
  22304. var to = fromPosition(forward, rootNode, from).map(curry(normalizePosition, forward));
  22305. var location = to.fold(function () {
  22306. return fromLocation.map(outside);
  22307. }, function (to) {
  22308. return readLocation(isInlineTarget, rootNode, to).map(curry(betweenInlines, forward, isInlineTarget, rootNode, from, to)).filter(curry(skipNoMovement, fromLocation));
  22309. });
  22310. return location.filter(isValidLocation);
  22311. };
  22312. var findLocationSimple = function (forward, location) {
  22313. if (forward) {
  22314. return location.fold(compose(Optional.some, Location.start), Optional.none, compose(Optional.some, Location.after), Optional.none);
  22315. } else {
  22316. return location.fold(Optional.none, compose(Optional.some, Location.before), Optional.none, compose(Optional.some, Location.end));
  22317. }
  22318. };
  22319. var findLocation$1 = function (forward, isInlineTarget, rootNode, pos) {
  22320. var from = normalizePosition(forward, pos);
  22321. var fromLocation = readLocation(isInlineTarget, rootNode, from);
  22322. return readLocation(isInlineTarget, rootNode, from).bind(curry(findLocationSimple, forward)).orThunk(function () {
  22323. return findLocationTraverse(forward, isInlineTarget, rootNode, fromLocation, pos);
  22324. });
  22325. };
  22326. curry(findLocation$1, false);
  22327. curry(findLocation$1, true);
  22328. var hasSelectionModifyApi = function (editor) {
  22329. return isFunction(editor.selection.getSel().modify);
  22330. };
  22331. var moveRel = function (forward, selection, pos) {
  22332. var delta = forward ? 1 : -1;
  22333. selection.setRng(CaretPosition(pos.container(), pos.offset() + delta).toRange());
  22334. selection.getSel().modify('move', forward ? 'forward' : 'backward', 'word');
  22335. return true;
  22336. };
  22337. var moveByWord = function (forward, editor) {
  22338. var rng = editor.selection.getRng();
  22339. var pos = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  22340. if (!hasSelectionModifyApi(editor)) {
  22341. return false;
  22342. } else if (forward && isBeforeInline(pos)) {
  22343. return moveRel(true, editor.selection, pos);
  22344. } else if (!forward && isAfterInline(pos)) {
  22345. return moveRel(false, editor.selection, pos);
  22346. } else {
  22347. return false;
  22348. }
  22349. };
  22350. var BreakType;
  22351. (function (BreakType) {
  22352. BreakType[BreakType['Br'] = 0] = 'Br';
  22353. BreakType[BreakType['Block'] = 1] = 'Block';
  22354. BreakType[BreakType['Wrap'] = 2] = 'Wrap';
  22355. BreakType[BreakType['Eol'] = 3] = 'Eol';
  22356. }(BreakType || (BreakType = {})));
  22357. var flip = function (direction, positions) {
  22358. return direction === HDirection.Backwards ? reverse(positions) : positions;
  22359. };
  22360. var walk = function (direction, caretWalker, pos) {
  22361. return direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
  22362. };
  22363. var getBreakType = function (scope, direction, currentPos, nextPos) {
  22364. if (isBr$5(nextPos.getNode(direction === HDirection.Forwards))) {
  22365. return BreakType.Br;
  22366. } else if (isInSameBlock(currentPos, nextPos) === false) {
  22367. return BreakType.Block;
  22368. } else {
  22369. return BreakType.Wrap;
  22370. }
  22371. };
  22372. var getPositionsUntil = function (predicate, direction, scope, start) {
  22373. var caretWalker = CaretWalker(scope);
  22374. var currentPos = start;
  22375. var positions = [];
  22376. while (currentPos) {
  22377. var nextPos = walk(direction, caretWalker, currentPos);
  22378. if (!nextPos) {
  22379. break;
  22380. }
  22381. if (isBr$5(nextPos.getNode(false))) {
  22382. if (direction === HDirection.Forwards) {
  22383. return {
  22384. positions: flip(direction, positions).concat([nextPos]),
  22385. breakType: BreakType.Br,
  22386. breakAt: Optional.some(nextPos)
  22387. };
  22388. } else {
  22389. return {
  22390. positions: flip(direction, positions),
  22391. breakType: BreakType.Br,
  22392. breakAt: Optional.some(nextPos)
  22393. };
  22394. }
  22395. }
  22396. if (!nextPos.isVisible()) {
  22397. currentPos = nextPos;
  22398. continue;
  22399. }
  22400. if (predicate(currentPos, nextPos)) {
  22401. var breakType = getBreakType(scope, direction, currentPos, nextPos);
  22402. return {
  22403. positions: flip(direction, positions),
  22404. breakType: breakType,
  22405. breakAt: Optional.some(nextPos)
  22406. };
  22407. }
  22408. positions.push(nextPos);
  22409. currentPos = nextPos;
  22410. }
  22411. return {
  22412. positions: flip(direction, positions),
  22413. breakType: BreakType.Eol,
  22414. breakAt: Optional.none()
  22415. };
  22416. };
  22417. var getAdjacentLinePositions = function (direction, getPositionsUntilBreak, scope, start) {
  22418. return getPositionsUntilBreak(scope, start).breakAt.map(function (pos) {
  22419. var positions = getPositionsUntilBreak(scope, pos).positions;
  22420. return direction === HDirection.Backwards ? positions.concat(pos) : [pos].concat(positions);
  22421. }).getOr([]);
  22422. };
  22423. var findClosestHorizontalPositionFromPoint = function (positions, x) {
  22424. return foldl(positions, function (acc, newPos) {
  22425. return acc.fold(function () {
  22426. return Optional.some(newPos);
  22427. }, function (lastPos) {
  22428. return lift2(head(lastPos.getClientRects()), head(newPos.getClientRects()), function (lastRect, newRect) {
  22429. var lastDist = Math.abs(x - lastRect.left);
  22430. var newDist = Math.abs(x - newRect.left);
  22431. return newDist <= lastDist ? newPos : lastPos;
  22432. }).or(acc);
  22433. });
  22434. }, Optional.none());
  22435. };
  22436. var findClosestHorizontalPosition = function (positions, pos) {
  22437. return head(pos.getClientRects()).bind(function (targetRect) {
  22438. return findClosestHorizontalPositionFromPoint(positions, targetRect.left);
  22439. });
  22440. };
  22441. var getPositionsUntilPreviousLine = curry(getPositionsUntil, CaretPosition.isAbove, -1);
  22442. var getPositionsUntilNextLine = curry(getPositionsUntil, CaretPosition.isBelow, 1);
  22443. var getPositionsAbove = curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
  22444. var getPositionsBelow = curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
  22445. var isAtFirstLine = function (scope, pos) {
  22446. return getPositionsUntilPreviousLine(scope, pos).breakAt.isNone();
  22447. };
  22448. var isAtLastLine = function (scope, pos) {
  22449. return getPositionsUntilNextLine(scope, pos).breakAt.isNone();
  22450. };
  22451. var getFirstLinePositions = function (scope) {
  22452. return firstPositionIn(scope).map(function (pos) {
  22453. return [pos].concat(getPositionsUntilNextLine(scope, pos).positions);
  22454. }).getOr([]);
  22455. };
  22456. var getLastLinePositions = function (scope) {
  22457. return lastPositionIn(scope).map(function (pos) {
  22458. return getPositionsUntilPreviousLine(scope, pos).positions.concat(pos);
  22459. }).getOr([]);
  22460. };
  22461. var getNodeClientRects = function (node) {
  22462. var toArrayWithNode = function (clientRects) {
  22463. return map$3(clientRects, function (rect) {
  22464. var clientRect = clone(rect);
  22465. clientRect.node = node;
  22466. return clientRect;
  22467. });
  22468. };
  22469. if (isElement$5(node)) {
  22470. return toArrayWithNode(node.getClientRects());
  22471. }
  22472. if (isText$7(node)) {
  22473. var rng = node.ownerDocument.createRange();
  22474. rng.setStart(node, 0);
  22475. rng.setEnd(node, node.data.length);
  22476. return toArrayWithNode(rng.getClientRects());
  22477. }
  22478. };
  22479. var getClientRects = function (nodes) {
  22480. return bind(nodes, getNodeClientRects);
  22481. };
  22482. var VDirection;
  22483. (function (VDirection) {
  22484. VDirection[VDirection['Up'] = -1] = 'Up';
  22485. VDirection[VDirection['Down'] = 1] = 'Down';
  22486. }(VDirection || (VDirection = {})));
  22487. var findUntil = function (direction, root, predicateFn, node) {
  22488. while (node = findNode$1(node, direction, isEditableCaretCandidate$1, root)) {
  22489. if (predicateFn(node)) {
  22490. return;
  22491. }
  22492. }
  22493. };
  22494. var walkUntil$1 = function (direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) {
  22495. var line = 0;
  22496. var result = [];
  22497. var add = function (node) {
  22498. var clientRects = getClientRects([node]);
  22499. if (direction === -1) {
  22500. clientRects = clientRects.reverse();
  22501. }
  22502. for (var i = 0; i < clientRects.length; i++) {
  22503. var clientRect = clientRects[i];
  22504. if (isBeflowFn(clientRect, targetClientRect)) {
  22505. continue;
  22506. }
  22507. if (result.length > 0 && isAboveFn(clientRect, last$1(result))) {
  22508. line++;
  22509. }
  22510. clientRect.line = line;
  22511. if (predicateFn(clientRect)) {
  22512. return true;
  22513. }
  22514. result.push(clientRect);
  22515. }
  22516. };
  22517. var targetClientRect = last$1(caretPosition.getClientRects());
  22518. if (!targetClientRect) {
  22519. return result;
  22520. }
  22521. var node = caretPosition.getNode();
  22522. add(node);
  22523. findUntil(direction, root, add, node);
  22524. return result;
  22525. };
  22526. var aboveLineNumber = function (lineNumber, clientRect) {
  22527. return clientRect.line > lineNumber;
  22528. };
  22529. var isLineNumber = function (lineNumber, clientRect) {
  22530. return clientRect.line === lineNumber;
  22531. };
  22532. var upUntil = curry(walkUntil$1, VDirection.Up, isAbove$1, isBelow$1);
  22533. var downUntil = curry(walkUntil$1, VDirection.Down, isBelow$1, isAbove$1);
  22534. var positionsUntil = function (direction, root, predicateFn, node) {
  22535. var caretWalker = CaretWalker(root);
  22536. var walkFn;
  22537. var isBelowFn;
  22538. var isAboveFn;
  22539. var caretPosition;
  22540. var result = [];
  22541. var line = 0;
  22542. var getClientRect = function (caretPosition) {
  22543. if (direction === 1) {
  22544. return last$1(caretPosition.getClientRects());
  22545. }
  22546. return last$1(caretPosition.getClientRects());
  22547. };
  22548. if (direction === 1) {
  22549. walkFn = caretWalker.next;
  22550. isBelowFn = isBelow$1;
  22551. isAboveFn = isAbove$1;
  22552. caretPosition = CaretPosition.after(node);
  22553. } else {
  22554. walkFn = caretWalker.prev;
  22555. isBelowFn = isAbove$1;
  22556. isAboveFn = isBelow$1;
  22557. caretPosition = CaretPosition.before(node);
  22558. }
  22559. var targetClientRect = getClientRect(caretPosition);
  22560. do {
  22561. if (!caretPosition.isVisible()) {
  22562. continue;
  22563. }
  22564. var rect = getClientRect(caretPosition);
  22565. if (isAboveFn(rect, targetClientRect)) {
  22566. continue;
  22567. }
  22568. if (result.length > 0 && isBelowFn(rect, last$1(result))) {
  22569. line++;
  22570. }
  22571. var clientRect = clone(rect);
  22572. clientRect.position = caretPosition;
  22573. clientRect.line = line;
  22574. if (predicateFn(clientRect)) {
  22575. return result;
  22576. }
  22577. result.push(clientRect);
  22578. } while (caretPosition = walkFn(caretPosition));
  22579. return result;
  22580. };
  22581. var isAboveLine = function (lineNumber) {
  22582. return function (clientRect) {
  22583. return aboveLineNumber(lineNumber, clientRect);
  22584. };
  22585. };
  22586. var isLine = function (lineNumber) {
  22587. return function (clientRect) {
  22588. return isLineNumber(lineNumber, clientRect);
  22589. };
  22590. };
  22591. var isContentEditableFalse$3 = isContentEditableFalse$b;
  22592. var findNode = findNode$1;
  22593. var distanceToRectLeft = function (clientRect, clientX) {
  22594. return Math.abs(clientRect.left - clientX);
  22595. };
  22596. var distanceToRectRight = function (clientRect, clientX) {
  22597. return Math.abs(clientRect.right - clientX);
  22598. };
  22599. var isInsideX = function (clientX, clientRect) {
  22600. return clientX >= clientRect.left && clientX <= clientRect.right;
  22601. };
  22602. var isInsideY = function (clientY, clientRect) {
  22603. return clientY >= clientRect.top && clientY <= clientRect.bottom;
  22604. };
  22605. var isNodeClientRect = function (rect) {
  22606. return hasNonNullableKey(rect, 'node');
  22607. };
  22608. var findClosestClientRect = function (clientRects, clientX, allowInside) {
  22609. if (allowInside === void 0) {
  22610. allowInside = always;
  22611. }
  22612. return reduce(clientRects, function (oldClientRect, clientRect) {
  22613. if (isInsideX(clientX, clientRect)) {
  22614. return allowInside(clientRect) ? clientRect : oldClientRect;
  22615. }
  22616. if (isInsideX(clientX, oldClientRect)) {
  22617. return allowInside(oldClientRect) ? oldClientRect : clientRect;
  22618. }
  22619. var oldDistance = Math.min(distanceToRectLeft(oldClientRect, clientX), distanceToRectRight(oldClientRect, clientX));
  22620. var newDistance = Math.min(distanceToRectLeft(clientRect, clientX), distanceToRectRight(clientRect, clientX));
  22621. if (newDistance === oldDistance && isNodeClientRect(clientRect) && isContentEditableFalse$3(clientRect.node)) {
  22622. return clientRect;
  22623. }
  22624. if (newDistance < oldDistance) {
  22625. return clientRect;
  22626. }
  22627. return oldClientRect;
  22628. });
  22629. };
  22630. var walkUntil = function (direction, root, predicateFn, startNode, includeChildren) {
  22631. var node = findNode(startNode, direction, isEditableCaretCandidate$1, root, !includeChildren);
  22632. do {
  22633. if (!node || predicateFn(node)) {
  22634. return;
  22635. }
  22636. } while (node = findNode(node, direction, isEditableCaretCandidate$1, root));
  22637. };
  22638. var findLineNodeRects = function (root, targetNodeRect, includeChildren) {
  22639. if (includeChildren === void 0) {
  22640. includeChildren = true;
  22641. }
  22642. var clientRects = [];
  22643. var collect = function (checkPosFn, node) {
  22644. var lineRects = filter$4(getClientRects([node]), function (clientRect) {
  22645. return !checkPosFn(clientRect, targetNodeRect);
  22646. });
  22647. clientRects = clientRects.concat(lineRects);
  22648. return lineRects.length === 0;
  22649. };
  22650. clientRects.push(targetNodeRect);
  22651. walkUntil(VDirection.Up, root, curry(collect, isAbove$1), targetNodeRect.node, includeChildren);
  22652. walkUntil(VDirection.Down, root, curry(collect, isBelow$1), targetNodeRect.node, includeChildren);
  22653. return clientRects;
  22654. };
  22655. var getFakeCaretTargets = function (root) {
  22656. return filter$4(from(root.getElementsByTagName('*')), isFakeCaretTarget);
  22657. };
  22658. var caretInfo = function (clientRect, clientX) {
  22659. return {
  22660. node: clientRect.node,
  22661. before: distanceToRectLeft(clientRect, clientX) < distanceToRectRight(clientRect, clientX)
  22662. };
  22663. };
  22664. var closestFakeCaret = function (root, clientX, clientY) {
  22665. var fakeTargetNodeRects = getClientRects(getFakeCaretTargets(root));
  22666. var targetNodeRects = filter$4(fakeTargetNodeRects, curry(isInsideY, clientY));
  22667. var checkInside = function (clientRect) {
  22668. return !isTable$3(clientRect.node) && !isMedia$2(clientRect.node);
  22669. };
  22670. var closestNodeRect = findClosestClientRect(targetNodeRects, clientX, checkInside);
  22671. if (closestNodeRect) {
  22672. var includeChildren = checkInside(closestNodeRect);
  22673. closestNodeRect = findClosestClientRect(findLineNodeRects(root, closestNodeRect, includeChildren), clientX, checkInside);
  22674. if (closestNodeRect && isFakeCaretTarget(closestNodeRect.node)) {
  22675. return caretInfo(closestNodeRect, clientX);
  22676. }
  22677. }
  22678. return null;
  22679. };
  22680. var moveToRange = function (editor, rng) {
  22681. editor.selection.setRng(rng);
  22682. scrollRangeIntoView(editor, editor.selection.getRng());
  22683. };
  22684. var renderRangeCaretOpt = function (editor, range, scrollIntoView) {
  22685. return Optional.some(renderRangeCaret(editor, range, scrollIntoView));
  22686. };
  22687. var moveHorizontally = function (editor, direction, range, isBefore, isAfter, isElement) {
  22688. var forwards = direction === HDirection.Forwards;
  22689. var caretWalker = CaretWalker(editor.getBody());
  22690. var getNextPosFn = curry(getVisualCaretPosition, forwards ? caretWalker.next : caretWalker.prev);
  22691. var isBeforeFn = forwards ? isBefore : isAfter;
  22692. if (!range.collapsed) {
  22693. var node = getSelectedNode(range);
  22694. if (isElement(node)) {
  22695. return showCaret(direction, editor, node, direction === HDirection.Backwards, false);
  22696. }
  22697. }
  22698. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22699. if (isBeforeFn(caretPosition)) {
  22700. return selectNode(editor, caretPosition.getNode(!forwards));
  22701. }
  22702. var nextCaretPosition = normalizePosition(forwards, getNextPosFn(caretPosition));
  22703. var rangeIsInContainerBlock = isRangeInCaretContainerBlock(range);
  22704. if (!nextCaretPosition) {
  22705. return rangeIsInContainerBlock ? Optional.some(range) : Optional.none();
  22706. }
  22707. if (isBeforeFn(nextCaretPosition)) {
  22708. return showCaret(direction, editor, nextCaretPosition.getNode(!forwards), forwards, false);
  22709. }
  22710. var peekCaretPosition = getNextPosFn(nextCaretPosition);
  22711. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  22712. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  22713. return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, false);
  22714. }
  22715. }
  22716. if (rangeIsInContainerBlock) {
  22717. return renderRangeCaretOpt(editor, nextCaretPosition.toRange(), false);
  22718. }
  22719. return Optional.none();
  22720. };
  22721. var moveVertically = function (editor, direction, range, isBefore, isAfter, isElement) {
  22722. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22723. var caretClientRect = last$1(caretPosition.getClientRects());
  22724. var forwards = direction === VDirection.Down;
  22725. if (!caretClientRect) {
  22726. return Optional.none();
  22727. }
  22728. var walkerFn = forwards ? downUntil : upUntil;
  22729. var linePositions = walkerFn(editor.getBody(), isAboveLine(1), caretPosition);
  22730. var nextLinePositions = filter$4(linePositions, isLine(1));
  22731. var clientX = caretClientRect.left;
  22732. var nextLineRect = findClosestClientRect(nextLinePositions, clientX);
  22733. if (nextLineRect && isElement(nextLineRect.node)) {
  22734. var dist1 = Math.abs(clientX - nextLineRect.left);
  22735. var dist2 = Math.abs(clientX - nextLineRect.right);
  22736. return showCaret(direction, editor, nextLineRect.node, dist1 < dist2, false);
  22737. }
  22738. var currentNode;
  22739. if (isBefore(caretPosition)) {
  22740. currentNode = caretPosition.getNode();
  22741. } else if (isAfter(caretPosition)) {
  22742. currentNode = caretPosition.getNode(true);
  22743. } else {
  22744. currentNode = getSelectedNode(range);
  22745. }
  22746. if (currentNode) {
  22747. var caretPositions = positionsUntil(direction, editor.getBody(), isAboveLine(1), currentNode);
  22748. var closestNextLineRect = findClosestClientRect(filter$4(caretPositions, isLine(1)), clientX);
  22749. if (closestNextLineRect) {
  22750. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  22751. }
  22752. closestNextLineRect = last$1(filter$4(caretPositions, isLine(0)));
  22753. if (closestNextLineRect) {
  22754. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  22755. }
  22756. }
  22757. if (nextLinePositions.length === 0) {
  22758. return getLineEndPoint(editor, forwards).filter(forwards ? isAfter : isBefore).map(function (pos) {
  22759. return renderRangeCaret(editor, pos.toRange(), false);
  22760. });
  22761. }
  22762. return Optional.none();
  22763. };
  22764. var getLineEndPoint = function (editor, forward) {
  22765. var rng = editor.selection.getRng();
  22766. var body = editor.getBody();
  22767. if (forward) {
  22768. var from = CaretPosition.fromRangeEnd(rng);
  22769. var result = getPositionsUntilNextLine(body, from);
  22770. return last$2(result.positions);
  22771. } else {
  22772. var from = CaretPosition.fromRangeStart(rng);
  22773. var result = getPositionsUntilPreviousLine(body, from);
  22774. return head(result.positions);
  22775. }
  22776. };
  22777. var moveToLineEndPoint$3 = function (editor, forward, isElementPosition) {
  22778. return getLineEndPoint(editor, forward).filter(isElementPosition).exists(function (pos) {
  22779. editor.selection.setRng(pos.toRange());
  22780. return true;
  22781. });
  22782. };
  22783. var setCaretPosition = function (editor, pos) {
  22784. var rng = editor.dom.createRng();
  22785. rng.setStart(pos.container(), pos.offset());
  22786. rng.setEnd(pos.container(), pos.offset());
  22787. editor.selection.setRng(rng);
  22788. };
  22789. var setSelected = function (state, elm) {
  22790. if (state) {
  22791. elm.setAttribute('data-mce-selected', 'inline-boundary');
  22792. } else {
  22793. elm.removeAttribute('data-mce-selected');
  22794. }
  22795. };
  22796. var renderCaretLocation = function (editor, caret, location) {
  22797. return renderCaret(caret, location).map(function (pos) {
  22798. setCaretPosition(editor, pos);
  22799. return location;
  22800. });
  22801. };
  22802. var findLocation = function (editor, caret, forward) {
  22803. var rootNode = editor.getBody();
  22804. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  22805. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22806. var location = findLocation$1(forward, isInlineTarget$1, rootNode, from);
  22807. return location.bind(function (location) {
  22808. return renderCaretLocation(editor, caret, location);
  22809. });
  22810. };
  22811. var toggleInlines = function (isInlineTarget, dom, elms) {
  22812. var inlineBoundaries = map$3(descendants(SugarElement.fromDom(dom.getRoot()), '*[data-mce-selected="inline-boundary"]'), function (e) {
  22813. return e.dom;
  22814. });
  22815. var selectedInlines = filter$4(inlineBoundaries, isInlineTarget);
  22816. var targetInlines = filter$4(elms, isInlineTarget);
  22817. each$k(difference(selectedInlines, targetInlines), curry(setSelected, false));
  22818. each$k(difference(targetInlines, selectedInlines), curry(setSelected, true));
  22819. };
  22820. var safeRemoveCaretContainer = function (editor, caret) {
  22821. if (editor.selection.isCollapsed() && editor.composing !== true && caret.get()) {
  22822. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22823. if (CaretPosition.isTextPosition(pos) && isAtZwsp(pos) === false) {
  22824. setCaretPosition(editor, removeAndReposition(caret.get(), pos));
  22825. caret.set(null);
  22826. }
  22827. }
  22828. };
  22829. var renderInsideInlineCaret = function (isInlineTarget, editor, caret, elms) {
  22830. if (editor.selection.isCollapsed()) {
  22831. var inlines = filter$4(elms, isInlineTarget);
  22832. each$k(inlines, function (_inline) {
  22833. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22834. readLocation(isInlineTarget, editor.getBody(), pos).bind(function (location) {
  22835. return renderCaretLocation(editor, caret, location);
  22836. });
  22837. });
  22838. }
  22839. };
  22840. var move$2 = function (editor, caret, forward) {
  22841. return isInlineBoundariesEnabled(editor) ? findLocation(editor, caret, forward).isSome() : false;
  22842. };
  22843. var moveWord = function (forward, editor, _caret) {
  22844. return isInlineBoundariesEnabled(editor) ? moveByWord(forward, editor) : false;
  22845. };
  22846. var setupSelectedState = function (editor) {
  22847. var caret = Cell(null);
  22848. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22849. editor.on('NodeChange', function (e) {
  22850. if (isInlineBoundariesEnabled(editor) && !(Env.browser.isIE() && e.initial)) {
  22851. toggleInlines(isInlineTarget$1, editor.dom, e.parents);
  22852. safeRemoveCaretContainer(editor, caret);
  22853. renderInsideInlineCaret(isInlineTarget$1, editor, caret, e.parents);
  22854. }
  22855. });
  22856. return caret;
  22857. };
  22858. var moveNextWord = curry(moveWord, true);
  22859. var movePrevWord = curry(moveWord, false);
  22860. var moveToLineEndPoint$2 = function (editor, forward, caret) {
  22861. if (isInlineBoundariesEnabled(editor)) {
  22862. var linePoint = getLineEndPoint(editor, forward).getOrThunk(function () {
  22863. var rng = editor.selection.getRng();
  22864. return forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  22865. });
  22866. return readLocation(curry(isInlineTarget, editor), editor.getBody(), linePoint).exists(function (loc) {
  22867. var outsideLoc = outside(loc);
  22868. return renderCaret(caret, outsideLoc).exists(function (pos) {
  22869. setCaretPosition(editor, pos);
  22870. return true;
  22871. });
  22872. });
  22873. } else {
  22874. return false;
  22875. }
  22876. };
  22877. var rangeFromPositions = function (from, to) {
  22878. var range = document.createRange();
  22879. range.setStart(from.container(), from.offset());
  22880. range.setEnd(to.container(), to.offset());
  22881. return range;
  22882. };
  22883. var hasOnlyTwoOrLessPositionsLeft = function (elm) {
  22884. return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  22885. var normalizedFirstPos = normalizePosition(true, firstPos);
  22886. var normalizedLastPos = normalizePosition(false, lastPos);
  22887. return nextPosition(elm, normalizedFirstPos).forall(function (pos) {
  22888. return pos.isEqual(normalizedLastPos);
  22889. });
  22890. }).getOr(true);
  22891. };
  22892. var setCaretLocation = function (editor, caret) {
  22893. return function (location) {
  22894. return renderCaret(caret, location).exists(function (pos) {
  22895. setCaretPosition(editor, pos);
  22896. return true;
  22897. });
  22898. };
  22899. };
  22900. var deleteFromTo = function (editor, caret, from, to) {
  22901. var rootNode = editor.getBody();
  22902. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22903. editor.undoManager.ignore(function () {
  22904. editor.selection.setRng(rangeFromPositions(from, to));
  22905. editor.execCommand('Delete');
  22906. readLocation(isInlineTarget$1, rootNode, CaretPosition.fromRangeStart(editor.selection.getRng())).map(inside).map(setCaretLocation(editor, caret));
  22907. });
  22908. editor.nodeChanged();
  22909. };
  22910. var rescope = function (rootNode, node) {
  22911. var parentBlock = getParentBlock$2(node, rootNode);
  22912. return parentBlock ? parentBlock : rootNode;
  22913. };
  22914. var backspaceDeleteCollapsed = function (editor, caret, forward, from) {
  22915. var rootNode = rescope(editor.getBody(), from.container());
  22916. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22917. var fromLocation = readLocation(isInlineTarget$1, rootNode, from);
  22918. return fromLocation.bind(function (location) {
  22919. if (forward) {
  22920. return location.fold(constant(Optional.some(inside(location))), Optional.none, constant(Optional.some(outside(location))), Optional.none);
  22921. } else {
  22922. return location.fold(Optional.none, constant(Optional.some(outside(location))), Optional.none, constant(Optional.some(inside(location))));
  22923. }
  22924. }).map(setCaretLocation(editor, caret)).getOrThunk(function () {
  22925. var toPosition = navigate(forward, rootNode, from);
  22926. var toLocation = toPosition.bind(function (pos) {
  22927. return readLocation(isInlineTarget$1, rootNode, pos);
  22928. });
  22929. return lift2(fromLocation, toLocation, function () {
  22930. return findRootInline(isInlineTarget$1, rootNode, from).exists(function (elm) {
  22931. if (hasOnlyTwoOrLessPositionsLeft(elm)) {
  22932. deleteElement$2(editor, forward, SugarElement.fromDom(elm));
  22933. return true;
  22934. } else {
  22935. return false;
  22936. }
  22937. });
  22938. }).orThunk(function () {
  22939. return toLocation.bind(function (_) {
  22940. return toPosition.map(function (to) {
  22941. if (forward) {
  22942. deleteFromTo(editor, caret, from, to);
  22943. } else {
  22944. deleteFromTo(editor, caret, to, from);
  22945. }
  22946. return true;
  22947. });
  22948. });
  22949. }).getOr(false);
  22950. });
  22951. };
  22952. var backspaceDelete$3 = function (editor, caret, forward) {
  22953. if (editor.selection.isCollapsed() && isInlineBoundariesEnabled(editor)) {
  22954. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  22955. return backspaceDeleteCollapsed(editor, caret, forward, from);
  22956. }
  22957. return false;
  22958. };
  22959. var getParentInlines = function (rootElm, startElm) {
  22960. var parents = parentsAndSelf(startElm, rootElm);
  22961. return findIndex$2(parents, isBlock$2).fold(constant(parents), function (index) {
  22962. return parents.slice(0, index);
  22963. });
  22964. };
  22965. var hasOnlyOneChild = function (elm) {
  22966. return childNodesCount(elm) === 1;
  22967. };
  22968. var deleteLastPosition = function (forward, editor, target, parentInlines) {
  22969. var isFormatElement$1 = curry(isFormatElement, editor);
  22970. var formatNodes = map$3(filter$4(parentInlines, isFormatElement$1), function (elm) {
  22971. return elm.dom;
  22972. });
  22973. if (formatNodes.length === 0) {
  22974. deleteElement$2(editor, forward, target);
  22975. } else {
  22976. var pos = replaceWithCaretFormat(target.dom, formatNodes);
  22977. editor.selection.setRng(pos.toRange());
  22978. }
  22979. };
  22980. var deleteCaret$1 = function (editor, forward) {
  22981. var rootElm = SugarElement.fromDom(editor.getBody());
  22982. var startElm = SugarElement.fromDom(editor.selection.getStart());
  22983. var parentInlines = filter$4(getParentInlines(rootElm, startElm), hasOnlyOneChild);
  22984. return last$2(parentInlines).exists(function (target) {
  22985. var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22986. if (willDeleteLastPositionInElement(forward, fromPos, target.dom) && !isEmptyCaretFormatElement(target)) {
  22987. deleteLastPosition(forward, editor, target, parentInlines);
  22988. return true;
  22989. } else {
  22990. return false;
  22991. }
  22992. });
  22993. };
  22994. var backspaceDelete$2 = function (editor, forward) {
  22995. return editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : false;
  22996. };
  22997. var deleteElement = function (editor, forward, element) {
  22998. editor._selectionOverrides.hideFakeCaret();
  22999. deleteElement$2(editor, forward, SugarElement.fromDom(element));
  23000. return true;
  23001. };
  23002. var deleteCaret = function (editor, forward) {
  23003. var isNearMedia = forward ? isBeforeMedia : isAfterMedia;
  23004. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23005. var fromPos = getNormalizedRangeEndPoint(direction, editor.getBody(), editor.selection.getRng());
  23006. if (isNearMedia(fromPos)) {
  23007. return deleteElement(editor, forward, fromPos.getNode(!forward));
  23008. } else {
  23009. return Optional.from(normalizePosition(forward, fromPos)).filter(function (pos) {
  23010. return isNearMedia(pos) && isMoveInsideSameBlock(fromPos, pos);
  23011. }).exists(function (pos) {
  23012. return deleteElement(editor, forward, pos.getNode(!forward));
  23013. });
  23014. }
  23015. };
  23016. var deleteRange = function (editor, forward) {
  23017. var selectedNode = editor.selection.getNode();
  23018. return isMedia$2(selectedNode) ? deleteElement(editor, forward, selectedNode) : false;
  23019. };
  23020. var backspaceDelete$1 = function (editor, forward) {
  23021. return editor.selection.isCollapsed() ? deleteCaret(editor, forward) : deleteRange(editor, forward);
  23022. };
  23023. var isEditable = function (target) {
  23024. return closest$3(target, function (elm) {
  23025. return isContentEditableTrue$4(elm.dom) || isContentEditableFalse$b(elm.dom);
  23026. }).exists(function (elm) {
  23027. return isContentEditableTrue$4(elm.dom);
  23028. });
  23029. };
  23030. var parseIndentValue = function (value) {
  23031. var number = parseInt(value, 10);
  23032. return isNaN(number) ? 0 : number;
  23033. };
  23034. var getIndentStyleName = function (useMargin, element) {
  23035. var indentStyleName = useMargin || isTable$2(element) ? 'margin' : 'padding';
  23036. var suffix = get$5(element, 'direction') === 'rtl' ? '-right' : '-left';
  23037. return indentStyleName + suffix;
  23038. };
  23039. var indentElement = function (dom, command, useMargin, value, unit, element) {
  23040. var indentStyleName = getIndentStyleName(useMargin, SugarElement.fromDom(element));
  23041. if (command === 'outdent') {
  23042. var styleValue = Math.max(0, parseIndentValue(element.style[indentStyleName]) - value);
  23043. dom.setStyle(element, indentStyleName, styleValue ? styleValue + unit : '');
  23044. } else {
  23045. var styleValue = parseIndentValue(element.style[indentStyleName]) + value + unit;
  23046. dom.setStyle(element, indentStyleName, styleValue);
  23047. }
  23048. };
  23049. var validateBlocks = function (editor, blocks) {
  23050. return forall(blocks, function (block) {
  23051. var indentStyleName = getIndentStyleName(shouldIndentUseMargin(editor), block);
  23052. var intentValue = getRaw(block, indentStyleName).map(parseIndentValue).getOr(0);
  23053. var contentEditable = editor.dom.getContentEditable(block.dom);
  23054. return contentEditable !== 'false' && intentValue > 0;
  23055. });
  23056. };
  23057. var canOutdent = function (editor) {
  23058. var blocks = getBlocksToIndent(editor);
  23059. return !editor.mode.isReadOnly() && (blocks.length > 1 || validateBlocks(editor, blocks));
  23060. };
  23061. var isListComponent = function (el) {
  23062. return isList(el) || isListItem(el);
  23063. };
  23064. var parentIsListComponent = function (el) {
  23065. return parent(el).exists(isListComponent);
  23066. };
  23067. var getBlocksToIndent = function (editor) {
  23068. return filter$4(fromDom$1(editor.selection.getSelectedBlocks()), function (el) {
  23069. return !isListComponent(el) && !parentIsListComponent(el) && isEditable(el);
  23070. });
  23071. };
  23072. var handle = function (editor, command) {
  23073. var dom = editor.dom, selection = editor.selection, formatter = editor.formatter;
  23074. var indentation = getIndentation(editor);
  23075. var indentUnit = /[a-z%]+$/i.exec(indentation)[0];
  23076. var indentValue = parseInt(indentation, 10);
  23077. var useMargin = shouldIndentUseMargin(editor);
  23078. var forcedRootBlock = getForcedRootBlock(editor);
  23079. if (!editor.queryCommandState('InsertUnorderedList') && !editor.queryCommandState('InsertOrderedList')) {
  23080. if (forcedRootBlock === '' && !dom.getParent(selection.getNode(), dom.isBlock)) {
  23081. formatter.apply('div');
  23082. }
  23083. }
  23084. each$k(getBlocksToIndent(editor), function (block) {
  23085. indentElement(dom, command, useMargin, indentValue, indentUnit, block.dom);
  23086. });
  23087. };
  23088. var backspaceDelete = function (editor, _forward) {
  23089. if (editor.selection.isCollapsed() && canOutdent(editor)) {
  23090. var dom = editor.dom;
  23091. var rng = editor.selection.getRng();
  23092. var pos = CaretPosition.fromRangeStart(rng);
  23093. var block = dom.getParent(rng.startContainer, dom.isBlock);
  23094. if (block !== null && isAtStartOfBlock(SugarElement.fromDom(block), pos)) {
  23095. handle(editor, 'outdent');
  23096. return true;
  23097. }
  23098. }
  23099. return false;
  23100. };
  23101. var nativeCommand = function (editor, command) {
  23102. editor.getDoc().execCommand(command, false, null);
  23103. };
  23104. var deleteCommand = function (editor, caret) {
  23105. if (backspaceDelete(editor)) {
  23106. return;
  23107. } else if (backspaceDelete$5(editor, false)) {
  23108. return;
  23109. } else if (backspaceDelete$6(editor, false)) {
  23110. return;
  23111. } else if (backspaceDelete$3(editor, caret, false)) {
  23112. return;
  23113. } else if (backspaceDelete$8(editor, false)) {
  23114. return;
  23115. } else if (backspaceDelete$9(editor)) {
  23116. return;
  23117. } else if (backspaceDelete$4(editor, false)) {
  23118. return;
  23119. } else if (backspaceDelete$1(editor, false)) {
  23120. return;
  23121. } else if (backspaceDelete$7(editor)) {
  23122. return;
  23123. } else if (backspaceDelete$2(editor, false)) {
  23124. return;
  23125. } else {
  23126. nativeCommand(editor, 'Delete');
  23127. paddEmptyBody(editor);
  23128. }
  23129. };
  23130. var forwardDeleteCommand = function (editor, caret) {
  23131. if (backspaceDelete$5(editor, true)) {
  23132. return;
  23133. } else if (backspaceDelete$6(editor, true)) {
  23134. return;
  23135. } else if (backspaceDelete$3(editor, caret, true)) {
  23136. return;
  23137. } else if (backspaceDelete$8(editor, true)) {
  23138. return;
  23139. } else if (backspaceDelete$9(editor)) {
  23140. return;
  23141. } else if (backspaceDelete$4(editor, true)) {
  23142. return;
  23143. } else if (backspaceDelete$1(editor, true)) {
  23144. return;
  23145. } else if (backspaceDelete$7(editor)) {
  23146. return;
  23147. } else if (backspaceDelete$2(editor, true)) {
  23148. return;
  23149. } else {
  23150. nativeCommand(editor, 'ForwardDelete');
  23151. }
  23152. };
  23153. var setup$f = function (editor, caret) {
  23154. editor.addCommand('delete', function () {
  23155. deleteCommand(editor, caret);
  23156. });
  23157. editor.addCommand('forwardDelete', function () {
  23158. forwardDeleteCommand(editor, caret);
  23159. });
  23160. };
  23161. var SIGNIFICANT_MOVE = 5;
  23162. var LONGPRESS_DELAY = 400;
  23163. var getTouch = function (event) {
  23164. if (event.touches === undefined || event.touches.length !== 1) {
  23165. return Optional.none();
  23166. }
  23167. return Optional.some(event.touches[0]);
  23168. };
  23169. var isFarEnough = function (touch, data) {
  23170. var distX = Math.abs(touch.clientX - data.x);
  23171. var distY = Math.abs(touch.clientY - data.y);
  23172. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  23173. };
  23174. var setup$e = function (editor) {
  23175. var startData = value();
  23176. var longpressFired = Cell(false);
  23177. var debounceLongpress = last(function (e) {
  23178. editor.fire('longpress', __assign(__assign({}, e), { type: 'longpress' }));
  23179. longpressFired.set(true);
  23180. }, LONGPRESS_DELAY);
  23181. editor.on('touchstart', function (e) {
  23182. getTouch(e).each(function (touch) {
  23183. debounceLongpress.cancel();
  23184. var data = {
  23185. x: touch.clientX,
  23186. y: touch.clientY,
  23187. target: e.target
  23188. };
  23189. debounceLongpress.throttle(e);
  23190. longpressFired.set(false);
  23191. startData.set(data);
  23192. });
  23193. }, true);
  23194. editor.on('touchmove', function (e) {
  23195. debounceLongpress.cancel();
  23196. getTouch(e).each(function (touch) {
  23197. startData.on(function (data) {
  23198. if (isFarEnough(touch, data)) {
  23199. startData.clear();
  23200. longpressFired.set(false);
  23201. editor.fire('longpresscancel');
  23202. }
  23203. });
  23204. });
  23205. }, true);
  23206. editor.on('touchend touchcancel', function (e) {
  23207. debounceLongpress.cancel();
  23208. if (e.type === 'touchcancel') {
  23209. return;
  23210. }
  23211. startData.get().filter(function (data) {
  23212. return data.target.isEqualNode(e.target);
  23213. }).each(function () {
  23214. if (longpressFired.get()) {
  23215. e.preventDefault();
  23216. } else {
  23217. editor.fire('tap', __assign(__assign({}, e), { type: 'tap' }));
  23218. }
  23219. });
  23220. }, true);
  23221. };
  23222. var isBlockElement = function (blockElements, node) {
  23223. return has$2(blockElements, node.nodeName);
  23224. };
  23225. var isValidTarget = function (blockElements, node) {
  23226. if (isText$7(node)) {
  23227. return true;
  23228. } else if (isElement$5(node)) {
  23229. return !isBlockElement(blockElements, node) && !isBookmarkNode$1(node);
  23230. } else {
  23231. return false;
  23232. }
  23233. };
  23234. var hasBlockParent = function (blockElements, root, node) {
  23235. return exists(parents(SugarElement.fromDom(node), SugarElement.fromDom(root)), function (elm) {
  23236. return isBlockElement(blockElements, elm.dom);
  23237. });
  23238. };
  23239. var shouldRemoveTextNode = function (blockElements, node) {
  23240. if (isText$7(node)) {
  23241. if (node.nodeValue.length === 0) {
  23242. return true;
  23243. } else if (/^\s+$/.test(node.nodeValue) && (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
  23244. return true;
  23245. }
  23246. }
  23247. return false;
  23248. };
  23249. var addRootBlocks = function (editor) {
  23250. var dom = editor.dom, selection = editor.selection;
  23251. var schema = editor.schema, blockElements = schema.getBlockElements();
  23252. var node = selection.getStart();
  23253. var rootNode = editor.getBody();
  23254. var rootBlockNode, tempNode, wrapped;
  23255. var forcedRootBlock = getForcedRootBlock(editor);
  23256. if (!node || !isElement$5(node) || !forcedRootBlock) {
  23257. return;
  23258. }
  23259. var rootNodeName = rootNode.nodeName.toLowerCase();
  23260. if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, node)) {
  23261. return;
  23262. }
  23263. var rng = selection.getRng();
  23264. var startContainer = rng.startContainer;
  23265. var startOffset = rng.startOffset;
  23266. var endContainer = rng.endContainer;
  23267. var endOffset = rng.endOffset;
  23268. var restoreSelection = hasFocus(editor);
  23269. node = rootNode.firstChild;
  23270. while (node) {
  23271. if (isValidTarget(blockElements, node)) {
  23272. if (shouldRemoveTextNode(blockElements, node)) {
  23273. tempNode = node;
  23274. node = node.nextSibling;
  23275. dom.remove(tempNode);
  23276. continue;
  23277. }
  23278. if (!rootBlockNode) {
  23279. rootBlockNode = dom.create(forcedRootBlock, getForcedRootBlockAttrs(editor));
  23280. node.parentNode.insertBefore(rootBlockNode, node);
  23281. wrapped = true;
  23282. }
  23283. tempNode = node;
  23284. node = node.nextSibling;
  23285. rootBlockNode.appendChild(tempNode);
  23286. } else {
  23287. rootBlockNode = null;
  23288. node = node.nextSibling;
  23289. }
  23290. }
  23291. if (wrapped && restoreSelection) {
  23292. rng.setStart(startContainer, startOffset);
  23293. rng.setEnd(endContainer, endOffset);
  23294. selection.setRng(rng);
  23295. editor.nodeChanged();
  23296. }
  23297. };
  23298. var setup$d = function (editor) {
  23299. if (getForcedRootBlock(editor)) {
  23300. editor.on('NodeChange', curry(addRootBlocks, editor));
  23301. }
  23302. };
  23303. var findBlockCaretContainer = function (editor) {
  23304. return descendant(SugarElement.fromDom(editor.getBody()), '*[data-mce-caret]').map(function (elm) {
  23305. return elm.dom;
  23306. }).getOrNull();
  23307. };
  23308. var removeIeControlRect = function (editor) {
  23309. editor.selection.setRng(editor.selection.getRng());
  23310. };
  23311. var showBlockCaretContainer = function (editor, blockCaretContainer) {
  23312. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  23313. showCaretContainerBlock(blockCaretContainer);
  23314. removeIeControlRect(editor);
  23315. editor.selection.scrollIntoView(blockCaretContainer);
  23316. }
  23317. };
  23318. var handleBlockContainer = function (editor, e) {
  23319. var blockCaretContainer = findBlockCaretContainer(editor);
  23320. if (!blockCaretContainer) {
  23321. return;
  23322. }
  23323. if (e.type === 'compositionstart') {
  23324. e.preventDefault();
  23325. e.stopPropagation();
  23326. showBlockCaretContainer(editor, blockCaretContainer);
  23327. return;
  23328. }
  23329. if (hasContent(blockCaretContainer)) {
  23330. showBlockCaretContainer(editor, blockCaretContainer);
  23331. editor.undoManager.add();
  23332. }
  23333. };
  23334. var setup$c = function (editor) {
  23335. editor.on('keyup compositionstart', curry(handleBlockContainer, editor));
  23336. };
  23337. var isContentEditableFalse$2 = isContentEditableFalse$b;
  23338. var moveToCeFalseHorizontally = function (direction, editor, range) {
  23339. return moveHorizontally(editor, direction, range, isBeforeContentEditableFalse, isAfterContentEditableFalse, isContentEditableFalse$2);
  23340. };
  23341. var moveToCeFalseVertically = function (direction, editor, range) {
  23342. var isBefore = function (caretPosition) {
  23343. return isBeforeContentEditableFalse(caretPosition) || isBeforeTable(caretPosition);
  23344. };
  23345. var isAfter = function (caretPosition) {
  23346. return isAfterContentEditableFalse(caretPosition) || isAfterTable(caretPosition);
  23347. };
  23348. return moveVertically(editor, direction, range, isBefore, isAfter, isContentEditableFalse$2);
  23349. };
  23350. var createTextBlock = function (editor) {
  23351. var textBlock = editor.dom.create(getForcedRootBlock(editor));
  23352. if (!Env.ie || Env.ie >= 11) {
  23353. textBlock.innerHTML = '<br data-mce-bogus="1">';
  23354. }
  23355. return textBlock;
  23356. };
  23357. var exitPreBlock = function (editor, direction, range) {
  23358. var caretWalker = CaretWalker(editor.getBody());
  23359. var getVisualCaretPosition$1 = curry(getVisualCaretPosition, direction === 1 ? caretWalker.next : caretWalker.prev);
  23360. if (range.collapsed && hasForcedRootBlock(editor)) {
  23361. var pre = editor.dom.getParent(range.startContainer, 'PRE');
  23362. if (!pre) {
  23363. return;
  23364. }
  23365. var caretPos = getVisualCaretPosition$1(CaretPosition.fromRangeStart(range));
  23366. if (!caretPos) {
  23367. var newBlock = createTextBlock(editor);
  23368. if (direction === 1) {
  23369. editor.$(pre).after(newBlock);
  23370. } else {
  23371. editor.$(pre).before(newBlock);
  23372. }
  23373. editor.selection.select(newBlock, true);
  23374. editor.selection.collapse();
  23375. }
  23376. }
  23377. };
  23378. var getHorizontalRange = function (editor, forward) {
  23379. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23380. var range = editor.selection.getRng();
  23381. return moveToCeFalseHorizontally(direction, editor, range).orThunk(function () {
  23382. exitPreBlock(editor, direction, range);
  23383. return Optional.none();
  23384. });
  23385. };
  23386. var getVerticalRange = function (editor, down) {
  23387. var direction = down ? 1 : -1;
  23388. var range = editor.selection.getRng();
  23389. return moveToCeFalseVertically(direction, editor, range).orThunk(function () {
  23390. exitPreBlock(editor, direction, range);
  23391. return Optional.none();
  23392. });
  23393. };
  23394. var moveH$2 = function (editor, forward) {
  23395. return getHorizontalRange(editor, forward).exists(function (newRange) {
  23396. moveToRange(editor, newRange);
  23397. return true;
  23398. });
  23399. };
  23400. var moveV$3 = function (editor, down) {
  23401. return getVerticalRange(editor, down).exists(function (newRange) {
  23402. moveToRange(editor, newRange);
  23403. return true;
  23404. });
  23405. };
  23406. var moveToLineEndPoint$1 = function (editor, forward) {
  23407. var isCefPosition = forward ? isAfterContentEditableFalse : isBeforeContentEditableFalse;
  23408. return moveToLineEndPoint$3(editor, forward, isCefPosition);
  23409. };
  23410. var isTarget = function (node) {
  23411. return contains$3(['figcaption'], name(node));
  23412. };
  23413. var rangeBefore = function (target) {
  23414. var rng = document.createRange();
  23415. rng.setStartBefore(target.dom);
  23416. rng.setEndBefore(target.dom);
  23417. return rng;
  23418. };
  23419. var insertElement = function (root, elm, forward) {
  23420. if (forward) {
  23421. append$1(root, elm);
  23422. } else {
  23423. prepend(root, elm);
  23424. }
  23425. };
  23426. var insertBr = function (root, forward) {
  23427. var br = SugarElement.fromTag('br');
  23428. insertElement(root, br, forward);
  23429. return rangeBefore(br);
  23430. };
  23431. var insertBlock = function (root, forward, blockName, attrs) {
  23432. var block = SugarElement.fromTag(blockName);
  23433. var br = SugarElement.fromTag('br');
  23434. setAll$1(block, attrs);
  23435. append$1(block, br);
  23436. insertElement(root, block, forward);
  23437. return rangeBefore(br);
  23438. };
  23439. var insertEmptyLine = function (root, rootBlockName, attrs, forward) {
  23440. if (rootBlockName === '') {
  23441. return insertBr(root, forward);
  23442. } else {
  23443. return insertBlock(root, forward, rootBlockName, attrs);
  23444. }
  23445. };
  23446. var getClosestTargetBlock = function (pos, root) {
  23447. var isRoot = curry(eq, root);
  23448. return closest$3(SugarElement.fromDom(pos.container()), isBlock$2, isRoot).filter(isTarget);
  23449. };
  23450. var isAtFirstOrLastLine = function (root, forward, pos) {
  23451. return forward ? isAtLastLine(root.dom, pos) : isAtFirstLine(root.dom, pos);
  23452. };
  23453. var moveCaretToNewEmptyLine = function (editor, forward) {
  23454. var root = SugarElement.fromDom(editor.getBody());
  23455. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23456. var rootBlock = getForcedRootBlock(editor);
  23457. var rootBlockAttrs = getForcedRootBlockAttrs(editor);
  23458. return getClosestTargetBlock(pos, root).exists(function () {
  23459. if (isAtFirstOrLastLine(root, forward, pos)) {
  23460. var rng = insertEmptyLine(root, rootBlock, rootBlockAttrs, forward);
  23461. editor.selection.setRng(rng);
  23462. return true;
  23463. } else {
  23464. return false;
  23465. }
  23466. });
  23467. };
  23468. var moveV$2 = function (editor, forward) {
  23469. if (editor.selection.isCollapsed()) {
  23470. return moveCaretToNewEmptyLine(editor, forward);
  23471. } else {
  23472. return false;
  23473. }
  23474. };
  23475. var defaultPatterns = function (patterns) {
  23476. return map$3(patterns, function (pattern) {
  23477. return __assign({
  23478. shiftKey: false,
  23479. altKey: false,
  23480. ctrlKey: false,
  23481. metaKey: false,
  23482. keyCode: 0,
  23483. action: noop
  23484. }, pattern);
  23485. });
  23486. };
  23487. var matchesEvent = function (pattern, evt) {
  23488. return evt.keyCode === pattern.keyCode && evt.shiftKey === pattern.shiftKey && evt.altKey === pattern.altKey && evt.ctrlKey === pattern.ctrlKey && evt.metaKey === pattern.metaKey;
  23489. };
  23490. var match$1 = function (patterns, evt) {
  23491. return bind(defaultPatterns(patterns), function (pattern) {
  23492. return matchesEvent(pattern, evt) ? [pattern] : [];
  23493. });
  23494. };
  23495. var action = function (f) {
  23496. var x = [];
  23497. for (var _i = 1; _i < arguments.length; _i++) {
  23498. x[_i - 1] = arguments[_i];
  23499. }
  23500. return function () {
  23501. return f.apply(null, x);
  23502. };
  23503. };
  23504. var execute = function (patterns, evt) {
  23505. return find$3(match$1(patterns, evt), function (pattern) {
  23506. return pattern.action();
  23507. });
  23508. };
  23509. var moveH$1 = function (editor, forward) {
  23510. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23511. var range = editor.selection.getRng();
  23512. return moveHorizontally(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(function (newRange) {
  23513. moveToRange(editor, newRange);
  23514. return true;
  23515. });
  23516. };
  23517. var moveV$1 = function (editor, down) {
  23518. var direction = down ? 1 : -1;
  23519. var range = editor.selection.getRng();
  23520. return moveVertically(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(function (newRange) {
  23521. moveToRange(editor, newRange);
  23522. return true;
  23523. });
  23524. };
  23525. var moveToLineEndPoint = function (editor, forward) {
  23526. var isNearMedia = forward ? isAfterMedia : isBeforeMedia;
  23527. return moveToLineEndPoint$3(editor, forward, isNearMedia);
  23528. };
  23529. var deflate = function (rect, delta) {
  23530. return {
  23531. left: rect.left - delta,
  23532. top: rect.top - delta,
  23533. right: rect.right + delta * 2,
  23534. bottom: rect.bottom + delta * 2,
  23535. width: rect.width + delta,
  23536. height: rect.height + delta
  23537. };
  23538. };
  23539. var getCorners = function (getYAxisValue, tds) {
  23540. return bind(tds, function (td) {
  23541. var rect = deflate(clone(td.getBoundingClientRect()), -1);
  23542. return [
  23543. {
  23544. x: rect.left,
  23545. y: getYAxisValue(rect),
  23546. cell: td
  23547. },
  23548. {
  23549. x: rect.right,
  23550. y: getYAxisValue(rect),
  23551. cell: td
  23552. }
  23553. ];
  23554. });
  23555. };
  23556. var findClosestCorner = function (corners, x, y) {
  23557. return foldl(corners, function (acc, newCorner) {
  23558. return acc.fold(function () {
  23559. return Optional.some(newCorner);
  23560. }, function (oldCorner) {
  23561. var oldDist = Math.sqrt(Math.abs(oldCorner.x - x) + Math.abs(oldCorner.y - y));
  23562. var newDist = Math.sqrt(Math.abs(newCorner.x - x) + Math.abs(newCorner.y - y));
  23563. return Optional.some(newDist < oldDist ? newCorner : oldCorner);
  23564. });
  23565. }, Optional.none());
  23566. };
  23567. var getClosestCell = function (getYAxisValue, isTargetCorner, table, x, y) {
  23568. var cells = descendants(SugarElement.fromDom(table), 'td,th,caption').map(function (e) {
  23569. return e.dom;
  23570. });
  23571. var corners = filter$4(getCorners(getYAxisValue, cells), function (corner) {
  23572. return isTargetCorner(corner, y);
  23573. });
  23574. return findClosestCorner(corners, x, y).map(function (corner) {
  23575. return corner.cell;
  23576. });
  23577. };
  23578. var getBottomValue = function (rect) {
  23579. return rect.bottom;
  23580. };
  23581. var getTopValue = function (rect) {
  23582. return rect.top;
  23583. };
  23584. var isAbove = function (corner, y) {
  23585. return corner.y < y;
  23586. };
  23587. var isBelow = function (corner, y) {
  23588. return corner.y > y;
  23589. };
  23590. var getClosestCellAbove = curry(getClosestCell, getBottomValue, isAbove);
  23591. var getClosestCellBelow = curry(getClosestCell, getTopValue, isBelow);
  23592. var findClosestPositionInAboveCell = function (table, pos) {
  23593. return head(pos.getClientRects()).bind(function (rect) {
  23594. return getClosestCellAbove(table, rect.left, rect.top);
  23595. }).bind(function (cell) {
  23596. return findClosestHorizontalPosition(getLastLinePositions(cell), pos);
  23597. });
  23598. };
  23599. var findClosestPositionInBelowCell = function (table, pos) {
  23600. return last$2(pos.getClientRects()).bind(function (rect) {
  23601. return getClosestCellBelow(table, rect.left, rect.top);
  23602. }).bind(function (cell) {
  23603. return findClosestHorizontalPosition(getFirstLinePositions(cell), pos);
  23604. });
  23605. };
  23606. var hasNextBreak = function (getPositionsUntil, scope, lineInfo) {
  23607. return lineInfo.breakAt.exists(function (breakPos) {
  23608. return getPositionsUntil(scope, breakPos).breakAt.isSome();
  23609. });
  23610. };
  23611. var startsWithWrapBreak = function (lineInfo) {
  23612. return lineInfo.breakType === BreakType.Wrap && lineInfo.positions.length === 0;
  23613. };
  23614. var startsWithBrBreak = function (lineInfo) {
  23615. return lineInfo.breakType === BreakType.Br && lineInfo.positions.length === 1;
  23616. };
  23617. var isAtTableCellLine = function (getPositionsUntil, scope, pos) {
  23618. var lineInfo = getPositionsUntil(scope, pos);
  23619. if (startsWithWrapBreak(lineInfo) || !isBr$5(pos.getNode()) && startsWithBrBreak(lineInfo)) {
  23620. return !hasNextBreak(getPositionsUntil, scope, lineInfo);
  23621. } else {
  23622. return lineInfo.breakAt.isNone();
  23623. }
  23624. };
  23625. var isAtFirstTableCellLine = curry(isAtTableCellLine, getPositionsUntilPreviousLine);
  23626. var isAtLastTableCellLine = curry(isAtTableCellLine, getPositionsUntilNextLine);
  23627. var isCaretAtStartOrEndOfTable = function (forward, rng, table) {
  23628. var caretPos = CaretPosition.fromRangeStart(rng);
  23629. return positionIn(!forward, table).exists(function (pos) {
  23630. return pos.isEqual(caretPos);
  23631. });
  23632. };
  23633. var navigateHorizontally = function (editor, forward, table, _td) {
  23634. var rng = editor.selection.getRng();
  23635. var direction = forward ? 1 : -1;
  23636. if (isFakeCaretTableBrowser() && isCaretAtStartOrEndOfTable(forward, rng, table)) {
  23637. showCaret(direction, editor, table, !forward, false).each(function (newRng) {
  23638. moveToRange(editor, newRng);
  23639. });
  23640. return true;
  23641. }
  23642. return false;
  23643. };
  23644. var getClosestAbovePosition = function (root, table, start) {
  23645. return findClosestPositionInAboveCell(table, start).orThunk(function () {
  23646. return head(start.getClientRects()).bind(function (rect) {
  23647. return findClosestHorizontalPositionFromPoint(getPositionsAbove(root, CaretPosition.before(table)), rect.left);
  23648. });
  23649. }).getOr(CaretPosition.before(table));
  23650. };
  23651. var getClosestBelowPosition = function (root, table, start) {
  23652. return findClosestPositionInBelowCell(table, start).orThunk(function () {
  23653. return head(start.getClientRects()).bind(function (rect) {
  23654. return findClosestHorizontalPositionFromPoint(getPositionsBelow(root, CaretPosition.after(table)), rect.left);
  23655. });
  23656. }).getOr(CaretPosition.after(table));
  23657. };
  23658. var getTable = function (previous, pos) {
  23659. var node = pos.getNode(previous);
  23660. return isElement$5(node) && node.nodeName === 'TABLE' ? Optional.some(node) : Optional.none();
  23661. };
  23662. var renderBlock = function (down, editor, table, pos) {
  23663. var forcedRootBlock = getForcedRootBlock(editor);
  23664. if (forcedRootBlock) {
  23665. editor.undoManager.transact(function () {
  23666. var element = SugarElement.fromTag(forcedRootBlock);
  23667. setAll$1(element, getForcedRootBlockAttrs(editor));
  23668. append$1(element, SugarElement.fromTag('br'));
  23669. if (down) {
  23670. after$3(SugarElement.fromDom(table), element);
  23671. } else {
  23672. before$4(SugarElement.fromDom(table), element);
  23673. }
  23674. var rng = editor.dom.createRng();
  23675. rng.setStart(element.dom, 0);
  23676. rng.setEnd(element.dom, 0);
  23677. moveToRange(editor, rng);
  23678. });
  23679. } else {
  23680. moveToRange(editor, pos.toRange());
  23681. }
  23682. };
  23683. var moveCaret = function (editor, down, pos) {
  23684. var table = down ? getTable(true, pos) : getTable(false, pos);
  23685. var last = down === false;
  23686. table.fold(function () {
  23687. return moveToRange(editor, pos.toRange());
  23688. }, function (table) {
  23689. return positionIn(last, editor.getBody()).filter(function (lastPos) {
  23690. return lastPos.isEqual(pos);
  23691. }).fold(function () {
  23692. return moveToRange(editor, pos.toRange());
  23693. }, function (_) {
  23694. return renderBlock(down, editor, table, pos);
  23695. });
  23696. });
  23697. };
  23698. var navigateVertically = function (editor, down, table, td) {
  23699. var rng = editor.selection.getRng();
  23700. var pos = CaretPosition.fromRangeStart(rng);
  23701. var root = editor.getBody();
  23702. if (!down && isAtFirstTableCellLine(td, pos)) {
  23703. var newPos = getClosestAbovePosition(root, table, pos);
  23704. moveCaret(editor, down, newPos);
  23705. return true;
  23706. } else if (down && isAtLastTableCellLine(td, pos)) {
  23707. var newPos = getClosestBelowPosition(root, table, pos);
  23708. moveCaret(editor, down, newPos);
  23709. return true;
  23710. } else {
  23711. return false;
  23712. }
  23713. };
  23714. var move$1 = function (editor, forward, mover) {
  23715. return Optional.from(editor.dom.getParent(editor.selection.getNode(), 'td,th')).bind(function (td) {
  23716. return Optional.from(editor.dom.getParent(td, 'table')).map(function (table) {
  23717. return mover(editor, forward, table, td);
  23718. });
  23719. }).getOr(false);
  23720. };
  23721. var moveH = function (editor, forward) {
  23722. return move$1(editor, forward, navigateHorizontally);
  23723. };
  23724. var moveV = function (editor, forward) {
  23725. return move$1(editor, forward, navigateVertically);
  23726. };
  23727. var executeKeydownOverride$3 = function (editor, caret, evt) {
  23728. var os = detect().os;
  23729. execute([
  23730. {
  23731. keyCode: VK.RIGHT,
  23732. action: action(moveH$2, editor, true)
  23733. },
  23734. {
  23735. keyCode: VK.LEFT,
  23736. action: action(moveH$2, editor, false)
  23737. },
  23738. {
  23739. keyCode: VK.UP,
  23740. action: action(moveV$3, editor, false)
  23741. },
  23742. {
  23743. keyCode: VK.DOWN,
  23744. action: action(moveV$3, editor, true)
  23745. },
  23746. {
  23747. keyCode: VK.RIGHT,
  23748. action: action(moveH, editor, true)
  23749. },
  23750. {
  23751. keyCode: VK.LEFT,
  23752. action: action(moveH, editor, false)
  23753. },
  23754. {
  23755. keyCode: VK.UP,
  23756. action: action(moveV, editor, false)
  23757. },
  23758. {
  23759. keyCode: VK.DOWN,
  23760. action: action(moveV, editor, true)
  23761. },
  23762. {
  23763. keyCode: VK.RIGHT,
  23764. action: action(moveH$1, editor, true)
  23765. },
  23766. {
  23767. keyCode: VK.LEFT,
  23768. action: action(moveH$1, editor, false)
  23769. },
  23770. {
  23771. keyCode: VK.UP,
  23772. action: action(moveV$1, editor, false)
  23773. },
  23774. {
  23775. keyCode: VK.DOWN,
  23776. action: action(moveV$1, editor, true)
  23777. },
  23778. {
  23779. keyCode: VK.RIGHT,
  23780. action: action(move$2, editor, caret, true)
  23781. },
  23782. {
  23783. keyCode: VK.LEFT,
  23784. action: action(move$2, editor, caret, false)
  23785. },
  23786. {
  23787. keyCode: VK.RIGHT,
  23788. ctrlKey: !os.isOSX(),
  23789. altKey: os.isOSX(),
  23790. action: action(moveNextWord, editor, caret)
  23791. },
  23792. {
  23793. keyCode: VK.LEFT,
  23794. ctrlKey: !os.isOSX(),
  23795. altKey: os.isOSX(),
  23796. action: action(movePrevWord, editor, caret)
  23797. },
  23798. {
  23799. keyCode: VK.UP,
  23800. action: action(moveV$2, editor, false)
  23801. },
  23802. {
  23803. keyCode: VK.DOWN,
  23804. action: action(moveV$2, editor, true)
  23805. }
  23806. ], evt).each(function (_) {
  23807. evt.preventDefault();
  23808. });
  23809. };
  23810. var setup$b = function (editor, caret) {
  23811. editor.on('keydown', function (evt) {
  23812. if (evt.isDefaultPrevented() === false) {
  23813. executeKeydownOverride$3(editor, caret, evt);
  23814. }
  23815. });
  23816. };
  23817. var executeKeydownOverride$2 = function (editor, caret, evt) {
  23818. execute([
  23819. {
  23820. keyCode: VK.BACKSPACE,
  23821. action: action(backspaceDelete, editor, false)
  23822. },
  23823. {
  23824. keyCode: VK.BACKSPACE,
  23825. action: action(backspaceDelete$5, editor, false)
  23826. },
  23827. {
  23828. keyCode: VK.DELETE,
  23829. action: action(backspaceDelete$5, editor, true)
  23830. },
  23831. {
  23832. keyCode: VK.BACKSPACE,
  23833. action: action(backspaceDelete$6, editor, false)
  23834. },
  23835. {
  23836. keyCode: VK.DELETE,
  23837. action: action(backspaceDelete$6, editor, true)
  23838. },
  23839. {
  23840. keyCode: VK.BACKSPACE,
  23841. action: action(backspaceDelete$3, editor, caret, false)
  23842. },
  23843. {
  23844. keyCode: VK.DELETE,
  23845. action: action(backspaceDelete$3, editor, caret, true)
  23846. },
  23847. {
  23848. keyCode: VK.BACKSPACE,
  23849. action: action(backspaceDelete$9, editor, false)
  23850. },
  23851. {
  23852. keyCode: VK.DELETE,
  23853. action: action(backspaceDelete$9, editor, true)
  23854. },
  23855. {
  23856. keyCode: VK.BACKSPACE,
  23857. action: action(backspaceDelete$4, editor, false)
  23858. },
  23859. {
  23860. keyCode: VK.DELETE,
  23861. action: action(backspaceDelete$4, editor, true)
  23862. },
  23863. {
  23864. keyCode: VK.BACKSPACE,
  23865. action: action(backspaceDelete$1, editor, false)
  23866. },
  23867. {
  23868. keyCode: VK.DELETE,
  23869. action: action(backspaceDelete$1, editor, true)
  23870. },
  23871. {
  23872. keyCode: VK.BACKSPACE,
  23873. action: action(backspaceDelete$7, editor, false)
  23874. },
  23875. {
  23876. keyCode: VK.DELETE,
  23877. action: action(backspaceDelete$7, editor, true)
  23878. },
  23879. {
  23880. keyCode: VK.BACKSPACE,
  23881. action: action(backspaceDelete$8, editor, false)
  23882. },
  23883. {
  23884. keyCode: VK.DELETE,
  23885. action: action(backspaceDelete$8, editor, true)
  23886. },
  23887. {
  23888. keyCode: VK.BACKSPACE,
  23889. action: action(backspaceDelete$2, editor, false)
  23890. },
  23891. {
  23892. keyCode: VK.DELETE,
  23893. action: action(backspaceDelete$2, editor, true)
  23894. }
  23895. ], evt).each(function (_) {
  23896. evt.preventDefault();
  23897. });
  23898. };
  23899. var executeKeyupOverride = function (editor, evt) {
  23900. execute([
  23901. {
  23902. keyCode: VK.BACKSPACE,
  23903. action: action(paddEmptyElement, editor)
  23904. },
  23905. {
  23906. keyCode: VK.DELETE,
  23907. action: action(paddEmptyElement, editor)
  23908. }
  23909. ], evt);
  23910. };
  23911. var setup$a = function (editor, caret) {
  23912. editor.on('keydown', function (evt) {
  23913. if (evt.isDefaultPrevented() === false) {
  23914. executeKeydownOverride$2(editor, caret, evt);
  23915. }
  23916. });
  23917. editor.on('keyup', function (evt) {
  23918. if (evt.isDefaultPrevented() === false) {
  23919. executeKeyupOverride(editor, evt);
  23920. }
  23921. });
  23922. };
  23923. var firstNonWhiteSpaceNodeSibling = function (node) {
  23924. while (node) {
  23925. if (node.nodeType === 1 || node.nodeType === 3 && node.data && /[\r\n\s]/.test(node.data)) {
  23926. return node;
  23927. }
  23928. node = node.nextSibling;
  23929. }
  23930. };
  23931. var moveToCaretPosition = function (editor, root) {
  23932. var node, lastNode = root;
  23933. var dom = editor.dom;
  23934. var moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
  23935. if (!root) {
  23936. return;
  23937. }
  23938. if (/^(LI|DT|DD)$/.test(root.nodeName)) {
  23939. var firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild);
  23940. if (firstChild && /^(UL|OL|DL)$/.test(firstChild.nodeName)) {
  23941. root.insertBefore(dom.doc.createTextNode(nbsp), root.firstChild);
  23942. }
  23943. }
  23944. var rng = dom.createRng();
  23945. root.normalize();
  23946. if (root.hasChildNodes()) {
  23947. var walker = new DomTreeWalker(root, root);
  23948. while (node = walker.current()) {
  23949. if (isText$7(node)) {
  23950. rng.setStart(node, 0);
  23951. rng.setEnd(node, 0);
  23952. break;
  23953. }
  23954. if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) {
  23955. rng.setStartBefore(node);
  23956. rng.setEndBefore(node);
  23957. break;
  23958. }
  23959. lastNode = node;
  23960. node = walker.next();
  23961. }
  23962. if (!node) {
  23963. rng.setStart(lastNode, 0);
  23964. rng.setEnd(lastNode, 0);
  23965. }
  23966. } else {
  23967. if (isBr$5(root)) {
  23968. if (root.nextSibling && dom.isBlock(root.nextSibling)) {
  23969. rng.setStartBefore(root);
  23970. rng.setEndBefore(root);
  23971. } else {
  23972. rng.setStartAfter(root);
  23973. rng.setEndAfter(root);
  23974. }
  23975. } else {
  23976. rng.setStart(root, 0);
  23977. rng.setEnd(root, 0);
  23978. }
  23979. }
  23980. editor.selection.setRng(rng);
  23981. scrollRangeIntoView(editor, rng);
  23982. };
  23983. var getEditableRoot$1 = function (dom, node) {
  23984. var root = dom.getRoot();
  23985. var parent, editableRoot;
  23986. parent = node;
  23987. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  23988. if (dom.getContentEditable(parent) === 'true') {
  23989. editableRoot = parent;
  23990. }
  23991. parent = parent.parentNode;
  23992. }
  23993. return parent !== root ? editableRoot : root;
  23994. };
  23995. var getParentBlock = function (editor) {
  23996. return Optional.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
  23997. };
  23998. var getParentBlockName = function (editor) {
  23999. return getParentBlock(editor).fold(constant(''), function (parentBlock) {
  24000. return parentBlock.nodeName.toUpperCase();
  24001. });
  24002. };
  24003. var isListItemParentBlock = function (editor) {
  24004. return getParentBlock(editor).filter(function (elm) {
  24005. return isListItem(SugarElement.fromDom(elm));
  24006. }).isSome();
  24007. };
  24008. var hasFirstChild = function (elm, name) {
  24009. return elm.firstChild && elm.firstChild.nodeName === name;
  24010. };
  24011. var isFirstChild = function (elm) {
  24012. var _a;
  24013. return ((_a = elm.parentNode) === null || _a === void 0 ? void 0 : _a.firstChild) === elm;
  24014. };
  24015. var hasParent = function (elm, parentName) {
  24016. return elm && elm.parentNode && elm.parentNode.nodeName === parentName;
  24017. };
  24018. var isListBlock = function (elm) {
  24019. return elm && /^(OL|UL|LI)$/.test(elm.nodeName);
  24020. };
  24021. var isNestedList = function (elm) {
  24022. return isListBlock(elm) && isListBlock(elm.parentNode);
  24023. };
  24024. var getContainerBlock = function (containerBlock) {
  24025. var containerBlockParent = containerBlock.parentNode;
  24026. if (/^(LI|DT|DD)$/.test(containerBlockParent.nodeName)) {
  24027. return containerBlockParent;
  24028. }
  24029. return containerBlock;
  24030. };
  24031. var isFirstOrLastLi = function (containerBlock, parentBlock, first) {
  24032. var node = containerBlock[first ? 'firstChild' : 'lastChild'];
  24033. while (node) {
  24034. if (isElement$5(node)) {
  24035. break;
  24036. }
  24037. node = node[first ? 'nextSibling' : 'previousSibling'];
  24038. }
  24039. return node === parentBlock;
  24040. };
  24041. var insert$3 = function (editor, createNewBlock, containerBlock, parentBlock, newBlockName) {
  24042. var dom = editor.dom;
  24043. var rng = editor.selection.getRng();
  24044. if (containerBlock === editor.getBody()) {
  24045. return;
  24046. }
  24047. if (isNestedList(containerBlock)) {
  24048. newBlockName = 'LI';
  24049. }
  24050. var newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR');
  24051. if (isFirstOrLastLi(containerBlock, parentBlock, true) && isFirstOrLastLi(containerBlock, parentBlock, false)) {
  24052. if (hasParent(containerBlock, 'LI')) {
  24053. var containerBlockParent = getContainerBlock(containerBlock);
  24054. dom.insertAfter(newBlock, containerBlockParent);
  24055. if (isFirstChild(containerBlock)) {
  24056. dom.remove(containerBlockParent);
  24057. } else {
  24058. dom.remove(containerBlock);
  24059. }
  24060. } else {
  24061. dom.replace(newBlock, containerBlock);
  24062. }
  24063. } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
  24064. if (hasParent(containerBlock, 'LI')) {
  24065. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  24066. newBlock.appendChild(dom.doc.createTextNode(' '));
  24067. newBlock.appendChild(containerBlock);
  24068. } else {
  24069. containerBlock.parentNode.insertBefore(newBlock, containerBlock);
  24070. }
  24071. dom.remove(parentBlock);
  24072. } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
  24073. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  24074. dom.remove(parentBlock);
  24075. } else {
  24076. containerBlock = getContainerBlock(containerBlock);
  24077. var tmpRng = rng.cloneRange();
  24078. tmpRng.setStartAfter(parentBlock);
  24079. tmpRng.setEndAfter(containerBlock);
  24080. var fragment = tmpRng.extractContents();
  24081. if (newBlockName === 'LI' && hasFirstChild(fragment, 'LI')) {
  24082. newBlock = fragment.firstChild;
  24083. dom.insertAfter(fragment, containerBlock);
  24084. } else {
  24085. dom.insertAfter(fragment, containerBlock);
  24086. dom.insertAfter(newBlock, containerBlock);
  24087. }
  24088. dom.remove(parentBlock);
  24089. }
  24090. moveToCaretPosition(editor, newBlock);
  24091. };
  24092. var trimZwsp = function (fragment) {
  24093. each$k(descendants$1(SugarElement.fromDom(fragment), isText$8), function (text) {
  24094. var rawNode = text.dom;
  24095. rawNode.nodeValue = trim$2(rawNode.nodeValue);
  24096. });
  24097. };
  24098. var isEmptyAnchor = function (dom, elm) {
  24099. return elm && elm.nodeName === 'A' && dom.isEmpty(elm);
  24100. };
  24101. var isTableCell = function (node) {
  24102. return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  24103. };
  24104. var emptyBlock = function (elm) {
  24105. elm.innerHTML = '<br data-mce-bogus="1">';
  24106. };
  24107. var containerAndSiblingName = function (container, nodeName) {
  24108. return container.nodeName === nodeName || container.previousSibling && container.previousSibling.nodeName === nodeName;
  24109. };
  24110. var canSplitBlock = function (dom, node) {
  24111. return node && dom.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.getContentEditable(node) !== 'true';
  24112. };
  24113. var trimInlineElementsOnLeftSideOfBlock = function (dom, nonEmptyElementsMap, block) {
  24114. var node = block;
  24115. var firstChilds = [];
  24116. var i;
  24117. if (!node) {
  24118. return;
  24119. }
  24120. while (node = node.firstChild) {
  24121. if (dom.isBlock(node)) {
  24122. return;
  24123. }
  24124. if (isElement$5(node) && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  24125. firstChilds.push(node);
  24126. }
  24127. }
  24128. i = firstChilds.length;
  24129. while (i--) {
  24130. node = firstChilds[i];
  24131. if (!node.hasChildNodes() || node.firstChild === node.lastChild && node.firstChild.nodeValue === '') {
  24132. dom.remove(node);
  24133. } else {
  24134. if (isEmptyAnchor(dom, node)) {
  24135. dom.remove(node);
  24136. }
  24137. }
  24138. }
  24139. };
  24140. var normalizeZwspOffset = function (start, container, offset) {
  24141. if (isText$7(container) === false) {
  24142. return offset;
  24143. } else if (start) {
  24144. return offset === 1 && container.data.charAt(offset - 1) === ZWSP$1 ? 0 : offset;
  24145. } else {
  24146. return offset === container.data.length - 1 && container.data.charAt(offset) === ZWSP$1 ? container.data.length : offset;
  24147. }
  24148. };
  24149. var includeZwspInRange = function (rng) {
  24150. var newRng = rng.cloneRange();
  24151. newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
  24152. newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
  24153. return newRng;
  24154. };
  24155. var trimLeadingLineBreaks = function (node) {
  24156. do {
  24157. if (isText$7(node)) {
  24158. node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
  24159. }
  24160. node = node.firstChild;
  24161. } while (node);
  24162. };
  24163. var getEditableRoot = function (dom, node) {
  24164. var root = dom.getRoot();
  24165. var parent, editableRoot;
  24166. parent = node;
  24167. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  24168. if (dom.getContentEditable(parent) === 'true') {
  24169. editableRoot = parent;
  24170. }
  24171. parent = parent.parentNode;
  24172. }
  24173. return parent !== root ? editableRoot : root;
  24174. };
  24175. var applyAttributes = function (editor, node, forcedRootBlockAttrs) {
  24176. var dom = editor.dom;
  24177. Optional.from(forcedRootBlockAttrs.style).map(dom.parseStyle).each(function (attrStyles) {
  24178. var currentStyles = getAllRaw(SugarElement.fromDom(node));
  24179. var newStyles = __assign(__assign({}, currentStyles), attrStyles);
  24180. dom.setStyles(node, newStyles);
  24181. });
  24182. var attrClassesOpt = Optional.from(forcedRootBlockAttrs.class).map(function (attrClasses) {
  24183. return attrClasses.split(/\s+/);
  24184. });
  24185. var currentClassesOpt = Optional.from(node.className).map(function (currentClasses) {
  24186. return filter$4(currentClasses.split(/\s+/), function (clazz) {
  24187. return clazz !== '';
  24188. });
  24189. });
  24190. lift2(attrClassesOpt, currentClassesOpt, function (attrClasses, currentClasses) {
  24191. var filteredClasses = filter$4(currentClasses, function (clazz) {
  24192. return !contains$3(attrClasses, clazz);
  24193. });
  24194. var newClasses = __spreadArray(__spreadArray([], attrClasses, true), filteredClasses, true);
  24195. dom.setAttrib(node, 'class', newClasses.join(' '));
  24196. });
  24197. var appliedAttrs = [
  24198. 'style',
  24199. 'class'
  24200. ];
  24201. var remainingAttrs = filter$3(forcedRootBlockAttrs, function (_, attrs) {
  24202. return !contains$3(appliedAttrs, attrs);
  24203. });
  24204. dom.setAttribs(node, remainingAttrs);
  24205. };
  24206. var setForcedBlockAttrs = function (editor, node) {
  24207. var forcedRootBlockName = getForcedRootBlock(editor);
  24208. if (forcedRootBlockName && forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
  24209. var forcedRootBlockAttrs = getForcedRootBlockAttrs(editor);
  24210. applyAttributes(editor, node, forcedRootBlockAttrs);
  24211. }
  24212. };
  24213. var wrapSelfAndSiblingsInDefaultBlock = function (editor, newBlockName, rng, container, offset) {
  24214. var newBlock, parentBlock, startNode, node, next, rootBlockName;
  24215. var blockName = newBlockName || 'P';
  24216. var dom = editor.dom, editableRoot = getEditableRoot(dom, container);
  24217. parentBlock = dom.getParent(container, dom.isBlock);
  24218. if (!parentBlock || !canSplitBlock(dom, parentBlock)) {
  24219. parentBlock = parentBlock || editableRoot;
  24220. if (parentBlock === editor.getBody() || isTableCell(parentBlock)) {
  24221. rootBlockName = parentBlock.nodeName.toLowerCase();
  24222. } else {
  24223. rootBlockName = parentBlock.parentNode.nodeName.toLowerCase();
  24224. }
  24225. if (!parentBlock.hasChildNodes()) {
  24226. newBlock = dom.create(blockName);
  24227. setForcedBlockAttrs(editor, newBlock);
  24228. parentBlock.appendChild(newBlock);
  24229. rng.setStart(newBlock, 0);
  24230. rng.setEnd(newBlock, 0);
  24231. return newBlock;
  24232. }
  24233. node = container;
  24234. while (node.parentNode !== parentBlock) {
  24235. node = node.parentNode;
  24236. }
  24237. while (node && !dom.isBlock(node)) {
  24238. startNode = node;
  24239. node = node.previousSibling;
  24240. }
  24241. if (startNode && editor.schema.isValidChild(rootBlockName, blockName.toLowerCase())) {
  24242. newBlock = dom.create(blockName);
  24243. setForcedBlockAttrs(editor, newBlock);
  24244. startNode.parentNode.insertBefore(newBlock, startNode);
  24245. node = startNode;
  24246. while (node && !dom.isBlock(node)) {
  24247. next = node.nextSibling;
  24248. newBlock.appendChild(node);
  24249. node = next;
  24250. }
  24251. rng.setStart(container, offset);
  24252. rng.setEnd(container, offset);
  24253. }
  24254. }
  24255. return container;
  24256. };
  24257. var addBrToBlockIfNeeded = function (dom, block) {
  24258. block.normalize();
  24259. var lastChild = block.lastChild;
  24260. if (!lastChild || /^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true))) {
  24261. dom.add(block, 'br');
  24262. }
  24263. };
  24264. var insert$2 = function (editor, evt) {
  24265. var tmpRng, container, offset, parentBlock;
  24266. var newBlock, fragment, containerBlock, parentBlockName, newBlockName, isAfterLastNodeInContainer;
  24267. var dom = editor.dom;
  24268. var schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
  24269. var rng = editor.selection.getRng();
  24270. var createNewBlock = function (name) {
  24271. var node = container, block, clonedNode, caretNode;
  24272. var textInlineElements = schema.getTextInlineElements();
  24273. if (name || parentBlockName === 'TABLE' || parentBlockName === 'HR') {
  24274. block = dom.create(name || newBlockName);
  24275. } else {
  24276. block = parentBlock.cloneNode(false);
  24277. }
  24278. caretNode = block;
  24279. if (shouldKeepStyles(editor) === false) {
  24280. dom.setAttrib(block, 'style', null);
  24281. dom.setAttrib(block, 'class', null);
  24282. } else {
  24283. do {
  24284. if (textInlineElements[node.nodeName]) {
  24285. if (isCaretNode(node) || isBookmarkNode$1(node)) {
  24286. continue;
  24287. }
  24288. clonedNode = node.cloneNode(false);
  24289. dom.setAttrib(clonedNode, 'id', '');
  24290. if (block.hasChildNodes()) {
  24291. clonedNode.appendChild(block.firstChild);
  24292. block.appendChild(clonedNode);
  24293. } else {
  24294. caretNode = clonedNode;
  24295. block.appendChild(clonedNode);
  24296. }
  24297. }
  24298. } while ((node = node.parentNode) && node !== editableRoot);
  24299. }
  24300. setForcedBlockAttrs(editor, block);
  24301. emptyBlock(caretNode);
  24302. return block;
  24303. };
  24304. var isCaretAtStartOrEndOfBlock = function (start) {
  24305. var node, name;
  24306. var normalizedOffset = normalizeZwspOffset(start, container, offset);
  24307. if (isText$7(container) && (start ? normalizedOffset > 0 : normalizedOffset < container.nodeValue.length)) {
  24308. return false;
  24309. }
  24310. if (container.parentNode === parentBlock && isAfterLastNodeInContainer && !start) {
  24311. return true;
  24312. }
  24313. if (start && isElement$5(container) && container === parentBlock.firstChild) {
  24314. return true;
  24315. }
  24316. if (containerAndSiblingName(container, 'TABLE') || containerAndSiblingName(container, 'HR')) {
  24317. return isAfterLastNodeInContainer && !start || !isAfterLastNodeInContainer && start;
  24318. }
  24319. var walker = new DomTreeWalker(container, parentBlock);
  24320. if (isText$7(container)) {
  24321. if (start && normalizedOffset === 0) {
  24322. walker.prev();
  24323. } else if (!start && normalizedOffset === container.nodeValue.length) {
  24324. walker.next();
  24325. }
  24326. }
  24327. while (node = walker.current()) {
  24328. if (isElement$5(node)) {
  24329. if (!node.getAttribute('data-mce-bogus')) {
  24330. name = node.nodeName.toLowerCase();
  24331. if (nonEmptyElementsMap[name] && name !== 'br') {
  24332. return false;
  24333. }
  24334. }
  24335. } else if (isText$7(node) && !isWhitespaceText(node.nodeValue)) {
  24336. return false;
  24337. }
  24338. if (start) {
  24339. walker.prev();
  24340. } else {
  24341. walker.next();
  24342. }
  24343. }
  24344. return true;
  24345. };
  24346. var insertNewBlockAfter = function () {
  24347. if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName !== 'HGROUP') {
  24348. newBlock = createNewBlock(newBlockName);
  24349. } else {
  24350. newBlock = createNewBlock();
  24351. }
  24352. if (shouldEndContainerOnEmptyBlock(editor) && canSplitBlock(dom, containerBlock) && dom.isEmpty(parentBlock)) {
  24353. newBlock = dom.split(containerBlock, parentBlock);
  24354. } else {
  24355. dom.insertAfter(newBlock, parentBlock);
  24356. }
  24357. moveToCaretPosition(editor, newBlock);
  24358. };
  24359. normalize$2(dom, rng).each(function (normRng) {
  24360. rng.setStart(normRng.startContainer, normRng.startOffset);
  24361. rng.setEnd(normRng.endContainer, normRng.endOffset);
  24362. });
  24363. container = rng.startContainer;
  24364. offset = rng.startOffset;
  24365. newBlockName = getForcedRootBlock(editor);
  24366. var shiftKey = !!(evt && evt.shiftKey);
  24367. var ctrlKey = !!(evt && evt.ctrlKey);
  24368. if (isElement$5(container) && container.hasChildNodes()) {
  24369. isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  24370. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  24371. if (isAfterLastNodeInContainer && isText$7(container)) {
  24372. offset = container.nodeValue.length;
  24373. } else {
  24374. offset = 0;
  24375. }
  24376. }
  24377. var editableRoot = getEditableRoot(dom, container);
  24378. if (!editableRoot) {
  24379. return;
  24380. }
  24381. if (newBlockName && !shiftKey || !newBlockName && shiftKey) {
  24382. container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset);
  24383. }
  24384. parentBlock = dom.getParent(container, dom.isBlock);
  24385. containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  24386. parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : '';
  24387. var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  24388. if (containerBlockName === 'LI' && !ctrlKey) {
  24389. parentBlock = containerBlock;
  24390. containerBlock = containerBlock.parentNode;
  24391. parentBlockName = containerBlockName;
  24392. }
  24393. if (/^(LI|DT|DD)$/.test(parentBlockName)) {
  24394. if (dom.isEmpty(parentBlock)) {
  24395. insert$3(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
  24396. return;
  24397. }
  24398. }
  24399. if (newBlockName && parentBlock === editor.getBody()) {
  24400. return;
  24401. }
  24402. newBlockName = newBlockName || 'P';
  24403. if (isCaretContainerBlock$1(parentBlock)) {
  24404. newBlock = showCaretContainerBlock(parentBlock);
  24405. if (dom.isEmpty(parentBlock)) {
  24406. emptyBlock(parentBlock);
  24407. }
  24408. setForcedBlockAttrs(editor, newBlock);
  24409. moveToCaretPosition(editor, newBlock);
  24410. } else if (isCaretAtStartOrEndOfBlock()) {
  24411. insertNewBlockAfter();
  24412. } else if (isCaretAtStartOrEndOfBlock(true)) {
  24413. newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
  24414. moveToCaretPosition(editor, containerAndSiblingName(parentBlock, 'HR') ? newBlock : parentBlock);
  24415. } else {
  24416. tmpRng = includeZwspInRange(rng).cloneRange();
  24417. tmpRng.setEndAfter(parentBlock);
  24418. fragment = tmpRng.extractContents();
  24419. trimZwsp(fragment);
  24420. trimLeadingLineBreaks(fragment);
  24421. newBlock = fragment.firstChild;
  24422. dom.insertAfter(fragment, parentBlock);
  24423. trimInlineElementsOnLeftSideOfBlock(dom, nonEmptyElementsMap, newBlock);
  24424. addBrToBlockIfNeeded(dom, parentBlock);
  24425. if (dom.isEmpty(parentBlock)) {
  24426. emptyBlock(parentBlock);
  24427. }
  24428. newBlock.normalize();
  24429. if (dom.isEmpty(newBlock)) {
  24430. dom.remove(newBlock);
  24431. insertNewBlockAfter();
  24432. } else {
  24433. setForcedBlockAttrs(editor, newBlock);
  24434. moveToCaretPosition(editor, newBlock);
  24435. }
  24436. }
  24437. dom.setAttrib(newBlock, 'id', '');
  24438. editor.fire('NewBlock', { newBlock: newBlock });
  24439. };
  24440. var hasRightSideContent = function (schema, container, parentBlock) {
  24441. var walker = new DomTreeWalker(container, parentBlock);
  24442. var node;
  24443. var nonEmptyElementsMap = schema.getNonEmptyElements();
  24444. while (node = walker.next()) {
  24445. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
  24446. return true;
  24447. }
  24448. }
  24449. };
  24450. var moveSelectionToBr = function (editor, brElm, extraBr) {
  24451. var rng = editor.dom.createRng();
  24452. if (!extraBr) {
  24453. rng.setStartAfter(brElm);
  24454. rng.setEndAfter(brElm);
  24455. } else {
  24456. rng.setStartBefore(brElm);
  24457. rng.setEndBefore(brElm);
  24458. }
  24459. editor.selection.setRng(rng);
  24460. scrollRangeIntoView(editor, rng);
  24461. };
  24462. var insertBrAtCaret = function (editor, evt) {
  24463. var selection = editor.selection;
  24464. var dom = editor.dom;
  24465. var rng = selection.getRng();
  24466. var brElm;
  24467. var extraBr;
  24468. normalize$2(dom, rng).each(function (normRng) {
  24469. rng.setStart(normRng.startContainer, normRng.startOffset);
  24470. rng.setEnd(normRng.endContainer, normRng.endOffset);
  24471. });
  24472. var offset = rng.startOffset;
  24473. var container = rng.startContainer;
  24474. if (container.nodeType === 1 && container.hasChildNodes()) {
  24475. var isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  24476. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  24477. if (isAfterLastNodeInContainer && container.nodeType === 3) {
  24478. offset = container.nodeValue.length;
  24479. } else {
  24480. offset = 0;
  24481. }
  24482. }
  24483. var parentBlock = dom.getParent(container, dom.isBlock);
  24484. var containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  24485. var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  24486. var isControlKey = !!(evt && evt.ctrlKey);
  24487. if (containerBlockName === 'LI' && !isControlKey) {
  24488. parentBlock = containerBlock;
  24489. }
  24490. if (container && container.nodeType === 3 && offset >= container.nodeValue.length) {
  24491. if (!hasRightSideContent(editor.schema, container, parentBlock)) {
  24492. brElm = dom.create('br');
  24493. rng.insertNode(brElm);
  24494. rng.setStartAfter(brElm);
  24495. rng.setEndAfter(brElm);
  24496. extraBr = true;
  24497. }
  24498. }
  24499. brElm = dom.create('br');
  24500. rangeInsertNode(dom, rng, brElm);
  24501. moveSelectionToBr(editor, brElm, extraBr);
  24502. editor.undoManager.add();
  24503. };
  24504. var insertBrBefore = function (editor, inline) {
  24505. var br = SugarElement.fromTag('br');
  24506. before$4(SugarElement.fromDom(inline), br);
  24507. editor.undoManager.add();
  24508. };
  24509. var insertBrAfter = function (editor, inline) {
  24510. if (!hasBrAfter(editor.getBody(), inline)) {
  24511. after$3(SugarElement.fromDom(inline), SugarElement.fromTag('br'));
  24512. }
  24513. var br = SugarElement.fromTag('br');
  24514. after$3(SugarElement.fromDom(inline), br);
  24515. moveSelectionToBr(editor, br.dom, false);
  24516. editor.undoManager.add();
  24517. };
  24518. var isBeforeBr = function (pos) {
  24519. return isBr$5(pos.getNode());
  24520. };
  24521. var hasBrAfter = function (rootNode, startNode) {
  24522. if (isBeforeBr(CaretPosition.after(startNode))) {
  24523. return true;
  24524. } else {
  24525. return nextPosition(rootNode, CaretPosition.after(startNode)).map(function (pos) {
  24526. return isBr$5(pos.getNode());
  24527. }).getOr(false);
  24528. }
  24529. };
  24530. var isAnchorLink = function (elm) {
  24531. return elm && elm.nodeName === 'A' && 'href' in elm;
  24532. };
  24533. var isInsideAnchor = function (location) {
  24534. return location.fold(never, isAnchorLink, isAnchorLink, never);
  24535. };
  24536. var readInlineAnchorLocation = function (editor) {
  24537. var isInlineTarget$1 = curry(isInlineTarget, editor);
  24538. var position = CaretPosition.fromRangeStart(editor.selection.getRng());
  24539. return readLocation(isInlineTarget$1, editor.getBody(), position).filter(isInsideAnchor);
  24540. };
  24541. var insertBrOutsideAnchor = function (editor, location) {
  24542. location.fold(noop, curry(insertBrBefore, editor), curry(insertBrAfter, editor), noop);
  24543. };
  24544. var insert$1 = function (editor, evt) {
  24545. var anchorLocation = readInlineAnchorLocation(editor);
  24546. if (anchorLocation.isSome()) {
  24547. anchorLocation.each(curry(insertBrOutsideAnchor, editor));
  24548. } else {
  24549. insertBrAtCaret(editor, evt);
  24550. }
  24551. };
  24552. var matchesSelector = function (editor, selector) {
  24553. return getParentBlock(editor).filter(function (parentBlock) {
  24554. return selector.length > 0 && is$2(SugarElement.fromDom(parentBlock), selector);
  24555. }).isSome();
  24556. };
  24557. var shouldInsertBr = function (editor) {
  24558. return matchesSelector(editor, getBrNewLineSelector(editor));
  24559. };
  24560. var shouldBlockNewLine$1 = function (editor) {
  24561. return matchesSelector(editor, getNoNewLineSelector(editor));
  24562. };
  24563. var newLineAction = Adt.generate([
  24564. { br: [] },
  24565. { block: [] },
  24566. { none: [] }
  24567. ]);
  24568. var shouldBlockNewLine = function (editor, _shiftKey) {
  24569. return shouldBlockNewLine$1(editor);
  24570. };
  24571. var isBrMode = function (requiredState) {
  24572. return function (editor, _shiftKey) {
  24573. var brMode = getForcedRootBlock(editor) === '';
  24574. return brMode === requiredState;
  24575. };
  24576. };
  24577. var inListBlock = function (requiredState) {
  24578. return function (editor, _shiftKey) {
  24579. return isListItemParentBlock(editor) === requiredState;
  24580. };
  24581. };
  24582. var inBlock = function (blockName, requiredState) {
  24583. return function (editor, _shiftKey) {
  24584. var state = getParentBlockName(editor) === blockName.toUpperCase();
  24585. return state === requiredState;
  24586. };
  24587. };
  24588. var inPreBlock = function (requiredState) {
  24589. return inBlock('pre', requiredState);
  24590. };
  24591. var inSummaryBlock = function () {
  24592. return inBlock('summary', true);
  24593. };
  24594. var shouldPutBrInPre = function (requiredState) {
  24595. return function (editor, _shiftKey) {
  24596. return shouldPutBrInPre$1(editor) === requiredState;
  24597. };
  24598. };
  24599. var inBrContext = function (editor, _shiftKey) {
  24600. return shouldInsertBr(editor);
  24601. };
  24602. var hasShiftKey = function (_editor, shiftKey) {
  24603. return shiftKey;
  24604. };
  24605. var canInsertIntoEditableRoot = function (editor) {
  24606. var forcedRootBlock = getForcedRootBlock(editor);
  24607. var rootEditable = getEditableRoot$1(editor.dom, editor.selection.getStart());
  24608. return rootEditable && editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock ? forcedRootBlock : 'P');
  24609. };
  24610. var match = function (predicates, action) {
  24611. return function (editor, shiftKey) {
  24612. var isMatch = foldl(predicates, function (res, p) {
  24613. return res && p(editor, shiftKey);
  24614. }, true);
  24615. return isMatch ? Optional.some(action) : Optional.none();
  24616. };
  24617. };
  24618. var getAction = function (editor, evt) {
  24619. return evaluateUntil([
  24620. match([shouldBlockNewLine], newLineAction.none()),
  24621. match([inSummaryBlock()], newLineAction.br()),
  24622. match([
  24623. inPreBlock(true),
  24624. shouldPutBrInPre(false),
  24625. hasShiftKey
  24626. ], newLineAction.br()),
  24627. match([
  24628. inPreBlock(true),
  24629. shouldPutBrInPre(false)
  24630. ], newLineAction.block()),
  24631. match([
  24632. inPreBlock(true),
  24633. shouldPutBrInPre(true),
  24634. hasShiftKey
  24635. ], newLineAction.block()),
  24636. match([
  24637. inPreBlock(true),
  24638. shouldPutBrInPre(true)
  24639. ], newLineAction.br()),
  24640. match([
  24641. inListBlock(true),
  24642. hasShiftKey
  24643. ], newLineAction.br()),
  24644. match([inListBlock(true)], newLineAction.block()),
  24645. match([
  24646. isBrMode(true),
  24647. hasShiftKey,
  24648. canInsertIntoEditableRoot
  24649. ], newLineAction.block()),
  24650. match([isBrMode(true)], newLineAction.br()),
  24651. match([inBrContext], newLineAction.br()),
  24652. match([
  24653. isBrMode(false),
  24654. hasShiftKey
  24655. ], newLineAction.br()),
  24656. match([canInsertIntoEditableRoot], newLineAction.block())
  24657. ], [
  24658. editor,
  24659. !!(evt && evt.shiftKey)
  24660. ]).getOr(newLineAction.none());
  24661. };
  24662. var insert = function (editor, evt) {
  24663. getAction(editor, evt).fold(function () {
  24664. insert$1(editor, evt);
  24665. }, function () {
  24666. insert$2(editor, evt);
  24667. }, noop);
  24668. };
  24669. var handleEnterKeyEvent = function (editor, event) {
  24670. if (event.isDefaultPrevented()) {
  24671. return;
  24672. }
  24673. event.preventDefault();
  24674. endTypingLevelIgnoreLocks(editor.undoManager);
  24675. editor.undoManager.transact(function () {
  24676. if (editor.selection.isCollapsed() === false) {
  24677. editor.execCommand('Delete');
  24678. }
  24679. insert(editor, event);
  24680. });
  24681. };
  24682. var setup$9 = function (editor) {
  24683. editor.on('keydown', function (event) {
  24684. if (event.keyCode === VK.ENTER) {
  24685. handleEnterKeyEvent(editor, event);
  24686. }
  24687. });
  24688. };
  24689. var executeKeydownOverride$1 = function (editor, caret, evt) {
  24690. execute([
  24691. {
  24692. keyCode: VK.END,
  24693. action: action(moveToLineEndPoint$1, editor, true)
  24694. },
  24695. {
  24696. keyCode: VK.HOME,
  24697. action: action(moveToLineEndPoint$1, editor, false)
  24698. },
  24699. {
  24700. keyCode: VK.END,
  24701. action: action(moveToLineEndPoint, editor, true)
  24702. },
  24703. {
  24704. keyCode: VK.HOME,
  24705. action: action(moveToLineEndPoint, editor, false)
  24706. },
  24707. {
  24708. keyCode: VK.END,
  24709. action: action(moveToLineEndPoint$2, editor, true, caret)
  24710. },
  24711. {
  24712. keyCode: VK.HOME,
  24713. action: action(moveToLineEndPoint$2, editor, false, caret)
  24714. }
  24715. ], evt).each(function (_) {
  24716. evt.preventDefault();
  24717. });
  24718. };
  24719. var setup$8 = function (editor, caret) {
  24720. editor.on('keydown', function (evt) {
  24721. if (evt.isDefaultPrevented() === false) {
  24722. executeKeydownOverride$1(editor, caret, evt);
  24723. }
  24724. });
  24725. };
  24726. var browser = detect().browser;
  24727. var setupIeInput = function (editor) {
  24728. var keypressThrotter = first(function () {
  24729. if (!editor.composing) {
  24730. normalizeNbspsInEditor(editor);
  24731. }
  24732. }, 0);
  24733. if (browser.isIE()) {
  24734. editor.on('keypress', function (_e) {
  24735. keypressThrotter.throttle();
  24736. });
  24737. editor.on('remove', function (_e) {
  24738. keypressThrotter.cancel();
  24739. });
  24740. }
  24741. };
  24742. var setup$7 = function (editor) {
  24743. setupIeInput(editor);
  24744. editor.on('input', function (e) {
  24745. if (e.isComposing === false) {
  24746. normalizeNbspsInEditor(editor);
  24747. }
  24748. });
  24749. };
  24750. var platform = detect();
  24751. var executeKeyupAction = function (editor, caret, evt) {
  24752. execute([
  24753. {
  24754. keyCode: VK.PAGE_UP,
  24755. action: action(moveToLineEndPoint$2, editor, false, caret)
  24756. },
  24757. {
  24758. keyCode: VK.PAGE_DOWN,
  24759. action: action(moveToLineEndPoint$2, editor, true, caret)
  24760. }
  24761. ], evt);
  24762. };
  24763. var stopImmediatePropagation = function (e) {
  24764. return e.stopImmediatePropagation();
  24765. };
  24766. var isPageUpDown = function (evt) {
  24767. return evt.keyCode === VK.PAGE_UP || evt.keyCode === VK.PAGE_DOWN;
  24768. };
  24769. var setNodeChangeBlocker = function (blocked, editor, block) {
  24770. if (block && !blocked.get()) {
  24771. editor.on('NodeChange', stopImmediatePropagation, true);
  24772. } else if (!block && blocked.get()) {
  24773. editor.off('NodeChange', stopImmediatePropagation);
  24774. }
  24775. blocked.set(block);
  24776. };
  24777. var setup$6 = function (editor, caret) {
  24778. if (platform.os.isOSX()) {
  24779. return;
  24780. }
  24781. var blocked = Cell(false);
  24782. editor.on('keydown', function (evt) {
  24783. if (isPageUpDown(evt)) {
  24784. setNodeChangeBlocker(blocked, editor, true);
  24785. }
  24786. });
  24787. editor.on('keyup', function (evt) {
  24788. if (evt.isDefaultPrevented() === false) {
  24789. executeKeyupAction(editor, caret, evt);
  24790. }
  24791. if (isPageUpDown(evt) && blocked.get()) {
  24792. setNodeChangeBlocker(blocked, editor, false);
  24793. editor.nodeChanged();
  24794. }
  24795. });
  24796. };
  24797. var insertTextAtPosition = function (text, pos) {
  24798. var container = pos.container();
  24799. var offset = pos.offset();
  24800. if (isText$7(container)) {
  24801. container.insertData(offset, text);
  24802. return Optional.some(CaretPosition(container, offset + text.length));
  24803. } else {
  24804. return getElementFromPosition(pos).map(function (elm) {
  24805. var textNode = SugarElement.fromText(text);
  24806. if (pos.isAtEnd()) {
  24807. after$3(elm, textNode);
  24808. } else {
  24809. before$4(elm, textNode);
  24810. }
  24811. return CaretPosition(textNode.dom, text.length);
  24812. });
  24813. }
  24814. };
  24815. var insertNbspAtPosition = curry(insertTextAtPosition, nbsp);
  24816. var insertSpaceAtPosition = curry(insertTextAtPosition, ' ');
  24817. var locationToCaretPosition = function (root) {
  24818. return function (location) {
  24819. return location.fold(function (element) {
  24820. return prevPosition(root.dom, CaretPosition.before(element));
  24821. }, function (element) {
  24822. return firstPositionIn(element);
  24823. }, function (element) {
  24824. return lastPositionIn(element);
  24825. }, function (element) {
  24826. return nextPosition(root.dom, CaretPosition.after(element));
  24827. });
  24828. };
  24829. };
  24830. var insertInlineBoundarySpaceOrNbsp = function (root, pos) {
  24831. return function (checkPos) {
  24832. return needsToHaveNbsp(root, checkPos) ? insertNbspAtPosition(pos) : insertSpaceAtPosition(pos);
  24833. };
  24834. };
  24835. var setSelection = function (editor) {
  24836. return function (pos) {
  24837. editor.selection.setRng(pos.toRange());
  24838. editor.nodeChanged();
  24839. return true;
  24840. };
  24841. };
  24842. var insertSpaceOrNbspAtSelection = function (editor) {
  24843. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  24844. var root = SugarElement.fromDom(editor.getBody());
  24845. if (editor.selection.isCollapsed()) {
  24846. var isInlineTarget$1 = curry(isInlineTarget, editor);
  24847. var caretPosition = CaretPosition.fromRangeStart(editor.selection.getRng());
  24848. return readLocation(isInlineTarget$1, editor.getBody(), caretPosition).bind(locationToCaretPosition(root)).bind(insertInlineBoundarySpaceOrNbsp(root, pos)).exists(setSelection(editor));
  24849. } else {
  24850. return false;
  24851. }
  24852. };
  24853. var executeKeydownOverride = function (editor, evt) {
  24854. execute([{
  24855. keyCode: VK.SPACEBAR,
  24856. action: action(insertSpaceOrNbspAtSelection, editor)
  24857. }], evt).each(function (_) {
  24858. evt.preventDefault();
  24859. });
  24860. };
  24861. var setup$5 = function (editor) {
  24862. editor.on('keydown', function (evt) {
  24863. if (evt.isDefaultPrevented() === false) {
  24864. executeKeydownOverride(editor, evt);
  24865. }
  24866. });
  24867. };
  24868. var registerKeyboardOverrides = function (editor) {
  24869. var caret = setupSelectedState(editor);
  24870. setup$c(editor);
  24871. setup$b(editor, caret);
  24872. setup$a(editor, caret);
  24873. setup$9(editor);
  24874. setup$5(editor);
  24875. setup$7(editor);
  24876. setup$8(editor, caret);
  24877. setup$6(editor, caret);
  24878. return caret;
  24879. };
  24880. var setup$4 = function (editor) {
  24881. if (!isRtc(editor)) {
  24882. return registerKeyboardOverrides(editor);
  24883. } else {
  24884. return Cell(null);
  24885. }
  24886. };
  24887. var NodeChange = function () {
  24888. function NodeChange(editor) {
  24889. this.lastPath = [];
  24890. this.editor = editor;
  24891. var lastRng;
  24892. var self = this;
  24893. if (!('onselectionchange' in editor.getDoc())) {
  24894. editor.on('NodeChange click mouseup keyup focus', function (e) {
  24895. var nativeRng = editor.selection.getRng();
  24896. var fakeRng = {
  24897. startContainer: nativeRng.startContainer,
  24898. startOffset: nativeRng.startOffset,
  24899. endContainer: nativeRng.endContainer,
  24900. endOffset: nativeRng.endOffset
  24901. };
  24902. if (e.type === 'nodechange' || !isEq$4(fakeRng, lastRng)) {
  24903. editor.fire('SelectionChange');
  24904. }
  24905. lastRng = fakeRng;
  24906. });
  24907. }
  24908. editor.on('contextmenu', function () {
  24909. editor.fire('SelectionChange');
  24910. });
  24911. editor.on('SelectionChange', function () {
  24912. var startElm = editor.selection.getStart(true);
  24913. if (!startElm || !Env.range && editor.selection.isCollapsed()) {
  24914. return;
  24915. }
  24916. if (hasAnyRanges(editor) && !self.isSameElementPath(startElm) && editor.dom.isChildOf(startElm, editor.getBody())) {
  24917. editor.nodeChanged({ selectionChange: true });
  24918. }
  24919. });
  24920. editor.on('mouseup', function (e) {
  24921. if (!e.isDefaultPrevented() && hasAnyRanges(editor)) {
  24922. if (editor.selection.getNode().nodeName === 'IMG') {
  24923. Delay.setEditorTimeout(editor, function () {
  24924. editor.nodeChanged();
  24925. });
  24926. } else {
  24927. editor.nodeChanged();
  24928. }
  24929. }
  24930. });
  24931. }
  24932. NodeChange.prototype.nodeChanged = function (args) {
  24933. var selection = this.editor.selection;
  24934. var node, parents, root;
  24935. if (this.editor.initialized && selection && !shouldDisableNodeChange(this.editor) && !this.editor.mode.isReadOnly()) {
  24936. root = this.editor.getBody();
  24937. node = selection.getStart(true) || root;
  24938. if (node.ownerDocument !== this.editor.getDoc() || !this.editor.dom.isChildOf(node, root)) {
  24939. node = root;
  24940. }
  24941. parents = [];
  24942. this.editor.dom.getParent(node, function (node) {
  24943. if (node === root) {
  24944. return true;
  24945. }
  24946. parents.push(node);
  24947. });
  24948. args = args || {};
  24949. args.element = node;
  24950. args.parents = parents;
  24951. this.editor.fire('NodeChange', args);
  24952. }
  24953. };
  24954. NodeChange.prototype.isSameElementPath = function (startElm) {
  24955. var i;
  24956. var currentPath = this.editor.$(startElm).parentsUntil(this.editor.getBody()).add(startElm);
  24957. if (currentPath.length === this.lastPath.length) {
  24958. for (i = currentPath.length; i >= 0; i--) {
  24959. if (currentPath[i] !== this.lastPath[i]) {
  24960. break;
  24961. }
  24962. }
  24963. if (i === -1) {
  24964. this.lastPath = currentPath;
  24965. return true;
  24966. }
  24967. }
  24968. this.lastPath = currentPath;
  24969. return false;
  24970. };
  24971. return NodeChange;
  24972. }();
  24973. var preventSummaryToggle = function (editor) {
  24974. editor.on('click', function (e) {
  24975. if (editor.dom.getParent(e.target, 'details')) {
  24976. e.preventDefault();
  24977. }
  24978. });
  24979. };
  24980. var filterDetails = function (editor) {
  24981. editor.parser.addNodeFilter('details', function (elms) {
  24982. each$k(elms, function (details) {
  24983. details.attr('data-mce-open', details.attr('open'));
  24984. details.attr('open', 'open');
  24985. });
  24986. });
  24987. editor.serializer.addNodeFilter('details', function (elms) {
  24988. each$k(elms, function (details) {
  24989. var open = details.attr('data-mce-open');
  24990. details.attr('open', isString$1(open) ? open : null);
  24991. details.attr('data-mce-open', null);
  24992. });
  24993. });
  24994. };
  24995. var setup$3 = function (editor) {
  24996. preventSummaryToggle(editor);
  24997. filterDetails(editor);
  24998. };
  24999. var isTextBlockNode = function (node) {
  25000. return isElement$5(node) && isTextBlock$2(SugarElement.fromDom(node));
  25001. };
  25002. var normalizeSelection = function (editor) {
  25003. var rng = editor.selection.getRng();
  25004. var startPos = CaretPosition.fromRangeStart(rng);
  25005. var endPos = CaretPosition.fromRangeEnd(rng);
  25006. if (CaretPosition.isElementPosition(startPos)) {
  25007. var container = startPos.container();
  25008. if (isTextBlockNode(container)) {
  25009. firstPositionIn(container).each(function (pos) {
  25010. return rng.setStart(pos.container(), pos.offset());
  25011. });
  25012. }
  25013. }
  25014. if (CaretPosition.isElementPosition(endPos)) {
  25015. var container = startPos.container();
  25016. if (isTextBlockNode(container)) {
  25017. lastPositionIn(container).each(function (pos) {
  25018. return rng.setEnd(pos.container(), pos.offset());
  25019. });
  25020. }
  25021. }
  25022. editor.selection.setRng(normalize(rng));
  25023. };
  25024. var setup$2 = function (editor) {
  25025. editor.on('click', function (e) {
  25026. if (e.detail >= 3) {
  25027. normalizeSelection(editor);
  25028. }
  25029. });
  25030. };
  25031. var getAbsolutePosition = function (elm) {
  25032. var clientRect = elm.getBoundingClientRect();
  25033. var doc = elm.ownerDocument;
  25034. var docElem = doc.documentElement;
  25035. var win = doc.defaultView;
  25036. return {
  25037. top: clientRect.top + win.pageYOffset - docElem.clientTop,
  25038. left: clientRect.left + win.pageXOffset - docElem.clientLeft
  25039. };
  25040. };
  25041. var getBodyPosition = function (editor) {
  25042. return editor.inline ? getAbsolutePosition(editor.getBody()) : {
  25043. left: 0,
  25044. top: 0
  25045. };
  25046. };
  25047. var getScrollPosition = function (editor) {
  25048. var body = editor.getBody();
  25049. return editor.inline ? {
  25050. left: body.scrollLeft,
  25051. top: body.scrollTop
  25052. } : {
  25053. left: 0,
  25054. top: 0
  25055. };
  25056. };
  25057. var getBodyScroll = function (editor) {
  25058. var body = editor.getBody(), docElm = editor.getDoc().documentElement;
  25059. var inlineScroll = {
  25060. left: body.scrollLeft,
  25061. top: body.scrollTop
  25062. };
  25063. var iframeScroll = {
  25064. left: body.scrollLeft || docElm.scrollLeft,
  25065. top: body.scrollTop || docElm.scrollTop
  25066. };
  25067. return editor.inline ? inlineScroll : iframeScroll;
  25068. };
  25069. var getMousePosition = function (editor, event) {
  25070. if (event.target.ownerDocument !== editor.getDoc()) {
  25071. var iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
  25072. var scrollPosition = getBodyScroll(editor);
  25073. return {
  25074. left: event.pageX - iframePosition.left + scrollPosition.left,
  25075. top: event.pageY - iframePosition.top + scrollPosition.top
  25076. };
  25077. }
  25078. return {
  25079. left: event.pageX,
  25080. top: event.pageY
  25081. };
  25082. };
  25083. var calculatePosition = function (bodyPosition, scrollPosition, mousePosition) {
  25084. return {
  25085. pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
  25086. pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
  25087. };
  25088. };
  25089. var calc = function (editor, event) {
  25090. return calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
  25091. };
  25092. var isContentEditableFalse$1 = isContentEditableFalse$b, isContentEditableTrue$1 = isContentEditableTrue$4;
  25093. var isDraggable = function (rootElm, elm) {
  25094. return isContentEditableFalse$1(elm) && elm !== rootElm;
  25095. };
  25096. var isValidDropTarget = function (editor, targetElement, dragElement) {
  25097. if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
  25098. return false;
  25099. }
  25100. return !isContentEditableFalse$1(targetElement);
  25101. };
  25102. var cloneElement = function (elm) {
  25103. var cloneElm = elm.cloneNode(true);
  25104. cloneElm.removeAttribute('data-mce-selected');
  25105. return cloneElm;
  25106. };
  25107. var createGhost = function (editor, elm, width, height) {
  25108. var dom = editor.dom;
  25109. var clonedElm = elm.cloneNode(true);
  25110. dom.setStyles(clonedElm, {
  25111. width: width,
  25112. height: height
  25113. });
  25114. dom.setAttrib(clonedElm, 'data-mce-selected', null);
  25115. var ghostElm = dom.create('div', {
  25116. 'class': 'mce-drag-container',
  25117. 'data-mce-bogus': 'all',
  25118. 'unselectable': 'on',
  25119. 'contenteditable': 'false'
  25120. });
  25121. dom.setStyles(ghostElm, {
  25122. position: 'absolute',
  25123. opacity: 0.5,
  25124. overflow: 'hidden',
  25125. border: 0,
  25126. padding: 0,
  25127. margin: 0,
  25128. width: width,
  25129. height: height
  25130. });
  25131. dom.setStyles(clonedElm, {
  25132. margin: 0,
  25133. boxSizing: 'border-box'
  25134. });
  25135. ghostElm.appendChild(clonedElm);
  25136. return ghostElm;
  25137. };
  25138. var appendGhostToBody = function (ghostElm, bodyElm) {
  25139. if (ghostElm.parentNode !== bodyElm) {
  25140. bodyElm.appendChild(ghostElm);
  25141. }
  25142. };
  25143. var moveGhost = function (ghostElm, position, width, height, maxX, maxY) {
  25144. var overflowX = 0, overflowY = 0;
  25145. ghostElm.style.left = position.pageX + 'px';
  25146. ghostElm.style.top = position.pageY + 'px';
  25147. if (position.pageX + width > maxX) {
  25148. overflowX = position.pageX + width - maxX;
  25149. }
  25150. if (position.pageY + height > maxY) {
  25151. overflowY = position.pageY + height - maxY;
  25152. }
  25153. ghostElm.style.width = width - overflowX + 'px';
  25154. ghostElm.style.height = height - overflowY + 'px';
  25155. };
  25156. var removeElement = function (elm) {
  25157. if (elm && elm.parentNode) {
  25158. elm.parentNode.removeChild(elm);
  25159. }
  25160. };
  25161. var isLeftMouseButtonPressed = function (e) {
  25162. return e.button === 0;
  25163. };
  25164. var applyRelPos = function (state, position) {
  25165. return {
  25166. pageX: position.pageX - state.relX,
  25167. pageY: position.pageY + 5
  25168. };
  25169. };
  25170. var start = function (state, editor) {
  25171. return function (e) {
  25172. if (isLeftMouseButtonPressed(e)) {
  25173. var ceElm = find$3(editor.dom.getParents(e.target), or(isContentEditableFalse$1, isContentEditableTrue$1)).getOr(null);
  25174. if (isDraggable(editor.getBody(), ceElm)) {
  25175. var elmPos = editor.dom.getPos(ceElm);
  25176. var bodyElm = editor.getBody();
  25177. var docElm = editor.getDoc().documentElement;
  25178. state.set({
  25179. element: ceElm,
  25180. dragging: false,
  25181. screenX: e.screenX,
  25182. screenY: e.screenY,
  25183. maxX: (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2,
  25184. maxY: (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2,
  25185. relX: e.pageX - elmPos.x,
  25186. relY: e.pageY - elmPos.y,
  25187. width: ceElm.offsetWidth,
  25188. height: ceElm.offsetHeight,
  25189. ghost: createGhost(editor, ceElm, ceElm.offsetWidth, ceElm.offsetHeight)
  25190. });
  25191. }
  25192. }
  25193. };
  25194. };
  25195. var move = function (state, editor) {
  25196. var throttledPlaceCaretAt = Delay.throttle(function (clientX, clientY) {
  25197. editor._selectionOverrides.hideFakeCaret();
  25198. editor.selection.placeCaretAt(clientX, clientY);
  25199. }, 0);
  25200. editor.on('remove', throttledPlaceCaretAt.stop);
  25201. return function (e) {
  25202. return state.on(function (state) {
  25203. var movement = Math.max(Math.abs(e.screenX - state.screenX), Math.abs(e.screenY - state.screenY));
  25204. if (!state.dragging && movement > 10) {
  25205. var args = editor.fire('dragstart', { target: state.element });
  25206. if (args.isDefaultPrevented()) {
  25207. return;
  25208. }
  25209. state.dragging = true;
  25210. editor.focus();
  25211. }
  25212. if (state.dragging) {
  25213. var targetPos = applyRelPos(state, calc(editor, e));
  25214. appendGhostToBody(state.ghost, editor.getBody());
  25215. moveGhost(state.ghost, targetPos, state.width, state.height, state.maxX, state.maxY);
  25216. throttledPlaceCaretAt(e.clientX, e.clientY);
  25217. }
  25218. });
  25219. };
  25220. };
  25221. var getRawTarget = function (selection) {
  25222. var rng = selection.getSel().getRangeAt(0);
  25223. var startContainer = rng.startContainer;
  25224. return startContainer.nodeType === 3 ? startContainer.parentNode : startContainer;
  25225. };
  25226. var drop = function (state, editor) {
  25227. return function (e) {
  25228. state.on(function (state) {
  25229. if (state.dragging) {
  25230. if (isValidDropTarget(editor, getRawTarget(editor.selection), state.element)) {
  25231. var targetClone_1 = cloneElement(state.element);
  25232. var args = editor.fire('drop', {
  25233. clientX: e.clientX,
  25234. clientY: e.clientY
  25235. });
  25236. if (!args.isDefaultPrevented()) {
  25237. editor.undoManager.transact(function () {
  25238. removeElement(state.element);
  25239. editor.insertContent(editor.dom.getOuterHTML(targetClone_1));
  25240. editor._selectionOverrides.hideFakeCaret();
  25241. });
  25242. }
  25243. }
  25244. editor.fire('dragend');
  25245. }
  25246. });
  25247. removeDragState(state);
  25248. };
  25249. };
  25250. var stop = function (state, editor) {
  25251. return function () {
  25252. state.on(function (state) {
  25253. if (state.dragging) {
  25254. editor.fire('dragend');
  25255. }
  25256. });
  25257. removeDragState(state);
  25258. };
  25259. };
  25260. var removeDragState = function (state) {
  25261. state.on(function (state) {
  25262. removeElement(state.ghost);
  25263. });
  25264. state.clear();
  25265. };
  25266. var bindFakeDragEvents = function (editor) {
  25267. var state = value();
  25268. var pageDom = DOMUtils.DOM;
  25269. var rootDocument = document;
  25270. var dragStartHandler = start(state, editor);
  25271. var dragHandler = move(state, editor);
  25272. var dropHandler = drop(state, editor);
  25273. var dragEndHandler = stop(state, editor);
  25274. editor.on('mousedown', dragStartHandler);
  25275. editor.on('mousemove', dragHandler);
  25276. editor.on('mouseup', dropHandler);
  25277. pageDom.bind(rootDocument, 'mousemove', dragHandler);
  25278. pageDom.bind(rootDocument, 'mouseup', dragEndHandler);
  25279. editor.on('remove', function () {
  25280. pageDom.unbind(rootDocument, 'mousemove', dragHandler);
  25281. pageDom.unbind(rootDocument, 'mouseup', dragEndHandler);
  25282. });
  25283. editor.on('keydown', function (e) {
  25284. if (e.keyCode === VK.ESC) {
  25285. dragEndHandler();
  25286. }
  25287. });
  25288. };
  25289. var blockIeDrop = function (editor) {
  25290. editor.on('drop', function (e) {
  25291. var realTarget = typeof e.clientX !== 'undefined' ? editor.getDoc().elementFromPoint(e.clientX, e.clientY) : null;
  25292. if (isContentEditableFalse$1(realTarget) || editor.dom.getContentEditableParent(realTarget) === 'false') {
  25293. e.preventDefault();
  25294. }
  25295. });
  25296. };
  25297. var blockUnsupportedFileDrop = function (editor) {
  25298. var preventFileDrop = function (e) {
  25299. if (!e.isDefaultPrevented()) {
  25300. var dataTransfer = e.dataTransfer;
  25301. if (dataTransfer && (contains$3(dataTransfer.types, 'Files') || dataTransfer.files.length > 0)) {
  25302. e.preventDefault();
  25303. if (e.type === 'drop') {
  25304. displayError(editor, 'Dropped file type is not supported');
  25305. }
  25306. }
  25307. }
  25308. };
  25309. var preventFileDropIfUIElement = function (e) {
  25310. if (isUIElement(editor, e.target)) {
  25311. preventFileDrop(e);
  25312. }
  25313. };
  25314. var setup = function () {
  25315. var pageDom = DOMUtils.DOM;
  25316. var dom = editor.dom;
  25317. var doc = document;
  25318. var editorRoot = editor.inline ? editor.getBody() : editor.getDoc();
  25319. var eventNames = [
  25320. 'drop',
  25321. 'dragover'
  25322. ];
  25323. each$k(eventNames, function (name) {
  25324. pageDom.bind(doc, name, preventFileDropIfUIElement);
  25325. dom.bind(editorRoot, name, preventFileDrop);
  25326. });
  25327. editor.on('remove', function () {
  25328. each$k(eventNames, function (name) {
  25329. pageDom.unbind(doc, name, preventFileDropIfUIElement);
  25330. dom.unbind(editorRoot, name, preventFileDrop);
  25331. });
  25332. });
  25333. };
  25334. editor.on('init', function () {
  25335. Delay.setEditorTimeout(editor, setup, 0);
  25336. });
  25337. };
  25338. var init$2 = function (editor) {
  25339. bindFakeDragEvents(editor);
  25340. blockIeDrop(editor);
  25341. if (shouldBlockUnsupportedDrop(editor)) {
  25342. blockUnsupportedFileDrop(editor);
  25343. }
  25344. };
  25345. var setup$1 = function (editor) {
  25346. var renderFocusCaret = first(function () {
  25347. if (!editor.removed && editor.getBody().contains(document.activeElement)) {
  25348. var rng = editor.selection.getRng();
  25349. if (rng.collapsed) {
  25350. var caretRange = renderRangeCaret(editor, rng, false);
  25351. editor.selection.setRng(caretRange);
  25352. }
  25353. }
  25354. }, 0);
  25355. editor.on('focus', function () {
  25356. renderFocusCaret.throttle();
  25357. });
  25358. editor.on('blur', function () {
  25359. renderFocusCaret.cancel();
  25360. });
  25361. };
  25362. var setup = function (editor) {
  25363. editor.on('init', function () {
  25364. editor.on('focusin', function (e) {
  25365. var target = e.target;
  25366. if (isMedia$2(target)) {
  25367. var ceRoot = getContentEditableRoot$1(editor.getBody(), target);
  25368. var node = isContentEditableFalse$b(ceRoot) ? ceRoot : target;
  25369. if (editor.selection.getNode() !== node) {
  25370. selectNode(editor, node).each(function (rng) {
  25371. return editor.selection.setRng(rng);
  25372. });
  25373. }
  25374. }
  25375. });
  25376. });
  25377. };
  25378. var isContentEditableTrue = isContentEditableTrue$4;
  25379. var isContentEditableFalse = isContentEditableFalse$b;
  25380. var getContentEditableRoot = function (editor, node) {
  25381. return getContentEditableRoot$1(editor.getBody(), node);
  25382. };
  25383. var SelectionOverrides = function (editor) {
  25384. var selection = editor.selection, dom = editor.dom;
  25385. var isBlock = dom.isBlock;
  25386. var rootNode = editor.getBody();
  25387. var fakeCaret = FakeCaret(editor, rootNode, isBlock, function () {
  25388. return hasFocus(editor);
  25389. });
  25390. var realSelectionId = 'sel-' + dom.uniqueId();
  25391. var elementSelectionAttr = 'data-mce-selected';
  25392. var selectedElement;
  25393. var isFakeSelectionElement = function (node) {
  25394. return dom.hasClass(node, 'mce-offscreen-selection');
  25395. };
  25396. var isFakeSelectionTargetElement = function (node) {
  25397. return node !== rootNode && (isContentEditableFalse(node) || isMedia$2(node)) && dom.isChildOf(node, rootNode);
  25398. };
  25399. var isNearFakeSelectionElement = function (pos) {
  25400. return isBeforeContentEditableFalse(pos) || isAfterContentEditableFalse(pos) || isBeforeMedia(pos) || isAfterMedia(pos);
  25401. };
  25402. var getRealSelectionElement = function () {
  25403. var container = dom.get(realSelectionId);
  25404. return container ? container.getElementsByTagName('*')[0] : container;
  25405. };
  25406. var setRange = function (range) {
  25407. if (range) {
  25408. selection.setRng(range);
  25409. }
  25410. };
  25411. var getRange = selection.getRng;
  25412. var showCaret = function (direction, node, before, scrollIntoView) {
  25413. if (scrollIntoView === void 0) {
  25414. scrollIntoView = true;
  25415. }
  25416. var e = editor.fire('ShowCaret', {
  25417. target: node,
  25418. direction: direction,
  25419. before: before
  25420. });
  25421. if (e.isDefaultPrevented()) {
  25422. return null;
  25423. }
  25424. if (scrollIntoView) {
  25425. selection.scrollIntoView(node, direction === -1);
  25426. }
  25427. return fakeCaret.show(before, node);
  25428. };
  25429. var showBlockCaretContainer = function (blockCaretContainer) {
  25430. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  25431. showCaretContainerBlock(blockCaretContainer);
  25432. setRange(getRange());
  25433. selection.scrollIntoView(blockCaretContainer);
  25434. }
  25435. };
  25436. var registerEvents = function () {
  25437. editor.on('mouseup', function (e) {
  25438. var range = getRange();
  25439. if (range.collapsed && isXYInContentArea(editor, e.clientX, e.clientY)) {
  25440. renderCaretAtRange(editor, range, false).each(setRange);
  25441. }
  25442. });
  25443. editor.on('click', function (e) {
  25444. var contentEditableRoot = getContentEditableRoot(editor, e.target);
  25445. if (contentEditableRoot) {
  25446. if (isContentEditableFalse(contentEditableRoot)) {
  25447. e.preventDefault();
  25448. editor.focus();
  25449. }
  25450. if (isContentEditableTrue(contentEditableRoot)) {
  25451. if (dom.isChildOf(contentEditableRoot, selection.getNode())) {
  25452. removeElementSelection();
  25453. }
  25454. }
  25455. }
  25456. });
  25457. editor.on('blur NewBlock', removeElementSelection);
  25458. editor.on('ResizeWindow FullscreenStateChanged', fakeCaret.reposition);
  25459. var hasNormalCaretPosition = function (elm) {
  25460. var start = elm.firstChild;
  25461. if (isNullable(start)) {
  25462. return false;
  25463. }
  25464. var startPos = CaretPosition.before(start);
  25465. if (isBr$5(startPos.getNode()) && elm.childNodes.length === 1) {
  25466. return !isNearFakeSelectionElement(startPos);
  25467. } else {
  25468. var caretWalker = CaretWalker(elm);
  25469. var newPos = caretWalker.next(startPos);
  25470. return newPos && !isNearFakeSelectionElement(newPos);
  25471. }
  25472. };
  25473. var isInSameBlock = function (node1, node2) {
  25474. var block1 = dom.getParent(node1, isBlock);
  25475. var block2 = dom.getParent(node2, isBlock);
  25476. return block1 === block2;
  25477. };
  25478. var hasBetterMouseTarget = function (targetNode, caretNode) {
  25479. var targetBlock = dom.getParent(targetNode, isBlock);
  25480. var caretBlock = dom.getParent(caretNode, isBlock);
  25481. if (isNullable(targetBlock)) {
  25482. return false;
  25483. }
  25484. if (targetNode !== caretBlock && dom.isChildOf(targetBlock, caretBlock) && isContentEditableFalse(getContentEditableRoot(editor, targetBlock)) === false) {
  25485. return true;
  25486. }
  25487. return !dom.isChildOf(caretBlock, targetBlock) && !isInSameBlock(targetBlock, caretBlock) && hasNormalCaretPosition(targetBlock);
  25488. };
  25489. editor.on('tap', function (e) {
  25490. var targetElm = e.target;
  25491. var contentEditableRoot = getContentEditableRoot(editor, targetElm);
  25492. if (isContentEditableFalse(contentEditableRoot)) {
  25493. e.preventDefault();
  25494. selectNode(editor, contentEditableRoot).each(setElementSelection);
  25495. } else if (isFakeSelectionTargetElement(targetElm)) {
  25496. selectNode(editor, targetElm).each(setElementSelection);
  25497. }
  25498. }, true);
  25499. editor.on('mousedown', function (e) {
  25500. var targetElm = e.target;
  25501. if (targetElm !== rootNode && targetElm.nodeName !== 'HTML' && !dom.isChildOf(targetElm, rootNode)) {
  25502. return;
  25503. }
  25504. if (isXYInContentArea(editor, e.clientX, e.clientY) === false) {
  25505. return;
  25506. }
  25507. var contentEditableRoot = getContentEditableRoot(editor, targetElm);
  25508. if (contentEditableRoot) {
  25509. if (isContentEditableFalse(contentEditableRoot)) {
  25510. e.preventDefault();
  25511. selectNode(editor, contentEditableRoot).each(setElementSelection);
  25512. } else {
  25513. removeElementSelection();
  25514. if (!(isContentEditableTrue(contentEditableRoot) && e.shiftKey) && !isXYWithinRange(e.clientX, e.clientY, selection.getRng())) {
  25515. hideFakeCaret();
  25516. selection.placeCaretAt(e.clientX, e.clientY);
  25517. }
  25518. }
  25519. } else if (isFakeSelectionTargetElement(targetElm)) {
  25520. selectNode(editor, targetElm).each(setElementSelection);
  25521. } else if (isFakeCaretTarget(targetElm) === false) {
  25522. removeElementSelection();
  25523. hideFakeCaret();
  25524. var fakeCaretInfo = closestFakeCaret(rootNode, e.clientX, e.clientY);
  25525. if (fakeCaretInfo) {
  25526. if (!hasBetterMouseTarget(targetElm, fakeCaretInfo.node)) {
  25527. e.preventDefault();
  25528. var range = showCaret(1, fakeCaretInfo.node, fakeCaretInfo.before, false);
  25529. setRange(range);
  25530. editor.getBody().focus();
  25531. }
  25532. }
  25533. }
  25534. });
  25535. editor.on('keypress', function (e) {
  25536. if (VK.modifierPressed(e)) {
  25537. return;
  25538. }
  25539. if (isContentEditableFalse(selection.getNode())) {
  25540. e.preventDefault();
  25541. }
  25542. });
  25543. editor.on('GetSelectionRange', function (e) {
  25544. var rng = e.range;
  25545. if (selectedElement) {
  25546. if (!selectedElement.parentNode) {
  25547. selectedElement = null;
  25548. return;
  25549. }
  25550. rng = rng.cloneRange();
  25551. rng.selectNode(selectedElement);
  25552. e.range = rng;
  25553. }
  25554. });
  25555. editor.on('SetSelectionRange', function (e) {
  25556. e.range = normalizeShortEndedElementSelection(e.range);
  25557. var rng = setElementSelection(e.range, e.forward);
  25558. if (rng) {
  25559. e.range = rng;
  25560. }
  25561. });
  25562. var isPasteBin = function (node) {
  25563. return node.id === 'mcepastebin';
  25564. };
  25565. editor.on('AfterSetSelectionRange', function (e) {
  25566. var rng = e.range;
  25567. var parentNode = rng.startContainer.parentNode;
  25568. if (!isRangeInCaretContainer(rng) && !isPasteBin(parentNode)) {
  25569. hideFakeCaret();
  25570. }
  25571. if (!isFakeSelectionElement(parentNode)) {
  25572. removeElementSelection();
  25573. }
  25574. });
  25575. editor.on('copy', function (e) {
  25576. var clipboardData = e.clipboardData;
  25577. if (!e.isDefaultPrevented() && e.clipboardData && !Env.ie) {
  25578. var realSelectionElement = getRealSelectionElement();
  25579. if (realSelectionElement) {
  25580. e.preventDefault();
  25581. clipboardData.clearData();
  25582. clipboardData.setData('text/html', realSelectionElement.outerHTML);
  25583. clipboardData.setData('text/plain', realSelectionElement.outerText || realSelectionElement.innerText);
  25584. }
  25585. }
  25586. });
  25587. init$2(editor);
  25588. setup$1(editor);
  25589. setup(editor);
  25590. };
  25591. var isWithinCaretContainer = function (node) {
  25592. return isCaretContainer$2(node) || startsWithCaretContainer$1(node) || endsWithCaretContainer$1(node);
  25593. };
  25594. var isRangeInCaretContainer = function (rng) {
  25595. return isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
  25596. };
  25597. var normalizeShortEndedElementSelection = function (rng) {
  25598. var shortEndedElements = editor.schema.getShortEndedElements();
  25599. var newRng = dom.createRng();
  25600. var startContainer = rng.startContainer;
  25601. var startOffset = rng.startOffset;
  25602. var endContainer = rng.endContainer;
  25603. var endOffset = rng.endOffset;
  25604. if (has$2(shortEndedElements, startContainer.nodeName.toLowerCase())) {
  25605. if (startOffset === 0) {
  25606. newRng.setStartBefore(startContainer);
  25607. } else {
  25608. newRng.setStartAfter(startContainer);
  25609. }
  25610. } else {
  25611. newRng.setStart(startContainer, startOffset);
  25612. }
  25613. if (has$2(shortEndedElements, endContainer.nodeName.toLowerCase())) {
  25614. if (endOffset === 0) {
  25615. newRng.setEndBefore(endContainer);
  25616. } else {
  25617. newRng.setEndAfter(endContainer);
  25618. }
  25619. } else {
  25620. newRng.setEnd(endContainer, endOffset);
  25621. }
  25622. return newRng;
  25623. };
  25624. var setupOffscreenSelection = function (node, targetClone, origTargetClone) {
  25625. var $ = editor.$;
  25626. var $realSelectionContainer = descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).fold(function () {
  25627. return $([]);
  25628. }, function (elm) {
  25629. return $([elm.dom]);
  25630. });
  25631. if ($realSelectionContainer.length === 0) {
  25632. $realSelectionContainer = $('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>').attr('id', realSelectionId);
  25633. $realSelectionContainer.appendTo(editor.getBody());
  25634. }
  25635. var newRange = dom.createRng();
  25636. if (targetClone === origTargetClone && Env.ie) {
  25637. $realSelectionContainer.empty().append('<p style="font-size: 0" data-mce-bogus="all">\xA0</p>').append(targetClone);
  25638. newRange.setStartAfter($realSelectionContainer[0].firstChild.firstChild);
  25639. newRange.setEndAfter(targetClone);
  25640. } else {
  25641. $realSelectionContainer.empty().append(nbsp).append(targetClone).append(nbsp);
  25642. newRange.setStart($realSelectionContainer[0].firstChild, 1);
  25643. newRange.setEnd($realSelectionContainer[0].lastChild, 0);
  25644. }
  25645. $realSelectionContainer.css({ top: dom.getPos(node, editor.getBody()).y });
  25646. $realSelectionContainer[0].focus();
  25647. var sel = selection.getSel();
  25648. sel.removeAllRanges();
  25649. sel.addRange(newRange);
  25650. return newRange;
  25651. };
  25652. var selectElement = function (elm) {
  25653. var targetClone = elm.cloneNode(true);
  25654. var e = editor.fire('ObjectSelected', {
  25655. target: elm,
  25656. targetClone: targetClone
  25657. });
  25658. if (e.isDefaultPrevented()) {
  25659. return null;
  25660. }
  25661. var range = setupOffscreenSelection(elm, e.targetClone, targetClone);
  25662. var nodeElm = SugarElement.fromDom(elm);
  25663. each$k(descendants(SugarElement.fromDom(editor.getBody()), '*[data-mce-selected]'), function (elm) {
  25664. if (!eq(nodeElm, elm)) {
  25665. remove$6(elm, elementSelectionAttr);
  25666. }
  25667. });
  25668. if (!dom.getAttrib(elm, elementSelectionAttr)) {
  25669. elm.setAttribute(elementSelectionAttr, '1');
  25670. }
  25671. selectedElement = elm;
  25672. hideFakeCaret();
  25673. return range;
  25674. };
  25675. var setElementSelection = function (range, forward) {
  25676. if (!range) {
  25677. return null;
  25678. }
  25679. if (range.collapsed) {
  25680. if (!isRangeInCaretContainer(range)) {
  25681. var dir = forward ? 1 : -1;
  25682. var caretPosition = getNormalizedRangeEndPoint(dir, rootNode, range);
  25683. var beforeNode = caretPosition.getNode(!forward);
  25684. if (isFakeCaretTarget(beforeNode)) {
  25685. return showCaret(dir, beforeNode, forward ? !caretPosition.isAtEnd() : false, false);
  25686. }
  25687. var afterNode = caretPosition.getNode(forward);
  25688. if (isFakeCaretTarget(afterNode)) {
  25689. return showCaret(dir, afterNode, forward ? false : !caretPosition.isAtEnd(), false);
  25690. }
  25691. }
  25692. return null;
  25693. }
  25694. var startContainer = range.startContainer;
  25695. var startOffset = range.startOffset;
  25696. var endOffset = range.endOffset;
  25697. if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse(startContainer.parentNode)) {
  25698. startContainer = startContainer.parentNode;
  25699. startOffset = dom.nodeIndex(startContainer);
  25700. startContainer = startContainer.parentNode;
  25701. }
  25702. if (startContainer.nodeType !== 1) {
  25703. return null;
  25704. }
  25705. if (endOffset === startOffset + 1 && startContainer === range.endContainer) {
  25706. var node = startContainer.childNodes[startOffset];
  25707. if (isFakeSelectionTargetElement(node)) {
  25708. return selectElement(node);
  25709. }
  25710. }
  25711. return null;
  25712. };
  25713. var removeElementSelection = function () {
  25714. if (selectedElement) {
  25715. selectedElement.removeAttribute(elementSelectionAttr);
  25716. }
  25717. descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).each(remove$7);
  25718. selectedElement = null;
  25719. };
  25720. var destroy = function () {
  25721. fakeCaret.destroy();
  25722. selectedElement = null;
  25723. };
  25724. var hideFakeCaret = function () {
  25725. fakeCaret.hide();
  25726. };
  25727. if (Env.ceFalse && !isRtc(editor)) {
  25728. registerEvents();
  25729. }
  25730. return {
  25731. showCaret: showCaret,
  25732. showBlockCaretContainer: showBlockCaretContainer,
  25733. hideFakeCaret: hideFakeCaret,
  25734. destroy: destroy
  25735. };
  25736. };
  25737. var Quirks = function (editor) {
  25738. var each = Tools.each;
  25739. var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, parser = editor.parser;
  25740. var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit;
  25741. var mceInternalUrlPrefix = 'data:text/mce-internal,';
  25742. var mceInternalDataType = isIE ? 'Text' : 'URL';
  25743. var setEditorCommandState = function (cmd, state) {
  25744. try {
  25745. editor.getDoc().execCommand(cmd, false, state);
  25746. } catch (ex) {
  25747. }
  25748. };
  25749. var isDefaultPrevented = function (e) {
  25750. return e.isDefaultPrevented();
  25751. };
  25752. var setMceInternalContent = function (e) {
  25753. var selectionHtml, internalContent;
  25754. if (e.dataTransfer) {
  25755. if (editor.selection.isCollapsed() && e.target.tagName === 'IMG') {
  25756. selection.select(e.target);
  25757. }
  25758. selectionHtml = editor.selection.getContent();
  25759. if (selectionHtml.length > 0) {
  25760. internalContent = mceInternalUrlPrefix + escape(editor.id) + ',' + escape(selectionHtml);
  25761. e.dataTransfer.setData(mceInternalDataType, internalContent);
  25762. }
  25763. }
  25764. };
  25765. var getMceInternalContent = function (e) {
  25766. var internalContent;
  25767. if (e.dataTransfer) {
  25768. internalContent = e.dataTransfer.getData(mceInternalDataType);
  25769. if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) {
  25770. internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(',');
  25771. return {
  25772. id: unescape(internalContent[0]),
  25773. html: unescape(internalContent[1])
  25774. };
  25775. }
  25776. }
  25777. return null;
  25778. };
  25779. var insertClipboardContents = function (content, internal) {
  25780. if (editor.queryCommandSupported('mceInsertClipboardContent')) {
  25781. editor.execCommand('mceInsertClipboardContent', false, {
  25782. content: content,
  25783. internal: internal
  25784. });
  25785. } else {
  25786. editor.execCommand('mceInsertContent', false, content);
  25787. }
  25788. };
  25789. var emptyEditorWhenDeleting = function () {
  25790. var serializeRng = function (rng) {
  25791. var body = dom.create('body');
  25792. var contents = rng.cloneContents();
  25793. body.appendChild(contents);
  25794. return selection.serializer.serialize(body, { format: 'html' });
  25795. };
  25796. var allContentsSelected = function (rng) {
  25797. var selection = serializeRng(rng);
  25798. var allRng = dom.createRng();
  25799. allRng.selectNode(editor.getBody());
  25800. var allSelection = serializeRng(allRng);
  25801. return selection === allSelection;
  25802. };
  25803. editor.on('keydown', function (e) {
  25804. var keyCode = e.keyCode;
  25805. var isCollapsed, body;
  25806. if (!isDefaultPrevented(e) && (keyCode === DELETE || keyCode === BACKSPACE)) {
  25807. isCollapsed = editor.selection.isCollapsed();
  25808. body = editor.getBody();
  25809. if (isCollapsed && !dom.isEmpty(body)) {
  25810. return;
  25811. }
  25812. if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
  25813. return;
  25814. }
  25815. e.preventDefault();
  25816. editor.setContent('');
  25817. if (body.firstChild && dom.isBlock(body.firstChild)) {
  25818. editor.selection.setCursorLocation(body.firstChild, 0);
  25819. } else {
  25820. editor.selection.setCursorLocation(body, 0);
  25821. }
  25822. editor.nodeChanged();
  25823. }
  25824. });
  25825. };
  25826. var selectAll = function () {
  25827. editor.shortcuts.add('meta+a', null, 'SelectAll');
  25828. };
  25829. var documentElementEditingFocus = function () {
  25830. if (!editor.inline) {
  25831. dom.bind(editor.getDoc(), 'mousedown mouseup', function (e) {
  25832. var rng;
  25833. if (e.target === editor.getDoc().documentElement) {
  25834. rng = selection.getRng();
  25835. editor.getBody().focus();
  25836. if (e.type === 'mousedown') {
  25837. if (isCaretContainer$2(rng.startContainer)) {
  25838. return;
  25839. }
  25840. selection.placeCaretAt(e.clientX, e.clientY);
  25841. } else {
  25842. selection.setRng(rng);
  25843. }
  25844. }
  25845. });
  25846. }
  25847. };
  25848. var removeHrOnBackspace = function () {
  25849. editor.on('keydown', function (e) {
  25850. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25851. if (!editor.getBody().getElementsByTagName('hr').length) {
  25852. return;
  25853. }
  25854. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25855. var node = selection.getNode();
  25856. var previousSibling = node.previousSibling;
  25857. if (node.nodeName === 'HR') {
  25858. dom.remove(node);
  25859. e.preventDefault();
  25860. return;
  25861. }
  25862. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'hr') {
  25863. dom.remove(previousSibling);
  25864. e.preventDefault();
  25865. }
  25866. }
  25867. }
  25868. });
  25869. };
  25870. var focusBody = function () {
  25871. if (!Range.prototype.getClientRects) {
  25872. editor.on('mousedown', function (e) {
  25873. if (!isDefaultPrevented(e) && e.target.nodeName === 'HTML') {
  25874. var body_1 = editor.getBody();
  25875. body_1.blur();
  25876. Delay.setEditorTimeout(editor, function () {
  25877. body_1.focus();
  25878. });
  25879. }
  25880. });
  25881. }
  25882. };
  25883. var selectControlElements = function () {
  25884. editor.on('click', function (e) {
  25885. var target = e.target;
  25886. if (/^(IMG|HR)$/.test(target.nodeName) && dom.getContentEditableParent(target) !== 'false') {
  25887. e.preventDefault();
  25888. editor.selection.select(target);
  25889. editor.nodeChanged();
  25890. }
  25891. if (target.nodeName === 'A' && dom.hasClass(target, 'mce-item-anchor')) {
  25892. e.preventDefault();
  25893. selection.select(target);
  25894. }
  25895. });
  25896. };
  25897. var removeStylesWhenDeletingAcrossBlockElements = function () {
  25898. var getAttributeApplyFunction = function () {
  25899. var template = dom.getAttribs(selection.getStart().cloneNode(false));
  25900. return function () {
  25901. var target = selection.getStart();
  25902. if (target !== editor.getBody()) {
  25903. dom.setAttrib(target, 'style', null);
  25904. each(template, function (attr) {
  25905. target.setAttributeNode(attr.cloneNode(true));
  25906. });
  25907. }
  25908. };
  25909. };
  25910. var isSelectionAcrossElements = function () {
  25911. return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock);
  25912. };
  25913. editor.on('keypress', function (e) {
  25914. var applyAttributes;
  25915. if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) {
  25916. applyAttributes = getAttributeApplyFunction();
  25917. editor.getDoc().execCommand('delete', false, null);
  25918. applyAttributes();
  25919. e.preventDefault();
  25920. return false;
  25921. }
  25922. });
  25923. dom.bind(editor.getDoc(), 'cut', function (e) {
  25924. var applyAttributes;
  25925. if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
  25926. applyAttributes = getAttributeApplyFunction();
  25927. Delay.setEditorTimeout(editor, function () {
  25928. applyAttributes();
  25929. });
  25930. }
  25931. });
  25932. };
  25933. var disableBackspaceIntoATable = function () {
  25934. editor.on('keydown', function (e) {
  25935. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25936. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25937. var previousSibling = selection.getNode().previousSibling;
  25938. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'table') {
  25939. e.preventDefault();
  25940. return false;
  25941. }
  25942. }
  25943. }
  25944. });
  25945. };
  25946. var removeBlockQuoteOnBackSpace = function () {
  25947. editor.on('keydown', function (e) {
  25948. var rng, parent;
  25949. if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) {
  25950. return;
  25951. }
  25952. rng = selection.getRng();
  25953. var container = rng.startContainer;
  25954. var offset = rng.startOffset;
  25955. var root = dom.getRoot();
  25956. parent = container;
  25957. if (!rng.collapsed || offset !== 0) {
  25958. return;
  25959. }
  25960. while (parent && parent.parentNode && parent.parentNode.firstChild === parent && parent.parentNode !== root) {
  25961. parent = parent.parentNode;
  25962. }
  25963. if (parent.tagName === 'BLOCKQUOTE') {
  25964. editor.formatter.toggle('blockquote', null, parent);
  25965. rng = dom.createRng();
  25966. rng.setStart(container, 0);
  25967. rng.setEnd(container, 0);
  25968. selection.setRng(rng);
  25969. }
  25970. });
  25971. };
  25972. var setGeckoEditingOptions = function () {
  25973. var setOpts = function () {
  25974. setEditorCommandState('StyleWithCSS', false);
  25975. setEditorCommandState('enableInlineTableEditing', false);
  25976. if (!getObjectResizing(editor)) {
  25977. setEditorCommandState('enableObjectResizing', false);
  25978. }
  25979. };
  25980. if (!isReadOnly$1(editor)) {
  25981. editor.on('BeforeExecCommand mousedown', setOpts);
  25982. }
  25983. };
  25984. var addBrAfterLastLinks = function () {
  25985. var fixLinks = function () {
  25986. each(dom.select('a'), function (node) {
  25987. var parentNode = node.parentNode;
  25988. var root = dom.getRoot();
  25989. if (parentNode.lastChild === node) {
  25990. while (parentNode && !dom.isBlock(parentNode)) {
  25991. if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
  25992. return;
  25993. }
  25994. parentNode = parentNode.parentNode;
  25995. }
  25996. dom.add(parentNode, 'br', { 'data-mce-bogus': 1 });
  25997. }
  25998. });
  25999. };
  26000. editor.on('SetContent ExecCommand', function (e) {
  26001. if (e.type === 'setcontent' || e.command === 'mceInsertLink') {
  26002. fixLinks();
  26003. }
  26004. });
  26005. };
  26006. var setDefaultBlockType = function () {
  26007. if (getForcedRootBlock(editor)) {
  26008. editor.on('init', function () {
  26009. setEditorCommandState('DefaultParagraphSeparator', getForcedRootBlock(editor));
  26010. });
  26011. }
  26012. };
  26013. var normalizeSelection = function () {
  26014. editor.on('keyup focusin mouseup', function (e) {
  26015. if (!VK.modifierPressed(e)) {
  26016. selection.normalize();
  26017. }
  26018. }, true);
  26019. };
  26020. var showBrokenImageIcon = function () {
  26021. editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}');
  26022. };
  26023. var restoreFocusOnKeyDown = function () {
  26024. if (!editor.inline) {
  26025. editor.on('keydown', function () {
  26026. if (document.activeElement === document.body) {
  26027. editor.getWin().focus();
  26028. }
  26029. });
  26030. }
  26031. };
  26032. var bodyHeight = function () {
  26033. if (!editor.inline) {
  26034. editor.contentStyles.push('body {min-height: 150px}');
  26035. editor.on('click', function (e) {
  26036. var rng;
  26037. if (e.target.nodeName === 'HTML') {
  26038. if (Env.ie > 11) {
  26039. editor.getBody().focus();
  26040. return;
  26041. }
  26042. rng = editor.selection.getRng();
  26043. editor.getBody().focus();
  26044. editor.selection.setRng(rng);
  26045. editor.selection.normalize();
  26046. editor.nodeChanged();
  26047. }
  26048. });
  26049. }
  26050. };
  26051. var blockCmdArrowNavigation = function () {
  26052. if (Env.mac) {
  26053. editor.on('keydown', function (e) {
  26054. if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) {
  26055. e.preventDefault();
  26056. var selection_1 = editor.selection.getSel();
  26057. selection_1.modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary');
  26058. }
  26059. });
  26060. }
  26061. };
  26062. var disableAutoUrlDetect = function () {
  26063. setEditorCommandState('AutoUrlDetect', false);
  26064. };
  26065. var tapLinksAndImages = function () {
  26066. editor.on('click', function (e) {
  26067. var elm = e.target;
  26068. do {
  26069. if (elm.tagName === 'A') {
  26070. e.preventDefault();
  26071. return;
  26072. }
  26073. } while (elm = elm.parentNode);
  26074. });
  26075. editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
  26076. };
  26077. var blockFormSubmitInsideEditor = function () {
  26078. editor.on('init', function () {
  26079. editor.dom.bind(editor.getBody(), 'submit', function (e) {
  26080. e.preventDefault();
  26081. });
  26082. });
  26083. };
  26084. var removeAppleInterchangeBrs = function () {
  26085. parser.addNodeFilter('br', function (nodes) {
  26086. var i = nodes.length;
  26087. while (i--) {
  26088. if (nodes[i].attr('class') === 'Apple-interchange-newline') {
  26089. nodes[i].remove();
  26090. }
  26091. }
  26092. });
  26093. };
  26094. var ieInternalDragAndDrop = function () {
  26095. editor.on('dragstart', function (e) {
  26096. setMceInternalContent(e);
  26097. });
  26098. editor.on('drop', function (e) {
  26099. if (!isDefaultPrevented(e)) {
  26100. var internalContent = getMceInternalContent(e);
  26101. if (internalContent && internalContent.id !== editor.id) {
  26102. e.preventDefault();
  26103. var rng = fromPoint(e.x, e.y, editor.getDoc());
  26104. selection.setRng(rng);
  26105. insertClipboardContents(internalContent.html, true);
  26106. }
  26107. }
  26108. });
  26109. };
  26110. var refreshContentEditable = noop;
  26111. var isHidden = function () {
  26112. if (!isGecko || editor.removed) {
  26113. return false;
  26114. }
  26115. var sel = editor.selection.getSel();
  26116. return !sel || !sel.rangeCount || sel.rangeCount === 0;
  26117. };
  26118. var setupRtc = function () {
  26119. if (isWebKit) {
  26120. documentElementEditingFocus();
  26121. selectControlElements();
  26122. blockFormSubmitInsideEditor();
  26123. selectAll();
  26124. if (Env.iOS) {
  26125. restoreFocusOnKeyDown();
  26126. bodyHeight();
  26127. tapLinksAndImages();
  26128. }
  26129. }
  26130. if (isGecko) {
  26131. focusBody();
  26132. setGeckoEditingOptions();
  26133. showBrokenImageIcon();
  26134. blockCmdArrowNavigation();
  26135. }
  26136. };
  26137. var setup = function () {
  26138. removeBlockQuoteOnBackSpace();
  26139. emptyEditorWhenDeleting();
  26140. if (!Env.windowsPhone) {
  26141. normalizeSelection();
  26142. }
  26143. if (isWebKit) {
  26144. documentElementEditingFocus();
  26145. selectControlElements();
  26146. setDefaultBlockType();
  26147. blockFormSubmitInsideEditor();
  26148. disableBackspaceIntoATable();
  26149. removeAppleInterchangeBrs();
  26150. if (Env.iOS) {
  26151. restoreFocusOnKeyDown();
  26152. bodyHeight();
  26153. tapLinksAndImages();
  26154. } else {
  26155. selectAll();
  26156. }
  26157. }
  26158. if (Env.ie >= 11) {
  26159. bodyHeight();
  26160. disableBackspaceIntoATable();
  26161. }
  26162. if (Env.ie) {
  26163. selectAll();
  26164. disableAutoUrlDetect();
  26165. ieInternalDragAndDrop();
  26166. }
  26167. if (isGecko) {
  26168. removeHrOnBackspace();
  26169. focusBody();
  26170. removeStylesWhenDeletingAcrossBlockElements();
  26171. setGeckoEditingOptions();
  26172. addBrAfterLastLinks();
  26173. showBrokenImageIcon();
  26174. blockCmdArrowNavigation();
  26175. disableBackspaceIntoATable();
  26176. }
  26177. };
  26178. if (isRtc(editor)) {
  26179. setupRtc();
  26180. } else {
  26181. setup();
  26182. }
  26183. return {
  26184. refreshContentEditable: refreshContentEditable,
  26185. isHidden: isHidden
  26186. };
  26187. };
  26188. var DOM$6 = DOMUtils.DOM;
  26189. var appendStyle = function (editor, text) {
  26190. var body = SugarElement.fromDom(editor.getBody());
  26191. var container = getStyleContainer(getRootNode(body));
  26192. var style = SugarElement.fromTag('style');
  26193. set$1(style, 'type', 'text/css');
  26194. append$1(style, SugarElement.fromText(text));
  26195. append$1(container, style);
  26196. editor.on('remove', function () {
  26197. remove$7(style);
  26198. });
  26199. };
  26200. var getRootName = function (editor) {
  26201. return editor.inline ? editor.getElement().nodeName.toLowerCase() : undefined;
  26202. };
  26203. var removeUndefined = function (obj) {
  26204. return filter$3(obj, function (v) {
  26205. return isUndefined(v) === false;
  26206. });
  26207. };
  26208. var mkParserSettings = function (editor) {
  26209. var settings = editor.settings;
  26210. var blobCache = editor.editorUpload.blobCache;
  26211. return removeUndefined({
  26212. allow_conditional_comments: settings.allow_conditional_comments,
  26213. allow_html_data_urls: settings.allow_html_data_urls,
  26214. allow_svg_data_urls: settings.allow_svg_data_urls,
  26215. allow_html_in_named_anchor: settings.allow_html_in_named_anchor,
  26216. allow_script_urls: settings.allow_script_urls,
  26217. allow_unsafe_link_target: settings.allow_unsafe_link_target,
  26218. convert_fonts_to_spans: settings.convert_fonts_to_spans,
  26219. fix_list_elements: settings.fix_list_elements,
  26220. font_size_legacy_values: settings.font_size_legacy_values,
  26221. forced_root_block: settings.forced_root_block,
  26222. forced_root_block_attrs: settings.forced_root_block_attrs,
  26223. padd_empty_with_br: settings.padd_empty_with_br,
  26224. preserve_cdata: settings.preserve_cdata,
  26225. remove_trailing_brs: settings.remove_trailing_brs,
  26226. inline_styles: settings.inline_styles,
  26227. root_name: getRootName(editor),
  26228. validate: true,
  26229. blob_cache: blobCache,
  26230. document: editor.getDoc(),
  26231. images_dataimg_filter: settings.images_dataimg_filter
  26232. });
  26233. };
  26234. var mkSerializerSettings = function (editor) {
  26235. var settings = editor.settings;
  26236. return __assign(__assign({}, mkParserSettings(editor)), removeUndefined({
  26237. url_converter: settings.url_converter,
  26238. url_converter_scope: settings.url_converter_scope,
  26239. element_format: settings.element_format,
  26240. entities: settings.entities,
  26241. entity_encoding: settings.entity_encoding,
  26242. indent: settings.indent,
  26243. indent_after: settings.indent_after,
  26244. indent_before: settings.indent_before,
  26245. block_elements: settings.block_elements,
  26246. boolean_attributes: settings.boolean_attributes,
  26247. custom_elements: settings.custom_elements,
  26248. extended_valid_elements: settings.extended_valid_elements,
  26249. invalid_elements: settings.invalid_elements,
  26250. invalid_styles: settings.invalid_styles,
  26251. move_caret_before_on_enter_elements: settings.move_caret_before_on_enter_elements,
  26252. non_empty_elements: settings.non_empty_elements,
  26253. schema: settings.schema,
  26254. self_closing_elements: settings.self_closing_elements,
  26255. short_ended_elements: settings.short_ended_elements,
  26256. special: settings.special,
  26257. text_block_elements: settings.text_block_elements,
  26258. text_inline_elements: settings.text_inline_elements,
  26259. valid_children: settings.valid_children,
  26260. valid_classes: settings.valid_classes,
  26261. valid_elements: settings.valid_elements,
  26262. valid_styles: settings.valid_styles,
  26263. verify_html: settings.verify_html,
  26264. whitespace_elements: settings.whitespace_elements
  26265. }));
  26266. };
  26267. var createParser = function (editor) {
  26268. var parser = DomParser(mkParserSettings(editor), editor.schema);
  26269. parser.addAttributeFilter('src,href,style,tabindex', function (nodes, name) {
  26270. var i = nodes.length, node, value;
  26271. var dom = editor.dom;
  26272. var internalName = 'data-mce-' + name;
  26273. while (i--) {
  26274. node = nodes[i];
  26275. value = node.attr(name);
  26276. if (value && !node.attr(internalName)) {
  26277. if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) {
  26278. continue;
  26279. }
  26280. if (name === 'style') {
  26281. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  26282. if (!value.length) {
  26283. value = null;
  26284. }
  26285. node.attr(internalName, value);
  26286. node.attr(name, value);
  26287. } else if (name === 'tabindex') {
  26288. node.attr(internalName, value);
  26289. node.attr(name, null);
  26290. } else {
  26291. node.attr(internalName, editor.convertURL(value, name, node.name));
  26292. }
  26293. }
  26294. }
  26295. });
  26296. parser.addNodeFilter('script', function (nodes) {
  26297. var i = nodes.length;
  26298. while (i--) {
  26299. var node = nodes[i];
  26300. var type = node.attr('type') || 'no/type';
  26301. if (type.indexOf('mce-') !== 0) {
  26302. node.attr('type', 'mce-' + type);
  26303. }
  26304. }
  26305. });
  26306. if (editor.settings.preserve_cdata) {
  26307. parser.addNodeFilter('#cdata', function (nodes) {
  26308. var i = nodes.length;
  26309. while (i--) {
  26310. var node = nodes[i];
  26311. node.type = 8;
  26312. node.name = '#comment';
  26313. node.value = '[CDATA[' + editor.dom.encode(node.value) + ']]';
  26314. }
  26315. });
  26316. }
  26317. parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function (nodes) {
  26318. var i = nodes.length;
  26319. var nonEmptyElements = editor.schema.getNonEmptyElements();
  26320. while (i--) {
  26321. var node = nodes[i];
  26322. if (node.isEmpty(nonEmptyElements) && node.getAll('br').length === 0) {
  26323. node.append(new AstNode('br', 1)).shortEnded = true;
  26324. }
  26325. }
  26326. });
  26327. return parser;
  26328. };
  26329. var autoFocus = function (editor) {
  26330. if (editor.settings.auto_focus) {
  26331. Delay.setEditorTimeout(editor, function () {
  26332. var focusEditor;
  26333. if (editor.settings.auto_focus === true) {
  26334. focusEditor = editor;
  26335. } else {
  26336. focusEditor = editor.editorManager.get(editor.settings.auto_focus);
  26337. }
  26338. if (!focusEditor.destroyed) {
  26339. focusEditor.focus();
  26340. }
  26341. }, 100);
  26342. }
  26343. };
  26344. var moveSelectionToFirstCaretPosition = function (editor) {
  26345. var root = editor.dom.getRoot();
  26346. if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) {
  26347. firstPositionIn(root).each(function (pos) {
  26348. var node = pos.getNode();
  26349. var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  26350. if (Env.browser.isIE()) {
  26351. storeNative(editor, caretPos.toRange());
  26352. } else {
  26353. editor.selection.setRng(caretPos.toRange());
  26354. }
  26355. });
  26356. }
  26357. };
  26358. var initEditor = function (editor) {
  26359. editor.bindPendingEventDelegates();
  26360. editor.initialized = true;
  26361. fireInit(editor);
  26362. editor.focus(true);
  26363. moveSelectionToFirstCaretPosition(editor);
  26364. editor.nodeChanged({ initial: true });
  26365. editor.execCallback('init_instance_callback', editor);
  26366. autoFocus(editor);
  26367. };
  26368. var getStyleSheetLoader$1 = function (editor) {
  26369. return editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader;
  26370. };
  26371. var makeStylesheetLoadingPromises = function (editor, css, framedFonts) {
  26372. var promises = [new promiseObj(function (resolve, reject) {
  26373. return getStyleSheetLoader$1(editor).loadAll(css, resolve, reject);
  26374. })];
  26375. if (editor.inline) {
  26376. return promises;
  26377. } else {
  26378. return promises.concat([new promiseObj(function (resolve, reject) {
  26379. return editor.ui.styleSheetLoader.loadAll(framedFonts, resolve, reject);
  26380. })]);
  26381. }
  26382. };
  26383. var loadContentCss = function (editor) {
  26384. var styleSheetLoader = getStyleSheetLoader$1(editor);
  26385. var fontCss = getFontCss(editor);
  26386. var css = editor.contentCSS;
  26387. var removeCss = function () {
  26388. styleSheetLoader.unloadAll(css);
  26389. if (!editor.inline) {
  26390. editor.ui.styleSheetLoader.unloadAll(fontCss);
  26391. }
  26392. };
  26393. var loaded = function () {
  26394. if (editor.removed) {
  26395. removeCss();
  26396. } else {
  26397. editor.on('remove', removeCss);
  26398. }
  26399. };
  26400. if (editor.contentStyles.length > 0) {
  26401. var contentCssText_1 = '';
  26402. Tools.each(editor.contentStyles, function (style) {
  26403. contentCssText_1 += style + '\r\n';
  26404. });
  26405. editor.dom.addStyle(contentCssText_1);
  26406. }
  26407. var allStylesheets = promiseObj.all(makeStylesheetLoadingPromises(editor, css, fontCss)).then(loaded).catch(loaded);
  26408. if (editor.settings.content_style) {
  26409. appendStyle(editor, editor.settings.content_style);
  26410. }
  26411. return allStylesheets;
  26412. };
  26413. var preInit = function (editor) {
  26414. var settings = editor.settings, doc = editor.getDoc(), body = editor.getBody();
  26415. firePreInit(editor);
  26416. if (!settings.browser_spellcheck && !settings.gecko_spellcheck) {
  26417. doc.body.spellcheck = false;
  26418. DOM$6.setAttrib(body, 'spellcheck', 'false');
  26419. }
  26420. editor.quirks = Quirks(editor);
  26421. firePostRender(editor);
  26422. var directionality = getDirectionality(editor);
  26423. if (directionality !== undefined) {
  26424. body.dir = directionality;
  26425. }
  26426. if (settings.protect) {
  26427. editor.on('BeforeSetContent', function (e) {
  26428. Tools.each(settings.protect, function (pattern) {
  26429. e.content = e.content.replace(pattern, function (str) {
  26430. return '<!--mce:protected ' + escape(str) + '-->';
  26431. });
  26432. });
  26433. });
  26434. }
  26435. editor.on('SetContent', function () {
  26436. editor.addVisual(editor.getBody());
  26437. });
  26438. editor.on('compositionstart compositionend', function (e) {
  26439. editor.composing = e.type === 'compositionstart';
  26440. });
  26441. };
  26442. var loadInitialContent = function (editor) {
  26443. if (!isRtc(editor)) {
  26444. editor.load({
  26445. initial: true,
  26446. format: 'html'
  26447. });
  26448. }
  26449. editor.startContent = editor.getContent({ format: 'raw' });
  26450. };
  26451. var initEditorWithInitialContent = function (editor) {
  26452. if (editor.removed !== true) {
  26453. loadInitialContent(editor);
  26454. initEditor(editor);
  26455. }
  26456. };
  26457. var initContentBody = function (editor, skipWrite) {
  26458. var settings = editor.settings;
  26459. var targetElm = editor.getElement();
  26460. var doc = editor.getDoc();
  26461. if (!settings.inline) {
  26462. editor.getElement().style.visibility = editor.orgVisibility;
  26463. }
  26464. if (!skipWrite && !editor.inline) {
  26465. doc.open();
  26466. doc.write(editor.iframeHTML);
  26467. doc.close();
  26468. }
  26469. if (editor.inline) {
  26470. DOM$6.addClass(targetElm, 'mce-content-body');
  26471. editor.contentDocument = doc = document;
  26472. editor.contentWindow = window;
  26473. editor.bodyElement = targetElm;
  26474. editor.contentAreaContainer = targetElm;
  26475. }
  26476. var body = editor.getBody();
  26477. body.disabled = true;
  26478. editor.readonly = !!settings.readonly;
  26479. if (!editor.readonly) {
  26480. if (editor.inline && DOM$6.getStyle(body, 'position', true) === 'static') {
  26481. body.style.position = 'relative';
  26482. }
  26483. body.contentEditable = editor.getParam('content_editable_state', true);
  26484. }
  26485. body.disabled = false;
  26486. editor.editorUpload = EditorUpload(editor);
  26487. editor.schema = Schema(settings);
  26488. editor.dom = DOMUtils(doc, {
  26489. keep_values: true,
  26490. url_converter: editor.convertURL,
  26491. url_converter_scope: editor,
  26492. hex_colors: settings.force_hex_style_colors,
  26493. update_styles: true,
  26494. root_element: editor.inline ? editor.getBody() : null,
  26495. collect: function () {
  26496. return editor.inline;
  26497. },
  26498. schema: editor.schema,
  26499. contentCssCors: shouldUseContentCssCors(editor),
  26500. referrerPolicy: getReferrerPolicy(editor),
  26501. onSetAttrib: function (e) {
  26502. editor.fire('SetAttrib', e);
  26503. }
  26504. });
  26505. editor.parser = createParser(editor);
  26506. editor.serializer = DomSerializer(mkSerializerSettings(editor), editor);
  26507. editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor);
  26508. editor.annotator = Annotator(editor);
  26509. editor.formatter = Formatter(editor);
  26510. editor.undoManager = UndoManager(editor);
  26511. editor._nodeChangeDispatcher = new NodeChange(editor);
  26512. editor._selectionOverrides = SelectionOverrides(editor);
  26513. setup$e(editor);
  26514. setup$3(editor);
  26515. if (!isRtc(editor)) {
  26516. setup$2(editor);
  26517. }
  26518. var caret = setup$4(editor);
  26519. setup$f(editor, caret);
  26520. setup$d(editor);
  26521. setup$g(editor);
  26522. var setupRtcThunk = setup$i(editor);
  26523. preInit(editor);
  26524. setupRtcThunk.fold(function () {
  26525. loadContentCss(editor).then(function () {
  26526. return initEditorWithInitialContent(editor);
  26527. });
  26528. }, function (setupRtc) {
  26529. editor.setProgressState(true);
  26530. loadContentCss(editor).then(function () {
  26531. setupRtc().then(function (_rtcMode) {
  26532. editor.setProgressState(false);
  26533. initEditorWithInitialContent(editor);
  26534. }, function (err) {
  26535. editor.notificationManager.open({
  26536. type: 'error',
  26537. text: String(err)
  26538. });
  26539. initEditorWithInitialContent(editor);
  26540. });
  26541. });
  26542. });
  26543. };
  26544. var DOM$5 = DOMUtils.DOM;
  26545. var relaxDomain = function (editor, ifr) {
  26546. if (document.domain !== window.location.hostname && Env.browser.isIE()) {
  26547. var bodyUuid = uuid('mce');
  26548. editor[bodyUuid] = function () {
  26549. initContentBody(editor);
  26550. };
  26551. 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);})()';
  26552. DOM$5.setAttrib(ifr, 'src', domainRelaxUrl);
  26553. return true;
  26554. }
  26555. return false;
  26556. };
  26557. var createIframeElement = function (id, title, height, customAttrs) {
  26558. var iframe = SugarElement.fromTag('iframe');
  26559. setAll$1(iframe, customAttrs);
  26560. setAll$1(iframe, {
  26561. id: id + '_ifr',
  26562. frameBorder: '0',
  26563. allowTransparency: 'true',
  26564. title: title
  26565. });
  26566. add$1(iframe, 'tox-edit-area__iframe');
  26567. return iframe;
  26568. };
  26569. var getIframeHtml = function (editor) {
  26570. var iframeHTML = getDocType(editor) + '<html><head>';
  26571. if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
  26572. iframeHTML += '<base href="' + editor.documentBaseURI.getURI() + '" />';
  26573. }
  26574. iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
  26575. var bodyId = getBodyId(editor);
  26576. var bodyClass = getBodyClass(editor);
  26577. var translatedAriaText = editor.translate(getIframeAriaText(editor));
  26578. if (getContentSecurityPolicy(editor)) {
  26579. iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + getContentSecurityPolicy(editor) + '" />';
  26580. }
  26581. iframeHTML += '</head>' + ('<body id="' + bodyId + '" class="mce-content-body ' + bodyClass + '" data-id="' + editor.id + '" aria-label="' + translatedAriaText + '">') + '<br>' + '</body></html>';
  26582. return iframeHTML;
  26583. };
  26584. var createIframe = function (editor, o) {
  26585. var iframeTitle = editor.translate('Rich Text Area');
  26586. var ifr = createIframeElement(editor.id, iframeTitle, o.height, getIframeAttrs(editor)).dom;
  26587. ifr.onload = function () {
  26588. ifr.onload = null;
  26589. editor.fire('load');
  26590. };
  26591. var isDomainRelaxed = relaxDomain(editor, ifr);
  26592. editor.contentAreaContainer = o.iframeContainer;
  26593. editor.iframeElement = ifr;
  26594. editor.iframeHTML = getIframeHtml(editor);
  26595. DOM$5.add(o.iframeContainer, ifr);
  26596. return isDomainRelaxed;
  26597. };
  26598. var init$1 = function (editor, boxInfo) {
  26599. var isDomainRelaxed = createIframe(editor, boxInfo);
  26600. if (boxInfo.editorContainer) {
  26601. DOM$5.get(boxInfo.editorContainer).style.display = editor.orgDisplay;
  26602. editor.hidden = DOM$5.isHidden(boxInfo.editorContainer);
  26603. }
  26604. editor.getElement().style.display = 'none';
  26605. DOM$5.setAttrib(editor.id, 'aria-hidden', 'true');
  26606. if (!isDomainRelaxed) {
  26607. initContentBody(editor);
  26608. }
  26609. };
  26610. var DOM$4 = DOMUtils.DOM;
  26611. var initPlugin = function (editor, initializedPlugins, plugin) {
  26612. var Plugin = PluginManager.get(plugin);
  26613. var pluginUrl = PluginManager.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, '');
  26614. plugin = Tools.trim(plugin);
  26615. if (Plugin && Tools.inArray(initializedPlugins, plugin) === -1) {
  26616. Tools.each(PluginManager.dependencies(plugin), function (dep) {
  26617. initPlugin(editor, initializedPlugins, dep);
  26618. });
  26619. if (editor.plugins[plugin]) {
  26620. return;
  26621. }
  26622. try {
  26623. var pluginInstance = new Plugin(editor, pluginUrl, editor.$);
  26624. editor.plugins[plugin] = pluginInstance;
  26625. if (pluginInstance.init) {
  26626. pluginInstance.init(editor, pluginUrl);
  26627. initializedPlugins.push(plugin);
  26628. }
  26629. } catch (e) {
  26630. pluginInitError(editor, plugin, e);
  26631. }
  26632. }
  26633. };
  26634. var trimLegacyPrefix = function (name) {
  26635. return name.replace(/^\-/, '');
  26636. };
  26637. var initPlugins = function (editor) {
  26638. var initializedPlugins = [];
  26639. Tools.each(getPlugins(editor).split(/[ ,]/), function (name) {
  26640. initPlugin(editor, initializedPlugins, trimLegacyPrefix(name));
  26641. });
  26642. };
  26643. var initIcons = function (editor) {
  26644. var iconPackName = Tools.trim(getIconPackName(editor));
  26645. var currentIcons = editor.ui.registry.getAll().icons;
  26646. var loadIcons = __assign(__assign({}, IconManager.get('default').icons), IconManager.get(iconPackName).icons);
  26647. each$j(loadIcons, function (svgData, icon) {
  26648. if (!has$2(currentIcons, icon)) {
  26649. editor.ui.registry.addIcon(icon, svgData);
  26650. }
  26651. });
  26652. };
  26653. var initTheme = function (editor) {
  26654. var theme = getTheme(editor);
  26655. if (isString$1(theme)) {
  26656. editor.settings.theme = trimLegacyPrefix(theme);
  26657. var Theme = ThemeManager.get(theme);
  26658. editor.theme = new Theme(editor, ThemeManager.urls[theme]);
  26659. if (editor.theme.init) {
  26660. editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ''), editor.$);
  26661. }
  26662. } else {
  26663. editor.theme = {};
  26664. }
  26665. };
  26666. var renderFromLoadedTheme = function (editor) {
  26667. return editor.theme.renderUI();
  26668. };
  26669. var renderFromThemeFunc = function (editor) {
  26670. var elm = editor.getElement();
  26671. var theme = getTheme(editor);
  26672. var info = theme(editor, elm);
  26673. if (info.editorContainer.nodeType) {
  26674. info.editorContainer.id = info.editorContainer.id || editor.id + '_parent';
  26675. }
  26676. if (info.iframeContainer && info.iframeContainer.nodeType) {
  26677. info.iframeContainer.id = info.iframeContainer.id || editor.id + '_iframecontainer';
  26678. }
  26679. info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
  26680. return info;
  26681. };
  26682. var createThemeFalseResult = function (element) {
  26683. return {
  26684. editorContainer: element,
  26685. iframeContainer: element,
  26686. api: {}
  26687. };
  26688. };
  26689. var renderThemeFalseIframe = function (targetElement) {
  26690. var iframeContainer = DOM$4.create('div');
  26691. DOM$4.insertAfter(iframeContainer, targetElement);
  26692. return createThemeFalseResult(iframeContainer);
  26693. };
  26694. var renderThemeFalse = function (editor) {
  26695. var targetElement = editor.getElement();
  26696. return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
  26697. };
  26698. var renderThemeUi = function (editor) {
  26699. var elm = editor.getElement();
  26700. editor.orgDisplay = elm.style.display;
  26701. if (isString$1(getTheme(editor))) {
  26702. return renderFromLoadedTheme(editor);
  26703. } else if (isFunction(getTheme(editor))) {
  26704. return renderFromThemeFunc(editor);
  26705. } else {
  26706. return renderThemeFalse(editor);
  26707. }
  26708. };
  26709. var augmentEditorUiApi = function (editor, api) {
  26710. var uiApiFacade = {
  26711. show: Optional.from(api.show).getOr(noop),
  26712. hide: Optional.from(api.hide).getOr(noop),
  26713. disable: Optional.from(api.disable).getOr(noop),
  26714. isDisabled: Optional.from(api.isDisabled).getOr(never),
  26715. enable: function () {
  26716. if (!editor.mode.isReadOnly()) {
  26717. Optional.from(api.enable).map(call);
  26718. }
  26719. }
  26720. };
  26721. editor.ui = __assign(__assign({}, editor.ui), uiApiFacade);
  26722. };
  26723. var init = function (editor) {
  26724. editor.fire('ScriptsLoaded');
  26725. initIcons(editor);
  26726. initTheme(editor);
  26727. initPlugins(editor);
  26728. var renderInfo = renderThemeUi(editor);
  26729. augmentEditorUiApi(editor, Optional.from(renderInfo.api).getOr({}));
  26730. var boxInfo = {
  26731. editorContainer: renderInfo.editorContainer,
  26732. iframeContainer: renderInfo.iframeContainer
  26733. };
  26734. editor.editorContainer = boxInfo.editorContainer ? boxInfo.editorContainer : null;
  26735. appendContentCssFromSettings(editor);
  26736. if (editor.inline) {
  26737. return initContentBody(editor);
  26738. } else {
  26739. return init$1(editor, boxInfo);
  26740. }
  26741. };
  26742. var DOM$3 = DOMUtils.DOM;
  26743. var hasSkipLoadPrefix = function (name) {
  26744. return name.charAt(0) === '-';
  26745. };
  26746. var loadLanguage = function (scriptLoader, editor) {
  26747. var languageCode = getLanguageCode(editor);
  26748. var languageUrl = getLanguageUrl(editor);
  26749. if (I18n.hasCode(languageCode) === false && languageCode !== 'en') {
  26750. var url_1 = languageUrl !== '' ? languageUrl : editor.editorManager.baseURL + '/langs/' + languageCode + '.js';
  26751. scriptLoader.add(url_1, noop, undefined, function () {
  26752. languageLoadError(editor, url_1, languageCode);
  26753. });
  26754. }
  26755. };
  26756. var loadTheme = function (scriptLoader, editor, suffix, callback) {
  26757. var theme = getTheme(editor);
  26758. if (isString$1(theme)) {
  26759. if (!hasSkipLoadPrefix(theme) && !has$2(ThemeManager.urls, theme)) {
  26760. var themeUrl = getThemeUrl(editor);
  26761. if (themeUrl) {
  26762. ThemeManager.load(theme, editor.documentBaseURI.toAbsolute(themeUrl));
  26763. } else {
  26764. ThemeManager.load(theme, 'themes/' + theme + '/theme' + suffix + '.js');
  26765. }
  26766. }
  26767. scriptLoader.loadQueue(function () {
  26768. ThemeManager.waitFor(theme, callback);
  26769. });
  26770. } else {
  26771. callback();
  26772. }
  26773. };
  26774. var getIconsUrlMetaFromUrl = function (editor) {
  26775. return Optional.from(getIconsUrl(editor)).filter(function (url) {
  26776. return url.length > 0;
  26777. }).map(function (url) {
  26778. return {
  26779. url: url,
  26780. name: Optional.none()
  26781. };
  26782. });
  26783. };
  26784. var getIconsUrlMetaFromName = function (editor, name, suffix) {
  26785. return Optional.from(name).filter(function (name) {
  26786. return name.length > 0 && !IconManager.has(name);
  26787. }).map(function (name) {
  26788. return {
  26789. url: editor.editorManager.baseURL + '/icons/' + name + '/icons' + suffix + '.js',
  26790. name: Optional.some(name)
  26791. };
  26792. });
  26793. };
  26794. var loadIcons = function (scriptLoader, editor, suffix) {
  26795. var defaultIconsUrl = getIconsUrlMetaFromName(editor, 'default', suffix);
  26796. var customIconsUrl = getIconsUrlMetaFromUrl(editor).orThunk(function () {
  26797. return getIconsUrlMetaFromName(editor, getIconPackName(editor), '');
  26798. });
  26799. each$k(cat([
  26800. defaultIconsUrl,
  26801. customIconsUrl
  26802. ]), function (urlMeta) {
  26803. scriptLoader.add(urlMeta.url, noop, undefined, function () {
  26804. iconsLoadError(editor, urlMeta.url, urlMeta.name.getOrUndefined());
  26805. });
  26806. });
  26807. };
  26808. var loadPlugins = function (editor, suffix) {
  26809. Tools.each(getExternalPlugins$1(editor), function (url, name) {
  26810. PluginManager.load(name, url, noop, undefined, function () {
  26811. pluginLoadError(editor, url, name);
  26812. });
  26813. editor.settings.plugins += ' ' + name;
  26814. });
  26815. Tools.each(getPlugins(editor).split(/[ ,]/), function (plugin) {
  26816. plugin = Tools.trim(plugin);
  26817. if (plugin && !PluginManager.urls[plugin]) {
  26818. if (hasSkipLoadPrefix(plugin)) {
  26819. plugin = plugin.substr(1, plugin.length);
  26820. var dependencies = PluginManager.dependencies(plugin);
  26821. Tools.each(dependencies, function (depPlugin) {
  26822. var defaultSettings = {
  26823. prefix: 'plugins/',
  26824. resource: depPlugin,
  26825. suffix: '/plugin' + suffix + '.js'
  26826. };
  26827. var dep = PluginManager.createUrl(defaultSettings, depPlugin);
  26828. PluginManager.load(dep.resource, dep, noop, undefined, function () {
  26829. pluginLoadError(editor, dep.prefix + dep.resource + dep.suffix, dep.resource);
  26830. });
  26831. });
  26832. } else {
  26833. var url_2 = {
  26834. prefix: 'plugins/',
  26835. resource: plugin,
  26836. suffix: '/plugin' + suffix + '.js'
  26837. };
  26838. PluginManager.load(plugin, url_2, noop, undefined, function () {
  26839. pluginLoadError(editor, url_2.prefix + url_2.resource + url_2.suffix, plugin);
  26840. });
  26841. }
  26842. }
  26843. });
  26844. };
  26845. var loadScripts = function (editor, suffix) {
  26846. var scriptLoader = ScriptLoader.ScriptLoader;
  26847. loadTheme(scriptLoader, editor, suffix, function () {
  26848. loadLanguage(scriptLoader, editor);
  26849. loadIcons(scriptLoader, editor, suffix);
  26850. loadPlugins(editor, suffix);
  26851. scriptLoader.loadQueue(function () {
  26852. if (!editor.removed) {
  26853. init(editor);
  26854. }
  26855. }, editor, function () {
  26856. if (!editor.removed) {
  26857. init(editor);
  26858. }
  26859. });
  26860. });
  26861. };
  26862. var getStyleSheetLoader = function (element, editor) {
  26863. return instance.forElement(element, {
  26864. contentCssCors: hasContentCssCors(editor),
  26865. referrerPolicy: getReferrerPolicy(editor)
  26866. });
  26867. };
  26868. var render = function (editor) {
  26869. var id = editor.id;
  26870. I18n.setCode(getLanguageCode(editor));
  26871. var readyHandler = function () {
  26872. DOM$3.unbind(window, 'ready', readyHandler);
  26873. editor.render();
  26874. };
  26875. if (!EventUtils.Event.domLoaded) {
  26876. DOM$3.bind(window, 'ready', readyHandler);
  26877. return;
  26878. }
  26879. if (!editor.getElement()) {
  26880. return;
  26881. }
  26882. if (!Env.contentEditable) {
  26883. return;
  26884. }
  26885. var element = SugarElement.fromDom(editor.getElement());
  26886. var snapshot = clone$3(element);
  26887. editor.on('remove', function () {
  26888. eachr(element.dom.attributes, function (attr) {
  26889. return remove$6(element, attr.name);
  26890. });
  26891. setAll$1(element, snapshot);
  26892. });
  26893. editor.ui.styleSheetLoader = getStyleSheetLoader(element, editor);
  26894. if (!isInline(editor)) {
  26895. editor.orgVisibility = editor.getElement().style.visibility;
  26896. editor.getElement().style.visibility = 'hidden';
  26897. } else {
  26898. editor.inline = true;
  26899. }
  26900. var form = editor.getElement().form || DOM$3.getParent(id, 'form');
  26901. if (form) {
  26902. editor.formElement = form;
  26903. if (hasHiddenInput(editor) && !isTextareaOrInput(editor.getElement())) {
  26904. DOM$3.insertAfter(DOM$3.create('input', {
  26905. type: 'hidden',
  26906. name: id
  26907. }), id);
  26908. editor.hasHiddenInput = true;
  26909. }
  26910. editor.formEventDelegate = function (e) {
  26911. editor.fire(e.type, e);
  26912. };
  26913. DOM$3.bind(form, 'submit reset', editor.formEventDelegate);
  26914. editor.on('reset', function () {
  26915. editor.resetContent();
  26916. });
  26917. if (shouldPatchSubmit(editor) && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
  26918. form._mceOldSubmit = form.submit;
  26919. form.submit = function () {
  26920. editor.editorManager.triggerSave();
  26921. editor.setDirty(false);
  26922. return form._mceOldSubmit(form);
  26923. };
  26924. }
  26925. }
  26926. editor.windowManager = WindowManager(editor);
  26927. editor.notificationManager = NotificationManager(editor);
  26928. if (isEncodingXml(editor)) {
  26929. editor.on('GetContent', function (e) {
  26930. if (e.save) {
  26931. e.content = DOM$3.encode(e.content);
  26932. }
  26933. });
  26934. }
  26935. if (shouldAddFormSubmitTrigger(editor)) {
  26936. editor.on('submit', function () {
  26937. if (editor.initialized) {
  26938. editor.save();
  26939. }
  26940. });
  26941. }
  26942. if (shouldAddUnloadTrigger(editor)) {
  26943. editor._beforeUnload = function () {
  26944. if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
  26945. editor.save({
  26946. format: 'raw',
  26947. no_events: true,
  26948. set_dirty: false
  26949. });
  26950. }
  26951. };
  26952. editor.editorManager.on('BeforeUnload', editor._beforeUnload);
  26953. }
  26954. editor.editorManager.add(editor);
  26955. loadScripts(editor, editor.suffix);
  26956. };
  26957. var addVisual = function (editor, elm) {
  26958. return addVisual$1(editor, elm);
  26959. };
  26960. var legacyPropNames = {
  26961. 'font-size': 'size',
  26962. 'font-family': 'face'
  26963. };
  26964. var getSpecifiedFontProp = function (propName, rootElm, elm) {
  26965. var getProperty = function (elm) {
  26966. return getRaw(elm, propName).orThunk(function () {
  26967. if (name(elm) === 'font') {
  26968. return get$9(legacyPropNames, propName).bind(function (legacyPropName) {
  26969. return getOpt(elm, legacyPropName);
  26970. });
  26971. } else {
  26972. return Optional.none();
  26973. }
  26974. });
  26975. };
  26976. var isRoot = function (elm) {
  26977. return eq(SugarElement.fromDom(rootElm), elm);
  26978. };
  26979. return closest$1(SugarElement.fromDom(elm), function (elm) {
  26980. return getProperty(elm);
  26981. }, isRoot);
  26982. };
  26983. var normalizeFontFamily = function (fontFamily) {
  26984. return fontFamily.replace(/[\'\"\\]/g, '').replace(/,\s+/g, ',');
  26985. };
  26986. var getComputedFontProp = function (propName, elm) {
  26987. return Optional.from(DOMUtils.DOM.getStyle(elm, propName, true));
  26988. };
  26989. var getFontProp = function (propName) {
  26990. return function (rootElm, elm) {
  26991. return Optional.from(elm).map(SugarElement.fromDom).filter(isElement$6).bind(function (element) {
  26992. return getSpecifiedFontProp(propName, rootElm, element.dom).or(getComputedFontProp(propName, element.dom));
  26993. }).getOr('');
  26994. };
  26995. };
  26996. var getFontSize = getFontProp('font-size');
  26997. var getFontFamily = compose(normalizeFontFamily, getFontProp('font-family'));
  26998. var findFirstCaretElement = function (editor) {
  26999. return firstPositionIn(editor.getBody()).map(function (caret) {
  27000. var container = caret.container();
  27001. return isText$7(container) ? container.parentNode : container;
  27002. });
  27003. };
  27004. var getCaretElement = function (editor) {
  27005. return Optional.from(editor.selection.getRng()).bind(function (rng) {
  27006. var root = editor.getBody();
  27007. var atStartOfNode = rng.startContainer === root && rng.startOffset === 0;
  27008. return atStartOfNode ? Optional.none() : Optional.from(editor.selection.getStart(true));
  27009. });
  27010. };
  27011. var bindRange = function (editor, binder) {
  27012. return getCaretElement(editor).orThunk(curry(findFirstCaretElement, editor)).map(SugarElement.fromDom).filter(isElement$6).bind(binder);
  27013. };
  27014. var mapRange = function (editor, mapper) {
  27015. return bindRange(editor, compose1(Optional.some, mapper));
  27016. };
  27017. var fromFontSizeNumber = function (editor, value) {
  27018. if (/^[0-9.]+$/.test(value)) {
  27019. var fontSizeNumber = parseInt(value, 10);
  27020. if (fontSizeNumber >= 1 && fontSizeNumber <= 7) {
  27021. var fontSizes = getFontStyleValues(editor);
  27022. var fontClasses = getFontSizeClasses(editor);
  27023. if (fontClasses) {
  27024. return fontClasses[fontSizeNumber - 1] || value;
  27025. } else {
  27026. return fontSizes[fontSizeNumber - 1] || value;
  27027. }
  27028. } else {
  27029. return value;
  27030. }
  27031. } else {
  27032. return value;
  27033. }
  27034. };
  27035. var normalizeFontNames = function (font) {
  27036. var fonts = font.split(/\s*,\s*/);
  27037. return map$3(fonts, function (font) {
  27038. if (font.indexOf(' ') !== -1 && !(startsWith(font, '"') || startsWith(font, '\''))) {
  27039. return '\'' + font + '\'';
  27040. } else {
  27041. return font;
  27042. }
  27043. }).join(',');
  27044. };
  27045. var fontNameAction = function (editor, value) {
  27046. var font = fromFontSizeNumber(editor, value);
  27047. editor.formatter.toggle('fontname', { value: normalizeFontNames(font) });
  27048. editor.nodeChanged();
  27049. };
  27050. var fontNameQuery = function (editor) {
  27051. return mapRange(editor, function (elm) {
  27052. return getFontFamily(editor.getBody(), elm.dom);
  27053. }).getOr('');
  27054. };
  27055. var fontSizeAction = function (editor, value) {
  27056. editor.formatter.toggle('fontsize', { value: fromFontSizeNumber(editor, value) });
  27057. editor.nodeChanged();
  27058. };
  27059. var fontSizeQuery = function (editor) {
  27060. return mapRange(editor, function (elm) {
  27061. return getFontSize(editor.getBody(), elm.dom);
  27062. }).getOr('');
  27063. };
  27064. var lineHeightQuery = function (editor) {
  27065. return mapRange(editor, function (elm) {
  27066. var root = SugarElement.fromDom(editor.getBody());
  27067. var specifiedStyle = closest$1(elm, function (elm) {
  27068. return getRaw(elm, 'line-height');
  27069. }, curry(eq, root));
  27070. var computedStyle = function () {
  27071. var lineHeight = parseFloat(get$5(elm, 'line-height'));
  27072. var fontSize = parseFloat(get$5(elm, 'font-size'));
  27073. return String(lineHeight / fontSize);
  27074. };
  27075. return specifiedStyle.getOrThunk(computedStyle);
  27076. }).getOr('');
  27077. };
  27078. var lineHeightAction = function (editor, lineHeight) {
  27079. editor.formatter.toggle('lineheight', { value: String(lineHeight) });
  27080. editor.nodeChanged();
  27081. };
  27082. var processValue = function (value) {
  27083. if (typeof value !== 'string') {
  27084. var details = Tools.extend({
  27085. paste: value.paste,
  27086. data: { paste: value.paste }
  27087. }, value);
  27088. return {
  27089. content: value.content,
  27090. details: details
  27091. };
  27092. }
  27093. return {
  27094. content: value,
  27095. details: {}
  27096. };
  27097. };
  27098. var insertAtCaret = function (editor, value) {
  27099. var result = processValue(value);
  27100. insertContent(editor, result.content, result.details);
  27101. };
  27102. var each$4 = Tools.each;
  27103. var map = Tools.map, inArray = Tools.inArray;
  27104. var EditorCommands = function () {
  27105. function EditorCommands(editor) {
  27106. this.commands = {
  27107. state: {},
  27108. exec: {},
  27109. value: {}
  27110. };
  27111. this.editor = editor;
  27112. this.setupCommands(editor);
  27113. }
  27114. EditorCommands.prototype.execCommand = function (command, ui, value, args) {
  27115. var func, state = false;
  27116. var self = this;
  27117. if (self.editor.removed) {
  27118. return;
  27119. }
  27120. if (command.toLowerCase() !== 'mcefocus') {
  27121. if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) {
  27122. self.editor.focus();
  27123. } else {
  27124. restore(self.editor);
  27125. }
  27126. }
  27127. args = self.editor.fire('BeforeExecCommand', {
  27128. command: command,
  27129. ui: ui,
  27130. value: value
  27131. });
  27132. if (args.isDefaultPrevented()) {
  27133. return false;
  27134. }
  27135. var customCommand = command.toLowerCase();
  27136. if (func = self.commands.exec[customCommand]) {
  27137. func(customCommand, ui, value);
  27138. self.editor.fire('ExecCommand', {
  27139. command: command,
  27140. ui: ui,
  27141. value: value
  27142. });
  27143. return true;
  27144. }
  27145. each$4(this.editor.plugins, function (p) {
  27146. if (p.execCommand && p.execCommand(command, ui, value)) {
  27147. self.editor.fire('ExecCommand', {
  27148. command: command,
  27149. ui: ui,
  27150. value: value
  27151. });
  27152. state = true;
  27153. return false;
  27154. }
  27155. });
  27156. if (state) {
  27157. return state;
  27158. }
  27159. if (self.editor.theme && self.editor.theme.execCommand && self.editor.theme.execCommand(command, ui, value)) {
  27160. self.editor.fire('ExecCommand', {
  27161. command: command,
  27162. ui: ui,
  27163. value: value
  27164. });
  27165. return true;
  27166. }
  27167. try {
  27168. state = self.editor.getDoc().execCommand(command, ui, value);
  27169. } catch (ex) {
  27170. }
  27171. if (state) {
  27172. self.editor.fire('ExecCommand', {
  27173. command: command,
  27174. ui: ui,
  27175. value: value
  27176. });
  27177. return true;
  27178. }
  27179. return false;
  27180. };
  27181. EditorCommands.prototype.queryCommandState = function (command) {
  27182. var func;
  27183. if (this.editor.quirks.isHidden() || this.editor.removed) {
  27184. return;
  27185. }
  27186. command = command.toLowerCase();
  27187. if (func = this.commands.state[command]) {
  27188. return func(command);
  27189. }
  27190. try {
  27191. return this.editor.getDoc().queryCommandState(command);
  27192. } catch (ex) {
  27193. }
  27194. return false;
  27195. };
  27196. EditorCommands.prototype.queryCommandValue = function (command) {
  27197. var func;
  27198. if (this.editor.quirks.isHidden() || this.editor.removed) {
  27199. return;
  27200. }
  27201. command = command.toLowerCase();
  27202. if (func = this.commands.value[command]) {
  27203. return func(command);
  27204. }
  27205. try {
  27206. return this.editor.getDoc().queryCommandValue(command);
  27207. } catch (ex) {
  27208. }
  27209. };
  27210. EditorCommands.prototype.addCommands = function (commandList, type) {
  27211. if (type === void 0) {
  27212. type = 'exec';
  27213. }
  27214. var self = this;
  27215. each$4(commandList, function (callback, command) {
  27216. each$4(command.toLowerCase().split(','), function (command) {
  27217. self.commands[type][command] = callback;
  27218. });
  27219. });
  27220. };
  27221. EditorCommands.prototype.addCommand = function (command, callback, scope) {
  27222. var _this = this;
  27223. command = command.toLowerCase();
  27224. this.commands.exec[command] = function (command, ui, value, args) {
  27225. return callback.call(scope || _this.editor, ui, value, args);
  27226. };
  27227. };
  27228. EditorCommands.prototype.queryCommandSupported = function (command) {
  27229. command = command.toLowerCase();
  27230. if (this.commands.exec[command]) {
  27231. return true;
  27232. }
  27233. try {
  27234. return this.editor.getDoc().queryCommandSupported(command);
  27235. } catch (ex) {
  27236. }
  27237. return false;
  27238. };
  27239. EditorCommands.prototype.addQueryStateHandler = function (command, callback, scope) {
  27240. var _this = this;
  27241. command = command.toLowerCase();
  27242. this.commands.state[command] = function () {
  27243. return callback.call(scope || _this.editor);
  27244. };
  27245. };
  27246. EditorCommands.prototype.addQueryValueHandler = function (command, callback, scope) {
  27247. var _this = this;
  27248. command = command.toLowerCase();
  27249. this.commands.value[command] = function () {
  27250. return callback.call(scope || _this.editor);
  27251. };
  27252. };
  27253. EditorCommands.prototype.hasCustomCommand = function (command) {
  27254. command = command.toLowerCase();
  27255. return !!this.commands.exec[command];
  27256. };
  27257. EditorCommands.prototype.execNativeCommand = function (command, ui, value) {
  27258. if (ui === undefined) {
  27259. ui = false;
  27260. }
  27261. if (value === undefined) {
  27262. value = null;
  27263. }
  27264. return this.editor.getDoc().execCommand(command, ui, value);
  27265. };
  27266. EditorCommands.prototype.isFormatMatch = function (name) {
  27267. return this.editor.formatter.match(name);
  27268. };
  27269. EditorCommands.prototype.toggleFormat = function (name, value) {
  27270. this.editor.formatter.toggle(name, value);
  27271. this.editor.nodeChanged();
  27272. };
  27273. EditorCommands.prototype.storeSelection = function (type) {
  27274. this.selectionBookmark = this.editor.selection.getBookmark(type);
  27275. };
  27276. EditorCommands.prototype.restoreSelection = function () {
  27277. this.editor.selection.moveToBookmark(this.selectionBookmark);
  27278. };
  27279. EditorCommands.prototype.setupCommands = function (editor) {
  27280. var self = this;
  27281. this.addCommands({
  27282. 'mceResetDesignMode,mceBeginUndoLevel': noop,
  27283. 'mceEndUndoLevel,mceAddUndoLevel': function () {
  27284. editor.undoManager.add();
  27285. },
  27286. 'mceFocus': function (_command, _ui, value) {
  27287. focus(editor, value);
  27288. },
  27289. 'Cut,Copy,Paste': function (command) {
  27290. var doc = editor.getDoc();
  27291. var failed;
  27292. try {
  27293. self.execNativeCommand(command);
  27294. } catch (ex) {
  27295. failed = true;
  27296. }
  27297. if (command === 'paste' && !doc.queryCommandEnabled(command)) {
  27298. failed = true;
  27299. }
  27300. if (failed || !doc.queryCommandSupported(command)) {
  27301. var msg = editor.translate('Your browser doesn\'t support direct access to the clipboard. ' + 'Please use the Ctrl+X/C/V keyboard shortcuts instead.');
  27302. if (Env.mac) {
  27303. msg = msg.replace(/Ctrl\+/g, '\u2318+');
  27304. }
  27305. editor.notificationManager.open({
  27306. text: msg,
  27307. type: 'error'
  27308. });
  27309. }
  27310. },
  27311. 'unlink': function () {
  27312. if (editor.selection.isCollapsed()) {
  27313. var elm = editor.dom.getParent(editor.selection.getStart(), 'a');
  27314. if (elm) {
  27315. editor.dom.remove(elm, true);
  27316. }
  27317. return;
  27318. }
  27319. editor.formatter.remove('link');
  27320. },
  27321. 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone': function (command) {
  27322. var align = command.substring(7);
  27323. if (align === 'full') {
  27324. align = 'justify';
  27325. }
  27326. each$4('left,center,right,justify'.split(','), function (name) {
  27327. if (align !== name) {
  27328. editor.formatter.remove('align' + name);
  27329. }
  27330. });
  27331. if (align !== 'none') {
  27332. self.toggleFormat('align' + align);
  27333. }
  27334. },
  27335. 'InsertUnorderedList,InsertOrderedList': function (command) {
  27336. var listParent;
  27337. self.execNativeCommand(command);
  27338. var listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
  27339. if (listElm) {
  27340. listParent = listElm.parentNode;
  27341. if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
  27342. self.storeSelection();
  27343. editor.dom.split(listParent, listElm);
  27344. self.restoreSelection();
  27345. }
  27346. }
  27347. },
  27348. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  27349. self.toggleFormat(command);
  27350. },
  27351. 'ForeColor,HiliteColor': function (command, ui, value) {
  27352. self.toggleFormat(command, { value: value });
  27353. },
  27354. 'FontName': function (command, ui, value) {
  27355. fontNameAction(editor, value);
  27356. },
  27357. 'FontSize': function (command, ui, value) {
  27358. fontSizeAction(editor, value);
  27359. },
  27360. 'LineHeight': function (command, ui, value) {
  27361. lineHeightAction(editor, value);
  27362. },
  27363. 'Lang': function (command, ui, lang) {
  27364. self.toggleFormat(command, {
  27365. value: lang.code,
  27366. customValue: lang.customCode
  27367. });
  27368. },
  27369. 'RemoveFormat': function (command) {
  27370. editor.formatter.remove(command);
  27371. },
  27372. 'mceBlockQuote': function () {
  27373. self.toggleFormat('blockquote');
  27374. },
  27375. 'FormatBlock': function (command, ui, value) {
  27376. return self.toggleFormat(value || 'p');
  27377. },
  27378. 'mceCleanup': function () {
  27379. var bookmark = editor.selection.getBookmark();
  27380. editor.setContent(editor.getContent());
  27381. editor.selection.moveToBookmark(bookmark);
  27382. },
  27383. 'mceRemoveNode': function (command, ui, value) {
  27384. var node = value || editor.selection.getNode();
  27385. if (node !== editor.getBody()) {
  27386. self.storeSelection();
  27387. editor.dom.remove(node, true);
  27388. self.restoreSelection();
  27389. }
  27390. },
  27391. 'mceSelectNodeDepth': function (command, ui, value) {
  27392. var counter = 0;
  27393. editor.dom.getParent(editor.selection.getNode(), function (node) {
  27394. if (node.nodeType === 1 && counter++ === value) {
  27395. editor.selection.select(node);
  27396. return false;
  27397. }
  27398. }, editor.getBody());
  27399. },
  27400. 'mceSelectNode': function (command, ui, value) {
  27401. editor.selection.select(value);
  27402. },
  27403. 'mceInsertContent': function (command, ui, value) {
  27404. insertAtCaret(editor, value);
  27405. },
  27406. 'mceInsertRawHTML': function (command, ui, value) {
  27407. editor.selection.setContent('tiny_mce_marker');
  27408. var content = editor.getContent();
  27409. editor.setContent(content.replace(/tiny_mce_marker/g, function () {
  27410. return value;
  27411. }));
  27412. },
  27413. 'mceInsertNewLine': function (command, ui, value) {
  27414. insert(editor, value);
  27415. },
  27416. 'mceToggleFormat': function (command, ui, value) {
  27417. self.toggleFormat(value);
  27418. },
  27419. 'mceSetContent': function (command, ui, value) {
  27420. editor.setContent(value);
  27421. },
  27422. 'Indent,Outdent': function (command) {
  27423. handle(editor, command);
  27424. },
  27425. 'mceRepaint': noop,
  27426. 'InsertHorizontalRule': function () {
  27427. editor.execCommand('mceInsertContent', false, '<hr />');
  27428. },
  27429. 'mceToggleVisualAid': function () {
  27430. editor.hasVisual = !editor.hasVisual;
  27431. editor.addVisual();
  27432. },
  27433. 'mceReplaceContent': function (command, ui, value) {
  27434. editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, editor.selection.getContent({ format: 'text' })));
  27435. },
  27436. 'mceInsertLink': function (command, ui, value) {
  27437. if (typeof value === 'string') {
  27438. value = { href: value };
  27439. }
  27440. var anchor = editor.dom.getParent(editor.selection.getNode(), 'a');
  27441. value.href = value.href.replace(/ /g, '%20');
  27442. if (!anchor || !value.href) {
  27443. editor.formatter.remove('link');
  27444. }
  27445. if (value.href) {
  27446. editor.formatter.apply('link', value, anchor);
  27447. }
  27448. },
  27449. 'selectAll': function () {
  27450. var editingHost = editor.dom.getParent(editor.selection.getStart(), isContentEditableTrue$4);
  27451. if (editingHost) {
  27452. var rng = editor.dom.createRng();
  27453. rng.selectNodeContents(editingHost);
  27454. editor.selection.setRng(rng);
  27455. }
  27456. },
  27457. 'mceNewDocument': function () {
  27458. editor.setContent('');
  27459. },
  27460. 'InsertLineBreak': function (command, ui, value) {
  27461. insert$1(editor, value);
  27462. return true;
  27463. }
  27464. });
  27465. var alignStates = function (name) {
  27466. return function () {
  27467. var selection = editor.selection;
  27468. var nodes = selection.isCollapsed() ? [editor.dom.getParent(selection.getNode(), editor.dom.isBlock)] : selection.getSelectedBlocks();
  27469. var matches = map(nodes, function (node) {
  27470. return !!editor.formatter.matchNode(node, name);
  27471. });
  27472. return inArray(matches, true) !== -1;
  27473. };
  27474. };
  27475. self.addCommands({
  27476. 'JustifyLeft': alignStates('alignleft'),
  27477. 'JustifyCenter': alignStates('aligncenter'),
  27478. 'JustifyRight': alignStates('alignright'),
  27479. 'JustifyFull': alignStates('alignjustify'),
  27480. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  27481. return self.isFormatMatch(command);
  27482. },
  27483. 'mceBlockQuote': function () {
  27484. return self.isFormatMatch('blockquote');
  27485. },
  27486. 'Outdent': function () {
  27487. return canOutdent(editor);
  27488. },
  27489. 'InsertUnorderedList,InsertOrderedList': function (command) {
  27490. var list = editor.dom.getParent(editor.selection.getNode(), 'ul,ol');
  27491. return list && (command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL');
  27492. }
  27493. }, 'state');
  27494. self.addCommands({
  27495. Undo: function () {
  27496. editor.undoManager.undo();
  27497. },
  27498. Redo: function () {
  27499. editor.undoManager.redo();
  27500. }
  27501. });
  27502. self.addQueryValueHandler('FontName', function () {
  27503. return fontNameQuery(editor);
  27504. }, this);
  27505. self.addQueryValueHandler('FontSize', function () {
  27506. return fontSizeQuery(editor);
  27507. }, this);
  27508. self.addQueryValueHandler('LineHeight', function () {
  27509. return lineHeightQuery(editor);
  27510. }, this);
  27511. };
  27512. return EditorCommands;
  27513. }();
  27514. var internalContentEditableAttr = 'data-mce-contenteditable';
  27515. var toggleClass = function (elm, cls, state) {
  27516. if (has(elm, cls) && state === false) {
  27517. remove$3(elm, cls);
  27518. } else if (state) {
  27519. add$1(elm, cls);
  27520. }
  27521. };
  27522. var setEditorCommandState = function (editor, cmd, state) {
  27523. try {
  27524. editor.getDoc().execCommand(cmd, false, String(state));
  27525. } catch (ex) {
  27526. }
  27527. };
  27528. var setContentEditable = function (elm, state) {
  27529. elm.dom.contentEditable = state ? 'true' : 'false';
  27530. };
  27531. var switchOffContentEditableTrue = function (elm) {
  27532. each$k(descendants(elm, '*[contenteditable="true"]'), function (elm) {
  27533. set$1(elm, internalContentEditableAttr, 'true');
  27534. setContentEditable(elm, false);
  27535. });
  27536. };
  27537. var switchOnContentEditableTrue = function (elm) {
  27538. each$k(descendants(elm, '*[' + internalContentEditableAttr + '="true"]'), function (elm) {
  27539. remove$6(elm, internalContentEditableAttr);
  27540. setContentEditable(elm, true);
  27541. });
  27542. };
  27543. var removeFakeSelection = function (editor) {
  27544. Optional.from(editor.selection.getNode()).each(function (elm) {
  27545. elm.removeAttribute('data-mce-selected');
  27546. });
  27547. };
  27548. var restoreFakeSelection = function (editor) {
  27549. editor.selection.setRng(editor.selection.getRng());
  27550. };
  27551. var toggleReadOnly = function (editor, state) {
  27552. var body = SugarElement.fromDom(editor.getBody());
  27553. toggleClass(body, 'mce-content-readonly', state);
  27554. if (state) {
  27555. editor.selection.controlSelection.hideResizeRect();
  27556. editor._selectionOverrides.hideFakeCaret();
  27557. removeFakeSelection(editor);
  27558. editor.readonly = true;
  27559. setContentEditable(body, false);
  27560. switchOffContentEditableTrue(body);
  27561. } else {
  27562. editor.readonly = false;
  27563. setContentEditable(body, true);
  27564. switchOnContentEditableTrue(body);
  27565. setEditorCommandState(editor, 'StyleWithCSS', false);
  27566. setEditorCommandState(editor, 'enableInlineTableEditing', false);
  27567. setEditorCommandState(editor, 'enableObjectResizing', false);
  27568. if (hasEditorOrUiFocus(editor)) {
  27569. editor.focus();
  27570. }
  27571. restoreFakeSelection(editor);
  27572. editor.nodeChanged();
  27573. }
  27574. };
  27575. var isReadOnly = function (editor) {
  27576. return editor.readonly;
  27577. };
  27578. var registerFilters = function (editor) {
  27579. editor.parser.addAttributeFilter('contenteditable', function (nodes) {
  27580. if (isReadOnly(editor)) {
  27581. each$k(nodes, function (node) {
  27582. node.attr(internalContentEditableAttr, node.attr('contenteditable'));
  27583. node.attr('contenteditable', 'false');
  27584. });
  27585. }
  27586. });
  27587. editor.serializer.addAttributeFilter(internalContentEditableAttr, function (nodes) {
  27588. if (isReadOnly(editor)) {
  27589. each$k(nodes, function (node) {
  27590. node.attr('contenteditable', node.attr(internalContentEditableAttr));
  27591. });
  27592. }
  27593. });
  27594. editor.serializer.addTempAttr(internalContentEditableAttr);
  27595. };
  27596. var registerReadOnlyContentFilters = function (editor) {
  27597. if (editor.serializer) {
  27598. registerFilters(editor);
  27599. } else {
  27600. editor.on('PreInit', function () {
  27601. registerFilters(editor);
  27602. });
  27603. }
  27604. };
  27605. var isClickEvent = function (e) {
  27606. return e.type === 'click';
  27607. };
  27608. var getAnchorHrefOpt = function (editor, elm) {
  27609. var isRoot = function (elm) {
  27610. return eq(elm, SugarElement.fromDom(editor.getBody()));
  27611. };
  27612. return closest$2(elm, 'a', isRoot).bind(function (a) {
  27613. return getOpt(a, 'href');
  27614. });
  27615. };
  27616. var processReadonlyEvents = function (editor, e) {
  27617. if (isClickEvent(e) && !VK.metaKeyPressed(e)) {
  27618. var elm = SugarElement.fromDom(e.target);
  27619. getAnchorHrefOpt(editor, elm).each(function (href) {
  27620. e.preventDefault();
  27621. if (/^#/.test(href)) {
  27622. var targetEl = editor.dom.select(href + ',[name="' + removeLeading(href, '#') + '"]');
  27623. if (targetEl.length) {
  27624. editor.selection.scrollIntoView(targetEl[0], true);
  27625. }
  27626. } else {
  27627. window.open(href, '_blank', 'rel=noopener noreferrer,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes,scrollbars=yes');
  27628. }
  27629. });
  27630. }
  27631. };
  27632. var registerReadOnlySelectionBlockers = function (editor) {
  27633. editor.on('ShowCaret', function (e) {
  27634. if (isReadOnly(editor)) {
  27635. e.preventDefault();
  27636. }
  27637. });
  27638. editor.on('ObjectSelected', function (e) {
  27639. if (isReadOnly(editor)) {
  27640. e.preventDefault();
  27641. }
  27642. });
  27643. };
  27644. 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', ' ');
  27645. var EventDispatcher = function () {
  27646. function EventDispatcher(settings) {
  27647. this.bindings = {};
  27648. this.settings = settings || {};
  27649. this.scope = this.settings.scope || this;
  27650. this.toggleEvent = this.settings.toggleEvent || never;
  27651. }
  27652. EventDispatcher.isNative = function (name) {
  27653. return !!nativeEvents[name.toLowerCase()];
  27654. };
  27655. EventDispatcher.prototype.fire = function (name, args) {
  27656. var lcName = name.toLowerCase();
  27657. var event = normalize$3(lcName, args || {}, this.scope);
  27658. if (this.settings.beforeFire) {
  27659. this.settings.beforeFire(event);
  27660. }
  27661. var handlers = this.bindings[lcName];
  27662. if (handlers) {
  27663. for (var i = 0, l = handlers.length; i < l; i++) {
  27664. var callback = handlers[i];
  27665. if (callback.removed) {
  27666. continue;
  27667. }
  27668. if (callback.once) {
  27669. this.off(lcName, callback.func);
  27670. }
  27671. if (event.isImmediatePropagationStopped()) {
  27672. return event;
  27673. }
  27674. if (callback.func.call(this.scope, event) === false) {
  27675. event.preventDefault();
  27676. return event;
  27677. }
  27678. }
  27679. }
  27680. return event;
  27681. };
  27682. EventDispatcher.prototype.on = function (name, callback, prepend, extra) {
  27683. if (callback === false) {
  27684. callback = never;
  27685. }
  27686. if (callback) {
  27687. var wrappedCallback = {
  27688. func: callback,
  27689. removed: false
  27690. };
  27691. if (extra) {
  27692. Tools.extend(wrappedCallback, extra);
  27693. }
  27694. var names = name.toLowerCase().split(' ');
  27695. var i = names.length;
  27696. while (i--) {
  27697. var currentName = names[i];
  27698. var handlers = this.bindings[currentName];
  27699. if (!handlers) {
  27700. handlers = [];
  27701. this.toggleEvent(currentName, true);
  27702. }
  27703. if (prepend) {
  27704. handlers = __spreadArray([wrappedCallback], handlers, true);
  27705. } else {
  27706. handlers = __spreadArray(__spreadArray([], handlers, true), [wrappedCallback], false);
  27707. }
  27708. this.bindings[currentName] = handlers;
  27709. }
  27710. }
  27711. return this;
  27712. };
  27713. EventDispatcher.prototype.off = function (name, callback) {
  27714. var _this = this;
  27715. if (name) {
  27716. var names = name.toLowerCase().split(' ');
  27717. var i = names.length;
  27718. while (i--) {
  27719. var currentName = names[i];
  27720. var handlers = this.bindings[currentName];
  27721. if (!currentName) {
  27722. each$j(this.bindings, function (_value, bindingName) {
  27723. _this.toggleEvent(bindingName, false);
  27724. delete _this.bindings[bindingName];
  27725. });
  27726. return this;
  27727. }
  27728. if (handlers) {
  27729. if (!callback) {
  27730. handlers.length = 0;
  27731. } else {
  27732. var filteredHandlers = partition(handlers, function (handler) {
  27733. return handler.func === callback;
  27734. });
  27735. handlers = filteredHandlers.fail;
  27736. this.bindings[currentName] = handlers;
  27737. each$k(filteredHandlers.pass, function (handler) {
  27738. handler.removed = true;
  27739. });
  27740. }
  27741. if (!handlers.length) {
  27742. this.toggleEvent(name, false);
  27743. delete this.bindings[currentName];
  27744. }
  27745. }
  27746. }
  27747. } else {
  27748. each$j(this.bindings, function (_value, name) {
  27749. _this.toggleEvent(name, false);
  27750. });
  27751. this.bindings = {};
  27752. }
  27753. return this;
  27754. };
  27755. EventDispatcher.prototype.once = function (name, callback, prepend) {
  27756. return this.on(name, callback, prepend, { once: true });
  27757. };
  27758. EventDispatcher.prototype.has = function (name) {
  27759. name = name.toLowerCase();
  27760. return !(!this.bindings[name] || this.bindings[name].length === 0);
  27761. };
  27762. return EventDispatcher;
  27763. }();
  27764. var getEventDispatcher = function (obj) {
  27765. if (!obj._eventDispatcher) {
  27766. obj._eventDispatcher = new EventDispatcher({
  27767. scope: obj,
  27768. toggleEvent: function (name, state) {
  27769. if (EventDispatcher.isNative(name) && obj.toggleNativeEvent) {
  27770. obj.toggleNativeEvent(name, state);
  27771. }
  27772. }
  27773. });
  27774. }
  27775. return obj._eventDispatcher;
  27776. };
  27777. var Observable = {
  27778. fire: function (name, args, bubble) {
  27779. var self = this;
  27780. if (self.removed && name !== 'remove' && name !== 'detach') {
  27781. return args;
  27782. }
  27783. var dispatcherArgs = getEventDispatcher(self).fire(name, args);
  27784. if (bubble !== false && self.parent) {
  27785. var parent_1 = self.parent();
  27786. while (parent_1 && !dispatcherArgs.isPropagationStopped()) {
  27787. parent_1.fire(name, dispatcherArgs, false);
  27788. parent_1 = parent_1.parent();
  27789. }
  27790. }
  27791. return dispatcherArgs;
  27792. },
  27793. on: function (name, callback, prepend) {
  27794. return getEventDispatcher(this).on(name, callback, prepend);
  27795. },
  27796. off: function (name, callback) {
  27797. return getEventDispatcher(this).off(name, callback);
  27798. },
  27799. once: function (name, callback) {
  27800. return getEventDispatcher(this).once(name, callback);
  27801. },
  27802. hasEventListeners: function (name) {
  27803. return getEventDispatcher(this).has(name);
  27804. }
  27805. };
  27806. var DOM$2 = DOMUtils.DOM;
  27807. var customEventRootDelegates;
  27808. var getEventTarget = function (editor, eventName) {
  27809. if (eventName === 'selectionchange') {
  27810. return editor.getDoc();
  27811. }
  27812. if (!editor.inline && /^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(eventName)) {
  27813. return editor.getDoc().documentElement;
  27814. }
  27815. var eventRoot = getEventRoot(editor);
  27816. if (eventRoot) {
  27817. if (!editor.eventRoot) {
  27818. editor.eventRoot = DOM$2.select(eventRoot)[0];
  27819. }
  27820. return editor.eventRoot;
  27821. }
  27822. return editor.getBody();
  27823. };
  27824. var isListening = function (editor) {
  27825. return !editor.hidden && !isReadOnly(editor);
  27826. };
  27827. var fireEvent = function (editor, eventName, e) {
  27828. if (isListening(editor)) {
  27829. editor.fire(eventName, e);
  27830. } else if (isReadOnly(editor)) {
  27831. processReadonlyEvents(editor, e);
  27832. }
  27833. };
  27834. var bindEventDelegate = function (editor, eventName) {
  27835. var delegate;
  27836. if (!editor.delegates) {
  27837. editor.delegates = {};
  27838. }
  27839. if (editor.delegates[eventName] || editor.removed) {
  27840. return;
  27841. }
  27842. var eventRootElm = getEventTarget(editor, eventName);
  27843. if (getEventRoot(editor)) {
  27844. if (!customEventRootDelegates) {
  27845. customEventRootDelegates = {};
  27846. editor.editorManager.on('removeEditor', function () {
  27847. if (!editor.editorManager.activeEditor) {
  27848. if (customEventRootDelegates) {
  27849. each$j(customEventRootDelegates, function (_value, name) {
  27850. editor.dom.unbind(getEventTarget(editor, name));
  27851. });
  27852. customEventRootDelegates = null;
  27853. }
  27854. }
  27855. });
  27856. }
  27857. if (customEventRootDelegates[eventName]) {
  27858. return;
  27859. }
  27860. delegate = function (e) {
  27861. var target = e.target;
  27862. var editors = editor.editorManager.get();
  27863. var i = editors.length;
  27864. while (i--) {
  27865. var body = editors[i].getBody();
  27866. if (body === target || DOM$2.isChildOf(target, body)) {
  27867. fireEvent(editors[i], eventName, e);
  27868. }
  27869. }
  27870. };
  27871. customEventRootDelegates[eventName] = delegate;
  27872. DOM$2.bind(eventRootElm, eventName, delegate);
  27873. } else {
  27874. delegate = function (e) {
  27875. fireEvent(editor, eventName, e);
  27876. };
  27877. DOM$2.bind(eventRootElm, eventName, delegate);
  27878. editor.delegates[eventName] = delegate;
  27879. }
  27880. };
  27881. var EditorObservable = __assign(__assign({}, Observable), {
  27882. bindPendingEventDelegates: function () {
  27883. var self = this;
  27884. Tools.each(self._pendingNativeEvents, function (name) {
  27885. bindEventDelegate(self, name);
  27886. });
  27887. },
  27888. toggleNativeEvent: function (name, state) {
  27889. var self = this;
  27890. if (name === 'focus' || name === 'blur') {
  27891. return;
  27892. }
  27893. if (self.removed) {
  27894. return;
  27895. }
  27896. if (state) {
  27897. if (self.initialized) {
  27898. bindEventDelegate(self, name);
  27899. } else {
  27900. if (!self._pendingNativeEvents) {
  27901. self._pendingNativeEvents = [name];
  27902. } else {
  27903. self._pendingNativeEvents.push(name);
  27904. }
  27905. }
  27906. } else if (self.initialized) {
  27907. self.dom.unbind(getEventTarget(self, name), name, self.delegates[name]);
  27908. delete self.delegates[name];
  27909. }
  27910. },
  27911. unbindAllNativeEvents: function () {
  27912. var self = this;
  27913. var body = self.getBody();
  27914. var dom = self.dom;
  27915. if (self.delegates) {
  27916. each$j(self.delegates, function (value, name) {
  27917. self.dom.unbind(getEventTarget(self, name), name, value);
  27918. });
  27919. delete self.delegates;
  27920. }
  27921. if (!self.inline && body && dom) {
  27922. body.onload = null;
  27923. dom.unbind(self.getWin());
  27924. dom.unbind(self.getDoc());
  27925. }
  27926. if (dom) {
  27927. dom.unbind(body);
  27928. dom.unbind(self.getContainer());
  27929. }
  27930. }
  27931. });
  27932. var defaultModes = [
  27933. 'design',
  27934. 'readonly'
  27935. ];
  27936. var switchToMode = function (editor, activeMode, availableModes, mode) {
  27937. var oldMode = availableModes[activeMode.get()];
  27938. var newMode = availableModes[mode];
  27939. try {
  27940. newMode.activate();
  27941. } catch (e) {
  27942. console.error('problem while activating editor mode ' + mode + ':', e);
  27943. return;
  27944. }
  27945. oldMode.deactivate();
  27946. if (oldMode.editorReadOnly !== newMode.editorReadOnly) {
  27947. toggleReadOnly(editor, newMode.editorReadOnly);
  27948. }
  27949. activeMode.set(mode);
  27950. fireSwitchMode(editor, mode);
  27951. };
  27952. var setMode = function (editor, availableModes, activeMode, mode) {
  27953. if (mode === activeMode.get()) {
  27954. return;
  27955. } else if (!has$2(availableModes, mode)) {
  27956. throw new Error('Editor mode \'' + mode + '\' is invalid');
  27957. }
  27958. if (editor.initialized) {
  27959. switchToMode(editor, activeMode, availableModes, mode);
  27960. } else {
  27961. editor.on('init', function () {
  27962. return switchToMode(editor, activeMode, availableModes, mode);
  27963. });
  27964. }
  27965. };
  27966. var registerMode = function (availableModes, mode, api) {
  27967. var _a;
  27968. if (contains$3(defaultModes, mode)) {
  27969. throw new Error('Cannot override default mode ' + mode);
  27970. }
  27971. return __assign(__assign({}, availableModes), (_a = {}, _a[mode] = __assign(__assign({}, api), {
  27972. deactivate: function () {
  27973. try {
  27974. api.deactivate();
  27975. } catch (e) {
  27976. console.error('problem while deactivating editor mode ' + mode + ':', e);
  27977. }
  27978. }
  27979. }), _a));
  27980. };
  27981. var create$4 = function (editor) {
  27982. var activeMode = Cell('design');
  27983. var availableModes = Cell({
  27984. design: {
  27985. activate: noop,
  27986. deactivate: noop,
  27987. editorReadOnly: false
  27988. },
  27989. readonly: {
  27990. activate: noop,
  27991. deactivate: noop,
  27992. editorReadOnly: true
  27993. }
  27994. });
  27995. registerReadOnlyContentFilters(editor);
  27996. registerReadOnlySelectionBlockers(editor);
  27997. return {
  27998. isReadOnly: function () {
  27999. return isReadOnly(editor);
  28000. },
  28001. set: function (mode) {
  28002. return setMode(editor, availableModes.get(), activeMode, mode);
  28003. },
  28004. get: function () {
  28005. return activeMode.get();
  28006. },
  28007. register: function (mode, api) {
  28008. availableModes.set(registerMode(availableModes.get(), mode, api));
  28009. }
  28010. };
  28011. };
  28012. var each$3 = Tools.each, explode$1 = Tools.explode;
  28013. var keyCodeLookup = {
  28014. f1: 112,
  28015. f2: 113,
  28016. f3: 114,
  28017. f4: 115,
  28018. f5: 116,
  28019. f6: 117,
  28020. f7: 118,
  28021. f8: 119,
  28022. f9: 120,
  28023. f10: 121,
  28024. f11: 122,
  28025. f12: 123
  28026. };
  28027. var modifierNames = Tools.makeMap('alt,ctrl,shift,meta,access');
  28028. var parseShortcut = function (pattern) {
  28029. var key;
  28030. var shortcut = {};
  28031. each$3(explode$1(pattern.toLowerCase(), '+'), function (value) {
  28032. if (value in modifierNames) {
  28033. shortcut[value] = true;
  28034. } else {
  28035. if (/^[0-9]{2,}$/.test(value)) {
  28036. shortcut.keyCode = parseInt(value, 10);
  28037. } else {
  28038. shortcut.charCode = value.charCodeAt(0);
  28039. shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);
  28040. }
  28041. }
  28042. });
  28043. var id = [shortcut.keyCode];
  28044. for (key in modifierNames) {
  28045. if (shortcut[key]) {
  28046. id.push(key);
  28047. } else {
  28048. shortcut[key] = false;
  28049. }
  28050. }
  28051. shortcut.id = id.join(',');
  28052. if (shortcut.access) {
  28053. shortcut.alt = true;
  28054. if (Env.mac) {
  28055. shortcut.ctrl = true;
  28056. } else {
  28057. shortcut.shift = true;
  28058. }
  28059. }
  28060. if (shortcut.meta) {
  28061. if (Env.mac) {
  28062. shortcut.meta = true;
  28063. } else {
  28064. shortcut.ctrl = true;
  28065. shortcut.meta = false;
  28066. }
  28067. }
  28068. return shortcut;
  28069. };
  28070. var Shortcuts = function () {
  28071. function Shortcuts(editor) {
  28072. this.shortcuts = {};
  28073. this.pendingPatterns = [];
  28074. this.editor = editor;
  28075. var self = this;
  28076. editor.on('keyup keypress keydown', function (e) {
  28077. if ((self.hasModifier(e) || self.isFunctionKey(e)) && !e.isDefaultPrevented()) {
  28078. each$3(self.shortcuts, function (shortcut) {
  28079. if (self.matchShortcut(e, shortcut)) {
  28080. self.pendingPatterns = shortcut.subpatterns.slice(0);
  28081. if (e.type === 'keydown') {
  28082. self.executeShortcutAction(shortcut);
  28083. }
  28084. return true;
  28085. }
  28086. });
  28087. if (self.matchShortcut(e, self.pendingPatterns[0])) {
  28088. if (self.pendingPatterns.length === 1) {
  28089. if (e.type === 'keydown') {
  28090. self.executeShortcutAction(self.pendingPatterns[0]);
  28091. }
  28092. }
  28093. self.pendingPatterns.shift();
  28094. }
  28095. }
  28096. });
  28097. }
  28098. Shortcuts.prototype.add = function (pattern, desc, cmdFunc, scope) {
  28099. var self = this;
  28100. var func = self.normalizeCommandFunc(cmdFunc);
  28101. each$3(explode$1(Tools.trim(pattern)), function (pattern) {
  28102. var shortcut = self.createShortcut(pattern, desc, func, scope);
  28103. self.shortcuts[shortcut.id] = shortcut;
  28104. });
  28105. return true;
  28106. };
  28107. Shortcuts.prototype.remove = function (pattern) {
  28108. var shortcut = this.createShortcut(pattern);
  28109. if (this.shortcuts[shortcut.id]) {
  28110. delete this.shortcuts[shortcut.id];
  28111. return true;
  28112. }
  28113. return false;
  28114. };
  28115. Shortcuts.prototype.normalizeCommandFunc = function (cmdFunc) {
  28116. var self = this;
  28117. var cmd = cmdFunc;
  28118. if (typeof cmd === 'string') {
  28119. return function () {
  28120. self.editor.execCommand(cmd, false, null);
  28121. };
  28122. } else if (Tools.isArray(cmd)) {
  28123. return function () {
  28124. self.editor.execCommand(cmd[0], cmd[1], cmd[2]);
  28125. };
  28126. } else {
  28127. return cmd;
  28128. }
  28129. };
  28130. Shortcuts.prototype.createShortcut = function (pattern, desc, cmdFunc, scope) {
  28131. var shortcuts = Tools.map(explode$1(pattern, '>'), parseShortcut);
  28132. shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {
  28133. func: cmdFunc,
  28134. scope: scope || this.editor
  28135. });
  28136. return Tools.extend(shortcuts[0], {
  28137. desc: this.editor.translate(desc),
  28138. subpatterns: shortcuts.slice(1)
  28139. });
  28140. };
  28141. Shortcuts.prototype.hasModifier = function (e) {
  28142. return e.altKey || e.ctrlKey || e.metaKey;
  28143. };
  28144. Shortcuts.prototype.isFunctionKey = function (e) {
  28145. return e.type === 'keydown' && e.keyCode >= 112 && e.keyCode <= 123;
  28146. };
  28147. Shortcuts.prototype.matchShortcut = function (e, shortcut) {
  28148. if (!shortcut) {
  28149. return false;
  28150. }
  28151. if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
  28152. return false;
  28153. }
  28154. if (shortcut.alt !== e.altKey || shortcut.shift !== e.shiftKey) {
  28155. return false;
  28156. }
  28157. if (e.keyCode === shortcut.keyCode || e.charCode && e.charCode === shortcut.charCode) {
  28158. e.preventDefault();
  28159. return true;
  28160. }
  28161. return false;
  28162. };
  28163. Shortcuts.prototype.executeShortcutAction = function (shortcut) {
  28164. return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
  28165. };
  28166. return Shortcuts;
  28167. }();
  28168. var create$3 = function () {
  28169. var buttons = {};
  28170. var menuItems = {};
  28171. var popups = {};
  28172. var icons = {};
  28173. var contextMenus = {};
  28174. var contextToolbars = {};
  28175. var sidebars = {};
  28176. var add = function (collection, type) {
  28177. return function (name, spec) {
  28178. return collection[name.toLowerCase()] = __assign(__assign({}, spec), { type: type });
  28179. };
  28180. };
  28181. var addIcon = function (name, svgData) {
  28182. return icons[name.toLowerCase()] = svgData;
  28183. };
  28184. return {
  28185. addButton: add(buttons, 'button'),
  28186. addGroupToolbarButton: add(buttons, 'grouptoolbarbutton'),
  28187. addToggleButton: add(buttons, 'togglebutton'),
  28188. addMenuButton: add(buttons, 'menubutton'),
  28189. addSplitButton: add(buttons, 'splitbutton'),
  28190. addMenuItem: add(menuItems, 'menuitem'),
  28191. addNestedMenuItem: add(menuItems, 'nestedmenuitem'),
  28192. addToggleMenuItem: add(menuItems, 'togglemenuitem'),
  28193. addAutocompleter: add(popups, 'autocompleter'),
  28194. addContextMenu: add(contextMenus, 'contextmenu'),
  28195. addContextToolbar: add(contextToolbars, 'contexttoolbar'),
  28196. addContextForm: add(contextToolbars, 'contextform'),
  28197. addSidebar: add(sidebars, 'sidebar'),
  28198. addIcon: addIcon,
  28199. getAll: function () {
  28200. return {
  28201. buttons: buttons,
  28202. menuItems: menuItems,
  28203. icons: icons,
  28204. popups: popups,
  28205. contextMenus: contextMenus,
  28206. contextToolbars: contextToolbars,
  28207. sidebars: sidebars
  28208. };
  28209. }
  28210. };
  28211. };
  28212. var registry = function () {
  28213. var bridge = create$3();
  28214. return {
  28215. addAutocompleter: bridge.addAutocompleter,
  28216. addButton: bridge.addButton,
  28217. addContextForm: bridge.addContextForm,
  28218. addContextMenu: bridge.addContextMenu,
  28219. addContextToolbar: bridge.addContextToolbar,
  28220. addIcon: bridge.addIcon,
  28221. addMenuButton: bridge.addMenuButton,
  28222. addMenuItem: bridge.addMenuItem,
  28223. addNestedMenuItem: bridge.addNestedMenuItem,
  28224. addSidebar: bridge.addSidebar,
  28225. addSplitButton: bridge.addSplitButton,
  28226. addToggleButton: bridge.addToggleButton,
  28227. addGroupToolbarButton: bridge.addGroupToolbarButton,
  28228. addToggleMenuItem: bridge.addToggleMenuItem,
  28229. getAll: bridge.getAll
  28230. };
  28231. };
  28232. var DOM$1 = DOMUtils.DOM;
  28233. var extend$3 = Tools.extend, each$2 = Tools.each;
  28234. var resolve = Tools.resolve;
  28235. var ie = Env.ie;
  28236. var Editor = function () {
  28237. function Editor(id, settings, editorManager) {
  28238. var _this = this;
  28239. this.plugins = {};
  28240. this.contentCSS = [];
  28241. this.contentStyles = [];
  28242. this.loadedCSS = {};
  28243. this.isNotDirty = false;
  28244. this.editorManager = editorManager;
  28245. this.documentBaseUrl = editorManager.documentBaseURL;
  28246. extend$3(this, EditorObservable);
  28247. this.settings = getEditorSettings(this, id, this.documentBaseUrl, editorManager.defaultSettings, settings);
  28248. if (this.settings.suffix) {
  28249. editorManager.suffix = this.settings.suffix;
  28250. }
  28251. this.suffix = editorManager.suffix;
  28252. if (this.settings.base_url) {
  28253. editorManager._setBaseUrl(this.settings.base_url);
  28254. }
  28255. this.baseUri = editorManager.baseURI;
  28256. if (this.settings.referrer_policy) {
  28257. ScriptLoader.ScriptLoader._setReferrerPolicy(this.settings.referrer_policy);
  28258. DOMUtils.DOM.styleSheetLoader._setReferrerPolicy(this.settings.referrer_policy);
  28259. }
  28260. AddOnManager.languageLoad = this.settings.language_load;
  28261. AddOnManager.baseURL = editorManager.baseURL;
  28262. this.id = id;
  28263. this.setDirty(false);
  28264. this.documentBaseURI = new URI(this.settings.document_base_url, { base_uri: this.baseUri });
  28265. this.baseURI = this.baseUri;
  28266. this.inline = !!this.settings.inline;
  28267. this.shortcuts = new Shortcuts(this);
  28268. this.editorCommands = new EditorCommands(this);
  28269. if (this.settings.cache_suffix) {
  28270. Env.cacheSuffix = this.settings.cache_suffix.replace(/^[\?\&]+/, '');
  28271. }
  28272. this.ui = {
  28273. registry: registry(),
  28274. styleSheetLoader: undefined,
  28275. show: noop,
  28276. hide: noop,
  28277. enable: noop,
  28278. disable: noop,
  28279. isDisabled: never
  28280. };
  28281. var self = this;
  28282. var modeInstance = create$4(self);
  28283. this.mode = modeInstance;
  28284. this.setMode = modeInstance.set;
  28285. editorManager.fire('SetupEditor', { editor: this });
  28286. this.execCallback('setup', this);
  28287. this.$ = DomQuery.overrideDefaults(function () {
  28288. return {
  28289. context: _this.inline ? _this.getBody() : _this.getDoc(),
  28290. element: _this.getBody()
  28291. };
  28292. });
  28293. }
  28294. Editor.prototype.render = function () {
  28295. render(this);
  28296. };
  28297. Editor.prototype.focus = function (skipFocus) {
  28298. this.execCommand('mceFocus', false, skipFocus);
  28299. };
  28300. Editor.prototype.hasFocus = function () {
  28301. return hasFocus(this);
  28302. };
  28303. Editor.prototype.execCallback = function (name) {
  28304. var x = [];
  28305. for (var _i = 1; _i < arguments.length; _i++) {
  28306. x[_i - 1] = arguments[_i];
  28307. }
  28308. var self = this;
  28309. var callback = self.settings[name], scope;
  28310. if (!callback) {
  28311. return;
  28312. }
  28313. if (self.callbackLookup && (scope = self.callbackLookup[name])) {
  28314. callback = scope.func;
  28315. scope = scope.scope;
  28316. }
  28317. if (typeof callback === 'string') {
  28318. scope = callback.replace(/\.\w+$/, '');
  28319. scope = scope ? resolve(scope) : 0;
  28320. callback = resolve(callback);
  28321. self.callbackLookup = self.callbackLookup || {};
  28322. self.callbackLookup[name] = {
  28323. func: callback,
  28324. scope: scope
  28325. };
  28326. }
  28327. return callback.apply(scope || self, x);
  28328. };
  28329. Editor.prototype.translate = function (text) {
  28330. return I18n.translate(text);
  28331. };
  28332. Editor.prototype.getParam = function (name, defaultVal, type) {
  28333. return getParam(this, name, defaultVal, type);
  28334. };
  28335. Editor.prototype.hasPlugin = function (name, loaded) {
  28336. var hasPlugin = contains$3(getPlugins(this).split(/[ ,]/), name);
  28337. if (hasPlugin) {
  28338. return loaded ? PluginManager.get(name) !== undefined : true;
  28339. } else {
  28340. return false;
  28341. }
  28342. };
  28343. Editor.prototype.nodeChanged = function (args) {
  28344. this._nodeChangeDispatcher.nodeChanged(args);
  28345. };
  28346. Editor.prototype.addCommand = function (name, callback, scope) {
  28347. this.editorCommands.addCommand(name, callback, scope);
  28348. };
  28349. Editor.prototype.addQueryStateHandler = function (name, callback, scope) {
  28350. this.editorCommands.addQueryStateHandler(name, callback, scope);
  28351. };
  28352. Editor.prototype.addQueryValueHandler = function (name, callback, scope) {
  28353. this.editorCommands.addQueryValueHandler(name, callback, scope);
  28354. };
  28355. Editor.prototype.addShortcut = function (pattern, desc, cmdFunc, scope) {
  28356. this.shortcuts.add(pattern, desc, cmdFunc, scope);
  28357. };
  28358. Editor.prototype.execCommand = function (cmd, ui, value, args) {
  28359. return this.editorCommands.execCommand(cmd, ui, value, args);
  28360. };
  28361. Editor.prototype.queryCommandState = function (cmd) {
  28362. return this.editorCommands.queryCommandState(cmd);
  28363. };
  28364. Editor.prototype.queryCommandValue = function (cmd) {
  28365. return this.editorCommands.queryCommandValue(cmd);
  28366. };
  28367. Editor.prototype.queryCommandSupported = function (cmd) {
  28368. return this.editorCommands.queryCommandSupported(cmd);
  28369. };
  28370. Editor.prototype.show = function () {
  28371. var self = this;
  28372. if (self.hidden) {
  28373. self.hidden = false;
  28374. if (self.inline) {
  28375. self.getBody().contentEditable = 'true';
  28376. } else {
  28377. DOM$1.show(self.getContainer());
  28378. DOM$1.hide(self.id);
  28379. }
  28380. self.load();
  28381. self.fire('show');
  28382. }
  28383. };
  28384. Editor.prototype.hide = function () {
  28385. var self = this, doc = self.getDoc();
  28386. if (!self.hidden) {
  28387. if (ie && doc && !self.inline) {
  28388. doc.execCommand('SelectAll');
  28389. }
  28390. self.save();
  28391. if (self.inline) {
  28392. self.getBody().contentEditable = 'false';
  28393. if (self === self.editorManager.focusedEditor) {
  28394. self.editorManager.focusedEditor = null;
  28395. }
  28396. } else {
  28397. DOM$1.hide(self.getContainer());
  28398. DOM$1.setStyle(self.id, 'display', self.orgDisplay);
  28399. }
  28400. self.hidden = true;
  28401. self.fire('hide');
  28402. }
  28403. };
  28404. Editor.prototype.isHidden = function () {
  28405. return !!this.hidden;
  28406. };
  28407. Editor.prototype.setProgressState = function (state, time) {
  28408. this.fire('ProgressState', {
  28409. state: state,
  28410. time: time
  28411. });
  28412. };
  28413. Editor.prototype.load = function (args) {
  28414. var self = this;
  28415. var elm = self.getElement(), html;
  28416. if (self.removed) {
  28417. return '';
  28418. }
  28419. if (elm) {
  28420. args = args || {};
  28421. args.load = true;
  28422. var value = isTextareaOrInput(elm) ? elm.value : elm.innerHTML;
  28423. html = self.setContent(value, args);
  28424. args.element = elm;
  28425. if (!args.no_events) {
  28426. self.fire('LoadContent', args);
  28427. }
  28428. args.element = elm = null;
  28429. return html;
  28430. }
  28431. };
  28432. Editor.prototype.save = function (args) {
  28433. var self = this;
  28434. var elm = self.getElement(), html, form;
  28435. if (!elm || !self.initialized || self.removed) {
  28436. return;
  28437. }
  28438. args = args || {};
  28439. args.save = true;
  28440. args.element = elm;
  28441. html = args.content = self.getContent(args);
  28442. if (!args.no_events) {
  28443. self.fire('SaveContent', args);
  28444. }
  28445. if (args.format === 'raw') {
  28446. self.fire('RawSaveContent', args);
  28447. }
  28448. html = args.content;
  28449. if (!isTextareaOrInput(elm)) {
  28450. if (args.is_removing || !self.inline) {
  28451. elm.innerHTML = html;
  28452. }
  28453. if (form = DOM$1.getParent(self.id, 'form')) {
  28454. each$2(form.elements, function (elm) {
  28455. if (elm.name === self.id) {
  28456. elm.value = html;
  28457. return false;
  28458. }
  28459. });
  28460. }
  28461. } else {
  28462. elm.value = html;
  28463. }
  28464. args.element = elm = null;
  28465. if (args.set_dirty !== false) {
  28466. self.setDirty(false);
  28467. }
  28468. return html;
  28469. };
  28470. Editor.prototype.setContent = function (content, args) {
  28471. return setContent(this, content, args);
  28472. };
  28473. Editor.prototype.getContent = function (args) {
  28474. return getContent(this, args);
  28475. };
  28476. Editor.prototype.insertContent = function (content, args) {
  28477. if (args) {
  28478. content = extend$3({ content: content }, args);
  28479. }
  28480. this.execCommand('mceInsertContent', false, content);
  28481. };
  28482. Editor.prototype.resetContent = function (initialContent) {
  28483. if (initialContent === undefined) {
  28484. setContent(this, this.startContent, { format: 'raw' });
  28485. } else {
  28486. setContent(this, initialContent);
  28487. }
  28488. this.undoManager.reset();
  28489. this.setDirty(false);
  28490. this.nodeChanged();
  28491. };
  28492. Editor.prototype.isDirty = function () {
  28493. return !this.isNotDirty;
  28494. };
  28495. Editor.prototype.setDirty = function (state) {
  28496. var oldState = !this.isNotDirty;
  28497. this.isNotDirty = !state;
  28498. if (state && state !== oldState) {
  28499. this.fire('dirty');
  28500. }
  28501. };
  28502. Editor.prototype.getContainer = function () {
  28503. var self = this;
  28504. if (!self.container) {
  28505. self.container = DOM$1.get(self.editorContainer || self.id + '_parent');
  28506. }
  28507. return self.container;
  28508. };
  28509. Editor.prototype.getContentAreaContainer = function () {
  28510. return this.contentAreaContainer;
  28511. };
  28512. Editor.prototype.getElement = function () {
  28513. if (!this.targetElm) {
  28514. this.targetElm = DOM$1.get(this.id);
  28515. }
  28516. return this.targetElm;
  28517. };
  28518. Editor.prototype.getWin = function () {
  28519. var self = this;
  28520. var elm;
  28521. if (!self.contentWindow) {
  28522. elm = self.iframeElement;
  28523. if (elm) {
  28524. self.contentWindow = elm.contentWindow;
  28525. }
  28526. }
  28527. return self.contentWindow;
  28528. };
  28529. Editor.prototype.getDoc = function () {
  28530. var self = this;
  28531. var win;
  28532. if (!self.contentDocument) {
  28533. win = self.getWin();
  28534. if (win) {
  28535. self.contentDocument = win.document;
  28536. }
  28537. }
  28538. return self.contentDocument;
  28539. };
  28540. Editor.prototype.getBody = function () {
  28541. var doc = this.getDoc();
  28542. return this.bodyElement || (doc ? doc.body : null);
  28543. };
  28544. Editor.prototype.convertURL = function (url, name, elm) {
  28545. var self = this, settings = self.settings;
  28546. if (settings.urlconverter_callback) {
  28547. return self.execCallback('urlconverter_callback', url, elm, true, name);
  28548. }
  28549. if (!settings.convert_urls || elm && elm.nodeName === 'LINK' || url.indexOf('file:') === 0 || url.length === 0) {
  28550. return url;
  28551. }
  28552. if (settings.relative_urls) {
  28553. return self.documentBaseURI.toRelative(url);
  28554. }
  28555. url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host);
  28556. return url;
  28557. };
  28558. Editor.prototype.addVisual = function (elm) {
  28559. addVisual(this, elm);
  28560. };
  28561. Editor.prototype.remove = function () {
  28562. remove(this);
  28563. };
  28564. Editor.prototype.destroy = function (automatic) {
  28565. destroy(this, automatic);
  28566. };
  28567. Editor.prototype.uploadImages = function (callback) {
  28568. return this.editorUpload.uploadImages(callback);
  28569. };
  28570. Editor.prototype._scanForImages = function () {
  28571. return this.editorUpload.scanForImages();
  28572. };
  28573. Editor.prototype.addButton = function () {
  28574. 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');
  28575. };
  28576. Editor.prototype.addSidebar = function () {
  28577. throw new Error('editor.addSidebar has been removed in tinymce 5x, use editor.ui.registry.addSidebar instead');
  28578. };
  28579. Editor.prototype.addMenuItem = function () {
  28580. throw new Error('editor.addMenuItem has been removed in tinymce 5x, use editor.ui.registry.addMenuItem instead');
  28581. };
  28582. Editor.prototype.addContextToolbar = function () {
  28583. throw new Error('editor.addContextToolbar has been removed in tinymce 5x, use editor.ui.registry.addContextToolbar instead');
  28584. };
  28585. return Editor;
  28586. }();
  28587. var DOM = DOMUtils.DOM;
  28588. var explode = Tools.explode, each$1 = Tools.each, extend$2 = Tools.extend;
  28589. var instanceCounter = 0, boundGlobalEvents = false;
  28590. var beforeUnloadDelegate;
  28591. var legacyEditors = [];
  28592. var editors = [];
  28593. var isValidLegacyKey = function (id) {
  28594. return id !== 'length';
  28595. };
  28596. var globalEventDelegate = function (e) {
  28597. var type = e.type;
  28598. each$1(EditorManager.get(), function (editor) {
  28599. switch (type) {
  28600. case 'scroll':
  28601. editor.fire('ScrollWindow', e);
  28602. break;
  28603. case 'resize':
  28604. editor.fire('ResizeWindow', e);
  28605. break;
  28606. }
  28607. });
  28608. };
  28609. var toggleGlobalEvents = function (state) {
  28610. if (state !== boundGlobalEvents) {
  28611. if (state) {
  28612. DomQuery(window).on('resize scroll', globalEventDelegate);
  28613. } else {
  28614. DomQuery(window).off('resize scroll', globalEventDelegate);
  28615. }
  28616. boundGlobalEvents = state;
  28617. }
  28618. };
  28619. var removeEditorFromList = function (targetEditor) {
  28620. var oldEditors = editors;
  28621. delete legacyEditors[targetEditor.id];
  28622. for (var i = 0; i < legacyEditors.length; i++) {
  28623. if (legacyEditors[i] === targetEditor) {
  28624. legacyEditors.splice(i, 1);
  28625. break;
  28626. }
  28627. }
  28628. editors = filter$4(editors, function (editor) {
  28629. return targetEditor !== editor;
  28630. });
  28631. if (EditorManager.activeEditor === targetEditor) {
  28632. EditorManager.activeEditor = editors.length > 0 ? editors[0] : null;
  28633. }
  28634. if (EditorManager.focusedEditor === targetEditor) {
  28635. EditorManager.focusedEditor = null;
  28636. }
  28637. return oldEditors.length !== editors.length;
  28638. };
  28639. var purgeDestroyedEditor = function (editor) {
  28640. if (editor && editor.initialized && !(editor.getContainer() || editor.getBody()).parentNode) {
  28641. removeEditorFromList(editor);
  28642. editor.unbindAllNativeEvents();
  28643. editor.destroy(true);
  28644. editor.removed = true;
  28645. editor = null;
  28646. }
  28647. return editor;
  28648. };
  28649. var isQuirksMode = document.compatMode !== 'CSS1Compat';
  28650. var EditorManager = __assign(__assign({}, Observable), {
  28651. baseURI: null,
  28652. baseURL: null,
  28653. defaultSettings: {},
  28654. documentBaseURL: null,
  28655. suffix: null,
  28656. $: DomQuery,
  28657. majorVersion: '5',
  28658. minorVersion: '10.2',
  28659. releaseDate: '2021-11-17',
  28660. editors: legacyEditors,
  28661. i18n: I18n,
  28662. activeEditor: null,
  28663. focusedEditor: null,
  28664. settings: {},
  28665. setup: function () {
  28666. var self = this;
  28667. var baseURL, documentBaseURL, suffix = '';
  28668. documentBaseURL = URI.getDocumentBaseUrl(document.location);
  28669. if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
  28670. documentBaseURL = documentBaseURL.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  28671. if (!/[\/\\]$/.test(documentBaseURL)) {
  28672. documentBaseURL += '/';
  28673. }
  28674. }
  28675. var preInit = window.tinymce || window.tinyMCEPreInit;
  28676. if (preInit) {
  28677. baseURL = preInit.base || preInit.baseURL;
  28678. suffix = preInit.suffix;
  28679. } else {
  28680. var scripts = document.getElementsByTagName('script');
  28681. for (var i = 0; i < scripts.length; i++) {
  28682. var src = scripts[i].src || '';
  28683. if (src === '') {
  28684. continue;
  28685. }
  28686. var srcScript = src.substring(src.lastIndexOf('/'));
  28687. if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
  28688. if (srcScript.indexOf('.min') !== -1) {
  28689. suffix = '.min';
  28690. }
  28691. baseURL = src.substring(0, src.lastIndexOf('/'));
  28692. break;
  28693. }
  28694. }
  28695. if (!baseURL && document.currentScript) {
  28696. var src = document.currentScript.src;
  28697. if (src.indexOf('.min') !== -1) {
  28698. suffix = '.min';
  28699. }
  28700. baseURL = src.substring(0, src.lastIndexOf('/'));
  28701. }
  28702. }
  28703. self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
  28704. self.documentBaseURL = documentBaseURL;
  28705. self.baseURI = new URI(self.baseURL);
  28706. self.suffix = suffix;
  28707. setup$l(self);
  28708. },
  28709. overrideDefaults: function (defaultSettings) {
  28710. var baseUrl = defaultSettings.base_url;
  28711. if (baseUrl) {
  28712. this._setBaseUrl(baseUrl);
  28713. }
  28714. var suffix = defaultSettings.suffix;
  28715. if (defaultSettings.suffix) {
  28716. this.suffix = suffix;
  28717. }
  28718. this.defaultSettings = defaultSettings;
  28719. var pluginBaseUrls = defaultSettings.plugin_base_urls;
  28720. if (pluginBaseUrls !== undefined) {
  28721. each$j(pluginBaseUrls, function (pluginBaseUrl, pluginName) {
  28722. AddOnManager.PluginManager.urls[pluginName] = pluginBaseUrl;
  28723. });
  28724. }
  28725. },
  28726. init: function (settings) {
  28727. var self = this;
  28728. var result;
  28729. 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', ' ');
  28730. var isInvalidInlineTarget = function (settings, elm) {
  28731. return settings.inline && elm.tagName.toLowerCase() in invalidInlineTargets;
  28732. };
  28733. var createId = function (elm) {
  28734. var id = elm.id;
  28735. if (!id) {
  28736. id = get$9(elm, 'name').filter(function (name) {
  28737. return !DOM.get(name);
  28738. }).getOrThunk(DOM.uniqueId);
  28739. elm.setAttribute('id', id);
  28740. }
  28741. return id;
  28742. };
  28743. var execCallback = function (name) {
  28744. var callback = settings[name];
  28745. if (!callback) {
  28746. return;
  28747. }
  28748. return callback.apply(self, []);
  28749. };
  28750. var hasClass = function (elm, className) {
  28751. return className.constructor === RegExp ? className.test(elm.className) : DOM.hasClass(elm, className);
  28752. };
  28753. var findTargets = function (settings) {
  28754. var targets = [];
  28755. if (Env.browser.isIE() && Env.browser.version.major < 11) {
  28756. 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/');
  28757. return [];
  28758. } else if (isQuirksMode) {
  28759. initError('Failed to initialize the editor as the document is not in standards mode. ' + 'TinyMCE requires standards mode.');
  28760. return [];
  28761. }
  28762. if (settings.types) {
  28763. each$1(settings.types, function (type) {
  28764. targets = targets.concat(DOM.select(type.selector));
  28765. });
  28766. return targets;
  28767. } else if (settings.selector) {
  28768. return DOM.select(settings.selector);
  28769. } else if (settings.target) {
  28770. return [settings.target];
  28771. }
  28772. switch (settings.mode) {
  28773. case 'exact':
  28774. var l = settings.elements || '';
  28775. if (l.length > 0) {
  28776. each$1(explode(l), function (id) {
  28777. var elm = DOM.get(id);
  28778. if (elm) {
  28779. targets.push(elm);
  28780. } else {
  28781. each$1(document.forms, function (f) {
  28782. each$1(f.elements, function (e) {
  28783. if (e.name === id) {
  28784. id = 'mce_editor_' + instanceCounter++;
  28785. DOM.setAttrib(e, 'id', id);
  28786. targets.push(e);
  28787. }
  28788. });
  28789. });
  28790. }
  28791. });
  28792. }
  28793. break;
  28794. case 'textareas':
  28795. case 'specific_textareas':
  28796. each$1(DOM.select('textarea'), function (elm) {
  28797. if (settings.editor_deselector && hasClass(elm, settings.editor_deselector)) {
  28798. return;
  28799. }
  28800. if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) {
  28801. targets.push(elm);
  28802. }
  28803. });
  28804. break;
  28805. }
  28806. return targets;
  28807. };
  28808. var provideResults = function (editors) {
  28809. result = editors;
  28810. };
  28811. var initEditors = function () {
  28812. var initCount = 0;
  28813. var editors = [];
  28814. var targets;
  28815. var createEditor = function (id, settings, targetElm) {
  28816. var editor = new Editor(id, settings, self);
  28817. editors.push(editor);
  28818. editor.on('init', function () {
  28819. if (++initCount === targets.length) {
  28820. provideResults(editors);
  28821. }
  28822. });
  28823. editor.targetElm = editor.targetElm || targetElm;
  28824. editor.render();
  28825. };
  28826. DOM.unbind(window, 'ready', initEditors);
  28827. execCallback('onpageload');
  28828. targets = DomQuery.unique(findTargets(settings));
  28829. if (settings.types) {
  28830. each$1(settings.types, function (type) {
  28831. Tools.each(targets, function (elm) {
  28832. if (DOM.is(elm, type.selector)) {
  28833. createEditor(createId(elm), extend$2({}, settings, type), elm);
  28834. return false;
  28835. }
  28836. return true;
  28837. });
  28838. });
  28839. return;
  28840. }
  28841. Tools.each(targets, function (elm) {
  28842. purgeDestroyedEditor(self.get(elm.id));
  28843. });
  28844. targets = Tools.grep(targets, function (elm) {
  28845. return !self.get(elm.id);
  28846. });
  28847. if (targets.length === 0) {
  28848. provideResults([]);
  28849. } else {
  28850. each$1(targets, function (elm) {
  28851. if (isInvalidInlineTarget(settings, elm)) {
  28852. initError('Could not initialize inline editor on invalid inline target element', elm);
  28853. } else {
  28854. createEditor(createId(elm), settings, elm);
  28855. }
  28856. });
  28857. }
  28858. };
  28859. self.settings = settings;
  28860. DOM.bind(window, 'ready', initEditors);
  28861. return new promiseObj(function (resolve) {
  28862. if (result) {
  28863. resolve(result);
  28864. } else {
  28865. provideResults = function (editors) {
  28866. resolve(editors);
  28867. };
  28868. }
  28869. });
  28870. },
  28871. get: function (id) {
  28872. if (arguments.length === 0) {
  28873. return editors.slice(0);
  28874. } else if (isString$1(id)) {
  28875. return find$3(editors, function (editor) {
  28876. return editor.id === id;
  28877. }).getOr(null);
  28878. } else if (isNumber(id)) {
  28879. return editors[id] ? editors[id] : null;
  28880. } else {
  28881. return null;
  28882. }
  28883. },
  28884. add: function (editor) {
  28885. var self = this;
  28886. var existingEditor = legacyEditors[editor.id];
  28887. if (existingEditor === editor) {
  28888. return editor;
  28889. }
  28890. if (self.get(editor.id) === null) {
  28891. if (isValidLegacyKey(editor.id)) {
  28892. legacyEditors[editor.id] = editor;
  28893. }
  28894. legacyEditors.push(editor);
  28895. editors.push(editor);
  28896. }
  28897. toggleGlobalEvents(true);
  28898. self.activeEditor = editor;
  28899. self.fire('AddEditor', { editor: editor });
  28900. if (!beforeUnloadDelegate) {
  28901. beforeUnloadDelegate = function (e) {
  28902. var event = self.fire('BeforeUnload');
  28903. if (event.returnValue) {
  28904. e.preventDefault();
  28905. e.returnValue = event.returnValue;
  28906. return event.returnValue;
  28907. }
  28908. };
  28909. window.addEventListener('beforeunload', beforeUnloadDelegate);
  28910. }
  28911. return editor;
  28912. },
  28913. createEditor: function (id, settings) {
  28914. return this.add(new Editor(id, settings, this));
  28915. },
  28916. remove: function (selector) {
  28917. var self = this;
  28918. var i, editor;
  28919. if (!selector) {
  28920. for (i = editors.length - 1; i >= 0; i--) {
  28921. self.remove(editors[i]);
  28922. }
  28923. return;
  28924. }
  28925. if (isString$1(selector)) {
  28926. each$1(DOM.select(selector), function (elm) {
  28927. editor = self.get(elm.id);
  28928. if (editor) {
  28929. self.remove(editor);
  28930. }
  28931. });
  28932. return;
  28933. }
  28934. editor = selector;
  28935. if (isNull(self.get(editor.id))) {
  28936. return null;
  28937. }
  28938. if (removeEditorFromList(editor)) {
  28939. self.fire('RemoveEditor', { editor: editor });
  28940. }
  28941. if (editors.length === 0) {
  28942. window.removeEventListener('beforeunload', beforeUnloadDelegate);
  28943. }
  28944. editor.remove();
  28945. toggleGlobalEvents(editors.length > 0);
  28946. return editor;
  28947. },
  28948. execCommand: function (cmd, ui, value) {
  28949. var self = this, editor = self.get(value);
  28950. switch (cmd) {
  28951. case 'mceAddEditor':
  28952. if (!self.get(value)) {
  28953. new Editor(value, self.settings, self).render();
  28954. }
  28955. return true;
  28956. case 'mceRemoveEditor':
  28957. if (editor) {
  28958. editor.remove();
  28959. }
  28960. return true;
  28961. case 'mceToggleEditor':
  28962. if (!editor) {
  28963. self.execCommand('mceAddEditor', false, value);
  28964. return true;
  28965. }
  28966. if (editor.isHidden()) {
  28967. editor.show();
  28968. } else {
  28969. editor.hide();
  28970. }
  28971. return true;
  28972. }
  28973. if (self.activeEditor) {
  28974. return self.activeEditor.execCommand(cmd, ui, value);
  28975. }
  28976. return false;
  28977. },
  28978. triggerSave: function () {
  28979. each$1(editors, function (editor) {
  28980. editor.save();
  28981. });
  28982. },
  28983. addI18n: function (code, items) {
  28984. I18n.add(code, items);
  28985. },
  28986. translate: function (text) {
  28987. return I18n.translate(text);
  28988. },
  28989. setActive: function (editor) {
  28990. var activeEditor = this.activeEditor;
  28991. if (this.activeEditor !== editor) {
  28992. if (activeEditor) {
  28993. activeEditor.fire('deactivate', { relatedTarget: editor });
  28994. }
  28995. editor.fire('activate', { relatedTarget: activeEditor });
  28996. }
  28997. this.activeEditor = editor;
  28998. },
  28999. _setBaseUrl: function (baseUrl) {
  29000. this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ''));
  29001. this.baseURI = new URI(this.baseURL);
  29002. }
  29003. });
  29004. EditorManager.setup();
  29005. var min$1 = Math.min, max$1 = Math.max, round$1 = Math.round;
  29006. var relativePosition = function (rect, targetRect, rel) {
  29007. var x = targetRect.x;
  29008. var y = targetRect.y;
  29009. var w = rect.w;
  29010. var h = rect.h;
  29011. var targetW = targetRect.w;
  29012. var targetH = targetRect.h;
  29013. var relChars = (rel || '').split('');
  29014. if (relChars[0] === 'b') {
  29015. y += targetH;
  29016. }
  29017. if (relChars[1] === 'r') {
  29018. x += targetW;
  29019. }
  29020. if (relChars[0] === 'c') {
  29021. y += round$1(targetH / 2);
  29022. }
  29023. if (relChars[1] === 'c') {
  29024. x += round$1(targetW / 2);
  29025. }
  29026. if (relChars[3] === 'b') {
  29027. y -= h;
  29028. }
  29029. if (relChars[4] === 'r') {
  29030. x -= w;
  29031. }
  29032. if (relChars[3] === 'c') {
  29033. y -= round$1(h / 2);
  29034. }
  29035. if (relChars[4] === 'c') {
  29036. x -= round$1(w / 2);
  29037. }
  29038. return create$2(x, y, w, h);
  29039. };
  29040. var findBestRelativePosition = function (rect, targetRect, constrainRect, rels) {
  29041. var pos, i;
  29042. for (i = 0; i < rels.length; i++) {
  29043. pos = relativePosition(rect, targetRect, rels[i]);
  29044. 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) {
  29045. return rels[i];
  29046. }
  29047. }
  29048. return null;
  29049. };
  29050. var inflate = function (rect, w, h) {
  29051. return create$2(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2);
  29052. };
  29053. var intersect = function (rect, cropRect) {
  29054. var x1 = max$1(rect.x, cropRect.x);
  29055. var y1 = max$1(rect.y, cropRect.y);
  29056. var x2 = min$1(rect.x + rect.w, cropRect.x + cropRect.w);
  29057. var y2 = min$1(rect.y + rect.h, cropRect.y + cropRect.h);
  29058. if (x2 - x1 < 0 || y2 - y1 < 0) {
  29059. return null;
  29060. }
  29061. return create$2(x1, y1, x2 - x1, y2 - y1);
  29062. };
  29063. var clamp = function (rect, clampRect, fixedSize) {
  29064. var x1 = rect.x;
  29065. var y1 = rect.y;
  29066. var x2 = rect.x + rect.w;
  29067. var y2 = rect.y + rect.h;
  29068. var cx2 = clampRect.x + clampRect.w;
  29069. var cy2 = clampRect.y + clampRect.h;
  29070. var underflowX1 = max$1(0, clampRect.x - x1);
  29071. var underflowY1 = max$1(0, clampRect.y - y1);
  29072. var overflowX2 = max$1(0, x2 - cx2);
  29073. var overflowY2 = max$1(0, y2 - cy2);
  29074. x1 += underflowX1;
  29075. y1 += underflowY1;
  29076. if (fixedSize) {
  29077. x2 += underflowX1;
  29078. y2 += underflowY1;
  29079. x1 -= overflowX2;
  29080. y1 -= overflowY2;
  29081. }
  29082. x2 -= overflowX2;
  29083. y2 -= overflowY2;
  29084. return create$2(x1, y1, x2 - x1, y2 - y1);
  29085. };
  29086. var create$2 = function (x, y, w, h) {
  29087. return {
  29088. x: x,
  29089. y: y,
  29090. w: w,
  29091. h: h
  29092. };
  29093. };
  29094. var fromClientRect = function (clientRect) {
  29095. return create$2(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
  29096. };
  29097. var Rect = {
  29098. inflate: inflate,
  29099. relativePosition: relativePosition,
  29100. findBestRelativePosition: findBestRelativePosition,
  29101. intersect: intersect,
  29102. clamp: clamp,
  29103. create: create$2,
  29104. fromClientRect: fromClientRect
  29105. };
  29106. var awaiter = function (resolveCb, rejectCb, timeout) {
  29107. if (timeout === void 0) {
  29108. timeout = 1000;
  29109. }
  29110. var done = false;
  29111. var timer = null;
  29112. var complete = function (completer) {
  29113. return function () {
  29114. var args = [];
  29115. for (var _i = 0; _i < arguments.length; _i++) {
  29116. args[_i] = arguments[_i];
  29117. }
  29118. if (!done) {
  29119. done = true;
  29120. if (timer !== null) {
  29121. clearTimeout(timer);
  29122. timer = null;
  29123. }
  29124. completer.apply(null, args);
  29125. }
  29126. };
  29127. };
  29128. var resolve = complete(resolveCb);
  29129. var reject = complete(rejectCb);
  29130. var start = function () {
  29131. var args = [];
  29132. for (var _i = 0; _i < arguments.length; _i++) {
  29133. args[_i] = arguments[_i];
  29134. }
  29135. if (!done && timer === null) {
  29136. timer = setTimeout(function () {
  29137. return reject.apply(null, args);
  29138. }, timeout);
  29139. }
  29140. };
  29141. return {
  29142. start: start,
  29143. resolve: resolve,
  29144. reject: reject
  29145. };
  29146. };
  29147. var create$1 = function () {
  29148. var tasks = {};
  29149. var resultFns = {};
  29150. var load = function (id, url) {
  29151. var loadErrMsg = 'Script at URL "' + url + '" failed to load';
  29152. var runErrMsg = 'Script at URL "' + url + '" did not call `tinymce.Resource.add(\'' + id + '\', data)` within 1 second';
  29153. if (tasks[id] !== undefined) {
  29154. return tasks[id];
  29155. } else {
  29156. var task = new promiseObj(function (resolve, reject) {
  29157. var waiter = awaiter(resolve, reject);
  29158. resultFns[id] = waiter.resolve;
  29159. ScriptLoader.ScriptLoader.loadScript(url, function () {
  29160. return waiter.start(runErrMsg);
  29161. }, function () {
  29162. return waiter.reject(loadErrMsg);
  29163. });
  29164. });
  29165. tasks[id] = task;
  29166. return task;
  29167. }
  29168. };
  29169. var add = function (id, data) {
  29170. if (resultFns[id] !== undefined) {
  29171. resultFns[id](data);
  29172. delete resultFns[id];
  29173. }
  29174. tasks[id] = promiseObj.resolve(data);
  29175. };
  29176. return {
  29177. load: load,
  29178. add: add
  29179. };
  29180. };
  29181. var Resource = create$1();
  29182. var each = Tools.each, extend$1 = Tools.extend;
  29183. var extendClass, initializing;
  29184. var Class = function () {
  29185. };
  29186. Class.extend = extendClass = function (props) {
  29187. var self = this;
  29188. var _super = self.prototype;
  29189. var Class = function () {
  29190. var i, mixins, mixin;
  29191. var self = this;
  29192. if (!initializing) {
  29193. if (self.init) {
  29194. self.init.apply(self, arguments);
  29195. }
  29196. mixins = self.Mixins;
  29197. if (mixins) {
  29198. i = mixins.length;
  29199. while (i--) {
  29200. mixin = mixins[i];
  29201. if (mixin.init) {
  29202. mixin.init.apply(self, arguments);
  29203. }
  29204. }
  29205. }
  29206. }
  29207. };
  29208. var dummy = function () {
  29209. return this;
  29210. };
  29211. var createMethod = function (name, fn) {
  29212. return function () {
  29213. var self = this;
  29214. var tmp = self._super;
  29215. self._super = _super[name];
  29216. var ret = fn.apply(self, arguments);
  29217. self._super = tmp;
  29218. return ret;
  29219. };
  29220. };
  29221. initializing = true;
  29222. var prototype = new self();
  29223. initializing = false;
  29224. if (props.Mixins) {
  29225. each(props.Mixins, function (mixin) {
  29226. for (var name_1 in mixin) {
  29227. if (name_1 !== 'init') {
  29228. props[name_1] = mixin[name_1];
  29229. }
  29230. }
  29231. });
  29232. if (_super.Mixins) {
  29233. props.Mixins = _super.Mixins.concat(props.Mixins);
  29234. }
  29235. }
  29236. if (props.Methods) {
  29237. each(props.Methods.split(','), function (name) {
  29238. props[name] = dummy;
  29239. });
  29240. }
  29241. if (props.Properties) {
  29242. each(props.Properties.split(','), function (name) {
  29243. var fieldName = '_' + name;
  29244. props[name] = function (value) {
  29245. var self = this;
  29246. if (value !== undefined) {
  29247. self[fieldName] = value;
  29248. return self;
  29249. }
  29250. return self[fieldName];
  29251. };
  29252. });
  29253. }
  29254. if (props.Statics) {
  29255. each(props.Statics, function (func, name) {
  29256. Class[name] = func;
  29257. });
  29258. }
  29259. if (props.Defaults && _super.Defaults) {
  29260. props.Defaults = extend$1({}, _super.Defaults, props.Defaults);
  29261. }
  29262. each$j(props, function (member, name) {
  29263. if (typeof member === 'function' && _super[name]) {
  29264. prototype[name] = createMethod(name, member);
  29265. } else {
  29266. prototype[name] = member;
  29267. }
  29268. });
  29269. Class.prototype = prototype;
  29270. Class.constructor = Class;
  29271. Class.extend = extendClass;
  29272. return Class;
  29273. };
  29274. var min = Math.min, max = Math.max, round = Math.round;
  29275. var Color = function (value) {
  29276. var self = {};
  29277. var r = 0, g = 0, b = 0;
  29278. var rgb2hsv = function (r, g, b) {
  29279. var h, s, v;
  29280. h = 0;
  29281. s = 0;
  29282. v = 0;
  29283. r = r / 255;
  29284. g = g / 255;
  29285. b = b / 255;
  29286. var minRGB = min(r, min(g, b));
  29287. var maxRGB = max(r, max(g, b));
  29288. if (minRGB === maxRGB) {
  29289. v = minRGB;
  29290. return {
  29291. h: 0,
  29292. s: 0,
  29293. v: v * 100
  29294. };
  29295. }
  29296. var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  29297. h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  29298. h = 60 * (h - d / (maxRGB - minRGB));
  29299. s = (maxRGB - minRGB) / maxRGB;
  29300. v = maxRGB;
  29301. return {
  29302. h: round(h),
  29303. s: round(s * 100),
  29304. v: round(v * 100)
  29305. };
  29306. };
  29307. var hsvToRgb = function (hue, saturation, brightness) {
  29308. hue = (parseInt(hue, 10) || 0) % 360;
  29309. saturation = parseInt(saturation, 10) / 100;
  29310. brightness = parseInt(brightness, 10) / 100;
  29311. saturation = max(0, min(saturation, 1));
  29312. brightness = max(0, min(brightness, 1));
  29313. if (saturation === 0) {
  29314. r = g = b = round(255 * brightness);
  29315. return;
  29316. }
  29317. var side = hue / 60;
  29318. var chroma = brightness * saturation;
  29319. var x = chroma * (1 - Math.abs(side % 2 - 1));
  29320. var match = brightness - chroma;
  29321. switch (Math.floor(side)) {
  29322. case 0:
  29323. r = chroma;
  29324. g = x;
  29325. b = 0;
  29326. break;
  29327. case 1:
  29328. r = x;
  29329. g = chroma;
  29330. b = 0;
  29331. break;
  29332. case 2:
  29333. r = 0;
  29334. g = chroma;
  29335. b = x;
  29336. break;
  29337. case 3:
  29338. r = 0;
  29339. g = x;
  29340. b = chroma;
  29341. break;
  29342. case 4:
  29343. r = x;
  29344. g = 0;
  29345. b = chroma;
  29346. break;
  29347. case 5:
  29348. r = chroma;
  29349. g = 0;
  29350. b = x;
  29351. break;
  29352. default:
  29353. r = g = b = 0;
  29354. }
  29355. r = round(255 * (r + match));
  29356. g = round(255 * (g + match));
  29357. b = round(255 * (b + match));
  29358. };
  29359. var toHex = function () {
  29360. var hex = function (val) {
  29361. val = parseInt(val, 10).toString(16);
  29362. return val.length > 1 ? val : '0' + val;
  29363. };
  29364. return '#' + hex(r) + hex(g) + hex(b);
  29365. };
  29366. var toRgb = function () {
  29367. return {
  29368. r: r,
  29369. g: g,
  29370. b: b
  29371. };
  29372. };
  29373. var toHsv = function () {
  29374. return rgb2hsv(r, g, b);
  29375. };
  29376. var parse = function (value) {
  29377. var matches;
  29378. if (typeof value === 'object') {
  29379. if ('r' in value) {
  29380. r = value.r;
  29381. g = value.g;
  29382. b = value.b;
  29383. } else if ('v' in value) {
  29384. hsvToRgb(value.h, value.s, value.v);
  29385. }
  29386. } else {
  29387. if (matches = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)[^\)]*\)/gi.exec(value)) {
  29388. r = parseInt(matches[1], 10);
  29389. g = parseInt(matches[2], 10);
  29390. b = parseInt(matches[3], 10);
  29391. } else if (matches = /#([0-F]{2})([0-F]{2})([0-F]{2})/gi.exec(value)) {
  29392. r = parseInt(matches[1], 16);
  29393. g = parseInt(matches[2], 16);
  29394. b = parseInt(matches[3], 16);
  29395. } else if (matches = /#([0-F])([0-F])([0-F])/gi.exec(value)) {
  29396. r = parseInt(matches[1] + matches[1], 16);
  29397. g = parseInt(matches[2] + matches[2], 16);
  29398. b = parseInt(matches[3] + matches[3], 16);
  29399. }
  29400. }
  29401. r = r < 0 ? 0 : r > 255 ? 255 : r;
  29402. g = g < 0 ? 0 : g > 255 ? 255 : g;
  29403. b = b < 0 ? 0 : b > 255 ? 255 : b;
  29404. return self;
  29405. };
  29406. if (value) {
  29407. parse(value);
  29408. }
  29409. self.toRgb = toRgb;
  29410. self.toHsv = toHsv;
  29411. self.toHex = toHex;
  29412. self.parse = parse;
  29413. return self;
  29414. };
  29415. var serialize = function (obj) {
  29416. var data = JSON.stringify(obj);
  29417. if (!isString$1(data)) {
  29418. return data;
  29419. }
  29420. return data.replace(/[\u0080-\uFFFF]/g, function (match) {
  29421. var hexCode = match.charCodeAt(0).toString(16);
  29422. return '\\u' + '0000'.substring(hexCode.length) + hexCode;
  29423. });
  29424. };
  29425. var JSONUtils = {
  29426. serialize: serialize,
  29427. parse: function (text) {
  29428. try {
  29429. return JSON.parse(text);
  29430. } catch (ex) {
  29431. }
  29432. }
  29433. };
  29434. var JSONP = {
  29435. callbacks: {},
  29436. count: 0,
  29437. send: function (settings) {
  29438. var self = this, dom = DOMUtils.DOM, count = settings.count !== undefined ? settings.count : self.count;
  29439. var id = 'tinymce_jsonp_' + count;
  29440. self.callbacks[count] = function (json) {
  29441. dom.remove(id);
  29442. delete self.callbacks[count];
  29443. settings.callback(json);
  29444. };
  29445. dom.add(dom.doc.body, 'script', {
  29446. id: id,
  29447. src: settings.url,
  29448. type: 'text/javascript'
  29449. });
  29450. self.count++;
  29451. }
  29452. };
  29453. var XHR = __assign(__assign({}, Observable), {
  29454. send: function (settings) {
  29455. var xhr, count = 0;
  29456. var ready = function () {
  29457. if (!settings.async || xhr.readyState === 4 || count++ > 10000) {
  29458. if (settings.success && count < 10000 && xhr.status === 200) {
  29459. settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings);
  29460. } else if (settings.error) {
  29461. settings.error.call(settings.error_scope, count > 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings);
  29462. }
  29463. xhr = null;
  29464. } else {
  29465. Delay.setTimeout(ready, 10);
  29466. }
  29467. };
  29468. settings.scope = settings.scope || this;
  29469. settings.success_scope = settings.success_scope || settings.scope;
  29470. settings.error_scope = settings.error_scope || settings.scope;
  29471. settings.async = settings.async !== false;
  29472. settings.data = settings.data || '';
  29473. XHR.fire('beforeInitialize', { settings: settings });
  29474. xhr = new XMLHttpRequest();
  29475. if (xhr.overrideMimeType) {
  29476. xhr.overrideMimeType(settings.content_type);
  29477. }
  29478. xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async);
  29479. if (settings.crossDomain) {
  29480. xhr.withCredentials = true;
  29481. }
  29482. if (settings.content_type) {
  29483. xhr.setRequestHeader('Content-Type', settings.content_type);
  29484. }
  29485. if (settings.requestheaders) {
  29486. Tools.each(settings.requestheaders, function (header) {
  29487. xhr.setRequestHeader(header.key, header.value);
  29488. });
  29489. }
  29490. xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  29491. xhr = XHR.fire('beforeSend', {
  29492. xhr: xhr,
  29493. settings: settings
  29494. }).xhr;
  29495. xhr.send(settings.data);
  29496. if (!settings.async) {
  29497. return ready();
  29498. }
  29499. Delay.setTimeout(ready, 10);
  29500. }
  29501. });
  29502. var extend = Tools.extend;
  29503. var JSONRequest = function () {
  29504. function JSONRequest(settings) {
  29505. this.settings = extend({}, settings);
  29506. this.count = 0;
  29507. }
  29508. JSONRequest.sendRPC = function (o) {
  29509. return new JSONRequest().send(o);
  29510. };
  29511. JSONRequest.prototype.send = function (args) {
  29512. var ecb = args.error, scb = args.success;
  29513. var xhrArgs = extend(this.settings, args);
  29514. xhrArgs.success = function (c, x) {
  29515. c = JSONUtils.parse(c);
  29516. if (typeof c === 'undefined') {
  29517. c = { error: 'JSON Parse error.' };
  29518. }
  29519. if (c.error) {
  29520. ecb.call(xhrArgs.error_scope || xhrArgs.scope, c.error, x);
  29521. } else {
  29522. scb.call(xhrArgs.success_scope || xhrArgs.scope, c.result);
  29523. }
  29524. };
  29525. xhrArgs.error = function (ty, x) {
  29526. if (ecb) {
  29527. ecb.call(xhrArgs.error_scope || xhrArgs.scope, ty, x);
  29528. }
  29529. };
  29530. xhrArgs.data = JSONUtils.serialize({
  29531. id: args.id || 'c' + this.count++,
  29532. method: args.method,
  29533. params: args.params
  29534. });
  29535. xhrArgs.content_type = 'application/json';
  29536. XHR.send(xhrArgs);
  29537. };
  29538. return JSONRequest;
  29539. }();
  29540. var create = function () {
  29541. return function () {
  29542. var data = {};
  29543. var keys = [];
  29544. var storage = {
  29545. getItem: function (key) {
  29546. var item = data[key];
  29547. return item ? item : null;
  29548. },
  29549. setItem: function (key, value) {
  29550. keys.push(key);
  29551. data[key] = String(value);
  29552. },
  29553. key: function (index) {
  29554. return keys[index];
  29555. },
  29556. removeItem: function (key) {
  29557. keys = keys.filter(function (k) {
  29558. return k === key;
  29559. });
  29560. delete data[key];
  29561. },
  29562. clear: function () {
  29563. keys = [];
  29564. data = {};
  29565. },
  29566. length: 0
  29567. };
  29568. Object.defineProperty(storage, 'length', {
  29569. get: function () {
  29570. return keys.length;
  29571. },
  29572. configurable: false,
  29573. enumerable: false
  29574. });
  29575. return storage;
  29576. }();
  29577. };
  29578. var localStorage;
  29579. try {
  29580. var test = '__storage_test__';
  29581. localStorage = window.localStorage;
  29582. localStorage.setItem(test, test);
  29583. localStorage.removeItem(test);
  29584. } catch (e) {
  29585. localStorage = create();
  29586. }
  29587. var LocalStorage = localStorage;
  29588. var publicApi = {
  29589. geom: { Rect: Rect },
  29590. util: {
  29591. Promise: promiseObj,
  29592. Delay: Delay,
  29593. Tools: Tools,
  29594. VK: VK,
  29595. URI: URI,
  29596. Class: Class,
  29597. EventDispatcher: EventDispatcher,
  29598. Observable: Observable,
  29599. I18n: I18n,
  29600. XHR: XHR,
  29601. JSON: JSONUtils,
  29602. JSONRequest: JSONRequest,
  29603. JSONP: JSONP,
  29604. LocalStorage: LocalStorage,
  29605. Color: Color,
  29606. ImageUploader: ImageUploader
  29607. },
  29608. dom: {
  29609. EventUtils: EventUtils,
  29610. Sizzle: Sizzle,
  29611. DomQuery: DomQuery,
  29612. TreeWalker: DomTreeWalker,
  29613. TextSeeker: TextSeeker,
  29614. DOMUtils: DOMUtils,
  29615. ScriptLoader: ScriptLoader,
  29616. RangeUtils: RangeUtils,
  29617. Serializer: DomSerializer,
  29618. StyleSheetLoader: StyleSheetLoader,
  29619. ControlSelection: ControlSelection,
  29620. BookmarkManager: BookmarkManager,
  29621. Selection: EditorSelection,
  29622. Event: EventUtils.Event
  29623. },
  29624. html: {
  29625. Styles: Styles,
  29626. Entities: Entities,
  29627. Node: AstNode,
  29628. Schema: Schema,
  29629. SaxParser: SaxParser,
  29630. DomParser: DomParser,
  29631. Writer: Writer,
  29632. Serializer: HtmlSerializer
  29633. },
  29634. Env: Env,
  29635. AddOnManager: AddOnManager,
  29636. Annotator: Annotator,
  29637. Formatter: Formatter,
  29638. UndoManager: UndoManager,
  29639. EditorCommands: EditorCommands,
  29640. WindowManager: WindowManager,
  29641. NotificationManager: NotificationManager,
  29642. EditorObservable: EditorObservable,
  29643. Shortcuts: Shortcuts,
  29644. Editor: Editor,
  29645. FocusManager: FocusManager,
  29646. EditorManager: EditorManager,
  29647. DOM: DOMUtils.DOM,
  29648. ScriptLoader: ScriptLoader.ScriptLoader,
  29649. PluginManager: PluginManager,
  29650. ThemeManager: ThemeManager,
  29651. IconManager: IconManager,
  29652. Resource: Resource,
  29653. trim: Tools.trim,
  29654. isArray: Tools.isArray,
  29655. is: Tools.is,
  29656. toArray: Tools.toArray,
  29657. makeMap: Tools.makeMap,
  29658. each: Tools.each,
  29659. map: Tools.map,
  29660. grep: Tools.grep,
  29661. inArray: Tools.inArray,
  29662. extend: Tools.extend,
  29663. create: Tools.create,
  29664. walk: Tools.walk,
  29665. createNS: Tools.createNS,
  29666. resolve: Tools.resolve,
  29667. explode: Tools.explode,
  29668. _addCacheSuffix: Tools._addCacheSuffix,
  29669. isOpera: Env.opera,
  29670. isWebKit: Env.webkit,
  29671. isIE: Env.ie,
  29672. isGecko: Env.gecko,
  29673. isMac: Env.mac
  29674. };
  29675. var tinymce = Tools.extend(EditorManager, publicApi);
  29676. var exportToModuleLoaders = function (tinymce) {
  29677. if (typeof module === 'object') {
  29678. try {
  29679. module.exports = tinymce;
  29680. } catch (_) {
  29681. }
  29682. }
  29683. };
  29684. var exportToWindowGlobal = function (tinymce) {
  29685. window.tinymce = tinymce;
  29686. window.tinyMCE = tinymce;
  29687. };
  29688. exportToWindowGlobal(tinymce);
  29689. exportToModuleLoaders(tinymce);
  29690. }());