tinymce.js 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074
  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.5 (2022-05-25)
  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 createMap = function (defaultValue, extendWith) {
  3469. var value = makeMap$2(defaultValue, ' ', makeMap$2(defaultValue.toUpperCase(), ' '));
  3470. return extend$5(value, extendWith);
  3471. };
  3472. var getTextRootBlockElements = function (schema) {
  3473. return createMap('td th li dt dd figcaption caption details summary', schema.getTextBlockElements());
  3474. };
  3475. var compileSchema = function (type) {
  3476. var schema = {};
  3477. var globalAttributes, blockContent;
  3478. var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
  3479. var add = function (name, attributes, children) {
  3480. var ni, attributesOrder, element;
  3481. var arrayToMap = function (array, obj) {
  3482. var map = {};
  3483. var i, l;
  3484. for (i = 0, l = array.length; i < l; i++) {
  3485. map[array[i]] = obj || {};
  3486. }
  3487. return map;
  3488. };
  3489. children = children || [];
  3490. attributes = attributes || '';
  3491. if (typeof children === 'string') {
  3492. children = split$1(children);
  3493. }
  3494. var names = split$1(name);
  3495. ni = names.length;
  3496. while (ni--) {
  3497. attributesOrder = split$1([
  3498. globalAttributes,
  3499. attributes
  3500. ].join(' '));
  3501. element = {
  3502. attributes: arrayToMap(attributesOrder),
  3503. attributesOrder: attributesOrder,
  3504. children: arrayToMap(children, dummyObj)
  3505. };
  3506. schema[names[ni]] = element;
  3507. }
  3508. };
  3509. var addAttrs = function (name, attributes) {
  3510. var ni, schemaItem, i, l;
  3511. var names = split$1(name);
  3512. ni = names.length;
  3513. var attrs = split$1(attributes);
  3514. while (ni--) {
  3515. schemaItem = schema[names[ni]];
  3516. for (i = 0, l = attrs.length; i < l; i++) {
  3517. schemaItem.attributes[attrs[i]] = {};
  3518. schemaItem.attributesOrder.push(attrs[i]);
  3519. }
  3520. }
  3521. };
  3522. if (mapCache[type]) {
  3523. return mapCache[type];
  3524. }
  3525. globalAttributes = 'id accesskey class dir lang style tabindex title role';
  3526. blockContent = 'address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul';
  3527. 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';
  3528. if (type !== 'html4') {
  3529. globalAttributes += ' contenteditable contextmenu draggable dropzone ' + 'hidden spellcheck translate';
  3530. blockContent += ' article aside details dialog figure main header footer hgroup section nav';
  3531. phrasingContent += ' audio canvas command datalist mark meter output picture ' + 'progress time wbr video ruby bdi keygen';
  3532. }
  3533. if (type !== 'html5-strict') {
  3534. globalAttributes += ' xml:lang';
  3535. html4PhrasingContent = 'acronym applet basefont big font strike tt';
  3536. phrasingContent = [
  3537. phrasingContent,
  3538. html4PhrasingContent
  3539. ].join(' ');
  3540. each$h(split$1(html4PhrasingContent), function (name) {
  3541. add(name, '', phrasingContent);
  3542. });
  3543. html4BlockContent = 'center dir isindex noframes';
  3544. blockContent = [
  3545. blockContent,
  3546. html4BlockContent
  3547. ].join(' ');
  3548. flowContent = [
  3549. blockContent,
  3550. phrasingContent
  3551. ].join(' ');
  3552. each$h(split$1(html4BlockContent), function (name) {
  3553. add(name, '', flowContent);
  3554. });
  3555. }
  3556. flowContent = flowContent || [
  3557. blockContent,
  3558. phrasingContent
  3559. ].join(' ');
  3560. add('html', 'manifest', 'head body');
  3561. add('head', '', 'base command link meta noscript script style title');
  3562. add('title hr noscript br');
  3563. add('base', 'href target');
  3564. add('link', 'href rel media hreflang type sizes hreflang');
  3565. add('meta', 'name http-equiv content charset');
  3566. add('style', 'media type scoped');
  3567. add('script', 'src async defer type charset');
  3568. add('body', 'onafterprint onbeforeprint onbeforeunload onblur onerror onfocus ' + 'onhashchange onload onmessage onoffline ononline onpagehide onpageshow ' + 'onpopstate onresize onscroll onstorage onunload', flowContent);
  3569. add('address dt dd div caption', '', flowContent);
  3570. 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);
  3571. add('blockquote', 'cite', flowContent);
  3572. add('ol', 'reversed start type', 'li');
  3573. add('ul', '', 'li');
  3574. add('li', 'value', flowContent);
  3575. add('dl', '', 'dt dd');
  3576. add('a', 'href target rel media hreflang type', phrasingContent);
  3577. add('q', 'cite', phrasingContent);
  3578. add('ins del', 'cite datetime', flowContent);
  3579. add('img', 'src sizes srcset alt usemap ismap width height');
  3580. add('iframe', 'src name width height', flowContent);
  3581. add('embed', 'src type width height');
  3582. add('object', 'data type typemustmatch name usemap form width height', [
  3583. flowContent,
  3584. 'param'
  3585. ].join(' '));
  3586. add('param', 'name value');
  3587. add('map', 'name', [
  3588. flowContent,
  3589. 'area'
  3590. ].join(' '));
  3591. add('area', 'alt coords shape href target rel media hreflang type');
  3592. add('table', 'border', 'caption colgroup thead tfoot tbody tr' + (type === 'html4' ? ' col' : ''));
  3593. add('colgroup', 'span', 'col');
  3594. add('col', 'span');
  3595. add('tbody thead tfoot', '', 'tr');
  3596. add('tr', '', 'td th');
  3597. add('td', 'colspan rowspan headers', flowContent);
  3598. add('th', 'colspan rowspan headers scope abbr', flowContent);
  3599. add('form', 'accept-charset action autocomplete enctype method name novalidate target', flowContent);
  3600. add('fieldset', 'disabled form name', [
  3601. flowContent,
  3602. 'legend'
  3603. ].join(' '));
  3604. add('label', 'form for', phrasingContent);
  3605. 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');
  3606. add('button', 'disabled form formaction formenctype formmethod formnovalidate formtarget name type value', type === 'html4' ? flowContent : phrasingContent);
  3607. add('select', 'disabled form multiple name required size', 'option optgroup');
  3608. add('optgroup', 'disabled label', 'option');
  3609. add('option', 'disabled label selected value');
  3610. add('textarea', 'cols dirname disabled form maxlength name readonly required rows wrap');
  3611. add('menu', 'type label', [
  3612. flowContent,
  3613. 'li'
  3614. ].join(' '));
  3615. add('noscript', '', flowContent);
  3616. if (type !== 'html4') {
  3617. add('wbr');
  3618. add('ruby', '', [
  3619. phrasingContent,
  3620. 'rt rp'
  3621. ].join(' '));
  3622. add('figcaption', '', flowContent);
  3623. add('mark rt rp summary bdi', '', phrasingContent);
  3624. add('canvas', 'width height', flowContent);
  3625. add('video', 'src crossorigin poster preload autoplay mediagroup loop ' + 'muted controls width height buffered', [
  3626. flowContent,
  3627. 'track source'
  3628. ].join(' '));
  3629. add('audio', 'src crossorigin preload autoplay mediagroup loop muted controls ' + 'buffered volume', [
  3630. flowContent,
  3631. 'track source'
  3632. ].join(' '));
  3633. add('picture', '', 'img source');
  3634. add('source', 'src srcset type media sizes');
  3635. add('track', 'kind src srclang label default');
  3636. add('datalist', '', [
  3637. phrasingContent,
  3638. 'option'
  3639. ].join(' '));
  3640. add('article section nav aside main header footer', '', flowContent);
  3641. add('hgroup', '', 'h1 h2 h3 h4 h5 h6');
  3642. add('figure', '', [
  3643. flowContent,
  3644. 'figcaption'
  3645. ].join(' '));
  3646. add('time', 'datetime', phrasingContent);
  3647. add('dialog', 'open', flowContent);
  3648. add('command', 'type label icon disabled checked radiogroup command');
  3649. add('output', 'for form name', phrasingContent);
  3650. add('progress', 'value max', phrasingContent);
  3651. add('meter', 'value min max low high optimum', phrasingContent);
  3652. add('details', 'open', [
  3653. flowContent,
  3654. 'summary'
  3655. ].join(' '));
  3656. add('keygen', 'autofocus challenge disabled form keytype name');
  3657. }
  3658. if (type !== 'html5-strict') {
  3659. addAttrs('script', 'language xml:space');
  3660. addAttrs('style', 'xml:space');
  3661. addAttrs('object', 'declare classid code codebase codetype archive standby align border hspace vspace');
  3662. addAttrs('embed', 'align name hspace vspace');
  3663. addAttrs('param', 'valuetype type');
  3664. addAttrs('a', 'charset name rev shape coords');
  3665. addAttrs('br', 'clear');
  3666. addAttrs('applet', 'codebase archive code object alt name width height align hspace vspace');
  3667. addAttrs('img', 'name longdesc align border hspace vspace');
  3668. addAttrs('iframe', 'longdesc frameborder marginwidth marginheight scrolling align');
  3669. addAttrs('font basefont', 'size color face');
  3670. addAttrs('input', 'usemap align');
  3671. addAttrs('select');
  3672. addAttrs('textarea');
  3673. addAttrs('h1 h2 h3 h4 h5 h6 div p legend caption', 'align');
  3674. addAttrs('ul', 'type compact');
  3675. addAttrs('li', 'type');
  3676. addAttrs('ol dl menu dir', 'compact');
  3677. addAttrs('pre', 'width xml:space');
  3678. addAttrs('hr', 'align noshade size width');
  3679. addAttrs('isindex', 'prompt');
  3680. addAttrs('table', 'summary width frame rules cellspacing cellpadding align bgcolor');
  3681. addAttrs('col', 'width align char charoff valign');
  3682. addAttrs('colgroup', 'width align char charoff valign');
  3683. addAttrs('thead', 'align char charoff valign');
  3684. addAttrs('tr', 'align char charoff valign bgcolor');
  3685. addAttrs('th', 'axis align char charoff valign nowrap bgcolor width height');
  3686. addAttrs('form', 'accept');
  3687. addAttrs('td', 'abbr axis scope align char charoff valign nowrap bgcolor width height');
  3688. addAttrs('tfoot', 'align char charoff valign');
  3689. addAttrs('tbody', 'align char charoff valign');
  3690. addAttrs('area', 'nohref');
  3691. addAttrs('body', 'background bgcolor text link vlink alink');
  3692. }
  3693. if (type !== 'html4') {
  3694. addAttrs('input button select textarea', 'autofocus');
  3695. addAttrs('input textarea', 'placeholder');
  3696. addAttrs('a', 'download');
  3697. addAttrs('link script img', 'crossorigin');
  3698. addAttrs('img', 'loading');
  3699. addAttrs('iframe', 'sandbox seamless allowfullscreen loading');
  3700. }
  3701. each$h(split$1('a form meter progress dfn'), function (name) {
  3702. if (schema[name]) {
  3703. delete schema[name].children[name];
  3704. }
  3705. });
  3706. delete schema.caption.children.table;
  3707. delete schema.script;
  3708. mapCache[type] = schema;
  3709. return schema;
  3710. };
  3711. var compileElementMap = function (value, mode) {
  3712. var styles;
  3713. if (value) {
  3714. styles = {};
  3715. if (typeof value === 'string') {
  3716. value = { '*': value };
  3717. }
  3718. each$h(value, function (value, key) {
  3719. styles[key] = styles[key.toUpperCase()] = mode === 'map' ? makeMap$2(value, /[, ]/) : explode$3(value, /[, ]/);
  3720. });
  3721. }
  3722. return styles;
  3723. };
  3724. var Schema = function (settings) {
  3725. var elements = {};
  3726. var children = {};
  3727. var patternElements = [];
  3728. var customElementsMap = {}, specialElements = {};
  3729. var createLookupTable = function (option, defaultValue, extendWith) {
  3730. var value = settings[option];
  3731. if (!value) {
  3732. value = mapCache[option];
  3733. if (!value) {
  3734. value = createMap(defaultValue, extendWith);
  3735. mapCache[option] = value;
  3736. }
  3737. } else {
  3738. value = makeMap$2(value, /[, ]/, makeMap$2(value.toUpperCase(), /[, ]/));
  3739. }
  3740. return value;
  3741. };
  3742. settings = settings || {};
  3743. var schemaItems = compileSchema(settings.schema);
  3744. if (settings.verify_html === false) {
  3745. settings.valid_elements = '*[*]';
  3746. }
  3747. var validStyles = compileElementMap(settings.valid_styles);
  3748. var invalidStyles = compileElementMap(settings.invalid_styles, 'map');
  3749. var validClasses = compileElementMap(settings.valid_classes, 'map');
  3750. var whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object code');
  3751. var selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
  3752. var shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link ' + 'meta param embed source wbr track');
  3753. var boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + 'noshade nowrap readonly selected autoplay loop controls');
  3754. var nonEmptyOrMoveCaretBeforeOnEnter = 'td th iframe video audio object script code';
  3755. var nonEmptyElementsMap = createLookupTable('non_empty_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' pre', shortEndedElementsMap);
  3756. var moveCaretBeforeOnEnterElementsMap = createLookupTable('move_caret_before_on_enter_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' table', shortEndedElementsMap);
  3757. 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');
  3758. 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);
  3759. var textInlineElementsMap = createLookupTable('text_inline_elements', 'span strong b em i font s strike u var cite ' + 'dfn code mark q sup sub samp');
  3760. each$h((settings.special || 'script noscript iframe noframes noembed title style textarea xmp').split(' '), function (name) {
  3761. specialElements[name] = new RegExp('</' + name + '[^>]*>', 'gi');
  3762. });
  3763. var patternToRegExp = function (str) {
  3764. return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
  3765. };
  3766. var addValidElements = function (validElements) {
  3767. var ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, value;
  3768. var elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/, attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/;
  3769. if (validElements) {
  3770. var validElementsArr = split$1(validElements, ',');
  3771. if (elements['@']) {
  3772. globalAttributes = elements['@'].attributes;
  3773. globalAttributesOrder = elements['@'].attributesOrder;
  3774. }
  3775. for (ei = 0, el = validElementsArr.length; ei < el; ei++) {
  3776. matches = elementRuleRegExp.exec(validElementsArr[ei]);
  3777. if (matches) {
  3778. prefix = matches[1];
  3779. elementName = matches[2];
  3780. outputName = matches[3];
  3781. attrData = matches[5];
  3782. attributes = {};
  3783. attributesOrder = [];
  3784. element = {
  3785. attributes: attributes,
  3786. attributesOrder: attributesOrder
  3787. };
  3788. if (prefix === '#') {
  3789. element.paddEmpty = true;
  3790. }
  3791. if (prefix === '-') {
  3792. element.removeEmpty = true;
  3793. }
  3794. if (matches[4] === '!') {
  3795. element.removeEmptyAttrs = true;
  3796. }
  3797. if (globalAttributes) {
  3798. each$j(globalAttributes, function (value, key) {
  3799. attributes[key] = value;
  3800. });
  3801. attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
  3802. }
  3803. if (attrData) {
  3804. attrData = split$1(attrData, '|');
  3805. for (ai = 0, al = attrData.length; ai < al; ai++) {
  3806. matches = attrRuleRegExp.exec(attrData[ai]);
  3807. if (matches) {
  3808. attr = {};
  3809. attrType = matches[1];
  3810. attrName = matches[2].replace(/[\\:]:/g, ':');
  3811. prefix = matches[3];
  3812. value = matches[4];
  3813. if (attrType === '!') {
  3814. element.attributesRequired = element.attributesRequired || [];
  3815. element.attributesRequired.push(attrName);
  3816. attr.required = true;
  3817. }
  3818. if (attrType === '-') {
  3819. delete attributes[attrName];
  3820. attributesOrder.splice(inArray$2(attributesOrder, attrName), 1);
  3821. continue;
  3822. }
  3823. if (prefix) {
  3824. if (prefix === '=') {
  3825. element.attributesDefault = element.attributesDefault || [];
  3826. element.attributesDefault.push({
  3827. name: attrName,
  3828. value: value
  3829. });
  3830. attr.defaultValue = value;
  3831. }
  3832. if (prefix === ':') {
  3833. element.attributesForced = element.attributesForced || [];
  3834. element.attributesForced.push({
  3835. name: attrName,
  3836. value: value
  3837. });
  3838. attr.forcedValue = value;
  3839. }
  3840. if (prefix === '<') {
  3841. attr.validValues = makeMap$2(value, '?');
  3842. }
  3843. }
  3844. if (hasPatternsRegExp.test(attrName)) {
  3845. element.attributePatterns = element.attributePatterns || [];
  3846. attr.pattern = patternToRegExp(attrName);
  3847. element.attributePatterns.push(attr);
  3848. } else {
  3849. if (!attributes[attrName]) {
  3850. attributesOrder.push(attrName);
  3851. }
  3852. attributes[attrName] = attr;
  3853. }
  3854. }
  3855. }
  3856. }
  3857. if (!globalAttributes && elementName === '@') {
  3858. globalAttributes = attributes;
  3859. globalAttributesOrder = attributesOrder;
  3860. }
  3861. if (outputName) {
  3862. element.outputName = elementName;
  3863. elements[outputName] = element;
  3864. }
  3865. if (hasPatternsRegExp.test(elementName)) {
  3866. element.pattern = patternToRegExp(elementName);
  3867. patternElements.push(element);
  3868. } else {
  3869. elements[elementName] = element;
  3870. }
  3871. }
  3872. }
  3873. }
  3874. };
  3875. var setValidElements = function (validElements) {
  3876. elements = {};
  3877. patternElements = [];
  3878. addValidElements(validElements);
  3879. each$h(schemaItems, function (element, name) {
  3880. children[name] = element.children;
  3881. });
  3882. };
  3883. var addCustomElements = function (customElements) {
  3884. var customElementRegExp = /^(~)?(.+)$/;
  3885. if (customElements) {
  3886. mapCache.text_block_elements = mapCache.block_elements = null;
  3887. each$h(split$1(customElements, ','), function (rule) {
  3888. var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2];
  3889. children[name] = children[cloneName];
  3890. customElementsMap[name] = cloneName;
  3891. if (!inline) {
  3892. blockElementsMap[name.toUpperCase()] = {};
  3893. blockElementsMap[name] = {};
  3894. }
  3895. if (!elements[name]) {
  3896. var customRule = elements[cloneName];
  3897. customRule = extend$5({}, customRule);
  3898. delete customRule.removeEmptyAttrs;
  3899. delete customRule.removeEmpty;
  3900. elements[name] = customRule;
  3901. }
  3902. each$h(children, function (element, elmName) {
  3903. if (element[cloneName]) {
  3904. children[elmName] = element = extend$5({}, children[elmName]);
  3905. element[name] = element[cloneName];
  3906. }
  3907. });
  3908. });
  3909. }
  3910. };
  3911. var addValidChildren = function (validChildren) {
  3912. 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]+)\[([^\]]+)]$/;
  3913. mapCache[settings.schema] = null;
  3914. if (validChildren) {
  3915. each$h(split$1(validChildren, ','), function (rule) {
  3916. var matches = childRuleRegExp.exec(rule);
  3917. var parent, prefix;
  3918. if (matches) {
  3919. prefix = matches[1];
  3920. if (prefix) {
  3921. parent = children[matches[2]];
  3922. } else {
  3923. parent = children[matches[2]] = { '#comment': {} };
  3924. }
  3925. parent = children[matches[2]];
  3926. each$h(split$1(matches[3], '|'), function (child) {
  3927. if (prefix === '-') {
  3928. delete parent[child];
  3929. } else {
  3930. parent[child] = {};
  3931. }
  3932. });
  3933. }
  3934. });
  3935. }
  3936. };
  3937. var getElementRule = function (name) {
  3938. var element = elements[name], i;
  3939. if (element) {
  3940. return element;
  3941. }
  3942. i = patternElements.length;
  3943. while (i--) {
  3944. element = patternElements[i];
  3945. if (element.pattern.test(name)) {
  3946. return element;
  3947. }
  3948. }
  3949. };
  3950. if (!settings.valid_elements) {
  3951. each$h(schemaItems, function (element, name) {
  3952. elements[name] = {
  3953. attributes: element.attributes,
  3954. attributesOrder: element.attributesOrder
  3955. };
  3956. children[name] = element.children;
  3957. });
  3958. if (settings.schema !== 'html5') {
  3959. each$h(split$1('strong/b em/i'), function (item) {
  3960. var items = split$1(item, '/');
  3961. elements[items[1]].outputName = items[0];
  3962. });
  3963. }
  3964. each$h(textInlineElementsMap, function (_val, name) {
  3965. if (elements[name]) {
  3966. if (settings.padd_empty_block_inline_children) {
  3967. elements[name].paddInEmptyBlock = true;
  3968. }
  3969. elements[name].removeEmpty = true;
  3970. }
  3971. });
  3972. each$h(split$1('ol ul blockquote a table tbody'), function (name) {
  3973. if (elements[name]) {
  3974. elements[name].removeEmpty = true;
  3975. }
  3976. });
  3977. each$h(split$1('p h1 h2 h3 h4 h5 h6 th td pre div address caption li'), function (name) {
  3978. elements[name].paddEmpty = true;
  3979. });
  3980. each$h(split$1('span'), function (name) {
  3981. elements[name].removeEmptyAttrs = true;
  3982. });
  3983. } else {
  3984. setValidElements(settings.valid_elements);
  3985. }
  3986. addCustomElements(settings.custom_elements);
  3987. addValidChildren(settings.valid_children);
  3988. addValidElements(settings.extended_valid_elements);
  3989. addValidChildren('+ol[ul|ol],+ul[ul|ol]');
  3990. each$h({
  3991. dd: 'dl',
  3992. dt: 'dl',
  3993. li: 'ul ol',
  3994. td: 'tr',
  3995. th: 'tr',
  3996. tr: 'tbody thead tfoot',
  3997. tbody: 'table',
  3998. thead: 'table',
  3999. tfoot: 'table',
  4000. legend: 'fieldset',
  4001. area: 'map',
  4002. param: 'video audio object'
  4003. }, function (parents, item) {
  4004. if (elements[item]) {
  4005. elements[item].parentsRequired = split$1(parents);
  4006. }
  4007. });
  4008. if (settings.invalid_elements) {
  4009. each$h(explode$3(settings.invalid_elements), function (item) {
  4010. if (elements[item]) {
  4011. delete elements[item];
  4012. }
  4013. });
  4014. }
  4015. if (!getElementRule('span')) {
  4016. addValidElements('span[!data-mce-type|*]');
  4017. }
  4018. var getValidStyles = constant(validStyles);
  4019. var getInvalidStyles = constant(invalidStyles);
  4020. var getValidClasses = constant(validClasses);
  4021. var getBoolAttrs = constant(boolAttrMap);
  4022. var getBlockElements = constant(blockElementsMap);
  4023. var getTextBlockElements = constant(textBlockElementsMap);
  4024. var getTextInlineElements = constant(textInlineElementsMap);
  4025. var getShortEndedElements = constant(shortEndedElementsMap);
  4026. var getSelfClosingElements = constant(selfClosingElementsMap);
  4027. var getNonEmptyElements = constant(nonEmptyElementsMap);
  4028. var getMoveCaretBeforeOnEnterElements = constant(moveCaretBeforeOnEnterElementsMap);
  4029. var getWhiteSpaceElements = constant(whiteSpaceElementsMap);
  4030. var getSpecialElements = constant(specialElements);
  4031. var isValidChild = function (name, child) {
  4032. var parent = children[name.toLowerCase()];
  4033. return !!(parent && parent[child.toLowerCase()]);
  4034. };
  4035. var isValid = function (name, attr) {
  4036. var attrPatterns, i;
  4037. var rule = getElementRule(name);
  4038. if (rule) {
  4039. if (attr) {
  4040. if (rule.attributes[attr]) {
  4041. return true;
  4042. }
  4043. attrPatterns = rule.attributePatterns;
  4044. if (attrPatterns) {
  4045. i = attrPatterns.length;
  4046. while (i--) {
  4047. if (attrPatterns[i].pattern.test(name)) {
  4048. return true;
  4049. }
  4050. }
  4051. }
  4052. } else {
  4053. return true;
  4054. }
  4055. }
  4056. return false;
  4057. };
  4058. var getCustomElements = constant(customElementsMap);
  4059. return {
  4060. children: children,
  4061. elements: elements,
  4062. getValidStyles: getValidStyles,
  4063. getValidClasses: getValidClasses,
  4064. getBlockElements: getBlockElements,
  4065. getInvalidStyles: getInvalidStyles,
  4066. getShortEndedElements: getShortEndedElements,
  4067. getTextBlockElements: getTextBlockElements,
  4068. getTextInlineElements: getTextInlineElements,
  4069. getBoolAttrs: getBoolAttrs,
  4070. getElementRule: getElementRule,
  4071. getSelfClosingElements: getSelfClosingElements,
  4072. getNonEmptyElements: getNonEmptyElements,
  4073. getMoveCaretBeforeOnEnterElements: getMoveCaretBeforeOnEnterElements,
  4074. getWhiteSpaceElements: getWhiteSpaceElements,
  4075. getSpecialElements: getSpecialElements,
  4076. isValidChild: isValidChild,
  4077. isValid: isValid,
  4078. getCustomElements: getCustomElements,
  4079. addValidElements: addValidElements,
  4080. setValidElements: setValidElements,
  4081. addCustomElements: addCustomElements,
  4082. addValidChildren: addValidChildren
  4083. };
  4084. };
  4085. var toHex = function (match, r, g, b) {
  4086. var hex = function (val) {
  4087. val = parseInt(val, 10).toString(16);
  4088. return val.length > 1 ? val : '0' + val;
  4089. };
  4090. return '#' + hex(r) + hex(g) + hex(b);
  4091. };
  4092. var Styles = function (settings, schema) {
  4093. var _this = this;
  4094. var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
  4095. var urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
  4096. var styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
  4097. var trimRightRegExp = /\s+$/;
  4098. var i;
  4099. var encodingLookup = {};
  4100. var validStyles;
  4101. var invalidStyles;
  4102. var invisibleChar = zeroWidth;
  4103. settings = settings || {};
  4104. if (schema) {
  4105. validStyles = schema.getValidStyles();
  4106. invalidStyles = schema.getInvalidStyles();
  4107. }
  4108. var encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' ');
  4109. for (i = 0; i < encodingItems.length; i++) {
  4110. encodingLookup[encodingItems[i]] = invisibleChar + i;
  4111. encodingLookup[invisibleChar + i] = encodingItems[i];
  4112. }
  4113. return {
  4114. toHex: function (color) {
  4115. return color.replace(rgbRegExp, toHex);
  4116. },
  4117. parse: function (css) {
  4118. var styles = {};
  4119. var matches, name, value, isEncoded;
  4120. var urlConverter = settings.url_converter;
  4121. var urlConverterScope = settings.url_converter_scope || _this;
  4122. var compress = function (prefix, suffix, noJoin) {
  4123. var top = styles[prefix + '-top' + suffix];
  4124. if (!top) {
  4125. return;
  4126. }
  4127. var right = styles[prefix + '-right' + suffix];
  4128. if (!right) {
  4129. return;
  4130. }
  4131. var bottom = styles[prefix + '-bottom' + suffix];
  4132. if (!bottom) {
  4133. return;
  4134. }
  4135. var left = styles[prefix + '-left' + suffix];
  4136. if (!left) {
  4137. return;
  4138. }
  4139. var box = [
  4140. top,
  4141. right,
  4142. bottom,
  4143. left
  4144. ];
  4145. i = box.length - 1;
  4146. while (i--) {
  4147. if (box[i] !== box[i + 1]) {
  4148. break;
  4149. }
  4150. }
  4151. if (i > -1 && noJoin) {
  4152. return;
  4153. }
  4154. styles[prefix + suffix] = i === -1 ? box[0] : box.join(' ');
  4155. delete styles[prefix + '-top' + suffix];
  4156. delete styles[prefix + '-right' + suffix];
  4157. delete styles[prefix + '-bottom' + suffix];
  4158. delete styles[prefix + '-left' + suffix];
  4159. };
  4160. var canCompress = function (key) {
  4161. var value = styles[key], i;
  4162. if (!value) {
  4163. return;
  4164. }
  4165. value = value.split(' ');
  4166. i = value.length;
  4167. while (i--) {
  4168. if (value[i] !== value[0]) {
  4169. return false;
  4170. }
  4171. }
  4172. styles[key] = value[0];
  4173. return true;
  4174. };
  4175. var compress2 = function (target, a, b, c) {
  4176. if (!canCompress(a)) {
  4177. return;
  4178. }
  4179. if (!canCompress(b)) {
  4180. return;
  4181. }
  4182. if (!canCompress(c)) {
  4183. return;
  4184. }
  4185. styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
  4186. delete styles[a];
  4187. delete styles[b];
  4188. delete styles[c];
  4189. };
  4190. var encode = function (str) {
  4191. isEncoded = true;
  4192. return encodingLookup[str];
  4193. };
  4194. var decode = function (str, keepSlashes) {
  4195. if (isEncoded) {
  4196. str = str.replace(/\uFEFF[0-9]/g, function (str) {
  4197. return encodingLookup[str];
  4198. });
  4199. }
  4200. if (!keepSlashes) {
  4201. str = str.replace(/\\([\'\";:])/g, '$1');
  4202. }
  4203. return str;
  4204. };
  4205. var decodeSingleHexSequence = function (escSeq) {
  4206. return String.fromCharCode(parseInt(escSeq.slice(1), 16));
  4207. };
  4208. var decodeHexSequences = function (value) {
  4209. return value.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
  4210. };
  4211. var processUrl = function (match, url, url2, url3, str, str2) {
  4212. str = str || str2;
  4213. if (str) {
  4214. str = decode(str);
  4215. return '\'' + str.replace(/\'/g, '\\\'') + '\'';
  4216. }
  4217. url = decode(url || url2 || url3);
  4218. if (!settings.allow_script_urls) {
  4219. var scriptUrl = url.replace(/[\s\r\n]+/g, '');
  4220. if (/(java|vb)script:/i.test(scriptUrl)) {
  4221. return '';
  4222. }
  4223. if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
  4224. return '';
  4225. }
  4226. }
  4227. if (urlConverter) {
  4228. url = urlConverter.call(urlConverterScope, url, 'style');
  4229. }
  4230. return 'url(\'' + url.replace(/\'/g, '\\\'') + '\')';
  4231. };
  4232. if (css) {
  4233. css = css.replace(/[\u0000-\u001F]/g, '');
  4234. css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function (str) {
  4235. return str.replace(/[;:]/g, encode);
  4236. });
  4237. while (matches = styleRegExp.exec(css)) {
  4238. styleRegExp.lastIndex = matches.index + matches[0].length;
  4239. name = matches[1].replace(trimRightRegExp, '').toLowerCase();
  4240. value = matches[2].replace(trimRightRegExp, '');
  4241. if (name && value) {
  4242. name = decodeHexSequences(name);
  4243. value = decodeHexSequences(value);
  4244. if (name.indexOf(invisibleChar) !== -1 || name.indexOf('"') !== -1) {
  4245. continue;
  4246. }
  4247. if (!settings.allow_script_urls && (name === 'behavior' || /expression\s*\(|\/\*|\*\//.test(value))) {
  4248. continue;
  4249. }
  4250. if (name === 'font-weight' && value === '700') {
  4251. value = 'bold';
  4252. } else if (name === 'color' || name === 'background-color') {
  4253. value = value.toLowerCase();
  4254. }
  4255. value = value.replace(rgbRegExp, toHex);
  4256. value = value.replace(urlOrStrRegExp, processUrl);
  4257. styles[name] = isEncoded ? decode(value, true) : value;
  4258. }
  4259. }
  4260. compress('border', '', true);
  4261. compress('border', '-width');
  4262. compress('border', '-color');
  4263. compress('border', '-style');
  4264. compress('padding', '');
  4265. compress('margin', '');
  4266. compress2('border', 'border-width', 'border-style', 'border-color');
  4267. if (styles.border === 'medium none') {
  4268. delete styles.border;
  4269. }
  4270. if (styles['border-image'] === 'none') {
  4271. delete styles['border-image'];
  4272. }
  4273. }
  4274. return styles;
  4275. },
  4276. serialize: function (styles, elementName) {
  4277. var css = '';
  4278. var serializeStyles = function (name) {
  4279. var value;
  4280. var styleList = validStyles[name];
  4281. if (styleList) {
  4282. for (var i_1 = 0, l = styleList.length; i_1 < l; i_1++) {
  4283. name = styleList[i_1];
  4284. value = styles[name];
  4285. if (value) {
  4286. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4287. }
  4288. }
  4289. }
  4290. };
  4291. var isValid = function (name, elementName) {
  4292. var styleMap = invalidStyles['*'];
  4293. if (styleMap && styleMap[name]) {
  4294. return false;
  4295. }
  4296. styleMap = invalidStyles[elementName];
  4297. return !(styleMap && styleMap[name]);
  4298. };
  4299. if (elementName && validStyles) {
  4300. serializeStyles('*');
  4301. serializeStyles(elementName);
  4302. } else {
  4303. each$j(styles, function (value, name) {
  4304. if (value && (!invalidStyles || isValid(name, elementName))) {
  4305. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4306. }
  4307. });
  4308. }
  4309. return css;
  4310. }
  4311. };
  4312. };
  4313. var deprecated = {
  4314. keyLocation: true,
  4315. layerX: true,
  4316. layerY: true,
  4317. returnValue: true,
  4318. webkitMovementX: true,
  4319. webkitMovementY: true,
  4320. keyIdentifier: true,
  4321. mozPressure: true
  4322. };
  4323. var isNativeEvent = function (event) {
  4324. return event instanceof Event || isFunction(event.initEvent);
  4325. };
  4326. var hasIsDefaultPrevented = function (event) {
  4327. return event.isDefaultPrevented === always || event.isDefaultPrevented === never;
  4328. };
  4329. var needsNormalizing = function (event) {
  4330. return isNullable(event.preventDefault) || isNativeEvent(event);
  4331. };
  4332. var clone$2 = function (originalEvent, data) {
  4333. var event = data !== null && data !== void 0 ? data : {};
  4334. for (var name_1 in originalEvent) {
  4335. if (!has$2(deprecated, name_1)) {
  4336. event[name_1] = originalEvent[name_1];
  4337. }
  4338. }
  4339. if (isNonNullable(event.composedPath)) {
  4340. event.composedPath = function () {
  4341. return originalEvent.composedPath();
  4342. };
  4343. }
  4344. return event;
  4345. };
  4346. var normalize$3 = function (type, originalEvent, fallbackTarget, data) {
  4347. var _a;
  4348. var event = clone$2(originalEvent, data);
  4349. event.type = type;
  4350. if (isNullable(event.target)) {
  4351. event.target = (_a = event.srcElement) !== null && _a !== void 0 ? _a : fallbackTarget;
  4352. }
  4353. if (needsNormalizing(originalEvent)) {
  4354. event.preventDefault = function () {
  4355. event.defaultPrevented = true;
  4356. event.isDefaultPrevented = always;
  4357. if (isFunction(originalEvent.preventDefault)) {
  4358. originalEvent.preventDefault();
  4359. } else if (isNativeEvent(originalEvent)) {
  4360. originalEvent.returnValue = false;
  4361. }
  4362. };
  4363. event.stopPropagation = function () {
  4364. event.cancelBubble = true;
  4365. event.isPropagationStopped = always;
  4366. if (isFunction(originalEvent.stopPropagation)) {
  4367. originalEvent.stopPropagation();
  4368. } else if (isNativeEvent(originalEvent)) {
  4369. originalEvent.cancelBubble = true;
  4370. }
  4371. };
  4372. event.stopImmediatePropagation = function () {
  4373. event.isImmediatePropagationStopped = always;
  4374. event.stopPropagation();
  4375. };
  4376. if (!hasIsDefaultPrevented(event)) {
  4377. event.isDefaultPrevented = event.defaultPrevented === true ? always : never;
  4378. event.isPropagationStopped = event.cancelBubble === true ? always : never;
  4379. event.isImmediatePropagationStopped = never;
  4380. }
  4381. }
  4382. return event;
  4383. };
  4384. var eventExpandoPrefix = 'mce-data-';
  4385. var mouseEventRe = /^(?:mouse|contextmenu)|click/;
  4386. var addEvent = function (target, name, callback, capture) {
  4387. if (target.addEventListener) {
  4388. target.addEventListener(name, callback, capture || false);
  4389. } else if (target.attachEvent) {
  4390. target.attachEvent('on' + name, callback);
  4391. }
  4392. };
  4393. var removeEvent = function (target, name, callback, capture) {
  4394. if (target.removeEventListener) {
  4395. target.removeEventListener(name, callback, capture || false);
  4396. } else if (target.detachEvent) {
  4397. target.detachEvent('on' + name, callback);
  4398. }
  4399. };
  4400. var isMouseEvent = function (event) {
  4401. return isNonNullable(event) && mouseEventRe.test(event.type);
  4402. };
  4403. var fix = function (originalEvent, data) {
  4404. var event = normalize$3(originalEvent.type, originalEvent, document, data);
  4405. if (isMouseEvent(originalEvent) && isUndefined(originalEvent.pageX) && !isUndefined(originalEvent.clientX)) {
  4406. var eventDoc = event.target.ownerDocument || document;
  4407. var doc = eventDoc.documentElement;
  4408. var body = eventDoc.body;
  4409. var mouseEvent = event;
  4410. mouseEvent.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  4411. mouseEvent.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  4412. }
  4413. if (isUndefined(event.metaKey)) {
  4414. event.metaKey = false;
  4415. }
  4416. return event;
  4417. };
  4418. var bindOnReady = function (win, callback, eventUtils) {
  4419. var doc = win.document, event = { type: 'ready' };
  4420. if (eventUtils.domLoaded) {
  4421. callback(event);
  4422. return;
  4423. }
  4424. var isDocReady = function () {
  4425. return doc.readyState === 'complete' || doc.readyState === 'interactive' && doc.body;
  4426. };
  4427. var readyHandler = function () {
  4428. removeEvent(win, 'DOMContentLoaded', readyHandler);
  4429. removeEvent(win, 'load', readyHandler);
  4430. if (!eventUtils.domLoaded) {
  4431. eventUtils.domLoaded = true;
  4432. callback(event);
  4433. }
  4434. win = null;
  4435. };
  4436. if (isDocReady()) {
  4437. readyHandler();
  4438. } else {
  4439. addEvent(win, 'DOMContentLoaded', readyHandler);
  4440. }
  4441. if (!eventUtils.domLoaded) {
  4442. addEvent(win, 'load', readyHandler);
  4443. }
  4444. };
  4445. var EventUtils = function () {
  4446. function EventUtils() {
  4447. this.domLoaded = false;
  4448. this.events = {};
  4449. this.count = 1;
  4450. this.expando = eventExpandoPrefix + (+new Date()).toString(32);
  4451. this.hasMouseEnterLeave = 'onmouseenter' in document.documentElement;
  4452. this.hasFocusIn = 'onfocusin' in document.documentElement;
  4453. this.count = 1;
  4454. }
  4455. EventUtils.prototype.bind = function (target, names, callback, scope) {
  4456. var self = this;
  4457. var id, callbackList, i, name, fakeName, nativeHandler, capture;
  4458. var win = window;
  4459. var defaultNativeHandler = function (evt) {
  4460. self.executeHandlers(fix(evt || win.event), id);
  4461. };
  4462. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4463. return;
  4464. }
  4465. if (!target[self.expando]) {
  4466. id = self.count++;
  4467. target[self.expando] = id;
  4468. self.events[id] = {};
  4469. } else {
  4470. id = target[self.expando];
  4471. }
  4472. scope = scope || target;
  4473. var namesList = names.split(' ');
  4474. i = namesList.length;
  4475. while (i--) {
  4476. name = namesList[i];
  4477. nativeHandler = defaultNativeHandler;
  4478. fakeName = capture = false;
  4479. if (name === 'DOMContentLoaded') {
  4480. name = 'ready';
  4481. }
  4482. if (self.domLoaded && name === 'ready' && target.readyState === 'complete') {
  4483. callback.call(scope, fix({ type: name }));
  4484. continue;
  4485. }
  4486. if (!self.hasMouseEnterLeave) {
  4487. fakeName = self.mouseEnterLeave[name];
  4488. if (fakeName) {
  4489. nativeHandler = function (evt) {
  4490. var current = evt.currentTarget;
  4491. var related = evt.relatedTarget;
  4492. if (related && current.contains) {
  4493. related = current.contains(related);
  4494. } else {
  4495. while (related && related !== current) {
  4496. related = related.parentNode;
  4497. }
  4498. }
  4499. if (!related) {
  4500. evt = fix(evt || win.event);
  4501. evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
  4502. evt.target = current;
  4503. self.executeHandlers(evt, id);
  4504. }
  4505. };
  4506. }
  4507. }
  4508. if (!self.hasFocusIn && (name === 'focusin' || name === 'focusout')) {
  4509. capture = true;
  4510. fakeName = name === 'focusin' ? 'focus' : 'blur';
  4511. nativeHandler = function (evt) {
  4512. evt = fix(evt || win.event);
  4513. evt.type = evt.type === 'focus' ? 'focusin' : 'focusout';
  4514. self.executeHandlers(evt, id);
  4515. };
  4516. }
  4517. callbackList = self.events[id][name];
  4518. if (!callbackList) {
  4519. self.events[id][name] = callbackList = [{
  4520. func: callback,
  4521. scope: scope
  4522. }];
  4523. callbackList.fakeName = fakeName;
  4524. callbackList.capture = capture;
  4525. callbackList.nativeHandler = nativeHandler;
  4526. if (name === 'ready') {
  4527. bindOnReady(target, nativeHandler, self);
  4528. } else {
  4529. addEvent(target, fakeName || name, nativeHandler, capture);
  4530. }
  4531. } else {
  4532. if (name === 'ready' && self.domLoaded) {
  4533. callback(fix({ type: name }));
  4534. } else {
  4535. callbackList.push({
  4536. func: callback,
  4537. scope: scope
  4538. });
  4539. }
  4540. }
  4541. }
  4542. target = callbackList = null;
  4543. return callback;
  4544. };
  4545. EventUtils.prototype.unbind = function (target, names, callback) {
  4546. var callbackList, i, ci, name, eventMap;
  4547. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4548. return this;
  4549. }
  4550. var id = target[this.expando];
  4551. if (id) {
  4552. eventMap = this.events[id];
  4553. if (names) {
  4554. var namesList = names.split(' ');
  4555. i = namesList.length;
  4556. while (i--) {
  4557. name = namesList[i];
  4558. callbackList = eventMap[name];
  4559. if (callbackList) {
  4560. if (callback) {
  4561. ci = callbackList.length;
  4562. while (ci--) {
  4563. if (callbackList[ci].func === callback) {
  4564. var nativeHandler = callbackList.nativeHandler;
  4565. var fakeName = callbackList.fakeName, capture = callbackList.capture;
  4566. callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
  4567. callbackList.nativeHandler = nativeHandler;
  4568. callbackList.fakeName = fakeName;
  4569. callbackList.capture = capture;
  4570. eventMap[name] = callbackList;
  4571. }
  4572. }
  4573. }
  4574. if (!callback || callbackList.length === 0) {
  4575. delete eventMap[name];
  4576. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  4577. }
  4578. }
  4579. }
  4580. } else {
  4581. each$j(eventMap, function (callbackList, name) {
  4582. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  4583. });
  4584. eventMap = {};
  4585. }
  4586. for (name in eventMap) {
  4587. if (has$2(eventMap, name)) {
  4588. return this;
  4589. }
  4590. }
  4591. delete this.events[id];
  4592. try {
  4593. delete target[this.expando];
  4594. } catch (ex) {
  4595. target[this.expando] = null;
  4596. }
  4597. }
  4598. return this;
  4599. };
  4600. EventUtils.prototype.fire = function (target, name, args) {
  4601. var id;
  4602. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4603. return this;
  4604. }
  4605. var event = fix({
  4606. type: name,
  4607. target: target
  4608. }, args);
  4609. do {
  4610. id = target[this.expando];
  4611. if (id) {
  4612. this.executeHandlers(event, id);
  4613. }
  4614. target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
  4615. } while (target && !event.isPropagationStopped());
  4616. return this;
  4617. };
  4618. EventUtils.prototype.clean = function (target) {
  4619. var i, children;
  4620. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4621. return this;
  4622. }
  4623. if (target[this.expando]) {
  4624. this.unbind(target);
  4625. }
  4626. if (!target.getElementsByTagName) {
  4627. target = target.document;
  4628. }
  4629. if (target && target.getElementsByTagName) {
  4630. this.unbind(target);
  4631. children = target.getElementsByTagName('*');
  4632. i = children.length;
  4633. while (i--) {
  4634. target = children[i];
  4635. if (target[this.expando]) {
  4636. this.unbind(target);
  4637. }
  4638. }
  4639. }
  4640. return this;
  4641. };
  4642. EventUtils.prototype.destroy = function () {
  4643. this.events = {};
  4644. };
  4645. EventUtils.prototype.cancel = function (e) {
  4646. if (e) {
  4647. e.preventDefault();
  4648. e.stopImmediatePropagation();
  4649. }
  4650. return false;
  4651. };
  4652. EventUtils.prototype.executeHandlers = function (evt, id) {
  4653. var container = this.events[id];
  4654. var callbackList = container && container[evt.type];
  4655. if (callbackList) {
  4656. for (var i = 0, l = callbackList.length; i < l; i++) {
  4657. var callback = callbackList[i];
  4658. if (callback && callback.func.call(callback.scope, evt) === false) {
  4659. evt.preventDefault();
  4660. }
  4661. if (evt.isImmediatePropagationStopped()) {
  4662. return;
  4663. }
  4664. }
  4665. }
  4666. };
  4667. EventUtils.Event = new EventUtils();
  4668. return EventUtils;
  4669. }();
  4670. 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) {
  4671. if (a === b) {
  4672. hasDuplicate = true;
  4673. }
  4674. return 0;
  4675. }, 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) {
  4676. var i = 0, len = this.length;
  4677. for (; i < len; i++) {
  4678. if (this[i] === elem) {
  4679. return i;
  4680. }
  4681. }
  4682. return -1;
  4683. }, 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 = {
  4684. ID: new RegExp('^#(' + identifier + ')'),
  4685. CLASS: new RegExp('^\\.(' + identifier + ')'),
  4686. TAG: new RegExp('^(' + identifier + '|[*])'),
  4687. ATTR: new RegExp('^' + attributes),
  4688. PSEUDO: new RegExp('^' + pseudos),
  4689. CHILD: new RegExp('^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(' + whitespace + '*(even|odd|(([+-]|)(\\d*)n|)' + whitespace + '*(?:([+-]|)' + whitespace + '*(\\d+)|))' + whitespace + '*\\)|)', 'i'),
  4690. bool: new RegExp('^(?:' + booleans + ')$', 'i'),
  4691. needsContext: new RegExp('^' + whitespace + '*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(' + whitespace + '*((?:-\\d)?\\d*)' + whitespace + '*\\)|)(?=[^-]|$)', 'i')
  4692. }, 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) {
  4693. var high = '0x' + escaped - 65536;
  4694. return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320);
  4695. };
  4696. try {
  4697. push$1.apply(arr = slice$1.call(preferredDoc.childNodes), preferredDoc.childNodes);
  4698. arr[preferredDoc.childNodes.length].nodeType;
  4699. } catch (e) {
  4700. push$1 = {
  4701. apply: arr.length ? function (target, els) {
  4702. push_native.apply(target, slice$1.call(els));
  4703. } : function (target, els) {
  4704. var j = target.length, i = 0;
  4705. while (target[j++] = els[i++]) {
  4706. }
  4707. target.length = j - 1;
  4708. }
  4709. };
  4710. }
  4711. var Sizzle = function (selector, context, results, seed) {
  4712. var match, elem, m, nodeType, i, groups, old, nid, newContext, newSelector;
  4713. if ((context ? context.ownerDocument || context : preferredDoc) !== document$1) {
  4714. setDocument(context);
  4715. }
  4716. context = context || document$1;
  4717. results = results || [];
  4718. if (!selector || typeof selector !== 'string') {
  4719. return results;
  4720. }
  4721. if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) {
  4722. return [];
  4723. }
  4724. if (documentIsHTML && !seed) {
  4725. if (match = rquickExpr$1.exec(selector)) {
  4726. if (m = match[1]) {
  4727. if (nodeType === 9) {
  4728. elem = context.getElementById(m);
  4729. if (elem && elem.parentNode) {
  4730. if (elem.id === m) {
  4731. results.push(elem);
  4732. return results;
  4733. }
  4734. } else {
  4735. return results;
  4736. }
  4737. } else {
  4738. if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains(context, elem) && elem.id === m) {
  4739. results.push(elem);
  4740. return results;
  4741. }
  4742. }
  4743. } else if (match[2]) {
  4744. push$1.apply(results, context.getElementsByTagName(selector));
  4745. return results;
  4746. } else if ((m = match[3]) && support.getElementsByClassName) {
  4747. push$1.apply(results, context.getElementsByClassName(m));
  4748. return results;
  4749. }
  4750. }
  4751. if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
  4752. nid = old = expando;
  4753. newContext = context;
  4754. newSelector = nodeType === 9 && selector;
  4755. if (nodeType === 1 && context.nodeName.toLowerCase() !== 'object') {
  4756. groups = tokenize(selector);
  4757. if (old = context.getAttribute('id')) {
  4758. nid = old.replace(rescape, '\\$&');
  4759. } else {
  4760. context.setAttribute('id', nid);
  4761. }
  4762. nid = '[id=\'' + nid + '\'] ';
  4763. i = groups.length;
  4764. while (i--) {
  4765. groups[i] = nid + toSelector(groups[i]);
  4766. }
  4767. newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
  4768. newSelector = groups.join(',');
  4769. }
  4770. if (newSelector) {
  4771. try {
  4772. push$1.apply(results, newContext.querySelectorAll(newSelector));
  4773. return results;
  4774. } catch (qsaError) {
  4775. } finally {
  4776. if (!old) {
  4777. context.removeAttribute('id');
  4778. }
  4779. }
  4780. }
  4781. }
  4782. }
  4783. return select$1(selector.replace(rtrim, '$1'), context, results, seed);
  4784. };
  4785. function createCache() {
  4786. var keys = [];
  4787. function cache(key, value) {
  4788. if (keys.push(key + ' ') > Expr.cacheLength) {
  4789. delete cache[keys.shift()];
  4790. }
  4791. return cache[key + ' '] = value;
  4792. }
  4793. return cache;
  4794. }
  4795. function markFunction(fn) {
  4796. fn[expando] = true;
  4797. return fn;
  4798. }
  4799. function siblingCheck(a, b) {
  4800. var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && (~b.sourceIndex || MAX_NEGATIVE) - (~a.sourceIndex || MAX_NEGATIVE);
  4801. if (diff) {
  4802. return diff;
  4803. }
  4804. if (cur) {
  4805. while (cur = cur.nextSibling) {
  4806. if (cur === b) {
  4807. return -1;
  4808. }
  4809. }
  4810. }
  4811. return a ? 1 : -1;
  4812. }
  4813. function createInputPseudo(type) {
  4814. return function (elem) {
  4815. var name = elem.nodeName.toLowerCase();
  4816. return name === 'input' && elem.type === type;
  4817. };
  4818. }
  4819. function createButtonPseudo(type) {
  4820. return function (elem) {
  4821. var name = elem.nodeName.toLowerCase();
  4822. return (name === 'input' || name === 'button') && elem.type === type;
  4823. };
  4824. }
  4825. function createPositionalPseudo(fn) {
  4826. return markFunction(function (argument) {
  4827. argument = +argument;
  4828. return markFunction(function (seed, matches) {
  4829. var j, matchIndexes = fn([], seed.length, argument), i = matchIndexes.length;
  4830. while (i--) {
  4831. if (seed[j = matchIndexes[i]]) {
  4832. seed[j] = !(matches[j] = seed[j]);
  4833. }
  4834. }
  4835. });
  4836. });
  4837. }
  4838. function testContext(context) {
  4839. return context && typeof context.getElementsByTagName !== strundefined && context;
  4840. }
  4841. support = Sizzle.support = {};
  4842. isXML = Sizzle.isXML = function (elem) {
  4843. var documentElement = elem && (elem.ownerDocument || elem).documentElement;
  4844. return documentElement ? documentElement.nodeName !== 'HTML' : false;
  4845. };
  4846. setDocument = Sizzle.setDocument = function (node) {
  4847. var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView;
  4848. function getTop(win) {
  4849. try {
  4850. return win.top;
  4851. } catch (ex) {
  4852. }
  4853. return null;
  4854. }
  4855. if (doc === document$1 || doc.nodeType !== 9 || !doc.documentElement) {
  4856. return document$1;
  4857. }
  4858. document$1 = doc;
  4859. docElem = doc.documentElement;
  4860. documentIsHTML = !isXML(doc);
  4861. if (parent && parent !== getTop(parent)) {
  4862. if (parent.addEventListener) {
  4863. parent.addEventListener('unload', function () {
  4864. setDocument();
  4865. }, false);
  4866. } else if (parent.attachEvent) {
  4867. parent.attachEvent('onunload', function () {
  4868. setDocument();
  4869. });
  4870. }
  4871. }
  4872. support.attributes = true;
  4873. support.getElementsByTagName = true;
  4874. support.getElementsByClassName = rnative.test(doc.getElementsByClassName);
  4875. support.getById = true;
  4876. Expr.find.ID = function (id, context) {
  4877. if (typeof context.getElementById !== strundefined && documentIsHTML) {
  4878. var m = context.getElementById(id);
  4879. return m && m.parentNode ? [m] : [];
  4880. }
  4881. };
  4882. Expr.filter.ID = function (id) {
  4883. var attrId = id.replace(runescape, funescape);
  4884. return function (elem) {
  4885. return elem.getAttribute('id') === attrId;
  4886. };
  4887. };
  4888. Expr.find.TAG = support.getElementsByTagName ? function (tag, context) {
  4889. if (typeof context.getElementsByTagName !== strundefined) {
  4890. return context.getElementsByTagName(tag);
  4891. }
  4892. } : function (tag, context) {
  4893. var elem, tmp = [], i = 0, results = context.getElementsByTagName(tag);
  4894. if (tag === '*') {
  4895. while (elem = results[i++]) {
  4896. if (elem.nodeType === 1) {
  4897. tmp.push(elem);
  4898. }
  4899. }
  4900. return tmp;
  4901. }
  4902. return results;
  4903. };
  4904. Expr.find.CLASS = support.getElementsByClassName && function (className, context) {
  4905. if (documentIsHTML) {
  4906. return context.getElementsByClassName(className);
  4907. }
  4908. };
  4909. rbuggyMatches = [];
  4910. rbuggyQSA = [];
  4911. support.disconnectedMatch = true;
  4912. rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join('|'));
  4913. rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join('|'));
  4914. hasCompare = rnative.test(docElem.compareDocumentPosition);
  4915. contains = hasCompare || rnative.test(docElem.contains) ? function (a, b) {
  4916. var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode;
  4917. return a === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
  4918. } : function (a, b) {
  4919. if (b) {
  4920. while (b = b.parentNode) {
  4921. if (b === a) {
  4922. return true;
  4923. }
  4924. }
  4925. }
  4926. return false;
  4927. };
  4928. sortOrder = hasCompare ? function (a, b) {
  4929. if (a === b) {
  4930. hasDuplicate = true;
  4931. return 0;
  4932. }
  4933. var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
  4934. if (compare) {
  4935. return compare;
  4936. }
  4937. compare = (a.ownerDocument || a) === (b.ownerDocument || b) ? a.compareDocumentPosition(b) : 1;
  4938. if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {
  4939. if (a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a)) {
  4940. return -1;
  4941. }
  4942. if (b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b)) {
  4943. return 1;
  4944. }
  4945. return sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
  4946. }
  4947. return compare & 4 ? -1 : 1;
  4948. } : function (a, b) {
  4949. if (a === b) {
  4950. hasDuplicate = true;
  4951. return 0;
  4952. }
  4953. var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [a], bp = [b];
  4954. if (!aup || !bup) {
  4955. return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
  4956. } else if (aup === bup) {
  4957. return siblingCheck(a, b);
  4958. }
  4959. cur = a;
  4960. while (cur = cur.parentNode) {
  4961. ap.unshift(cur);
  4962. }
  4963. cur = b;
  4964. while (cur = cur.parentNode) {
  4965. bp.unshift(cur);
  4966. }
  4967. while (ap[i] === bp[i]) {
  4968. i++;
  4969. }
  4970. return i ? siblingCheck(ap[i], bp[i]) : ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0;
  4971. };
  4972. return doc;
  4973. };
  4974. Sizzle.matches = function (expr, elements) {
  4975. return Sizzle(expr, null, null, elements);
  4976. };
  4977. Sizzle.matchesSelector = function (elem, expr) {
  4978. if ((elem.ownerDocument || elem) !== document$1) {
  4979. setDocument(elem);
  4980. }
  4981. expr = expr.replace(rattributeQuotes, '=\'$1\']');
  4982. if (support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
  4983. try {
  4984. var ret = matches.call(elem, expr);
  4985. if (ret || support.disconnectedMatch || elem.document && elem.document.nodeType !== 11) {
  4986. return ret;
  4987. }
  4988. } catch (e) {
  4989. }
  4990. }
  4991. return Sizzle(expr, document$1, null, [elem]).length > 0;
  4992. };
  4993. Sizzle.contains = function (context, elem) {
  4994. if ((context.ownerDocument || context) !== document$1) {
  4995. setDocument(context);
  4996. }
  4997. return contains(context, elem);
  4998. };
  4999. Sizzle.attr = function (elem, name) {
  5000. if ((elem.ownerDocument || elem) !== document$1) {
  5001. setDocument(elem);
  5002. }
  5003. var fn = Expr.attrHandle[name.toLowerCase()], val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;
  5004. return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
  5005. };
  5006. Sizzle.error = function (msg) {
  5007. throw new Error('Syntax error, unrecognized expression: ' + msg);
  5008. };
  5009. Sizzle.uniqueSort = function (results) {
  5010. var elem, duplicates = [], j = 0, i = 0;
  5011. hasDuplicate = !support.detectDuplicates;
  5012. sortInput = !support.sortStable && results.slice(0);
  5013. results.sort(sortOrder);
  5014. if (hasDuplicate) {
  5015. while (elem = results[i++]) {
  5016. if (elem === results[i]) {
  5017. j = duplicates.push(i);
  5018. }
  5019. }
  5020. while (j--) {
  5021. results.splice(duplicates[j], 1);
  5022. }
  5023. }
  5024. sortInput = null;
  5025. return results;
  5026. };
  5027. getText = Sizzle.getText = function (elem) {
  5028. var node, ret = '', i = 0, nodeType = elem.nodeType;
  5029. if (!nodeType) {
  5030. while (node = elem[i++]) {
  5031. ret += getText(node);
  5032. }
  5033. } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
  5034. if (typeof elem.textContent === 'string') {
  5035. return elem.textContent;
  5036. } else {
  5037. for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5038. ret += getText(elem);
  5039. }
  5040. }
  5041. } else if (nodeType === 3 || nodeType === 4) {
  5042. return elem.nodeValue;
  5043. }
  5044. return ret;
  5045. };
  5046. Expr = Sizzle.selectors = {
  5047. cacheLength: 50,
  5048. createPseudo: markFunction,
  5049. match: matchExpr,
  5050. attrHandle: {},
  5051. find: {},
  5052. relative: {
  5053. '>': {
  5054. dir: 'parentNode',
  5055. first: true
  5056. },
  5057. ' ': { dir: 'parentNode' },
  5058. '+': {
  5059. dir: 'previousSibling',
  5060. first: true
  5061. },
  5062. '~': { dir: 'previousSibling' }
  5063. },
  5064. preFilter: {
  5065. ATTR: function (match) {
  5066. match[1] = match[1].replace(runescape, funescape);
  5067. match[3] = (match[3] || match[4] || match[5] || '').replace(runescape, funescape);
  5068. if (match[2] === '~=') {
  5069. match[3] = ' ' + match[3] + ' ';
  5070. }
  5071. return match.slice(0, 4);
  5072. },
  5073. CHILD: function (match) {
  5074. match[1] = match[1].toLowerCase();
  5075. if (match[1].slice(0, 3) === 'nth') {
  5076. if (!match[3]) {
  5077. Sizzle.error(match[0]);
  5078. }
  5079. match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === 'even' || match[3] === 'odd'));
  5080. match[5] = +(match[7] + match[8] || match[3] === 'odd');
  5081. } else if (match[3]) {
  5082. Sizzle.error(match[0]);
  5083. }
  5084. return match;
  5085. },
  5086. PSEUDO: function (match) {
  5087. var excess, unquoted = !match[6] && match[2];
  5088. if (matchExpr.CHILD.test(match[0])) {
  5089. return null;
  5090. }
  5091. if (match[3]) {
  5092. match[2] = match[4] || match[5] || '';
  5093. } else if (unquoted && rpseudo.test(unquoted) && (excess = tokenize(unquoted, true)) && (excess = unquoted.indexOf(')', unquoted.length - excess) - unquoted.length)) {
  5094. match[0] = match[0].slice(0, excess);
  5095. match[2] = unquoted.slice(0, excess);
  5096. }
  5097. return match.slice(0, 3);
  5098. }
  5099. },
  5100. filter: {
  5101. TAG: function (nodeNameSelector) {
  5102. var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
  5103. return nodeNameSelector === '*' ? function () {
  5104. return true;
  5105. } : function (elem) {
  5106. return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
  5107. };
  5108. },
  5109. CLASS: function (className) {
  5110. var pattern = classCache[className + ' '];
  5111. return pattern || (pattern = new RegExp('(^|' + whitespace + ')' + className + '(' + whitespace + '|$)')) && classCache(className, function (elem) {
  5112. return pattern.test(typeof elem.className === 'string' && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute('class') || '');
  5113. });
  5114. },
  5115. ATTR: function (name, operator, check) {
  5116. return function (elem) {
  5117. var result = Sizzle.attr(elem, name);
  5118. if (result == null) {
  5119. return operator === '!=';
  5120. }
  5121. if (!operator) {
  5122. return true;
  5123. }
  5124. result += '';
  5125. 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;
  5126. };
  5127. },
  5128. CHILD: function (type, what, argument, first, last) {
  5129. var simple = type.slice(0, 3) !== 'nth', forward = type.slice(-4) !== 'last', ofType = what === 'of-type';
  5130. return first === 1 && last === 0 ? function (elem) {
  5131. return !!elem.parentNode;
  5132. } : function (elem, context, xml) {
  5133. var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? 'nextSibling' : 'previousSibling', parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType;
  5134. if (parent) {
  5135. if (simple) {
  5136. while (dir) {
  5137. node = elem;
  5138. while (node = node[dir]) {
  5139. if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
  5140. return false;
  5141. }
  5142. }
  5143. start = dir = type === 'only' && !start && 'nextSibling';
  5144. }
  5145. return true;
  5146. }
  5147. start = [forward ? parent.firstChild : parent.lastChild];
  5148. if (forward && useCache) {
  5149. outerCache = parent[expando] || (parent[expando] = {});
  5150. cache = outerCache[type] || [];
  5151. nodeIndex = cache[0] === dirruns && cache[1];
  5152. diff = cache[0] === dirruns && cache[2];
  5153. node = nodeIndex && parent.childNodes[nodeIndex];
  5154. while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5155. if (node.nodeType === 1 && ++diff && node === elem) {
  5156. outerCache[type] = [
  5157. dirruns,
  5158. nodeIndex,
  5159. diff
  5160. ];
  5161. break;
  5162. }
  5163. }
  5164. } else if (useCache && (cache = (elem[expando] || (elem[expando] = {}))[type]) && cache[0] === dirruns) {
  5165. diff = cache[1];
  5166. } else {
  5167. while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5168. if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) {
  5169. if (useCache) {
  5170. (node[expando] || (node[expando] = {}))[type] = [
  5171. dirruns,
  5172. diff
  5173. ];
  5174. }
  5175. if (node === elem) {
  5176. break;
  5177. }
  5178. }
  5179. }
  5180. }
  5181. diff -= last;
  5182. return diff === first || diff % first === 0 && diff / first >= 0;
  5183. }
  5184. };
  5185. },
  5186. PSEUDO: function (pseudo, argument) {
  5187. var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error('unsupported pseudo: ' + pseudo);
  5188. if (fn[expando]) {
  5189. return fn(argument);
  5190. }
  5191. if (fn.length > 1) {
  5192. args = [
  5193. pseudo,
  5194. pseudo,
  5195. '',
  5196. argument
  5197. ];
  5198. return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) {
  5199. var idx, matched = fn(seed, argument), i = matched.length;
  5200. while (i--) {
  5201. idx = indexOf.call(seed, matched[i]);
  5202. seed[idx] = !(matches[idx] = matched[i]);
  5203. }
  5204. }) : function (elem) {
  5205. return fn(elem, 0, args);
  5206. };
  5207. }
  5208. return fn;
  5209. }
  5210. },
  5211. pseudos: {
  5212. not: markFunction(function (selector) {
  5213. var input = [], results = [], matcher = compile(selector.replace(rtrim, '$1'));
  5214. return matcher[expando] ? markFunction(function (seed, matches, context, xml) {
  5215. var elem, unmatched = matcher(seed, null, xml, []), i = seed.length;
  5216. while (i--) {
  5217. if (elem = unmatched[i]) {
  5218. seed[i] = !(matches[i] = elem);
  5219. }
  5220. }
  5221. }) : function (elem, context, xml) {
  5222. input[0] = elem;
  5223. matcher(input, null, xml, results);
  5224. input[0] = null;
  5225. return !results.pop();
  5226. };
  5227. }),
  5228. has: markFunction(function (selector) {
  5229. return function (elem) {
  5230. return Sizzle(selector, elem).length > 0;
  5231. };
  5232. }),
  5233. contains: markFunction(function (text) {
  5234. text = text.replace(runescape, funescape);
  5235. return function (elem) {
  5236. return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1;
  5237. };
  5238. }),
  5239. lang: markFunction(function (lang) {
  5240. if (!ridentifier.test(lang || '')) {
  5241. Sizzle.error('unsupported lang: ' + lang);
  5242. }
  5243. lang = lang.replace(runescape, funescape).toLowerCase();
  5244. return function (elem) {
  5245. var elemLang;
  5246. do {
  5247. if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute('xml:lang') || elem.getAttribute('lang')) {
  5248. elemLang = elemLang.toLowerCase();
  5249. return elemLang === lang || elemLang.indexOf(lang + '-') === 0;
  5250. }
  5251. } while ((elem = elem.parentNode) && elem.nodeType === 1);
  5252. return false;
  5253. };
  5254. }),
  5255. target: function (elem) {
  5256. var hash = window.location && window.location.hash;
  5257. return hash && hash.slice(1) === elem.id;
  5258. },
  5259. root: function (elem) {
  5260. return elem === docElem;
  5261. },
  5262. focus: function (elem) {
  5263. return elem === document$1.activeElement && (!document$1.hasFocus || document$1.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
  5264. },
  5265. enabled: function (elem) {
  5266. return elem.disabled === false;
  5267. },
  5268. disabled: function (elem) {
  5269. return elem.disabled === true;
  5270. },
  5271. checked: function (elem) {
  5272. var nodeName = elem.nodeName.toLowerCase();
  5273. return nodeName === 'input' && !!elem.checked || nodeName === 'option' && !!elem.selected;
  5274. },
  5275. selected: function (elem) {
  5276. if (elem.parentNode) {
  5277. elem.parentNode.selectedIndex;
  5278. }
  5279. return elem.selected === true;
  5280. },
  5281. empty: function (elem) {
  5282. for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5283. if (elem.nodeType < 6) {
  5284. return false;
  5285. }
  5286. }
  5287. return true;
  5288. },
  5289. parent: function (elem) {
  5290. return !Expr.pseudos.empty(elem);
  5291. },
  5292. header: function (elem) {
  5293. return rheader.test(elem.nodeName);
  5294. },
  5295. input: function (elem) {
  5296. return rinputs.test(elem.nodeName);
  5297. },
  5298. button: function (elem) {
  5299. var name = elem.nodeName.toLowerCase();
  5300. return name === 'input' && elem.type === 'button' || name === 'button';
  5301. },
  5302. text: function (elem) {
  5303. var attr;
  5304. return elem.nodeName.toLowerCase() === 'input' && elem.type === 'text' && ((attr = elem.getAttribute('type')) == null || attr.toLowerCase() === 'text');
  5305. },
  5306. first: createPositionalPseudo(function () {
  5307. return [0];
  5308. }),
  5309. last: createPositionalPseudo(function (matchIndexes, length) {
  5310. return [length - 1];
  5311. }),
  5312. eq: createPositionalPseudo(function (matchIndexes, length, argument) {
  5313. return [argument < 0 ? argument + length : argument];
  5314. }),
  5315. even: createPositionalPseudo(function (matchIndexes, length) {
  5316. var i = 0;
  5317. for (; i < length; i += 2) {
  5318. matchIndexes.push(i);
  5319. }
  5320. return matchIndexes;
  5321. }),
  5322. odd: createPositionalPseudo(function (matchIndexes, length) {
  5323. var i = 1;
  5324. for (; i < length; i += 2) {
  5325. matchIndexes.push(i);
  5326. }
  5327. return matchIndexes;
  5328. }),
  5329. lt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5330. var i = argument < 0 ? argument + length : argument;
  5331. for (; --i >= 0;) {
  5332. matchIndexes.push(i);
  5333. }
  5334. return matchIndexes;
  5335. }),
  5336. gt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5337. var i = argument < 0 ? argument + length : argument;
  5338. for (; ++i < length;) {
  5339. matchIndexes.push(i);
  5340. }
  5341. return matchIndexes;
  5342. })
  5343. }
  5344. };
  5345. Expr.pseudos.nth = Expr.pseudos.eq;
  5346. each$k([
  5347. 'radio',
  5348. 'checkbox',
  5349. 'file',
  5350. 'password',
  5351. 'image'
  5352. ], function (i) {
  5353. Expr.pseudos[i] = createInputPseudo(i);
  5354. });
  5355. each$k([
  5356. 'submit',
  5357. 'reset'
  5358. ], function (i) {
  5359. Expr.pseudos[i] = createButtonPseudo(i);
  5360. });
  5361. function setFilters() {
  5362. }
  5363. setFilters.prototype = Expr.filters = Expr.pseudos;
  5364. Expr.setFilters = new setFilters();
  5365. tokenize = Sizzle.tokenize = function (selector, parseOnly) {
  5366. var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + ' '];
  5367. if (cached) {
  5368. return parseOnly ? 0 : cached.slice(0);
  5369. }
  5370. soFar = selector;
  5371. groups = [];
  5372. preFilters = Expr.preFilter;
  5373. while (soFar) {
  5374. if (!matched || (match = rcomma.exec(soFar))) {
  5375. if (match) {
  5376. soFar = soFar.slice(match[0].length) || soFar;
  5377. }
  5378. groups.push(tokens = []);
  5379. }
  5380. matched = false;
  5381. if (match = rcombinators.exec(soFar)) {
  5382. matched = match.shift();
  5383. tokens.push({
  5384. value: matched,
  5385. type: match[0].replace(rtrim, ' ')
  5386. });
  5387. soFar = soFar.slice(matched.length);
  5388. }
  5389. for (type in Expr.filter) {
  5390. if (!Expr.filter.hasOwnProperty(type)) {
  5391. continue;
  5392. }
  5393. if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) {
  5394. matched = match.shift();
  5395. tokens.push({
  5396. value: matched,
  5397. type: type,
  5398. matches: match
  5399. });
  5400. soFar = soFar.slice(matched.length);
  5401. }
  5402. }
  5403. if (!matched) {
  5404. break;
  5405. }
  5406. }
  5407. return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : tokenCache(selector, groups).slice(0);
  5408. };
  5409. function toSelector(tokens) {
  5410. var i = 0, len = tokens.length, selector = '';
  5411. for (; i < len; i++) {
  5412. selector += tokens[i].value;
  5413. }
  5414. return selector;
  5415. }
  5416. function addCombinator(matcher, combinator, base) {
  5417. var dir = combinator.dir, checkNonElements = base && dir === 'parentNode', doneName = done++;
  5418. return combinator.first ? function (elem, context, xml) {
  5419. while (elem = elem[dir]) {
  5420. if (elem.nodeType === 1 || checkNonElements) {
  5421. return matcher(elem, context, xml);
  5422. }
  5423. }
  5424. } : function (elem, context, xml) {
  5425. var oldCache, outerCache, newCache = [
  5426. dirruns,
  5427. doneName
  5428. ];
  5429. if (xml) {
  5430. while (elem = elem[dir]) {
  5431. if (elem.nodeType === 1 || checkNonElements) {
  5432. if (matcher(elem, context, xml)) {
  5433. return true;
  5434. }
  5435. }
  5436. }
  5437. } else {
  5438. while (elem = elem[dir]) {
  5439. if (elem.nodeType === 1 || checkNonElements) {
  5440. outerCache = elem[expando] || (elem[expando] = {});
  5441. if ((oldCache = outerCache[dir]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
  5442. return newCache[2] = oldCache[2];
  5443. } else {
  5444. outerCache[dir] = newCache;
  5445. if (newCache[2] = matcher(elem, context, xml)) {
  5446. return true;
  5447. }
  5448. }
  5449. }
  5450. }
  5451. }
  5452. };
  5453. }
  5454. function elementMatcher(matchers) {
  5455. return matchers.length > 1 ? function (elem, context, xml) {
  5456. var i = matchers.length;
  5457. while (i--) {
  5458. if (!matchers[i](elem, context, xml)) {
  5459. return false;
  5460. }
  5461. }
  5462. return true;
  5463. } : matchers[0];
  5464. }
  5465. function multipleContexts(selector, contexts, results) {
  5466. var i = 0, len = contexts.length;
  5467. for (; i < len; i++) {
  5468. Sizzle(selector, contexts[i], results);
  5469. }
  5470. return results;
  5471. }
  5472. function condense(unmatched, map, filter, context, xml) {
  5473. var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null;
  5474. for (; i < len; i++) {
  5475. if (elem = unmatched[i]) {
  5476. if (!filter || filter(elem, context, xml)) {
  5477. newUnmatched.push(elem);
  5478. if (mapped) {
  5479. map.push(i);
  5480. }
  5481. }
  5482. }
  5483. }
  5484. return newUnmatched;
  5485. }
  5486. function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
  5487. if (postFilter && !postFilter[expando]) {
  5488. postFilter = setMatcher(postFilter);
  5489. }
  5490. if (postFinder && !postFinder[expando]) {
  5491. postFinder = setMatcher(postFinder, postSelector);
  5492. }
  5493. return markFunction(function (seed, results, context, xml) {
  5494. 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;
  5495. if (matcher) {
  5496. matcher(matcherIn, matcherOut, context, xml);
  5497. }
  5498. if (postFilter) {
  5499. temp = condense(matcherOut, postMap);
  5500. postFilter(temp, [], context, xml);
  5501. i = temp.length;
  5502. while (i--) {
  5503. if (elem = temp[i]) {
  5504. matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
  5505. }
  5506. }
  5507. }
  5508. if (seed) {
  5509. if (postFinder || preFilter) {
  5510. if (postFinder) {
  5511. temp = [];
  5512. i = matcherOut.length;
  5513. while (i--) {
  5514. if (elem = matcherOut[i]) {
  5515. temp.push(matcherIn[i] = elem);
  5516. }
  5517. }
  5518. postFinder(null, matcherOut = [], temp, xml);
  5519. }
  5520. i = matcherOut.length;
  5521. while (i--) {
  5522. if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf.call(seed, elem) : preMap[i]) > -1) {
  5523. seed[temp] = !(results[temp] = elem);
  5524. }
  5525. }
  5526. }
  5527. } else {
  5528. matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
  5529. if (postFinder) {
  5530. postFinder(null, results, matcherOut, xml);
  5531. } else {
  5532. push$1.apply(results, matcherOut);
  5533. }
  5534. }
  5535. });
  5536. }
  5537. function matcherFromTokens(tokens) {
  5538. 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) {
  5539. return elem === checkContext;
  5540. }, implicitRelative, true), matchAnyContext = addCombinator(function (elem) {
  5541. return indexOf.call(checkContext, elem) > -1;
  5542. }, implicitRelative, true), matchers = [function (elem, context, xml) {
  5543. var ret = !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
  5544. checkContext = null;
  5545. return ret;
  5546. }];
  5547. for (; i < len; i++) {
  5548. if (matcher = Expr.relative[tokens[i].type]) {
  5549. matchers = [addCombinator(elementMatcher(matchers), matcher)];
  5550. } else {
  5551. matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);
  5552. if (matcher[expando]) {
  5553. j = ++i;
  5554. for (; j < len; j++) {
  5555. if (Expr.relative[tokens[j].type]) {
  5556. break;
  5557. }
  5558. }
  5559. 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));
  5560. }
  5561. matchers.push(matcher);
  5562. }
  5563. }
  5564. return elementMatcher(matchers);
  5565. }
  5566. function matcherFromGroupMatchers(elementMatchers, setMatchers) {
  5567. var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function (seed, context, xml, results, outermost) {
  5568. 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;
  5569. if (outermost) {
  5570. outermostContext = context !== document$1 && context;
  5571. }
  5572. for (; i !== len && (elem = elems[i]) != null; i++) {
  5573. if (byElement && elem) {
  5574. j = 0;
  5575. while (matcher = elementMatchers[j++]) {
  5576. if (matcher(elem, context, xml)) {
  5577. results.push(elem);
  5578. break;
  5579. }
  5580. }
  5581. if (outermost) {
  5582. dirruns = dirrunsUnique;
  5583. }
  5584. }
  5585. if (bySet) {
  5586. if (elem = !matcher && elem) {
  5587. matchedCount--;
  5588. }
  5589. if (seed) {
  5590. unmatched.push(elem);
  5591. }
  5592. }
  5593. }
  5594. matchedCount += i;
  5595. if (bySet && i !== matchedCount) {
  5596. j = 0;
  5597. while (matcher = setMatchers[j++]) {
  5598. matcher(unmatched, setMatched, context, xml);
  5599. }
  5600. if (seed) {
  5601. if (matchedCount > 0) {
  5602. while (i--) {
  5603. if (!(unmatched[i] || setMatched[i])) {
  5604. setMatched[i] = pop.call(results);
  5605. }
  5606. }
  5607. }
  5608. setMatched = condense(setMatched);
  5609. }
  5610. push$1.apply(results, setMatched);
  5611. if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
  5612. Sizzle.uniqueSort(results);
  5613. }
  5614. }
  5615. if (outermost) {
  5616. dirruns = dirrunsUnique;
  5617. outermostContext = contextBackup;
  5618. }
  5619. return unmatched;
  5620. };
  5621. return bySet ? markFunction(superMatcher) : superMatcher;
  5622. }
  5623. compile = Sizzle.compile = function (selector, match) {
  5624. var i, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + ' '];
  5625. if (!cached) {
  5626. if (!match) {
  5627. match = tokenize(selector);
  5628. }
  5629. i = match.length;
  5630. while (i--) {
  5631. cached = matcherFromTokens(match[i]);
  5632. if (cached[expando]) {
  5633. setMatchers.push(cached);
  5634. } else {
  5635. elementMatchers.push(cached);
  5636. }
  5637. }
  5638. cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
  5639. cached.selector = selector;
  5640. }
  5641. return cached;
  5642. };
  5643. select$1 = Sizzle.select = function (selector, context, results, seed) {
  5644. var i, tokens, token, type, find, compiled = typeof selector === 'function' && selector, match = !seed && tokenize(selector = compiled.selector || selector);
  5645. results = results || [];
  5646. if (match.length === 1) {
  5647. tokens = match[0] = match[0].slice(0);
  5648. if (tokens.length > 2 && (token = tokens[0]).type === 'ID' && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
  5649. context = (Expr.find.ID(token.matches[0].replace(runescape, funescape), context) || [])[0];
  5650. if (!context) {
  5651. return results;
  5652. } else if (compiled) {
  5653. context = context.parentNode;
  5654. }
  5655. selector = selector.slice(tokens.shift().value.length);
  5656. }
  5657. i = matchExpr.needsContext.test(selector) ? 0 : tokens.length;
  5658. while (i--) {
  5659. token = tokens[i];
  5660. if (Expr.relative[type = token.type]) {
  5661. break;
  5662. }
  5663. if (find = Expr.find[type]) {
  5664. if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {
  5665. tokens.splice(i, 1);
  5666. selector = seed.length && toSelector(tokens);
  5667. if (!selector) {
  5668. push$1.apply(results, seed);
  5669. return results;
  5670. }
  5671. break;
  5672. }
  5673. }
  5674. }
  5675. }
  5676. (compiled || compile(selector, match))(seed, context, !documentIsHTML, results, rsibling.test(selector) && testContext(context.parentNode) || context);
  5677. return results;
  5678. };
  5679. support.sortStable = expando.split('').sort(sortOrder).join('') === expando;
  5680. support.detectDuplicates = !!hasDuplicate;
  5681. setDocument();
  5682. support.sortDetached = true;
  5683. var doc = document;
  5684. var push = Array.prototype.push;
  5685. var slice = Array.prototype.slice;
  5686. var rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
  5687. var Event$1 = EventUtils.Event;
  5688. var skipUniques = Tools.makeMap('children,contents,next,prev');
  5689. var isDefined = function (obj) {
  5690. return typeof obj !== 'undefined';
  5691. };
  5692. var isString = function (obj) {
  5693. return typeof obj === 'string';
  5694. };
  5695. var isWindow = function (obj) {
  5696. return obj && obj === obj.window;
  5697. };
  5698. var createFragment$1 = function (html, fragDoc) {
  5699. fragDoc = fragDoc || doc;
  5700. var container = fragDoc.createElement('div');
  5701. var frag = fragDoc.createDocumentFragment();
  5702. container.innerHTML = html;
  5703. var node;
  5704. while (node = container.firstChild) {
  5705. frag.appendChild(node);
  5706. }
  5707. return frag;
  5708. };
  5709. var domManipulate = function (targetNodes, sourceItem, callback, reverse) {
  5710. var i;
  5711. if (isString(sourceItem)) {
  5712. sourceItem = createFragment$1(sourceItem, getElementDocument(targetNodes[0]));
  5713. } else if (sourceItem.length && !sourceItem.nodeType) {
  5714. sourceItem = DomQuery.makeArray(sourceItem);
  5715. if (reverse) {
  5716. for (i = sourceItem.length - 1; i >= 0; i--) {
  5717. domManipulate(targetNodes, sourceItem[i], callback, reverse);
  5718. }
  5719. } else {
  5720. for (i = 0; i < sourceItem.length; i++) {
  5721. domManipulate(targetNodes, sourceItem[i], callback, reverse);
  5722. }
  5723. }
  5724. return targetNodes;
  5725. }
  5726. if (sourceItem.nodeType) {
  5727. i = targetNodes.length;
  5728. while (i--) {
  5729. callback.call(targetNodes[i], sourceItem);
  5730. }
  5731. }
  5732. return targetNodes;
  5733. };
  5734. var hasClass = function (node, className) {
  5735. return node && className && (' ' + node.className + ' ').indexOf(' ' + className + ' ') !== -1;
  5736. };
  5737. var wrap$2 = function (elements, wrapper, all) {
  5738. var lastParent, newWrapper;
  5739. wrapper = DomQuery(wrapper)[0];
  5740. elements.each(function () {
  5741. var self = this;
  5742. if (!all || lastParent !== self.parentNode) {
  5743. lastParent = self.parentNode;
  5744. newWrapper = wrapper.cloneNode(false);
  5745. self.parentNode.insertBefore(newWrapper, self);
  5746. newWrapper.appendChild(self);
  5747. } else {
  5748. newWrapper.appendChild(self);
  5749. }
  5750. });
  5751. return elements;
  5752. };
  5753. var numericCssMap = Tools.makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom', ' ');
  5754. var booleanMap = Tools.makeMap('checked compact declare defer disabled ismap multiple nohref noshade nowrap readonly selected', ' ');
  5755. var propFix = {
  5756. for: 'htmlFor',
  5757. class: 'className',
  5758. readonly: 'readOnly'
  5759. };
  5760. var cssFix = { float: 'cssFloat' };
  5761. var attrHooks = {}, cssHooks = {};
  5762. var DomQueryConstructor = function (selector, context) {
  5763. return new DomQuery.fn.init(selector, context);
  5764. };
  5765. var inArray$1 = function (item, array) {
  5766. var i;
  5767. if (array.indexOf) {
  5768. return array.indexOf(item);
  5769. }
  5770. i = array.length;
  5771. while (i--) {
  5772. if (array[i] === item) {
  5773. return i;
  5774. }
  5775. }
  5776. return -1;
  5777. };
  5778. var whiteSpaceRegExp = /^\s*|\s*$/g;
  5779. var trim$1 = function (str) {
  5780. return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp, '');
  5781. };
  5782. var each$g = function (obj, callback) {
  5783. var length, key, i, value;
  5784. if (obj) {
  5785. length = obj.length;
  5786. if (length === undefined) {
  5787. for (key in obj) {
  5788. if (obj.hasOwnProperty(key)) {
  5789. value = obj[key];
  5790. if (callback.call(value, key, value) === false) {
  5791. break;
  5792. }
  5793. }
  5794. }
  5795. } else {
  5796. for (i = 0; i < length; i++) {
  5797. value = obj[i];
  5798. if (callback.call(value, i, value) === false) {
  5799. break;
  5800. }
  5801. }
  5802. }
  5803. }
  5804. return obj;
  5805. };
  5806. var grep$2 = function (array, callback) {
  5807. var out = [];
  5808. each$g(array, function (i, item) {
  5809. if (callback(item, i)) {
  5810. out.push(item);
  5811. }
  5812. });
  5813. return out;
  5814. };
  5815. var getElementDocument = function (element) {
  5816. if (!element) {
  5817. return doc;
  5818. }
  5819. if (element.nodeType === 9) {
  5820. return element;
  5821. }
  5822. return element.ownerDocument;
  5823. };
  5824. DomQueryConstructor.fn = DomQueryConstructor.prototype = {
  5825. constructor: DomQueryConstructor,
  5826. selector: '',
  5827. context: null,
  5828. length: 0,
  5829. init: function (selector, context) {
  5830. var self = this;
  5831. var match, node;
  5832. if (!selector) {
  5833. return self;
  5834. }
  5835. if (selector.nodeType) {
  5836. self.context = self[0] = selector;
  5837. self.length = 1;
  5838. return self;
  5839. }
  5840. if (context && context.nodeType) {
  5841. self.context = context;
  5842. } else {
  5843. if (context) {
  5844. return DomQuery(selector).attr(context);
  5845. }
  5846. self.context = context = document;
  5847. }
  5848. if (isString(selector)) {
  5849. self.selector = selector;
  5850. if (selector.charAt(0) === '<' && selector.charAt(selector.length - 1) === '>' && selector.length >= 3) {
  5851. match = [
  5852. null,
  5853. selector,
  5854. null
  5855. ];
  5856. } else {
  5857. match = rquickExpr.exec(selector);
  5858. }
  5859. if (match) {
  5860. if (match[1]) {
  5861. node = createFragment$1(selector, getElementDocument(context)).firstChild;
  5862. while (node) {
  5863. push.call(self, node);
  5864. node = node.nextSibling;
  5865. }
  5866. } else {
  5867. node = getElementDocument(context).getElementById(match[2]);
  5868. if (!node) {
  5869. return self;
  5870. }
  5871. if (node.id !== match[2]) {
  5872. return self.find(selector);
  5873. }
  5874. self.length = 1;
  5875. self[0] = node;
  5876. }
  5877. } else {
  5878. return DomQuery(context).find(selector);
  5879. }
  5880. } else {
  5881. this.add(selector, false);
  5882. }
  5883. return self;
  5884. },
  5885. toArray: function () {
  5886. return Tools.toArray(this);
  5887. },
  5888. add: function (items, sort) {
  5889. var self = this;
  5890. var nodes, i;
  5891. if (isString(items)) {
  5892. return self.add(DomQuery(items));
  5893. }
  5894. if (sort !== false) {
  5895. nodes = DomQuery.unique(self.toArray().concat(DomQuery.makeArray(items)));
  5896. self.length = nodes.length;
  5897. for (i = 0; i < nodes.length; i++) {
  5898. self[i] = nodes[i];
  5899. }
  5900. } else {
  5901. push.apply(self, DomQuery.makeArray(items));
  5902. }
  5903. return self;
  5904. },
  5905. attr: function (name, value) {
  5906. var self = this;
  5907. var hook;
  5908. if (typeof name === 'object') {
  5909. each$g(name, function (name, value) {
  5910. self.attr(name, value);
  5911. });
  5912. } else if (isDefined(value)) {
  5913. this.each(function () {
  5914. var hook;
  5915. if (this.nodeType === 1) {
  5916. hook = attrHooks[name];
  5917. if (hook && hook.set) {
  5918. hook.set(this, value);
  5919. return;
  5920. }
  5921. if (value === null) {
  5922. this.removeAttribute(name, 2);
  5923. } else {
  5924. this.setAttribute(name, value, 2);
  5925. }
  5926. }
  5927. });
  5928. } else {
  5929. if (self[0] && self[0].nodeType === 1) {
  5930. hook = attrHooks[name];
  5931. if (hook && hook.get) {
  5932. return hook.get(self[0], name);
  5933. }
  5934. if (booleanMap[name]) {
  5935. return self.prop(name) ? name : undefined;
  5936. }
  5937. value = self[0].getAttribute(name, 2);
  5938. if (value === null) {
  5939. value = undefined;
  5940. }
  5941. }
  5942. return value;
  5943. }
  5944. return self;
  5945. },
  5946. removeAttr: function (name) {
  5947. return this.attr(name, null);
  5948. },
  5949. prop: function (name, value) {
  5950. var self = this;
  5951. name = propFix[name] || name;
  5952. if (typeof name === 'object') {
  5953. each$g(name, function (name, value) {
  5954. self.prop(name, value);
  5955. });
  5956. } else if (isDefined(value)) {
  5957. this.each(function () {
  5958. if (this.nodeType === 1) {
  5959. this[name] = value;
  5960. }
  5961. });
  5962. } else {
  5963. if (self[0] && self[0].nodeType && name in self[0]) {
  5964. return self[0][name];
  5965. }
  5966. return value;
  5967. }
  5968. return self;
  5969. },
  5970. css: function (name, value) {
  5971. var self = this;
  5972. var elm, hook;
  5973. var camel = function (name) {
  5974. return name.replace(/-(\D)/g, function (a, b) {
  5975. return b.toUpperCase();
  5976. });
  5977. };
  5978. var dashed = function (name) {
  5979. return name.replace(/[A-Z]/g, function (a) {
  5980. return '-' + a;
  5981. });
  5982. };
  5983. if (typeof name === 'object') {
  5984. each$g(name, function (name, value) {
  5985. self.css(name, value);
  5986. });
  5987. } else {
  5988. if (isDefined(value)) {
  5989. name = camel(name);
  5990. if (typeof value === 'number' && !numericCssMap[name]) {
  5991. value = value.toString() + 'px';
  5992. }
  5993. self.each(function () {
  5994. var style = this.style;
  5995. hook = cssHooks[name];
  5996. if (hook && hook.set) {
  5997. hook.set(this, value);
  5998. return;
  5999. }
  6000. try {
  6001. this.style[cssFix[name] || name] = value;
  6002. } catch (ex) {
  6003. }
  6004. if (value === null || value === '') {
  6005. if (style.removeProperty) {
  6006. style.removeProperty(dashed(name));
  6007. } else {
  6008. style.removeAttribute(name);
  6009. }
  6010. }
  6011. });
  6012. } else {
  6013. elm = self[0];
  6014. hook = cssHooks[name];
  6015. if (hook && hook.get) {
  6016. return hook.get(elm);
  6017. }
  6018. if (elm.ownerDocument.defaultView) {
  6019. try {
  6020. return elm.ownerDocument.defaultView.getComputedStyle(elm, null).getPropertyValue(dashed(name));
  6021. } catch (ex) {
  6022. return undefined;
  6023. }
  6024. } else if (elm.currentStyle) {
  6025. return elm.currentStyle[camel(name)];
  6026. } else {
  6027. return '';
  6028. }
  6029. }
  6030. }
  6031. return self;
  6032. },
  6033. remove: function () {
  6034. var self = this;
  6035. var node, i = this.length;
  6036. while (i--) {
  6037. node = self[i];
  6038. Event$1.clean(node);
  6039. if (node.parentNode) {
  6040. node.parentNode.removeChild(node);
  6041. }
  6042. }
  6043. return this;
  6044. },
  6045. empty: function () {
  6046. var self = this;
  6047. var node, i = this.length;
  6048. while (i--) {
  6049. node = self[i];
  6050. while (node.firstChild) {
  6051. node.removeChild(node.firstChild);
  6052. }
  6053. }
  6054. return this;
  6055. },
  6056. html: function (value) {
  6057. var self = this;
  6058. var i;
  6059. if (isDefined(value)) {
  6060. i = self.length;
  6061. try {
  6062. while (i--) {
  6063. self[i].innerHTML = value;
  6064. }
  6065. } catch (ex) {
  6066. DomQuery(self[i]).empty().append(value);
  6067. }
  6068. return self;
  6069. }
  6070. return self[0] ? self[0].innerHTML : '';
  6071. },
  6072. text: function (value) {
  6073. var self = this;
  6074. var i;
  6075. if (isDefined(value)) {
  6076. i = self.length;
  6077. while (i--) {
  6078. if ('innerText' in self[i]) {
  6079. self[i].innerText = value;
  6080. } else {
  6081. self[0].textContent = value;
  6082. }
  6083. }
  6084. return self;
  6085. }
  6086. return self[0] ? self[0].innerText || self[0].textContent : '';
  6087. },
  6088. append: function () {
  6089. return domManipulate(this, arguments, function (node) {
  6090. if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6091. this.appendChild(node);
  6092. }
  6093. });
  6094. },
  6095. prepend: function () {
  6096. return domManipulate(this, arguments, function (node) {
  6097. if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6098. this.insertBefore(node, this.firstChild);
  6099. }
  6100. }, true);
  6101. },
  6102. before: function () {
  6103. var self = this;
  6104. if (self[0] && self[0].parentNode) {
  6105. return domManipulate(self, arguments, function (node) {
  6106. this.parentNode.insertBefore(node, this);
  6107. });
  6108. }
  6109. return self;
  6110. },
  6111. after: function () {
  6112. var self = this;
  6113. if (self[0] && self[0].parentNode) {
  6114. return domManipulate(self, arguments, function (node) {
  6115. this.parentNode.insertBefore(node, this.nextSibling);
  6116. }, true);
  6117. }
  6118. return self;
  6119. },
  6120. appendTo: function (val) {
  6121. DomQuery(val).append(this);
  6122. return this;
  6123. },
  6124. prependTo: function (val) {
  6125. DomQuery(val).prepend(this);
  6126. return this;
  6127. },
  6128. replaceWith: function (content) {
  6129. return this.before(content).remove();
  6130. },
  6131. wrap: function (content) {
  6132. return wrap$2(this, content);
  6133. },
  6134. wrapAll: function (content) {
  6135. return wrap$2(this, content, true);
  6136. },
  6137. wrapInner: function (content) {
  6138. this.each(function () {
  6139. DomQuery(this).contents().wrapAll(content);
  6140. });
  6141. return this;
  6142. },
  6143. unwrap: function () {
  6144. return this.parent().each(function () {
  6145. DomQuery(this).replaceWith(this.childNodes);
  6146. });
  6147. },
  6148. clone: function () {
  6149. var result = [];
  6150. this.each(function () {
  6151. result.push(this.cloneNode(true));
  6152. });
  6153. return DomQuery(result);
  6154. },
  6155. addClass: function (className) {
  6156. return this.toggleClass(className, true);
  6157. },
  6158. removeClass: function (className) {
  6159. return this.toggleClass(className, false);
  6160. },
  6161. toggleClass: function (className, state) {
  6162. var self = this;
  6163. if (typeof className !== 'string') {
  6164. return self;
  6165. }
  6166. if (className.indexOf(' ') !== -1) {
  6167. each$g(className.split(' '), function () {
  6168. self.toggleClass(this, state);
  6169. });
  6170. } else {
  6171. self.each(function (index, node) {
  6172. var classState = hasClass(node, className);
  6173. if (classState !== state) {
  6174. var existingClassName = node.className;
  6175. if (classState) {
  6176. node.className = trim$1((' ' + existingClassName + ' ').replace(' ' + className + ' ', ' '));
  6177. } else {
  6178. node.className += existingClassName ? ' ' + className : className;
  6179. }
  6180. }
  6181. });
  6182. }
  6183. return self;
  6184. },
  6185. hasClass: function (className) {
  6186. return hasClass(this[0], className);
  6187. },
  6188. each: function (callback) {
  6189. return each$g(this, callback);
  6190. },
  6191. on: function (name, callback) {
  6192. return this.each(function () {
  6193. Event$1.bind(this, name, callback);
  6194. });
  6195. },
  6196. off: function (name, callback) {
  6197. return this.each(function () {
  6198. Event$1.unbind(this, name, callback);
  6199. });
  6200. },
  6201. trigger: function (name) {
  6202. return this.each(function () {
  6203. if (typeof name === 'object') {
  6204. Event$1.fire(this, name.type, name);
  6205. } else {
  6206. Event$1.fire(this, name);
  6207. }
  6208. });
  6209. },
  6210. show: function () {
  6211. return this.css('display', '');
  6212. },
  6213. hide: function () {
  6214. return this.css('display', 'none');
  6215. },
  6216. slice: function () {
  6217. return DomQuery(slice.apply(this, arguments));
  6218. },
  6219. eq: function (index) {
  6220. return index === -1 ? this.slice(index) : this.slice(index, +index + 1);
  6221. },
  6222. first: function () {
  6223. return this.eq(0);
  6224. },
  6225. last: function () {
  6226. return this.eq(-1);
  6227. },
  6228. find: function (selector) {
  6229. var i, l;
  6230. var ret = [];
  6231. for (i = 0, l = this.length; i < l; i++) {
  6232. DomQuery.find(selector, this[i], ret);
  6233. }
  6234. return DomQuery(ret);
  6235. },
  6236. filter: function (selector) {
  6237. if (typeof selector === 'function') {
  6238. return DomQuery(grep$2(this.toArray(), function (item, i) {
  6239. return selector(i, item);
  6240. }));
  6241. }
  6242. return DomQuery(DomQuery.filter(selector, this.toArray()));
  6243. },
  6244. closest: function (selector) {
  6245. var result = [];
  6246. if (selector instanceof DomQuery) {
  6247. selector = selector[0];
  6248. }
  6249. this.each(function (i, node) {
  6250. while (node) {
  6251. if (typeof selector === 'string' && DomQuery(node).is(selector)) {
  6252. result.push(node);
  6253. break;
  6254. } else if (node === selector) {
  6255. result.push(node);
  6256. break;
  6257. }
  6258. node = node.parentNode;
  6259. }
  6260. });
  6261. return DomQuery(result);
  6262. },
  6263. offset: function (offset) {
  6264. var elm, doc, docElm;
  6265. var x = 0, y = 0, pos;
  6266. if (!offset) {
  6267. elm = this[0];
  6268. if (elm) {
  6269. doc = elm.ownerDocument;
  6270. docElm = doc.documentElement;
  6271. if (elm.getBoundingClientRect) {
  6272. pos = elm.getBoundingClientRect();
  6273. x = pos.left + (docElm.scrollLeft || doc.body.scrollLeft) - docElm.clientLeft;
  6274. y = pos.top + (docElm.scrollTop || doc.body.scrollTop) - docElm.clientTop;
  6275. }
  6276. }
  6277. return {
  6278. left: x,
  6279. top: y
  6280. };
  6281. }
  6282. return this.css(offset);
  6283. },
  6284. push: push,
  6285. sort: Array.prototype.sort,
  6286. splice: Array.prototype.splice
  6287. };
  6288. Tools.extend(DomQueryConstructor, {
  6289. extend: Tools.extend,
  6290. makeArray: function (object) {
  6291. if (isWindow(object) || object.nodeType) {
  6292. return [object];
  6293. }
  6294. return Tools.toArray(object);
  6295. },
  6296. inArray: inArray$1,
  6297. isArray: Tools.isArray,
  6298. each: each$g,
  6299. trim: trim$1,
  6300. grep: grep$2,
  6301. find: Sizzle,
  6302. expr: Sizzle.selectors,
  6303. unique: Sizzle.uniqueSort,
  6304. text: Sizzle.getText,
  6305. contains: Sizzle.contains,
  6306. filter: function (expr, elems, not) {
  6307. var i = elems.length;
  6308. if (not) {
  6309. expr = ':not(' + expr + ')';
  6310. }
  6311. while (i--) {
  6312. if (elems[i].nodeType !== 1) {
  6313. elems.splice(i, 1);
  6314. }
  6315. }
  6316. if (elems.length === 1) {
  6317. elems = DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [];
  6318. } else {
  6319. elems = DomQuery.find.matches(expr, elems);
  6320. }
  6321. return elems;
  6322. }
  6323. });
  6324. var dir = function (el, prop, until) {
  6325. var matched = [];
  6326. var cur = el[prop];
  6327. if (typeof until !== 'string' && until instanceof DomQuery) {
  6328. until = until[0];
  6329. }
  6330. while (cur && cur.nodeType !== 9) {
  6331. if (until !== undefined) {
  6332. if (cur === until) {
  6333. break;
  6334. }
  6335. if (typeof until === 'string' && DomQuery(cur).is(until)) {
  6336. break;
  6337. }
  6338. }
  6339. if (cur.nodeType === 1) {
  6340. matched.push(cur);
  6341. }
  6342. cur = cur[prop];
  6343. }
  6344. return matched;
  6345. };
  6346. var sibling$1 = function (node, siblingName, nodeType, until) {
  6347. var result = [];
  6348. if (until instanceof DomQuery) {
  6349. until = until[0];
  6350. }
  6351. for (; node; node = node[siblingName]) {
  6352. if (nodeType && node.nodeType !== nodeType) {
  6353. continue;
  6354. }
  6355. if (until !== undefined) {
  6356. if (node === until) {
  6357. break;
  6358. }
  6359. if (typeof until === 'string' && DomQuery(node).is(until)) {
  6360. break;
  6361. }
  6362. }
  6363. result.push(node);
  6364. }
  6365. return result;
  6366. };
  6367. var firstSibling = function (node, siblingName, nodeType) {
  6368. for (node = node[siblingName]; node; node = node[siblingName]) {
  6369. if (node.nodeType === nodeType) {
  6370. return node;
  6371. }
  6372. }
  6373. return null;
  6374. };
  6375. each$g({
  6376. parent: function (node) {
  6377. var parent = node.parentNode;
  6378. return parent && parent.nodeType !== 11 ? parent : null;
  6379. },
  6380. parents: function (node) {
  6381. return dir(node, 'parentNode');
  6382. },
  6383. next: function (node) {
  6384. return firstSibling(node, 'nextSibling', 1);
  6385. },
  6386. prev: function (node) {
  6387. return firstSibling(node, 'previousSibling', 1);
  6388. },
  6389. children: function (node) {
  6390. return sibling$1(node.firstChild, 'nextSibling', 1);
  6391. },
  6392. contents: function (node) {
  6393. return Tools.toArray((node.nodeName === 'iframe' ? node.contentDocument || node.contentWindow.document : node).childNodes);
  6394. }
  6395. }, function (name, fn) {
  6396. DomQueryConstructor.fn[name] = function (selector) {
  6397. var self = this;
  6398. var result = [];
  6399. self.each(function () {
  6400. var nodes = fn.call(result, this, selector, result);
  6401. if (nodes) {
  6402. if (DomQuery.isArray(nodes)) {
  6403. result.push.apply(result, nodes);
  6404. } else {
  6405. result.push(nodes);
  6406. }
  6407. }
  6408. });
  6409. if (this.length > 1) {
  6410. if (!skipUniques[name]) {
  6411. result = DomQuery.unique(result);
  6412. }
  6413. if (name.indexOf('parents') === 0) {
  6414. result = result.reverse();
  6415. }
  6416. }
  6417. var wrappedResult = DomQuery(result);
  6418. if (selector) {
  6419. return wrappedResult.filter(selector);
  6420. }
  6421. return wrappedResult;
  6422. };
  6423. });
  6424. each$g({
  6425. parentsUntil: function (node, until) {
  6426. return dir(node, 'parentNode', until);
  6427. },
  6428. nextUntil: function (node, until) {
  6429. return sibling$1(node, 'nextSibling', 1, until).slice(1);
  6430. },
  6431. prevUntil: function (node, until) {
  6432. return sibling$1(node, 'previousSibling', 1, until).slice(1);
  6433. }
  6434. }, function (name, fn) {
  6435. DomQueryConstructor.fn[name] = function (selector, filter) {
  6436. var self = this;
  6437. var result = [];
  6438. self.each(function () {
  6439. var nodes = fn.call(result, this, selector, result);
  6440. if (nodes) {
  6441. if (DomQuery.isArray(nodes)) {
  6442. result.push.apply(result, nodes);
  6443. } else {
  6444. result.push(nodes);
  6445. }
  6446. }
  6447. });
  6448. if (this.length > 1) {
  6449. result = DomQuery.unique(result);
  6450. if (name.indexOf('parents') === 0 || name === 'prevUntil') {
  6451. result = result.reverse();
  6452. }
  6453. }
  6454. var wrappedResult = DomQuery(result);
  6455. if (filter) {
  6456. return wrappedResult.filter(filter);
  6457. }
  6458. return wrappedResult;
  6459. };
  6460. });
  6461. DomQueryConstructor.fn.is = function (selector) {
  6462. return !!selector && this.filter(selector).length > 0;
  6463. };
  6464. DomQueryConstructor.fn.init.prototype = DomQueryConstructor.fn;
  6465. DomQueryConstructor.overrideDefaults = function (callback) {
  6466. var defaults;
  6467. var sub = function (selector, context) {
  6468. defaults = defaults || callback();
  6469. if (arguments.length === 0) {
  6470. selector = defaults.element;
  6471. }
  6472. if (!context) {
  6473. context = defaults.context;
  6474. }
  6475. return new sub.fn.init(selector, context);
  6476. };
  6477. DomQuery.extend(sub, this);
  6478. return sub;
  6479. };
  6480. DomQueryConstructor.attrHooks = attrHooks;
  6481. DomQueryConstructor.cssHooks = cssHooks;
  6482. var DomQuery = DomQueryConstructor;
  6483. var each$f = Tools.each;
  6484. var grep$1 = Tools.grep;
  6485. var isIE = Env.ie;
  6486. var simpleSelectorRe = /^([a-z0-9],?)+$/i;
  6487. var setupAttrHooks = function (styles, settings, getContext) {
  6488. var keepValues = settings.keep_values;
  6489. var keepUrlHook = {
  6490. set: function ($elm, value, name) {
  6491. if (settings.url_converter && value !== null) {
  6492. value = settings.url_converter.call(settings.url_converter_scope || getContext(), value, name, $elm[0]);
  6493. }
  6494. $elm.attr('data-mce-' + name, value).attr(name, value);
  6495. },
  6496. get: function ($elm, name) {
  6497. return $elm.attr('data-mce-' + name) || $elm.attr(name);
  6498. }
  6499. };
  6500. var attrHooks = {
  6501. style: {
  6502. set: function ($elm, value) {
  6503. if (value !== null && typeof value === 'object') {
  6504. $elm.css(value);
  6505. return;
  6506. }
  6507. if (keepValues) {
  6508. $elm.attr('data-mce-style', value);
  6509. }
  6510. if (value !== null && typeof value === 'string') {
  6511. $elm.removeAttr('style');
  6512. $elm.css(styles.parse(value));
  6513. } else {
  6514. $elm.attr('style', value);
  6515. }
  6516. },
  6517. get: function ($elm) {
  6518. var value = $elm.attr('data-mce-style') || $elm.attr('style');
  6519. value = styles.serialize(styles.parse(value), $elm[0].nodeName);
  6520. return value;
  6521. }
  6522. }
  6523. };
  6524. if (keepValues) {
  6525. attrHooks.href = attrHooks.src = keepUrlHook;
  6526. }
  6527. return attrHooks;
  6528. };
  6529. var updateInternalStyleAttr = function (styles, $elm) {
  6530. var rawValue = $elm.attr('style');
  6531. var value = styles.serialize(styles.parse(rawValue), $elm[0].nodeName);
  6532. if (!value) {
  6533. value = null;
  6534. }
  6535. $elm.attr('data-mce-style', value);
  6536. };
  6537. var findNodeIndex = function (node, normalized) {
  6538. var idx = 0, lastNodeType, nodeType;
  6539. if (node) {
  6540. for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
  6541. nodeType = node.nodeType;
  6542. if (normalized && nodeType === 3) {
  6543. if (nodeType === lastNodeType || !node.nodeValue.length) {
  6544. continue;
  6545. }
  6546. }
  6547. idx++;
  6548. lastNodeType = nodeType;
  6549. }
  6550. }
  6551. return idx;
  6552. };
  6553. var DOMUtils = function (doc, settings) {
  6554. if (settings === void 0) {
  6555. settings = {};
  6556. }
  6557. var addedStyles = {};
  6558. var win = window;
  6559. var files = {};
  6560. var counter = 0;
  6561. var stdMode = true;
  6562. var boxModel = true;
  6563. var styleSheetLoader = instance.forElement(SugarElement.fromDom(doc), {
  6564. contentCssCors: settings.contentCssCors,
  6565. referrerPolicy: settings.referrerPolicy
  6566. });
  6567. var boundEvents = [];
  6568. var schema = settings.schema ? settings.schema : Schema({});
  6569. var styles = Styles({
  6570. url_converter: settings.url_converter,
  6571. url_converter_scope: settings.url_converter_scope
  6572. }, settings.schema);
  6573. var events = settings.ownEvents ? new EventUtils() : EventUtils.Event;
  6574. var blockElementsMap = schema.getBlockElements();
  6575. var $ = DomQuery.overrideDefaults(function () {
  6576. return {
  6577. context: doc,
  6578. element: self.getRoot()
  6579. };
  6580. });
  6581. var isBlock = function (node) {
  6582. if (typeof node === 'string') {
  6583. return !!blockElementsMap[node];
  6584. } else if (node) {
  6585. var type = node.nodeType;
  6586. if (type) {
  6587. return !!(type === 1 && blockElementsMap[node.nodeName]);
  6588. }
  6589. }
  6590. return false;
  6591. };
  6592. var get = function (elm) {
  6593. return elm && doc && isString$1(elm) ? doc.getElementById(elm) : elm;
  6594. };
  6595. var $$ = function (elm) {
  6596. return $(typeof elm === 'string' ? get(elm) : elm);
  6597. };
  6598. var getAttrib = function (elm, name, defaultVal) {
  6599. var hook, value;
  6600. var $elm = $$(elm);
  6601. if ($elm.length) {
  6602. hook = attrHooks[name];
  6603. if (hook && hook.get) {
  6604. value = hook.get($elm, name);
  6605. } else {
  6606. value = $elm.attr(name);
  6607. }
  6608. }
  6609. if (typeof value === 'undefined') {
  6610. value = defaultVal || '';
  6611. }
  6612. return value;
  6613. };
  6614. var getAttribs = function (elm) {
  6615. var node = get(elm);
  6616. if (!node) {
  6617. return [];
  6618. }
  6619. return node.attributes;
  6620. };
  6621. var setAttrib = function (elm, name, value) {
  6622. if (value === '') {
  6623. value = null;
  6624. }
  6625. var $elm = $$(elm);
  6626. var originalValue = $elm.attr(name);
  6627. if (!$elm.length) {
  6628. return;
  6629. }
  6630. var hook = attrHooks[name];
  6631. if (hook && hook.set) {
  6632. hook.set($elm, value, name);
  6633. } else {
  6634. $elm.attr(name, value);
  6635. }
  6636. if (originalValue !== value && settings.onSetAttrib) {
  6637. settings.onSetAttrib({
  6638. attrElm: $elm,
  6639. attrName: name,
  6640. attrValue: value
  6641. });
  6642. }
  6643. };
  6644. var clone = function (node, deep) {
  6645. if (!isIE || node.nodeType !== 1 || deep) {
  6646. return node.cloneNode(deep);
  6647. } else {
  6648. var clone_1 = doc.createElement(node.nodeName);
  6649. each$f(getAttribs(node), function (attr) {
  6650. setAttrib(clone_1, attr.nodeName, getAttrib(node, attr.nodeName));
  6651. });
  6652. return clone_1;
  6653. }
  6654. };
  6655. var getRoot = function () {
  6656. return settings.root_element || doc.body;
  6657. };
  6658. var getViewPort = function (argWin) {
  6659. var vp = getBounds(argWin);
  6660. return {
  6661. x: vp.x,
  6662. y: vp.y,
  6663. w: vp.width,
  6664. h: vp.height
  6665. };
  6666. };
  6667. var getPos$1 = function (elm, rootElm) {
  6668. return getPos(doc.body, get(elm), rootElm);
  6669. };
  6670. var setStyle = function (elm, name, value) {
  6671. var $elm = isString$1(name) ? $$(elm).css(name, value) : $$(elm).css(name);
  6672. if (settings.update_styles) {
  6673. updateInternalStyleAttr(styles, $elm);
  6674. }
  6675. };
  6676. var setStyles = function (elm, stylesArg) {
  6677. var $elm = $$(elm).css(stylesArg);
  6678. if (settings.update_styles) {
  6679. updateInternalStyleAttr(styles, $elm);
  6680. }
  6681. };
  6682. var getStyle = function (elm, name, computed) {
  6683. var $elm = $$(elm);
  6684. if (computed) {
  6685. return $elm.css(name);
  6686. }
  6687. name = name.replace(/-(\D)/g, function (a, b) {
  6688. return b.toUpperCase();
  6689. });
  6690. if (name === 'float') {
  6691. name = Env.browser.isIE() ? 'styleFloat' : 'cssFloat';
  6692. }
  6693. return $elm[0] && $elm[0].style ? $elm[0].style[name] : undefined;
  6694. };
  6695. var getSize = function (elm) {
  6696. var w, h;
  6697. elm = get(elm);
  6698. w = getStyle(elm, 'width');
  6699. h = getStyle(elm, 'height');
  6700. if (w.indexOf('px') === -1) {
  6701. w = 0;
  6702. }
  6703. if (h.indexOf('px') === -1) {
  6704. h = 0;
  6705. }
  6706. return {
  6707. w: parseInt(w, 10) || elm.offsetWidth || elm.clientWidth,
  6708. h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight
  6709. };
  6710. };
  6711. var getRect = function (elm) {
  6712. elm = get(elm);
  6713. var pos = getPos$1(elm);
  6714. var size = getSize(elm);
  6715. return {
  6716. x: pos.x,
  6717. y: pos.y,
  6718. w: size.w,
  6719. h: size.h
  6720. };
  6721. };
  6722. var is = function (elm, selector) {
  6723. var i;
  6724. if (!elm) {
  6725. return false;
  6726. }
  6727. if (!Array.isArray(elm)) {
  6728. if (selector === '*') {
  6729. return elm.nodeType === 1;
  6730. }
  6731. if (simpleSelectorRe.test(selector)) {
  6732. var selectors = selector.toLowerCase().split(/,/);
  6733. var elmName = elm.nodeName.toLowerCase();
  6734. for (i = selectors.length - 1; i >= 0; i--) {
  6735. if (selectors[i] === elmName) {
  6736. return true;
  6737. }
  6738. }
  6739. return false;
  6740. }
  6741. if (elm.nodeType && elm.nodeType !== 1) {
  6742. return false;
  6743. }
  6744. }
  6745. var elms = !Array.isArray(elm) ? [elm] : elm;
  6746. return Sizzle(selector, elms[0].ownerDocument || elms[0], null, elms).length > 0;
  6747. };
  6748. var getParents = function (elm, selector, root, collect) {
  6749. var result = [];
  6750. var selectorVal;
  6751. var node = get(elm);
  6752. collect = collect === undefined;
  6753. root = root || (getRoot().nodeName !== 'BODY' ? getRoot().parentNode : null);
  6754. if (Tools.is(selector, 'string')) {
  6755. selectorVal = selector;
  6756. if (selector === '*') {
  6757. selector = function (node) {
  6758. return node.nodeType === 1;
  6759. };
  6760. } else {
  6761. selector = function (node) {
  6762. return is(node, selectorVal);
  6763. };
  6764. }
  6765. }
  6766. while (node) {
  6767. if (node === root || isNullable(node.nodeType) || isDocument$1(node) || isDocumentFragment(node)) {
  6768. break;
  6769. }
  6770. if (!selector || typeof selector === 'function' && selector(node)) {
  6771. if (collect) {
  6772. result.push(node);
  6773. } else {
  6774. return [node];
  6775. }
  6776. }
  6777. node = node.parentNode;
  6778. }
  6779. return collect ? result : null;
  6780. };
  6781. var getParent = function (node, selector, root) {
  6782. var parents = getParents(node, selector, root, false);
  6783. return parents && parents.length > 0 ? parents[0] : null;
  6784. };
  6785. var _findSib = function (node, selector, name) {
  6786. var func = selector;
  6787. if (node) {
  6788. if (typeof selector === 'string') {
  6789. func = function (node) {
  6790. return is(node, selector);
  6791. };
  6792. }
  6793. for (node = node[name]; node; node = node[name]) {
  6794. if (typeof func === 'function' && func(node)) {
  6795. return node;
  6796. }
  6797. }
  6798. }
  6799. return null;
  6800. };
  6801. var getNext = function (node, selector) {
  6802. return _findSib(node, selector, 'nextSibling');
  6803. };
  6804. var getPrev = function (node, selector) {
  6805. return _findSib(node, selector, 'previousSibling');
  6806. };
  6807. var select = function (selector, scope) {
  6808. return Sizzle(selector, get(scope) || settings.root_element || doc, []);
  6809. };
  6810. var run = function (elm, func, scope) {
  6811. var result;
  6812. var node = typeof elm === 'string' ? get(elm) : elm;
  6813. if (!node) {
  6814. return false;
  6815. }
  6816. if (Tools.isArray(node) && (node.length || node.length === 0)) {
  6817. result = [];
  6818. each$f(node, function (elm, i) {
  6819. if (elm) {
  6820. result.push(func.call(scope, typeof elm === 'string' ? get(elm) : elm, i));
  6821. }
  6822. });
  6823. return result;
  6824. }
  6825. var context = scope ? scope : this;
  6826. return func.call(context, node);
  6827. };
  6828. var setAttribs = function (elm, attrs) {
  6829. $$(elm).each(function (i, node) {
  6830. each$f(attrs, function (value, name) {
  6831. setAttrib(node, name, value);
  6832. });
  6833. });
  6834. };
  6835. var setHTML = function (elm, html) {
  6836. var $elm = $$(elm);
  6837. if (isIE) {
  6838. $elm.each(function (i, target) {
  6839. if (target.canHaveHTML === false) {
  6840. return;
  6841. }
  6842. while (target.firstChild) {
  6843. target.removeChild(target.firstChild);
  6844. }
  6845. try {
  6846. target.innerHTML = '<br>' + html;
  6847. target.removeChild(target.firstChild);
  6848. } catch (ex) {
  6849. DomQuery('<div></div>').html('<br>' + html).contents().slice(1).appendTo(target);
  6850. }
  6851. return html;
  6852. });
  6853. } else {
  6854. $elm.html(html);
  6855. }
  6856. };
  6857. var add = function (parentElm, name, attrs, html, create) {
  6858. return run(parentElm, function (parentElm) {
  6859. var newElm = typeof name === 'string' ? doc.createElement(name) : name;
  6860. setAttribs(newElm, attrs);
  6861. if (html) {
  6862. if (typeof html !== 'string' && html.nodeType) {
  6863. newElm.appendChild(html);
  6864. } else if (typeof html === 'string') {
  6865. setHTML(newElm, html);
  6866. }
  6867. }
  6868. return !create ? parentElm.appendChild(newElm) : newElm;
  6869. });
  6870. };
  6871. var create = function (name, attrs, html) {
  6872. return add(doc.createElement(name), name, attrs, html, true);
  6873. };
  6874. var decode = Entities.decode;
  6875. var encode = Entities.encodeAllRaw;
  6876. var createHTML = function (name, attrs, html) {
  6877. var outHtml = '', key;
  6878. outHtml += '<' + name;
  6879. for (key in attrs) {
  6880. if (hasNonNullableKey(attrs, key)) {
  6881. outHtml += ' ' + key + '="' + encode(attrs[key]) + '"';
  6882. }
  6883. }
  6884. if (typeof html !== 'undefined') {
  6885. return outHtml + '>' + html + '</' + name + '>';
  6886. }
  6887. return outHtml + ' />';
  6888. };
  6889. var createFragment = function (html) {
  6890. var node;
  6891. var container = doc.createElement('div');
  6892. var frag = doc.createDocumentFragment();
  6893. frag.appendChild(container);
  6894. if (html) {
  6895. container.innerHTML = html;
  6896. }
  6897. while (node = container.firstChild) {
  6898. frag.appendChild(node);
  6899. }
  6900. frag.removeChild(container);
  6901. return frag;
  6902. };
  6903. var remove = function (node, keepChildren) {
  6904. var $node = $$(node);
  6905. if (keepChildren) {
  6906. $node.each(function () {
  6907. var child;
  6908. while (child = this.firstChild) {
  6909. if (child.nodeType === 3 && child.data.length === 0) {
  6910. this.removeChild(child);
  6911. } else {
  6912. this.parentNode.insertBefore(child, this);
  6913. }
  6914. }
  6915. }).remove();
  6916. } else {
  6917. $node.remove();
  6918. }
  6919. return $node.length > 1 ? $node.toArray() : $node[0];
  6920. };
  6921. var removeAllAttribs = function (e) {
  6922. return run(e, function (e) {
  6923. var i;
  6924. var attrs = e.attributes;
  6925. for (i = attrs.length - 1; i >= 0; i--) {
  6926. e.removeAttributeNode(attrs.item(i));
  6927. }
  6928. });
  6929. };
  6930. var parseStyle = function (cssText) {
  6931. return styles.parse(cssText);
  6932. };
  6933. var serializeStyle = function (stylesArg, name) {
  6934. return styles.serialize(stylesArg, name);
  6935. };
  6936. var addStyle = function (cssText) {
  6937. var head, styleElm;
  6938. if (self !== DOMUtils.DOM && doc === document) {
  6939. if (addedStyles[cssText]) {
  6940. return;
  6941. }
  6942. addedStyles[cssText] = true;
  6943. }
  6944. styleElm = doc.getElementById('mceDefaultStyles');
  6945. if (!styleElm) {
  6946. styleElm = doc.createElement('style');
  6947. styleElm.id = 'mceDefaultStyles';
  6948. styleElm.type = 'text/css';
  6949. head = doc.getElementsByTagName('head')[0];
  6950. if (head.firstChild) {
  6951. head.insertBefore(styleElm, head.firstChild);
  6952. } else {
  6953. head.appendChild(styleElm);
  6954. }
  6955. }
  6956. if (styleElm.styleSheet) {
  6957. styleElm.styleSheet.cssText += cssText;
  6958. } else {
  6959. styleElm.appendChild(doc.createTextNode(cssText));
  6960. }
  6961. };
  6962. var loadCSS = function (urls) {
  6963. if (!urls) {
  6964. urls = '';
  6965. }
  6966. each$k(urls.split(','), function (url) {
  6967. files[url] = true;
  6968. styleSheetLoader.load(url, noop);
  6969. });
  6970. };
  6971. var toggleClass = function (elm, cls, state) {
  6972. $$(elm).toggleClass(cls, state).each(function () {
  6973. if (this.className === '') {
  6974. DomQuery(this).attr('class', null);
  6975. }
  6976. });
  6977. };
  6978. var addClass = function (elm, cls) {
  6979. $$(elm).addClass(cls);
  6980. };
  6981. var removeClass = function (elm, cls) {
  6982. toggleClass(elm, cls, false);
  6983. };
  6984. var hasClass = function (elm, cls) {
  6985. return $$(elm).hasClass(cls);
  6986. };
  6987. var show = function (elm) {
  6988. $$(elm).show();
  6989. };
  6990. var hide = function (elm) {
  6991. $$(elm).hide();
  6992. };
  6993. var isHidden = function (elm) {
  6994. return $$(elm).css('display') === 'none';
  6995. };
  6996. var uniqueId = function (prefix) {
  6997. return (!prefix ? 'mce_' : prefix) + counter++;
  6998. };
  6999. var getOuterHTML = function (elm) {
  7000. var node = typeof elm === 'string' ? get(elm) : elm;
  7001. return isElement$5(node) ? node.outerHTML : DomQuery('<div></div>').append(DomQuery(node).clone()).html();
  7002. };
  7003. var setOuterHTML = function (elm, html) {
  7004. $$(elm).each(function () {
  7005. try {
  7006. if ('outerHTML' in this) {
  7007. this.outerHTML = html;
  7008. return;
  7009. }
  7010. } catch (ex) {
  7011. }
  7012. remove(DomQuery(this).html(html), true);
  7013. });
  7014. };
  7015. var insertAfter = function (node, reference) {
  7016. var referenceNode = get(reference);
  7017. return run(node, function (node) {
  7018. var parent = referenceNode.parentNode;
  7019. var nextSibling = referenceNode.nextSibling;
  7020. if (nextSibling) {
  7021. parent.insertBefore(node, nextSibling);
  7022. } else {
  7023. parent.appendChild(node);
  7024. }
  7025. return node;
  7026. });
  7027. };
  7028. var replace = function (newElm, oldElm, keepChildren) {
  7029. return run(oldElm, function (oldElm) {
  7030. if (Tools.is(oldElm, 'array')) {
  7031. newElm = newElm.cloneNode(true);
  7032. }
  7033. if (keepChildren) {
  7034. each$f(grep$1(oldElm.childNodes), function (node) {
  7035. newElm.appendChild(node);
  7036. });
  7037. }
  7038. return oldElm.parentNode.replaceChild(newElm, oldElm);
  7039. });
  7040. };
  7041. var rename = function (elm, name) {
  7042. var newElm;
  7043. if (elm.nodeName !== name.toUpperCase()) {
  7044. newElm = create(name);
  7045. each$f(getAttribs(elm), function (attrNode) {
  7046. setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
  7047. });
  7048. replace(newElm, elm, true);
  7049. }
  7050. return newElm || elm;
  7051. };
  7052. var findCommonAncestor = function (a, b) {
  7053. var ps = a, pe;
  7054. while (ps) {
  7055. pe = b;
  7056. while (pe && ps !== pe) {
  7057. pe = pe.parentNode;
  7058. }
  7059. if (ps === pe) {
  7060. break;
  7061. }
  7062. ps = ps.parentNode;
  7063. }
  7064. if (!ps && a.ownerDocument) {
  7065. return a.ownerDocument.documentElement;
  7066. }
  7067. return ps;
  7068. };
  7069. var toHex = function (rgbVal) {
  7070. return styles.toHex(Tools.trim(rgbVal));
  7071. };
  7072. var isNonEmptyElement = function (node) {
  7073. if (isElement$5(node)) {
  7074. var isNamedAnchor = node.nodeName.toLowerCase() === 'a' && !getAttrib(node, 'href') && getAttrib(node, 'id');
  7075. if (getAttrib(node, 'name') || getAttrib(node, 'data-mce-bookmark') || isNamedAnchor) {
  7076. return true;
  7077. }
  7078. }
  7079. return false;
  7080. };
  7081. var isEmpty = function (node, elements) {
  7082. var type, name, brCount = 0;
  7083. if (isNonEmptyElement(node)) {
  7084. return false;
  7085. }
  7086. node = node.firstChild;
  7087. if (node) {
  7088. var walker = new DomTreeWalker(node, node.parentNode);
  7089. var whitespace = schema ? schema.getWhiteSpaceElements() : {};
  7090. elements = elements || (schema ? schema.getNonEmptyElements() : null);
  7091. do {
  7092. type = node.nodeType;
  7093. if (isElement$5(node)) {
  7094. var bogusVal = node.getAttribute('data-mce-bogus');
  7095. if (bogusVal) {
  7096. node = walker.next(bogusVal === 'all');
  7097. continue;
  7098. }
  7099. name = node.nodeName.toLowerCase();
  7100. if (elements && elements[name]) {
  7101. if (name === 'br') {
  7102. brCount++;
  7103. node = walker.next();
  7104. continue;
  7105. }
  7106. return false;
  7107. }
  7108. if (isNonEmptyElement(node)) {
  7109. return false;
  7110. }
  7111. }
  7112. if (type === 8) {
  7113. return false;
  7114. }
  7115. if (type === 3 && !isWhitespaceText(node.nodeValue)) {
  7116. return false;
  7117. }
  7118. if (type === 3 && node.parentNode && whitespace[node.parentNode.nodeName] && isWhitespaceText(node.nodeValue)) {
  7119. return false;
  7120. }
  7121. node = walker.next();
  7122. } while (node);
  7123. }
  7124. return brCount <= 1;
  7125. };
  7126. var createRng = function () {
  7127. return doc.createRange();
  7128. };
  7129. var split = function (parentElm, splitElm, replacementElm) {
  7130. var range = createRng();
  7131. var beforeFragment;
  7132. var afterFragment;
  7133. var parentNode;
  7134. if (parentElm && splitElm) {
  7135. range.setStart(parentElm.parentNode, findNodeIndex(parentElm));
  7136. range.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
  7137. beforeFragment = range.extractContents();
  7138. range = createRng();
  7139. range.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
  7140. range.setEnd(parentElm.parentNode, findNodeIndex(parentElm) + 1);
  7141. afterFragment = range.extractContents();
  7142. parentNode = parentElm.parentNode;
  7143. parentNode.insertBefore(trimNode(self, beforeFragment), parentElm);
  7144. if (replacementElm) {
  7145. parentNode.insertBefore(replacementElm, parentElm);
  7146. } else {
  7147. parentNode.insertBefore(splitElm, parentElm);
  7148. }
  7149. parentNode.insertBefore(trimNode(self, afterFragment), parentElm);
  7150. remove(parentElm);
  7151. return replacementElm || splitElm;
  7152. }
  7153. };
  7154. var bind = function (target, name, func, scope) {
  7155. if (Tools.isArray(target)) {
  7156. var i = target.length;
  7157. var rv = [];
  7158. while (i--) {
  7159. rv[i] = bind(target[i], name, func, scope);
  7160. }
  7161. return rv;
  7162. }
  7163. if (settings.collect && (target === doc || target === win)) {
  7164. boundEvents.push([
  7165. target,
  7166. name,
  7167. func,
  7168. scope
  7169. ]);
  7170. }
  7171. var output = events.bind(target, name, func, scope || self);
  7172. return output;
  7173. };
  7174. var unbind = function (target, name, func) {
  7175. if (Tools.isArray(target)) {
  7176. var i = target.length;
  7177. var rv = [];
  7178. while (i--) {
  7179. rv[i] = unbind(target[i], name, func);
  7180. }
  7181. return rv;
  7182. } else {
  7183. if (boundEvents.length > 0 && (target === doc || target === win)) {
  7184. var i = boundEvents.length;
  7185. while (i--) {
  7186. var item = boundEvents[i];
  7187. if (target === item[0] && (!name || name === item[1]) && (!func || func === item[2])) {
  7188. events.unbind(item[0], item[1], item[2]);
  7189. }
  7190. }
  7191. }
  7192. return events.unbind(target, name, func);
  7193. }
  7194. };
  7195. var fire = function (target, name, evt) {
  7196. return events.fire(target, name, evt);
  7197. };
  7198. var getContentEditable = function (node) {
  7199. if (node && isElement$5(node)) {
  7200. var contentEditable = node.getAttribute('data-mce-contenteditable');
  7201. if (contentEditable && contentEditable !== 'inherit') {
  7202. return contentEditable;
  7203. }
  7204. return node.contentEditable !== 'inherit' ? node.contentEditable : null;
  7205. } else {
  7206. return null;
  7207. }
  7208. };
  7209. var getContentEditableParent = function (node) {
  7210. var root = getRoot();
  7211. var state = null;
  7212. for (; node && node !== root; node = node.parentNode) {
  7213. state = getContentEditable(node);
  7214. if (state !== null) {
  7215. break;
  7216. }
  7217. }
  7218. return state;
  7219. };
  7220. var destroy = function () {
  7221. if (boundEvents.length > 0) {
  7222. var i = boundEvents.length;
  7223. while (i--) {
  7224. var item = boundEvents[i];
  7225. events.unbind(item[0], item[1], item[2]);
  7226. }
  7227. }
  7228. each$j(files, function (_, url) {
  7229. styleSheetLoader.unload(url);
  7230. delete files[url];
  7231. });
  7232. if (Sizzle.setDocument) {
  7233. Sizzle.setDocument();
  7234. }
  7235. };
  7236. var isChildOf = function (node, parent) {
  7237. if (!isIE) {
  7238. return node === parent || parent.contains(node);
  7239. } else {
  7240. while (node) {
  7241. if (parent === node) {
  7242. return true;
  7243. }
  7244. node = node.parentNode;
  7245. }
  7246. return false;
  7247. }
  7248. };
  7249. var dumpRng = function (r) {
  7250. return 'startContainer: ' + r.startContainer.nodeName + ', startOffset: ' + r.startOffset + ', endContainer: ' + r.endContainer.nodeName + ', endOffset: ' + r.endOffset;
  7251. };
  7252. var self = {
  7253. doc: doc,
  7254. settings: settings,
  7255. win: win,
  7256. files: files,
  7257. stdMode: stdMode,
  7258. boxModel: boxModel,
  7259. styleSheetLoader: styleSheetLoader,
  7260. boundEvents: boundEvents,
  7261. styles: styles,
  7262. schema: schema,
  7263. events: events,
  7264. isBlock: isBlock,
  7265. $: $,
  7266. $$: $$,
  7267. root: null,
  7268. clone: clone,
  7269. getRoot: getRoot,
  7270. getViewPort: getViewPort,
  7271. getRect: getRect,
  7272. getSize: getSize,
  7273. getParent: getParent,
  7274. getParents: getParents,
  7275. get: get,
  7276. getNext: getNext,
  7277. getPrev: getPrev,
  7278. select: select,
  7279. is: is,
  7280. add: add,
  7281. create: create,
  7282. createHTML: createHTML,
  7283. createFragment: createFragment,
  7284. remove: remove,
  7285. setStyle: setStyle,
  7286. getStyle: getStyle,
  7287. setStyles: setStyles,
  7288. removeAllAttribs: removeAllAttribs,
  7289. setAttrib: setAttrib,
  7290. setAttribs: setAttribs,
  7291. getAttrib: getAttrib,
  7292. getPos: getPos$1,
  7293. parseStyle: parseStyle,
  7294. serializeStyle: serializeStyle,
  7295. addStyle: addStyle,
  7296. loadCSS: loadCSS,
  7297. addClass: addClass,
  7298. removeClass: removeClass,
  7299. hasClass: hasClass,
  7300. toggleClass: toggleClass,
  7301. show: show,
  7302. hide: hide,
  7303. isHidden: isHidden,
  7304. uniqueId: uniqueId,
  7305. setHTML: setHTML,
  7306. getOuterHTML: getOuterHTML,
  7307. setOuterHTML: setOuterHTML,
  7308. decode: decode,
  7309. encode: encode,
  7310. insertAfter: insertAfter,
  7311. replace: replace,
  7312. rename: rename,
  7313. findCommonAncestor: findCommonAncestor,
  7314. toHex: toHex,
  7315. run: run,
  7316. getAttribs: getAttribs,
  7317. isEmpty: isEmpty,
  7318. createRng: createRng,
  7319. nodeIndex: findNodeIndex,
  7320. split: split,
  7321. bind: bind,
  7322. unbind: unbind,
  7323. fire: fire,
  7324. getContentEditable: getContentEditable,
  7325. getContentEditableParent: getContentEditableParent,
  7326. destroy: destroy,
  7327. isChildOf: isChildOf,
  7328. dumpRng: dumpRng
  7329. };
  7330. var attrHooks = setupAttrHooks(styles, settings, constant(self));
  7331. return self;
  7332. };
  7333. DOMUtils.DOM = DOMUtils(document);
  7334. DOMUtils.nodeIndex = findNodeIndex;
  7335. var DOM$a = DOMUtils.DOM;
  7336. var each$e = Tools.each, grep = Tools.grep;
  7337. var QUEUED = 0;
  7338. var LOADING = 1;
  7339. var LOADED = 2;
  7340. var FAILED = 3;
  7341. var ScriptLoader = function () {
  7342. function ScriptLoader(settings) {
  7343. if (settings === void 0) {
  7344. settings = {};
  7345. }
  7346. this.states = {};
  7347. this.queue = [];
  7348. this.scriptLoadedCallbacks = {};
  7349. this.queueLoadedCallbacks = [];
  7350. this.loading = 0;
  7351. this.settings = settings;
  7352. }
  7353. ScriptLoader.prototype._setReferrerPolicy = function (referrerPolicy) {
  7354. this.settings.referrerPolicy = referrerPolicy;
  7355. };
  7356. ScriptLoader.prototype.loadScript = function (url, success, failure) {
  7357. var dom = DOM$a;
  7358. var elm;
  7359. var cleanup = function () {
  7360. dom.remove(id);
  7361. if (elm) {
  7362. elm.onerror = elm.onload = elm = null;
  7363. }
  7364. };
  7365. var done = function () {
  7366. cleanup();
  7367. success();
  7368. };
  7369. var error = function () {
  7370. cleanup();
  7371. if (isFunction(failure)) {
  7372. failure();
  7373. } else {
  7374. if (typeof console !== 'undefined' && console.log) {
  7375. console.log('Failed to load script: ' + url);
  7376. }
  7377. }
  7378. };
  7379. var id = dom.uniqueId();
  7380. elm = document.createElement('script');
  7381. elm.id = id;
  7382. elm.type = 'text/javascript';
  7383. elm.src = Tools._addCacheSuffix(url);
  7384. if (this.settings.referrerPolicy) {
  7385. dom.setAttrib(elm, 'referrerpolicy', this.settings.referrerPolicy);
  7386. }
  7387. elm.onload = done;
  7388. elm.onerror = error;
  7389. (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
  7390. };
  7391. ScriptLoader.prototype.isDone = function (url) {
  7392. return this.states[url] === LOADED;
  7393. };
  7394. ScriptLoader.prototype.markDone = function (url) {
  7395. this.states[url] = LOADED;
  7396. };
  7397. ScriptLoader.prototype.add = function (url, success, scope, failure) {
  7398. var state = this.states[url];
  7399. this.queue.push(url);
  7400. if (state === undefined) {
  7401. this.states[url] = QUEUED;
  7402. }
  7403. if (success) {
  7404. if (!this.scriptLoadedCallbacks[url]) {
  7405. this.scriptLoadedCallbacks[url] = [];
  7406. }
  7407. this.scriptLoadedCallbacks[url].push({
  7408. success: success,
  7409. failure: failure,
  7410. scope: scope || this
  7411. });
  7412. }
  7413. };
  7414. ScriptLoader.prototype.load = function (url, success, scope, failure) {
  7415. return this.add(url, success, scope, failure);
  7416. };
  7417. ScriptLoader.prototype.remove = function (url) {
  7418. delete this.states[url];
  7419. delete this.scriptLoadedCallbacks[url];
  7420. };
  7421. ScriptLoader.prototype.loadQueue = function (success, scope, failure) {
  7422. this.loadScripts(this.queue, success, scope, failure);
  7423. };
  7424. ScriptLoader.prototype.loadScripts = function (scripts, success, scope, failure) {
  7425. var self = this;
  7426. var failures = [];
  7427. var execCallbacks = function (name, url) {
  7428. each$e(self.scriptLoadedCallbacks[url], function (callback) {
  7429. if (isFunction(callback[name])) {
  7430. callback[name].call(callback.scope);
  7431. }
  7432. });
  7433. self.scriptLoadedCallbacks[url] = undefined;
  7434. };
  7435. self.queueLoadedCallbacks.push({
  7436. success: success,
  7437. failure: failure,
  7438. scope: scope || this
  7439. });
  7440. var loadScripts = function () {
  7441. var loadingScripts = grep(scripts);
  7442. scripts.length = 0;
  7443. each$e(loadingScripts, function (url) {
  7444. if (self.states[url] === LOADED) {
  7445. execCallbacks('success', url);
  7446. return;
  7447. }
  7448. if (self.states[url] === FAILED) {
  7449. execCallbacks('failure', url);
  7450. return;
  7451. }
  7452. if (self.states[url] !== LOADING) {
  7453. self.states[url] = LOADING;
  7454. self.loading++;
  7455. self.loadScript(url, function () {
  7456. self.states[url] = LOADED;
  7457. self.loading--;
  7458. execCallbacks('success', url);
  7459. loadScripts();
  7460. }, function () {
  7461. self.states[url] = FAILED;
  7462. self.loading--;
  7463. failures.push(url);
  7464. execCallbacks('failure', url);
  7465. loadScripts();
  7466. });
  7467. }
  7468. });
  7469. if (!self.loading) {
  7470. var notifyCallbacks = self.queueLoadedCallbacks.slice(0);
  7471. self.queueLoadedCallbacks.length = 0;
  7472. each$e(notifyCallbacks, function (callback) {
  7473. if (failures.length === 0) {
  7474. if (isFunction(callback.success)) {
  7475. callback.success.call(callback.scope);
  7476. }
  7477. } else {
  7478. if (isFunction(callback.failure)) {
  7479. callback.failure.call(callback.scope, failures);
  7480. }
  7481. }
  7482. });
  7483. }
  7484. };
  7485. loadScripts();
  7486. };
  7487. ScriptLoader.ScriptLoader = new ScriptLoader();
  7488. return ScriptLoader;
  7489. }();
  7490. var Cell = function (initial) {
  7491. var value = initial;
  7492. var get = function () {
  7493. return value;
  7494. };
  7495. var set = function (v) {
  7496. value = v;
  7497. };
  7498. return {
  7499. get: get,
  7500. set: set
  7501. };
  7502. };
  7503. var isRaw = function (str) {
  7504. return isObject(str) && has$2(str, 'raw');
  7505. };
  7506. var isTokenised = function (str) {
  7507. return isArray$1(str) && str.length > 1;
  7508. };
  7509. var data = {};
  7510. var currentCode = Cell('en');
  7511. var getLanguageData = function () {
  7512. return get$9(data, currentCode.get());
  7513. };
  7514. var getData = function () {
  7515. return map$2(data, function (value) {
  7516. return __assign({}, value);
  7517. });
  7518. };
  7519. var setCode = function (newCode) {
  7520. if (newCode) {
  7521. currentCode.set(newCode);
  7522. }
  7523. };
  7524. var getCode = function () {
  7525. return currentCode.get();
  7526. };
  7527. var add$4 = function (code, items) {
  7528. var langData = data[code];
  7529. if (!langData) {
  7530. data[code] = langData = {};
  7531. }
  7532. each$j(items, function (translation, name) {
  7533. langData[name.toLowerCase()] = translation;
  7534. });
  7535. };
  7536. var translate = function (text) {
  7537. var langData = getLanguageData().getOr({});
  7538. var toString = function (obj) {
  7539. if (isFunction(obj)) {
  7540. return Object.prototype.toString.call(obj);
  7541. }
  7542. return !isEmpty(obj) ? '' + obj : '';
  7543. };
  7544. var isEmpty = function (text) {
  7545. return text === '' || text === null || text === undefined;
  7546. };
  7547. var getLangData = function (text) {
  7548. var textstr = toString(text);
  7549. return get$9(langData, textstr.toLowerCase()).map(toString).getOr(textstr);
  7550. };
  7551. var removeContext = function (str) {
  7552. return str.replace(/{context:\w+}$/, '');
  7553. };
  7554. if (isEmpty(text)) {
  7555. return '';
  7556. }
  7557. if (isRaw(text)) {
  7558. return toString(text.raw);
  7559. }
  7560. if (isTokenised(text)) {
  7561. var values_1 = text.slice(1);
  7562. var substitued = getLangData(text[0]).replace(/\{([0-9]+)\}/g, function ($1, $2) {
  7563. return has$2(values_1, $2) ? toString(values_1[$2]) : $1;
  7564. });
  7565. return removeContext(substitued);
  7566. }
  7567. return removeContext(getLangData(text));
  7568. };
  7569. var isRtl$1 = function () {
  7570. return getLanguageData().bind(function (items) {
  7571. return get$9(items, '_dir');
  7572. }).exists(function (dir) {
  7573. return dir === 'rtl';
  7574. });
  7575. };
  7576. var hasCode = function (code) {
  7577. return has$2(data, code);
  7578. };
  7579. var I18n = {
  7580. getData: getData,
  7581. setCode: setCode,
  7582. getCode: getCode,
  7583. add: add$4,
  7584. translate: translate,
  7585. isRtl: isRtl$1,
  7586. hasCode: hasCode
  7587. };
  7588. var AddOnManager = function () {
  7589. var items = [];
  7590. var urls = {};
  7591. var lookup = {};
  7592. var _listeners = [];
  7593. var runListeners = function (name, state) {
  7594. var matchedListeners = filter$4(_listeners, function (listener) {
  7595. return listener.name === name && listener.state === state;
  7596. });
  7597. each$k(matchedListeners, function (listener) {
  7598. return listener.callback();
  7599. });
  7600. };
  7601. var get = function (name) {
  7602. if (lookup[name]) {
  7603. return lookup[name].instance;
  7604. }
  7605. return undefined;
  7606. };
  7607. var dependencies = function (name) {
  7608. var result;
  7609. if (lookup[name]) {
  7610. result = lookup[name].dependencies;
  7611. }
  7612. return result || [];
  7613. };
  7614. var requireLangPack = function (name, languages) {
  7615. if (AddOnManager.languageLoad !== false) {
  7616. waitFor(name, function () {
  7617. var language = I18n.getCode();
  7618. var wrappedLanguages = ',' + (languages || '') + ',';
  7619. if (!language || languages && wrappedLanguages.indexOf(',' + language + ',') === -1) {
  7620. return;
  7621. }
  7622. ScriptLoader.ScriptLoader.add(urls[name] + '/langs/' + language + '.js');
  7623. }, 'loaded');
  7624. }
  7625. };
  7626. var add = function (id, addOn, dependencies) {
  7627. var addOnConstructor = addOn;
  7628. items.push(addOnConstructor);
  7629. lookup[id] = {
  7630. instance: addOnConstructor,
  7631. dependencies: dependencies
  7632. };
  7633. runListeners(id, 'added');
  7634. return addOnConstructor;
  7635. };
  7636. var remove = function (name) {
  7637. delete urls[name];
  7638. delete lookup[name];
  7639. };
  7640. var createUrl = function (baseUrl, dep) {
  7641. if (typeof dep === 'object') {
  7642. return dep;
  7643. }
  7644. return typeof baseUrl === 'string' ? {
  7645. prefix: '',
  7646. resource: dep,
  7647. suffix: ''
  7648. } : {
  7649. prefix: baseUrl.prefix,
  7650. resource: dep,
  7651. suffix: baseUrl.suffix
  7652. };
  7653. };
  7654. var addComponents = function (pluginName, scripts) {
  7655. var pluginUrl = urls[pluginName];
  7656. each$k(scripts, function (script) {
  7657. ScriptLoader.ScriptLoader.add(pluginUrl + '/' + script);
  7658. });
  7659. };
  7660. var loadDependencies = function (name, addOnUrl, success, scope) {
  7661. var deps = dependencies(name);
  7662. each$k(deps, function (dep) {
  7663. var newUrl = createUrl(addOnUrl, dep);
  7664. load(newUrl.resource, newUrl, undefined, undefined);
  7665. });
  7666. if (success) {
  7667. if (scope) {
  7668. success.call(scope);
  7669. } else {
  7670. success.call(ScriptLoader);
  7671. }
  7672. }
  7673. };
  7674. var load = function (name, addOnUrl, success, scope, failure) {
  7675. if (urls[name]) {
  7676. return;
  7677. }
  7678. var urlString = typeof addOnUrl === 'string' ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
  7679. if (urlString.indexOf('/') !== 0 && urlString.indexOf('://') === -1) {
  7680. urlString = AddOnManager.baseURL + '/' + urlString;
  7681. }
  7682. urls[name] = urlString.substring(0, urlString.lastIndexOf('/'));
  7683. var done = function () {
  7684. runListeners(name, 'loaded');
  7685. loadDependencies(name, addOnUrl, success, scope);
  7686. };
  7687. if (lookup[name]) {
  7688. done();
  7689. } else {
  7690. ScriptLoader.ScriptLoader.add(urlString, done, scope, failure);
  7691. }
  7692. };
  7693. var waitFor = function (name, callback, state) {
  7694. if (state === void 0) {
  7695. state = 'added';
  7696. }
  7697. if (has$2(lookup, name) && state === 'added') {
  7698. callback();
  7699. } else if (has$2(urls, name) && state === 'loaded') {
  7700. callback();
  7701. } else {
  7702. _listeners.push({
  7703. name: name,
  7704. state: state,
  7705. callback: callback
  7706. });
  7707. }
  7708. };
  7709. return {
  7710. items: items,
  7711. urls: urls,
  7712. lookup: lookup,
  7713. _listeners: _listeners,
  7714. get: get,
  7715. dependencies: dependencies,
  7716. requireLangPack: requireLangPack,
  7717. add: add,
  7718. remove: remove,
  7719. createUrl: createUrl,
  7720. addComponents: addComponents,
  7721. load: load,
  7722. waitFor: waitFor
  7723. };
  7724. };
  7725. AddOnManager.languageLoad = true;
  7726. AddOnManager.baseURL = '';
  7727. AddOnManager.PluginManager = AddOnManager();
  7728. AddOnManager.ThemeManager = AddOnManager();
  7729. var singleton = function (doRevoke) {
  7730. var subject = Cell(Optional.none());
  7731. var revoke = function () {
  7732. return subject.get().each(doRevoke);
  7733. };
  7734. var clear = function () {
  7735. revoke();
  7736. subject.set(Optional.none());
  7737. };
  7738. var isSet = function () {
  7739. return subject.get().isSome();
  7740. };
  7741. var get = function () {
  7742. return subject.get();
  7743. };
  7744. var set = function (s) {
  7745. revoke();
  7746. subject.set(Optional.some(s));
  7747. };
  7748. return {
  7749. clear: clear,
  7750. isSet: isSet,
  7751. get: get,
  7752. set: set
  7753. };
  7754. };
  7755. var value = function () {
  7756. var subject = singleton(noop);
  7757. var on = function (f) {
  7758. return subject.get().each(f);
  7759. };
  7760. return __assign(__assign({}, subject), { on: on });
  7761. };
  7762. var first = function (fn, rate) {
  7763. var timer = null;
  7764. var cancel = function () {
  7765. if (!isNull(timer)) {
  7766. clearTimeout(timer);
  7767. timer = null;
  7768. }
  7769. };
  7770. var throttle = function () {
  7771. var args = [];
  7772. for (var _i = 0; _i < arguments.length; _i++) {
  7773. args[_i] = arguments[_i];
  7774. }
  7775. if (isNull(timer)) {
  7776. timer = setTimeout(function () {
  7777. timer = null;
  7778. fn.apply(null, args);
  7779. }, rate);
  7780. }
  7781. };
  7782. return {
  7783. cancel: cancel,
  7784. throttle: throttle
  7785. };
  7786. };
  7787. var last = function (fn, rate) {
  7788. var timer = null;
  7789. var cancel = function () {
  7790. if (!isNull(timer)) {
  7791. clearTimeout(timer);
  7792. timer = null;
  7793. }
  7794. };
  7795. var throttle = function () {
  7796. var args = [];
  7797. for (var _i = 0; _i < arguments.length; _i++) {
  7798. args[_i] = arguments[_i];
  7799. }
  7800. cancel();
  7801. timer = setTimeout(function () {
  7802. timer = null;
  7803. fn.apply(null, args);
  7804. }, rate);
  7805. };
  7806. return {
  7807. cancel: cancel,
  7808. throttle: throttle
  7809. };
  7810. };
  7811. var read$4 = function (element, attr) {
  7812. var value = get$6(element, attr);
  7813. return value === undefined || value === '' ? [] : value.split(' ');
  7814. };
  7815. var add$3 = function (element, attr, id) {
  7816. var old = read$4(element, attr);
  7817. var nu = old.concat([id]);
  7818. set$1(element, attr, nu.join(' '));
  7819. return true;
  7820. };
  7821. var remove$5 = function (element, attr, id) {
  7822. var nu = filter$4(read$4(element, attr), function (v) {
  7823. return v !== id;
  7824. });
  7825. if (nu.length > 0) {
  7826. set$1(element, attr, nu.join(' '));
  7827. } else {
  7828. remove$6(element, attr);
  7829. }
  7830. return false;
  7831. };
  7832. var supports = function (element) {
  7833. return element.dom.classList !== undefined;
  7834. };
  7835. var get$4 = function (element) {
  7836. return read$4(element, 'class');
  7837. };
  7838. var add$2 = function (element, clazz) {
  7839. return add$3(element, 'class', clazz);
  7840. };
  7841. var remove$4 = function (element, clazz) {
  7842. return remove$5(element, 'class', clazz);
  7843. };
  7844. var add$1 = function (element, clazz) {
  7845. if (supports(element)) {
  7846. element.dom.classList.add(clazz);
  7847. } else {
  7848. add$2(element, clazz);
  7849. }
  7850. };
  7851. var cleanClass = function (element) {
  7852. var classList = supports(element) ? element.dom.classList : get$4(element);
  7853. if (classList.length === 0) {
  7854. remove$6(element, 'class');
  7855. }
  7856. };
  7857. var remove$3 = function (element, clazz) {
  7858. if (supports(element)) {
  7859. var classList = element.dom.classList;
  7860. classList.remove(clazz);
  7861. } else {
  7862. remove$4(element, clazz);
  7863. }
  7864. cleanClass(element);
  7865. };
  7866. var has = function (element, clazz) {
  7867. return supports(element) && element.dom.classList.contains(clazz);
  7868. };
  7869. var descendants$1 = function (scope, predicate) {
  7870. var result = [];
  7871. each$k(children(scope), function (x) {
  7872. if (predicate(x)) {
  7873. result = result.concat([x]);
  7874. }
  7875. result = result.concat(descendants$1(x, predicate));
  7876. });
  7877. return result;
  7878. };
  7879. var descendants = function (scope, selector) {
  7880. return all(selector, scope);
  7881. };
  7882. var annotation = constant('mce-annotation');
  7883. var dataAnnotation = constant('data-mce-annotation');
  7884. var dataAnnotationId = constant('data-mce-annotation-uid');
  7885. var identify = function (editor, annotationName) {
  7886. var rng = editor.selection.getRng();
  7887. var start = SugarElement.fromDom(rng.startContainer);
  7888. var root = SugarElement.fromDom(editor.getBody());
  7889. var selector = annotationName.fold(function () {
  7890. return '.' + annotation();
  7891. }, function (an) {
  7892. return '[' + dataAnnotation() + '="' + an + '"]';
  7893. });
  7894. var newStart = child$1(start, rng.startOffset).getOr(start);
  7895. var closest = closest$2(newStart, selector, function (n) {
  7896. return eq(n, root);
  7897. });
  7898. var getAttr = function (c, property) {
  7899. if (has$1(c, property)) {
  7900. return Optional.some(get$6(c, property));
  7901. } else {
  7902. return Optional.none();
  7903. }
  7904. };
  7905. return closest.bind(function (c) {
  7906. return getAttr(c, '' + dataAnnotationId()).bind(function (uid) {
  7907. return getAttr(c, '' + dataAnnotation()).map(function (name) {
  7908. var elements = findMarkers(editor, uid);
  7909. return {
  7910. uid: uid,
  7911. name: name,
  7912. elements: elements
  7913. };
  7914. });
  7915. });
  7916. });
  7917. };
  7918. var isAnnotation = function (elem) {
  7919. return isElement$6(elem) && has(elem, annotation());
  7920. };
  7921. var findMarkers = function (editor, uid) {
  7922. var body = SugarElement.fromDom(editor.getBody());
  7923. return descendants(body, '[' + dataAnnotationId() + '="' + uid + '"]');
  7924. };
  7925. var findAll = function (editor, name) {
  7926. var body = SugarElement.fromDom(editor.getBody());
  7927. var markers = descendants(body, '[' + dataAnnotation() + '="' + name + '"]');
  7928. var directory = {};
  7929. each$k(markers, function (m) {
  7930. var uid = get$6(m, dataAnnotationId());
  7931. var nodesAlready = get$9(directory, uid).getOr([]);
  7932. directory[uid] = nodesAlready.concat([m]);
  7933. });
  7934. return directory;
  7935. };
  7936. var setup$n = function (editor, _registry) {
  7937. var changeCallbacks = Cell({});
  7938. var initData = function () {
  7939. return {
  7940. listeners: [],
  7941. previous: value()
  7942. };
  7943. };
  7944. var withCallbacks = function (name, f) {
  7945. updateCallbacks(name, function (data) {
  7946. f(data);
  7947. return data;
  7948. });
  7949. };
  7950. var updateCallbacks = function (name, f) {
  7951. var callbackMap = changeCallbacks.get();
  7952. var data = get$9(callbackMap, name).getOrThunk(initData);
  7953. var outputData = f(data);
  7954. callbackMap[name] = outputData;
  7955. changeCallbacks.set(callbackMap);
  7956. };
  7957. var fireCallbacks = function (name, uid, elements) {
  7958. withCallbacks(name, function (data) {
  7959. each$k(data.listeners, function (f) {
  7960. return f(true, name, {
  7961. uid: uid,
  7962. nodes: map$3(elements, function (elem) {
  7963. return elem.dom;
  7964. })
  7965. });
  7966. });
  7967. });
  7968. };
  7969. var fireNoAnnotation = function (name) {
  7970. withCallbacks(name, function (data) {
  7971. each$k(data.listeners, function (f) {
  7972. return f(false, name);
  7973. });
  7974. });
  7975. };
  7976. var onNodeChange = last(function () {
  7977. var callbackMap = changeCallbacks.get();
  7978. var annotations = sort(keys(callbackMap));
  7979. each$k(annotations, function (name) {
  7980. updateCallbacks(name, function (data) {
  7981. var prev = data.previous.get();
  7982. identify(editor, Optional.some(name)).fold(function () {
  7983. if (prev.isSome()) {
  7984. fireNoAnnotation(name);
  7985. data.previous.clear();
  7986. }
  7987. }, function (_a) {
  7988. var uid = _a.uid, name = _a.name, elements = _a.elements;
  7989. if (!is$1(prev, uid)) {
  7990. fireCallbacks(name, uid, elements);
  7991. data.previous.set(uid);
  7992. }
  7993. });
  7994. return {
  7995. previous: data.previous,
  7996. listeners: data.listeners
  7997. };
  7998. });
  7999. });
  8000. }, 30);
  8001. editor.on('remove', function () {
  8002. onNodeChange.cancel();
  8003. });
  8004. editor.on('NodeChange', function () {
  8005. onNodeChange.throttle();
  8006. });
  8007. var addListener = function (name, f) {
  8008. updateCallbacks(name, function (data) {
  8009. return {
  8010. previous: data.previous,
  8011. listeners: data.listeners.concat([f])
  8012. };
  8013. });
  8014. };
  8015. return { addListener: addListener };
  8016. };
  8017. var setup$m = function (editor, registry) {
  8018. var identifyParserNode = function (span) {
  8019. return Optional.from(span.attr(dataAnnotation())).bind(registry.lookup);
  8020. };
  8021. editor.on('init', function () {
  8022. editor.serializer.addNodeFilter('span', function (spans) {
  8023. each$k(spans, function (span) {
  8024. identifyParserNode(span).each(function (settings) {
  8025. if (settings.persistent === false) {
  8026. span.unwrap();
  8027. }
  8028. });
  8029. });
  8030. });
  8031. });
  8032. };
  8033. var create$7 = function () {
  8034. var annotations = {};
  8035. var register = function (name, settings) {
  8036. annotations[name] = {
  8037. name: name,
  8038. settings: settings
  8039. };
  8040. };
  8041. var lookup = function (name) {
  8042. return get$9(annotations, name).map(function (a) {
  8043. return a.settings;
  8044. });
  8045. };
  8046. return {
  8047. register: register,
  8048. lookup: lookup
  8049. };
  8050. };
  8051. var unique = 0;
  8052. var generate = function (prefix) {
  8053. var date = new Date();
  8054. var time = date.getTime();
  8055. var random = Math.floor(Math.random() * 1000000000);
  8056. unique++;
  8057. return prefix + '_' + random + unique + String(time);
  8058. };
  8059. var add = function (element, classes) {
  8060. each$k(classes, function (x) {
  8061. add$1(element, x);
  8062. });
  8063. };
  8064. var fromHtml = function (html, scope) {
  8065. var doc = scope || document;
  8066. var div = doc.createElement('div');
  8067. div.innerHTML = html;
  8068. return children(SugarElement.fromDom(div));
  8069. };
  8070. var fromDom$1 = function (nodes) {
  8071. return map$3(nodes, SugarElement.fromDom);
  8072. };
  8073. var get$3 = function (element) {
  8074. return element.dom.innerHTML;
  8075. };
  8076. var set = function (element, content) {
  8077. var owner = owner$1(element);
  8078. var docDom = owner.dom;
  8079. var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  8080. var contentElements = fromHtml(content, docDom);
  8081. append(fragment, contentElements);
  8082. empty(element);
  8083. append$1(element, fragment);
  8084. };
  8085. var clone$1 = function (original, isDeep) {
  8086. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  8087. };
  8088. var shallow = function (original) {
  8089. return clone$1(original, false);
  8090. };
  8091. var deep$1 = function (original) {
  8092. return clone$1(original, true);
  8093. };
  8094. var TextWalker = function (startNode, rootNode, isBoundary) {
  8095. if (isBoundary === void 0) {
  8096. isBoundary = never;
  8097. }
  8098. var walker = new DomTreeWalker(startNode, rootNode);
  8099. var walk = function (direction) {
  8100. var next;
  8101. do {
  8102. next = walker[direction]();
  8103. } while (next && !isText$7(next) && !isBoundary(next));
  8104. return Optional.from(next).filter(isText$7);
  8105. };
  8106. return {
  8107. current: function () {
  8108. return Optional.from(walker.current()).filter(isText$7);
  8109. },
  8110. next: function () {
  8111. return walk('next');
  8112. },
  8113. prev: function () {
  8114. return walk('prev');
  8115. },
  8116. prev2: function () {
  8117. return walk('prev2');
  8118. }
  8119. };
  8120. };
  8121. var TextSeeker = function (dom, isBoundary) {
  8122. var isBlockBoundary = isBoundary ? isBoundary : function (node) {
  8123. return dom.isBlock(node) || isBr$5(node) || isContentEditableFalse$b(node);
  8124. };
  8125. var walk = function (node, offset, walker, process) {
  8126. if (isText$7(node)) {
  8127. var newOffset = process(node, offset, node.data);
  8128. if (newOffset !== -1) {
  8129. return Optional.some({
  8130. container: node,
  8131. offset: newOffset
  8132. });
  8133. }
  8134. }
  8135. return walker().bind(function (next) {
  8136. return walk(next.container, next.offset, walker, process);
  8137. });
  8138. };
  8139. var backwards = function (node, offset, process, root) {
  8140. var walker = TextWalker(node, root, isBlockBoundary);
  8141. return walk(node, offset, function () {
  8142. return walker.prev().map(function (prev) {
  8143. return {
  8144. container: prev,
  8145. offset: prev.length
  8146. };
  8147. });
  8148. }, process).getOrNull();
  8149. };
  8150. var forwards = function (node, offset, process, root) {
  8151. var walker = TextWalker(node, root, isBlockBoundary);
  8152. return walk(node, offset, function () {
  8153. return walker.next().map(function (next) {
  8154. return {
  8155. container: next,
  8156. offset: 0
  8157. };
  8158. });
  8159. }, process).getOrNull();
  8160. };
  8161. return {
  8162. backwards: backwards,
  8163. forwards: forwards
  8164. };
  8165. };
  8166. var round$2 = Math.round;
  8167. var clone = function (rect) {
  8168. if (!rect) {
  8169. return {
  8170. left: 0,
  8171. top: 0,
  8172. bottom: 0,
  8173. right: 0,
  8174. width: 0,
  8175. height: 0
  8176. };
  8177. }
  8178. return {
  8179. left: round$2(rect.left),
  8180. top: round$2(rect.top),
  8181. bottom: round$2(rect.bottom),
  8182. right: round$2(rect.right),
  8183. width: round$2(rect.width),
  8184. height: round$2(rect.height)
  8185. };
  8186. };
  8187. var collapse = function (rect, toStart) {
  8188. rect = clone(rect);
  8189. if (toStart) {
  8190. rect.right = rect.left;
  8191. } else {
  8192. rect.left = rect.left + rect.width;
  8193. rect.right = rect.left;
  8194. }
  8195. rect.width = 0;
  8196. return rect;
  8197. };
  8198. var isEqual = function (rect1, rect2) {
  8199. return rect1.left === rect2.left && rect1.top === rect2.top && rect1.bottom === rect2.bottom && rect1.right === rect2.right;
  8200. };
  8201. var isValidOverflow = function (overflowY, rect1, rect2) {
  8202. return overflowY >= 0 && overflowY <= Math.min(rect1.height, rect2.height) / 2;
  8203. };
  8204. var isAbove$1 = function (rect1, rect2) {
  8205. var halfHeight = Math.min(rect2.height / 2, rect1.height / 2);
  8206. if (rect1.bottom - halfHeight < rect2.top) {
  8207. return true;
  8208. }
  8209. if (rect1.top > rect2.bottom) {
  8210. return false;
  8211. }
  8212. return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
  8213. };
  8214. var isBelow$1 = function (rect1, rect2) {
  8215. if (rect1.top > rect2.bottom) {
  8216. return true;
  8217. }
  8218. if (rect1.bottom < rect2.top) {
  8219. return false;
  8220. }
  8221. return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
  8222. };
  8223. var containsXY = function (rect, clientX, clientY) {
  8224. return clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
  8225. };
  8226. var clamp$2 = function (value, min, max) {
  8227. return Math.min(Math.max(value, min), max);
  8228. };
  8229. var getSelectedNode = function (range) {
  8230. var startContainer = range.startContainer, startOffset = range.startOffset;
  8231. if (startContainer.hasChildNodes() && range.endOffset === startOffset + 1) {
  8232. return startContainer.childNodes[startOffset];
  8233. }
  8234. return null;
  8235. };
  8236. var getNode$1 = function (container, offset) {
  8237. if (isElement$5(container) && container.hasChildNodes()) {
  8238. var childNodes = container.childNodes;
  8239. var safeOffset = clamp$2(offset, 0, childNodes.length - 1);
  8240. return childNodes[safeOffset];
  8241. } else {
  8242. return container;
  8243. }
  8244. };
  8245. var getNodeUnsafe = function (container, offset) {
  8246. if (offset < 0 && isElement$5(container) && container.hasChildNodes()) {
  8247. return undefined;
  8248. } else {
  8249. return getNode$1(container, offset);
  8250. }
  8251. };
  8252. 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]');
  8253. var isExtendingChar = function (ch) {
  8254. return typeof ch === 'string' && ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
  8255. };
  8256. var or = 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 true;
  8265. }
  8266. }
  8267. return false;
  8268. };
  8269. };
  8270. var and = function () {
  8271. var args = [];
  8272. for (var _i = 0; _i < arguments.length; _i++) {
  8273. args[_i] = arguments[_i];
  8274. }
  8275. return function (x) {
  8276. for (var i = 0; i < args.length; i++) {
  8277. if (!args[i](x)) {
  8278. return false;
  8279. }
  8280. }
  8281. return true;
  8282. };
  8283. };
  8284. var isElement$3 = isElement$5;
  8285. var isCaretCandidate$2 = isCaretCandidate$3;
  8286. var isBlock$1 = matchStyleValues('display', 'block table');
  8287. var isFloated = matchStyleValues('float', 'left right');
  8288. var isValidElementCaretCandidate = and(isElement$3, isCaretCandidate$2, not(isFloated));
  8289. var isNotPre = not(matchStyleValues('white-space', 'pre pre-line pre-wrap'));
  8290. var isText$4 = isText$7;
  8291. var isBr$2 = isBr$5;
  8292. var nodeIndex$1 = DOMUtils.nodeIndex;
  8293. var resolveIndex$1 = getNodeUnsafe;
  8294. var createRange$1 = function (doc) {
  8295. return 'createRange' in doc ? doc.createRange() : DOMUtils.DOM.createRng();
  8296. };
  8297. var isWhiteSpace$1 = function (chr) {
  8298. return chr && /[\r\n\t ]/.test(chr);
  8299. };
  8300. var isRange = function (rng) {
  8301. return !!rng.setStart && !!rng.setEnd;
  8302. };
  8303. var isHiddenWhiteSpaceRange = function (range) {
  8304. var container = range.startContainer;
  8305. var offset = range.startOffset;
  8306. if (isWhiteSpace$1(range.toString()) && isNotPre(container.parentNode) && isText$7(container)) {
  8307. var text = container.data;
  8308. if (isWhiteSpace$1(text[offset - 1]) || isWhiteSpace$1(text[offset + 1])) {
  8309. return true;
  8310. }
  8311. }
  8312. return false;
  8313. };
  8314. var getBrClientRect = function (brNode) {
  8315. var doc = brNode.ownerDocument;
  8316. var rng = createRange$1(doc);
  8317. var nbsp$1 = doc.createTextNode(nbsp);
  8318. var parentNode = brNode.parentNode;
  8319. parentNode.insertBefore(nbsp$1, brNode);
  8320. rng.setStart(nbsp$1, 0);
  8321. rng.setEnd(nbsp$1, 1);
  8322. var clientRect = clone(rng.getBoundingClientRect());
  8323. parentNode.removeChild(nbsp$1);
  8324. return clientRect;
  8325. };
  8326. var getBoundingClientRectWebKitText = function (rng) {
  8327. var sc = rng.startContainer;
  8328. var ec = rng.endContainer;
  8329. var so = rng.startOffset;
  8330. var eo = rng.endOffset;
  8331. if (sc === ec && isText$7(ec) && so === 0 && eo === 1) {
  8332. var newRng = rng.cloneRange();
  8333. newRng.setEndAfter(ec);
  8334. return getBoundingClientRect$1(newRng);
  8335. } else {
  8336. return null;
  8337. }
  8338. };
  8339. var isZeroRect = function (r) {
  8340. return r.left === 0 && r.right === 0 && r.top === 0 && r.bottom === 0;
  8341. };
  8342. var getBoundingClientRect$1 = function (item) {
  8343. var clientRect;
  8344. var clientRects = item.getClientRects();
  8345. if (clientRects.length > 0) {
  8346. clientRect = clone(clientRects[0]);
  8347. } else {
  8348. clientRect = clone(item.getBoundingClientRect());
  8349. }
  8350. if (!isRange(item) && isBr$2(item) && isZeroRect(clientRect)) {
  8351. return getBrClientRect(item);
  8352. }
  8353. if (isZeroRect(clientRect) && isRange(item)) {
  8354. return getBoundingClientRectWebKitText(item);
  8355. }
  8356. return clientRect;
  8357. };
  8358. var collapseAndInflateWidth = function (clientRect, toStart) {
  8359. var newClientRect = collapse(clientRect, toStart);
  8360. newClientRect.width = 1;
  8361. newClientRect.right = newClientRect.left + 1;
  8362. return newClientRect;
  8363. };
  8364. var getCaretPositionClientRects = function (caretPosition) {
  8365. var clientRects = [];
  8366. var addUniqueAndValidRect = function (clientRect) {
  8367. if (clientRect.height === 0) {
  8368. return;
  8369. }
  8370. if (clientRects.length > 0) {
  8371. if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
  8372. return;
  8373. }
  8374. }
  8375. clientRects.push(clientRect);
  8376. };
  8377. var addCharacterOffset = function (container, offset) {
  8378. var range = createRange$1(container.ownerDocument);
  8379. if (offset < container.data.length) {
  8380. if (isExtendingChar(container.data[offset])) {
  8381. return clientRects;
  8382. }
  8383. if (isExtendingChar(container.data[offset - 1])) {
  8384. range.setStart(container, offset);
  8385. range.setEnd(container, offset + 1);
  8386. if (!isHiddenWhiteSpaceRange(range)) {
  8387. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  8388. return clientRects;
  8389. }
  8390. }
  8391. }
  8392. if (offset > 0) {
  8393. range.setStart(container, offset - 1);
  8394. range.setEnd(container, offset);
  8395. if (!isHiddenWhiteSpaceRange(range)) {
  8396. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  8397. }
  8398. }
  8399. if (offset < container.data.length) {
  8400. range.setStart(container, offset);
  8401. range.setEnd(container, offset + 1);
  8402. if (!isHiddenWhiteSpaceRange(range)) {
  8403. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), true));
  8404. }
  8405. }
  8406. };
  8407. var container = caretPosition.container();
  8408. var offset = caretPosition.offset();
  8409. if (isText$4(container)) {
  8410. addCharacterOffset(container, offset);
  8411. return clientRects;
  8412. }
  8413. if (isElement$3(container)) {
  8414. if (caretPosition.isAtEnd()) {
  8415. var node = resolveIndex$1(container, offset);
  8416. if (isText$4(node)) {
  8417. addCharacterOffset(node, node.data.length);
  8418. }
  8419. if (isValidElementCaretCandidate(node) && !isBr$2(node)) {
  8420. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  8421. }
  8422. } else {
  8423. var node = resolveIndex$1(container, offset);
  8424. if (isText$4(node)) {
  8425. addCharacterOffset(node, 0);
  8426. }
  8427. if (isValidElementCaretCandidate(node) && caretPosition.isAtEnd()) {
  8428. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  8429. return clientRects;
  8430. }
  8431. var beforeNode = resolveIndex$1(caretPosition.container(), caretPosition.offset() - 1);
  8432. if (isValidElementCaretCandidate(beforeNode) && !isBr$2(beforeNode)) {
  8433. if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
  8434. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(beforeNode), false));
  8435. }
  8436. }
  8437. if (isValidElementCaretCandidate(node)) {
  8438. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), true));
  8439. }
  8440. }
  8441. }
  8442. return clientRects;
  8443. };
  8444. var CaretPosition = function (container, offset, clientRects) {
  8445. var isAtStart = function () {
  8446. if (isText$4(container)) {
  8447. return offset === 0;
  8448. }
  8449. return offset === 0;
  8450. };
  8451. var isAtEnd = function () {
  8452. if (isText$4(container)) {
  8453. return offset >= container.data.length;
  8454. }
  8455. return offset >= container.childNodes.length;
  8456. };
  8457. var toRange = function () {
  8458. var range = createRange$1(container.ownerDocument);
  8459. range.setStart(container, offset);
  8460. range.setEnd(container, offset);
  8461. return range;
  8462. };
  8463. var getClientRects = function () {
  8464. if (!clientRects) {
  8465. clientRects = getCaretPositionClientRects(CaretPosition(container, offset));
  8466. }
  8467. return clientRects;
  8468. };
  8469. var isVisible = function () {
  8470. return getClientRects().length > 0;
  8471. };
  8472. var isEqual = function (caretPosition) {
  8473. return caretPosition && container === caretPosition.container() && offset === caretPosition.offset();
  8474. };
  8475. var getNode = function (before) {
  8476. return resolveIndex$1(container, before ? offset - 1 : offset);
  8477. };
  8478. return {
  8479. container: constant(container),
  8480. offset: constant(offset),
  8481. toRange: toRange,
  8482. getClientRects: getClientRects,
  8483. isVisible: isVisible,
  8484. isAtStart: isAtStart,
  8485. isAtEnd: isAtEnd,
  8486. isEqual: isEqual,
  8487. getNode: getNode
  8488. };
  8489. };
  8490. CaretPosition.fromRangeStart = function (range) {
  8491. return CaretPosition(range.startContainer, range.startOffset);
  8492. };
  8493. CaretPosition.fromRangeEnd = function (range) {
  8494. return CaretPosition(range.endContainer, range.endOffset);
  8495. };
  8496. CaretPosition.after = function (node) {
  8497. return CaretPosition(node.parentNode, nodeIndex$1(node) + 1);
  8498. };
  8499. CaretPosition.before = function (node) {
  8500. return CaretPosition(node.parentNode, nodeIndex$1(node));
  8501. };
  8502. CaretPosition.isAbove = function (pos1, pos2) {
  8503. return lift2(head(pos2.getClientRects()), last$2(pos1.getClientRects()), isAbove$1).getOr(false);
  8504. };
  8505. CaretPosition.isBelow = function (pos1, pos2) {
  8506. return lift2(last$2(pos2.getClientRects()), head(pos1.getClientRects()), isBelow$1).getOr(false);
  8507. };
  8508. CaretPosition.isAtStart = function (pos) {
  8509. return pos ? pos.isAtStart() : false;
  8510. };
  8511. CaretPosition.isAtEnd = function (pos) {
  8512. return pos ? pos.isAtEnd() : false;
  8513. };
  8514. CaretPosition.isTextPosition = function (pos) {
  8515. return pos ? isText$7(pos.container()) : false;
  8516. };
  8517. CaretPosition.isElementPosition = function (pos) {
  8518. return CaretPosition.isTextPosition(pos) === false;
  8519. };
  8520. var trimEmptyTextNode$1 = function (dom, node) {
  8521. if (isText$7(node) && node.data.length === 0) {
  8522. dom.remove(node);
  8523. }
  8524. };
  8525. var insertNode = function (dom, rng, node) {
  8526. rng.insertNode(node);
  8527. trimEmptyTextNode$1(dom, node.previousSibling);
  8528. trimEmptyTextNode$1(dom, node.nextSibling);
  8529. };
  8530. var insertFragment = function (dom, rng, frag) {
  8531. var firstChild = Optional.from(frag.firstChild);
  8532. var lastChild = Optional.from(frag.lastChild);
  8533. rng.insertNode(frag);
  8534. firstChild.each(function (child) {
  8535. return trimEmptyTextNode$1(dom, child.previousSibling);
  8536. });
  8537. lastChild.each(function (child) {
  8538. return trimEmptyTextNode$1(dom, child.nextSibling);
  8539. });
  8540. };
  8541. var rangeInsertNode = function (dom, rng, node) {
  8542. if (isDocumentFragment(node)) {
  8543. insertFragment(dom, rng, node);
  8544. } else {
  8545. insertNode(dom, rng, node);
  8546. }
  8547. };
  8548. var isText$3 = isText$7;
  8549. var isBogus = isBogus$2;
  8550. var nodeIndex = DOMUtils.nodeIndex;
  8551. var normalizedParent = function (node) {
  8552. var parentNode = node.parentNode;
  8553. if (isBogus(parentNode)) {
  8554. return normalizedParent(parentNode);
  8555. }
  8556. return parentNode;
  8557. };
  8558. var getChildNodes = function (node) {
  8559. if (!node) {
  8560. return [];
  8561. }
  8562. return reduce(node.childNodes, function (result, node) {
  8563. if (isBogus(node) && node.nodeName !== 'BR') {
  8564. result = result.concat(getChildNodes(node));
  8565. } else {
  8566. result.push(node);
  8567. }
  8568. return result;
  8569. }, []);
  8570. };
  8571. var normalizedTextOffset = function (node, offset) {
  8572. while (node = node.previousSibling) {
  8573. if (!isText$3(node)) {
  8574. break;
  8575. }
  8576. offset += node.data.length;
  8577. }
  8578. return offset;
  8579. };
  8580. var equal = function (a) {
  8581. return function (b) {
  8582. return a === b;
  8583. };
  8584. };
  8585. var normalizedNodeIndex = function (node) {
  8586. var nodes, index;
  8587. nodes = getChildNodes(normalizedParent(node));
  8588. index = findIndex$1(nodes, equal(node), node);
  8589. nodes = nodes.slice(0, index + 1);
  8590. var numTextFragments = reduce(nodes, function (result, node, i) {
  8591. if (isText$3(node) && isText$3(nodes[i - 1])) {
  8592. result++;
  8593. }
  8594. return result;
  8595. }, 0);
  8596. nodes = filter$2(nodes, matchNodeNames([node.nodeName]));
  8597. index = findIndex$1(nodes, equal(node), node);
  8598. return index - numTextFragments;
  8599. };
  8600. var createPathItem = function (node) {
  8601. var name;
  8602. if (isText$3(node)) {
  8603. name = 'text()';
  8604. } else {
  8605. name = node.nodeName.toLowerCase();
  8606. }
  8607. return name + '[' + normalizedNodeIndex(node) + ']';
  8608. };
  8609. var parentsUntil$1 = function (root, node, predicate) {
  8610. var parents = [];
  8611. for (node = node.parentNode; node !== root; node = node.parentNode) {
  8612. if (predicate && predicate(node)) {
  8613. break;
  8614. }
  8615. parents.push(node);
  8616. }
  8617. return parents;
  8618. };
  8619. var create$6 = function (root, caretPosition) {
  8620. var container, offset, path = [], outputOffset, childNodes, parents;
  8621. container = caretPosition.container();
  8622. offset = caretPosition.offset();
  8623. if (isText$3(container)) {
  8624. outputOffset = normalizedTextOffset(container, offset);
  8625. } else {
  8626. childNodes = container.childNodes;
  8627. if (offset >= childNodes.length) {
  8628. outputOffset = 'after';
  8629. offset = childNodes.length - 1;
  8630. } else {
  8631. outputOffset = 'before';
  8632. }
  8633. container = childNodes[offset];
  8634. }
  8635. path.push(createPathItem(container));
  8636. parents = parentsUntil$1(root, container);
  8637. parents = filter$2(parents, not(isBogus$2));
  8638. path = path.concat(map$1(parents, function (node) {
  8639. return createPathItem(node);
  8640. }));
  8641. return path.reverse().join('/') + ',' + outputOffset;
  8642. };
  8643. var resolvePathItem = function (node, name, index) {
  8644. var nodes = getChildNodes(node);
  8645. nodes = filter$2(nodes, function (node, index) {
  8646. return !isText$3(node) || !isText$3(nodes[index - 1]);
  8647. });
  8648. nodes = filter$2(nodes, matchNodeNames([name]));
  8649. return nodes[index];
  8650. };
  8651. var findTextPosition = function (container, offset) {
  8652. var node = container, targetOffset = 0, dataLen;
  8653. while (isText$3(node)) {
  8654. dataLen = node.data.length;
  8655. if (offset >= targetOffset && offset <= targetOffset + dataLen) {
  8656. container = node;
  8657. offset = offset - targetOffset;
  8658. break;
  8659. }
  8660. if (!isText$3(node.nextSibling)) {
  8661. container = node;
  8662. offset = dataLen;
  8663. break;
  8664. }
  8665. targetOffset += dataLen;
  8666. node = node.nextSibling;
  8667. }
  8668. if (isText$3(container) && offset > container.data.length) {
  8669. offset = container.data.length;
  8670. }
  8671. return CaretPosition(container, offset);
  8672. };
  8673. var resolve$2 = function (root, path) {
  8674. var offset;
  8675. if (!path) {
  8676. return null;
  8677. }
  8678. var parts = path.split(',');
  8679. var paths = parts[0].split('/');
  8680. offset = parts.length > 1 ? parts[1] : 'before';
  8681. var container = reduce(paths, function (result, value) {
  8682. var match = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value);
  8683. if (!match) {
  8684. return null;
  8685. }
  8686. if (match[1] === 'text()') {
  8687. match[1] = '#text';
  8688. }
  8689. return resolvePathItem(result, match[1], parseInt(match[2], 10));
  8690. }, root);
  8691. if (!container) {
  8692. return null;
  8693. }
  8694. if (!isText$3(container)) {
  8695. if (offset === 'after') {
  8696. offset = nodeIndex(container) + 1;
  8697. } else {
  8698. offset = nodeIndex(container);
  8699. }
  8700. return CaretPosition(container.parentNode, offset);
  8701. }
  8702. return findTextPosition(container, parseInt(offset, 10));
  8703. };
  8704. var isContentEditableFalse$9 = isContentEditableFalse$b;
  8705. var getNormalizedTextOffset = function (trim, container, offset) {
  8706. var node, trimmedOffset;
  8707. trimmedOffset = trim(container.data.slice(0, offset)).length;
  8708. for (node = container.previousSibling; node && isText$7(node); node = node.previousSibling) {
  8709. trimmedOffset += trim(node.data).length;
  8710. }
  8711. return trimmedOffset;
  8712. };
  8713. var getPoint = function (dom, trim, normalized, rng, start) {
  8714. var container = rng[start ? 'startContainer' : 'endContainer'];
  8715. var offset = rng[start ? 'startOffset' : 'endOffset'];
  8716. var point = [];
  8717. var childNodes, after = 0;
  8718. var root = dom.getRoot();
  8719. if (isText$7(container)) {
  8720. point.push(normalized ? getNormalizedTextOffset(trim, container, offset) : offset);
  8721. } else {
  8722. childNodes = container.childNodes;
  8723. if (offset >= childNodes.length && childNodes.length) {
  8724. after = 1;
  8725. offset = Math.max(0, childNodes.length - 1);
  8726. }
  8727. point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
  8728. }
  8729. for (; container && container !== root; container = container.parentNode) {
  8730. point.push(dom.nodeIndex(container, normalized));
  8731. }
  8732. return point;
  8733. };
  8734. var getLocation = function (trim, selection, normalized, rng) {
  8735. var dom = selection.dom, bookmark = {};
  8736. bookmark.start = getPoint(dom, trim, normalized, rng, true);
  8737. if (!selection.isCollapsed()) {
  8738. bookmark.end = getPoint(dom, trim, normalized, rng, false);
  8739. }
  8740. if (isRangeInCaretContainerBlock(rng)) {
  8741. bookmark.isFakeCaret = true;
  8742. }
  8743. return bookmark;
  8744. };
  8745. var findIndex = function (dom, name, element) {
  8746. var count = 0;
  8747. Tools.each(dom.select(name), function (node) {
  8748. if (node.getAttribute('data-mce-bogus') === 'all') {
  8749. return;
  8750. }
  8751. if (node === element) {
  8752. return false;
  8753. }
  8754. count++;
  8755. });
  8756. return count;
  8757. };
  8758. var moveEndPoint$1 = function (rng, start) {
  8759. var container, offset, childNodes;
  8760. var prefix = start ? 'start' : 'end';
  8761. container = rng[prefix + 'Container'];
  8762. offset = rng[prefix + 'Offset'];
  8763. if (isElement$5(container) && container.nodeName === 'TR') {
  8764. childNodes = container.childNodes;
  8765. container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
  8766. if (container) {
  8767. offset = start ? 0 : container.childNodes.length;
  8768. rng['set' + (start ? 'Start' : 'End')](container, offset);
  8769. }
  8770. }
  8771. };
  8772. var normalizeTableCellSelection = function (rng) {
  8773. moveEndPoint$1(rng, true);
  8774. moveEndPoint$1(rng, false);
  8775. return rng;
  8776. };
  8777. var findSibling = function (node, offset) {
  8778. var sibling;
  8779. if (isElement$5(node)) {
  8780. node = getNode$1(node, offset);
  8781. if (isContentEditableFalse$9(node)) {
  8782. return node;
  8783. }
  8784. }
  8785. if (isCaretContainer$2(node)) {
  8786. if (isText$7(node) && isCaretContainerBlock$1(node)) {
  8787. node = node.parentNode;
  8788. }
  8789. sibling = node.previousSibling;
  8790. if (isContentEditableFalse$9(sibling)) {
  8791. return sibling;
  8792. }
  8793. sibling = node.nextSibling;
  8794. if (isContentEditableFalse$9(sibling)) {
  8795. return sibling;
  8796. }
  8797. }
  8798. };
  8799. var findAdjacentContentEditableFalseElm = function (rng) {
  8800. return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
  8801. };
  8802. var getOffsetBookmark = function (trim, normalized, selection) {
  8803. var element = selection.getNode();
  8804. var name = element ? element.nodeName : null;
  8805. var rng = selection.getRng();
  8806. if (isContentEditableFalse$9(element) || name === 'IMG') {
  8807. return {
  8808. name: name,
  8809. index: findIndex(selection.dom, name, element)
  8810. };
  8811. }
  8812. var sibling = findAdjacentContentEditableFalseElm(rng);
  8813. if (sibling) {
  8814. name = sibling.tagName;
  8815. return {
  8816. name: name,
  8817. index: findIndex(selection.dom, name, sibling)
  8818. };
  8819. }
  8820. return getLocation(trim, selection, normalized, rng);
  8821. };
  8822. var getCaretBookmark = function (selection) {
  8823. var rng = selection.getRng();
  8824. return {
  8825. start: create$6(selection.dom.getRoot(), CaretPosition.fromRangeStart(rng)),
  8826. end: create$6(selection.dom.getRoot(), CaretPosition.fromRangeEnd(rng))
  8827. };
  8828. };
  8829. var getRangeBookmark = function (selection) {
  8830. return { rng: selection.getRng() };
  8831. };
  8832. var createBookmarkSpan = function (dom, id, filled) {
  8833. var args = {
  8834. 'data-mce-type': 'bookmark',
  8835. id: id,
  8836. 'style': 'overflow:hidden;line-height:0px'
  8837. };
  8838. return filled ? dom.create('span', args, '&#xFEFF;') : dom.create('span', args);
  8839. };
  8840. var getPersistentBookmark = function (selection, filled) {
  8841. var dom = selection.dom;
  8842. var rng = selection.getRng();
  8843. var id = dom.uniqueId();
  8844. var collapsed = selection.isCollapsed();
  8845. var element = selection.getNode();
  8846. var name = element.nodeName;
  8847. if (name === 'IMG') {
  8848. return {
  8849. name: name,
  8850. index: findIndex(dom, name, element)
  8851. };
  8852. }
  8853. var rng2 = normalizeTableCellSelection(rng.cloneRange());
  8854. if (!collapsed) {
  8855. rng2.collapse(false);
  8856. var endBookmarkNode = createBookmarkSpan(dom, id + '_end', filled);
  8857. rangeInsertNode(dom, rng2, endBookmarkNode);
  8858. }
  8859. rng = normalizeTableCellSelection(rng);
  8860. rng.collapse(true);
  8861. var startBookmarkNode = createBookmarkSpan(dom, id + '_start', filled);
  8862. rangeInsertNode(dom, rng, startBookmarkNode);
  8863. selection.moveToBookmark({
  8864. id: id,
  8865. keep: true
  8866. });
  8867. return { id: id };
  8868. };
  8869. var getBookmark$2 = function (selection, type, normalized) {
  8870. if (type === 2) {
  8871. return getOffsetBookmark(trim$2, normalized, selection);
  8872. } else if (type === 3) {
  8873. return getCaretBookmark(selection);
  8874. } else if (type) {
  8875. return getRangeBookmark(selection);
  8876. } else {
  8877. return getPersistentBookmark(selection, false);
  8878. }
  8879. };
  8880. var getUndoBookmark = curry(getOffsetBookmark, identity, true);
  8881. var DOM$9 = DOMUtils.DOM;
  8882. var defaultPreviewStyles = 'font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow';
  8883. var getBodySetting = function (editor, name, defaultValue) {
  8884. var value = editor.getParam(name, defaultValue);
  8885. if (value.indexOf('=') !== -1) {
  8886. var bodyObj = editor.getParam(name, '', 'hash');
  8887. return get$9(bodyObj, editor.id).getOr(defaultValue);
  8888. } else {
  8889. return value;
  8890. }
  8891. };
  8892. var getIframeAttrs = function (editor) {
  8893. return editor.getParam('iframe_attrs', {});
  8894. };
  8895. var getDocType = function (editor) {
  8896. return editor.getParam('doctype', '<!DOCTYPE html>');
  8897. };
  8898. var getDocumentBaseUrl = function (editor) {
  8899. return editor.getParam('document_base_url', '');
  8900. };
  8901. var getBodyId = function (editor) {
  8902. return getBodySetting(editor, 'body_id', 'tinymce');
  8903. };
  8904. var getBodyClass = function (editor) {
  8905. return getBodySetting(editor, 'body_class', '');
  8906. };
  8907. var getContentSecurityPolicy = function (editor) {
  8908. return editor.getParam('content_security_policy', '');
  8909. };
  8910. var shouldPutBrInPre$1 = function (editor) {
  8911. return editor.getParam('br_in_pre', true);
  8912. };
  8913. var getForcedRootBlock = function (editor) {
  8914. if (editor.getParam('force_p_newlines', false)) {
  8915. return 'p';
  8916. }
  8917. var block = editor.getParam('forced_root_block', 'p');
  8918. if (block === false) {
  8919. return '';
  8920. } else if (block === true) {
  8921. return 'p';
  8922. } else {
  8923. return block;
  8924. }
  8925. };
  8926. var getForcedRootBlockAttrs = function (editor) {
  8927. return editor.getParam('forced_root_block_attrs', {});
  8928. };
  8929. var getBrNewLineSelector = function (editor) {
  8930. return editor.getParam('br_newline_selector', '.mce-toc h2,figcaption,caption');
  8931. };
  8932. var getNoNewLineSelector = function (editor) {
  8933. return editor.getParam('no_newline_selector', '');
  8934. };
  8935. var shouldKeepStyles = function (editor) {
  8936. return editor.getParam('keep_styles', true);
  8937. };
  8938. var shouldEndContainerOnEmptyBlock = function (editor) {
  8939. return editor.getParam('end_container_on_empty_block', false);
  8940. };
  8941. var getFontStyleValues = function (editor) {
  8942. return Tools.explode(editor.getParam('font_size_style_values', 'xx-small,x-small,small,medium,large,x-large,xx-large'));
  8943. };
  8944. var getFontSizeClasses = function (editor) {
  8945. return Tools.explode(editor.getParam('font_size_classes', ''));
  8946. };
  8947. var getImagesDataImgFilter = function (editor) {
  8948. return editor.getParam('images_dataimg_filter', always, 'function');
  8949. };
  8950. var isAutomaticUploadsEnabled = function (editor) {
  8951. return editor.getParam('automatic_uploads', true, 'boolean');
  8952. };
  8953. var shouldReuseFileName = function (editor) {
  8954. return editor.getParam('images_reuse_filename', false, 'boolean');
  8955. };
  8956. var shouldReplaceBlobUris = function (editor) {
  8957. return editor.getParam('images_replace_blob_uris', true, 'boolean');
  8958. };
  8959. var getIconPackName = function (editor) {
  8960. return editor.getParam('icons', '', 'string');
  8961. };
  8962. var getIconsUrl = function (editor) {
  8963. return editor.getParam('icons_url', '', 'string');
  8964. };
  8965. var getImageUploadUrl = function (editor) {
  8966. return editor.getParam('images_upload_url', '', 'string');
  8967. };
  8968. var getImageUploadBasePath = function (editor) {
  8969. return editor.getParam('images_upload_base_path', '', 'string');
  8970. };
  8971. var getImagesUploadCredentials = function (editor) {
  8972. return editor.getParam('images_upload_credentials', false, 'boolean');
  8973. };
  8974. var getImagesUploadHandler = function (editor) {
  8975. return editor.getParam('images_upload_handler', null, 'function');
  8976. };
  8977. var shouldUseContentCssCors = function (editor) {
  8978. return editor.getParam('content_css_cors', false, 'boolean');
  8979. };
  8980. var getReferrerPolicy = function (editor) {
  8981. return editor.getParam('referrer_policy', '', 'string');
  8982. };
  8983. var getLanguageCode = function (editor) {
  8984. return editor.getParam('language', 'en', 'string');
  8985. };
  8986. var getLanguageUrl = function (editor) {
  8987. return editor.getParam('language_url', '', 'string');
  8988. };
  8989. var shouldIndentUseMargin = function (editor) {
  8990. return editor.getParam('indent_use_margin', false);
  8991. };
  8992. var getIndentation = function (editor) {
  8993. return editor.getParam('indentation', '40px', 'string');
  8994. };
  8995. var getContentCss = function (editor) {
  8996. var contentCss = editor.getParam('content_css');
  8997. if (isString$1(contentCss)) {
  8998. return map$3(contentCss.split(','), trim$4);
  8999. } else if (isArray$1(contentCss)) {
  9000. return contentCss;
  9001. } else if (contentCss === false || editor.inline) {
  9002. return [];
  9003. } else {
  9004. return ['default'];
  9005. }
  9006. };
  9007. var getFontCss = function (editor) {
  9008. var fontCss = editor.getParam('font_css', []);
  9009. return isArray$1(fontCss) ? fontCss : map$3(fontCss.split(','), trim$4);
  9010. };
  9011. var getDirectionality = function (editor) {
  9012. return editor.getParam('directionality', I18n.isRtl() ? 'rtl' : undefined);
  9013. };
  9014. var getInlineBoundarySelector = function (editor) {
  9015. return editor.getParam('inline_boundaries_selector', 'a[href],code,.mce-annotation', 'string');
  9016. };
  9017. var getObjectResizing = function (editor) {
  9018. var selector = editor.getParam('object_resizing');
  9019. if (selector === false || Env.iOS) {
  9020. return false;
  9021. } else {
  9022. return isString$1(selector) ? selector : 'table,img,figure.image,div,video,iframe';
  9023. }
  9024. };
  9025. var getResizeImgProportional = function (editor) {
  9026. return editor.getParam('resize_img_proportional', true, 'boolean');
  9027. };
  9028. var getPlaceholder = function (editor) {
  9029. return editor.getParam('placeholder', DOM$9.getAttrib(editor.getElement(), 'placeholder'), 'string');
  9030. };
  9031. var getEventRoot = function (editor) {
  9032. return editor.getParam('event_root');
  9033. };
  9034. var getServiceMessage = function (editor) {
  9035. return editor.getParam('service_message');
  9036. };
  9037. var getTheme = function (editor) {
  9038. return editor.getParam('theme');
  9039. };
  9040. var shouldValidate = function (editor) {
  9041. return editor.getParam('validate');
  9042. };
  9043. var isInlineBoundariesEnabled = function (editor) {
  9044. return editor.getParam('inline_boundaries') !== false;
  9045. };
  9046. var getFormats = function (editor) {
  9047. return editor.getParam('formats');
  9048. };
  9049. var getPreviewStyles = function (editor) {
  9050. var style = editor.getParam('preview_styles', defaultPreviewStyles);
  9051. if (isString$1(style)) {
  9052. return style;
  9053. } else {
  9054. return '';
  9055. }
  9056. };
  9057. var canFormatEmptyLines = function (editor) {
  9058. return editor.getParam('format_empty_lines', false, 'boolean');
  9059. };
  9060. var getCustomUiSelector = function (editor) {
  9061. return editor.getParam('custom_ui_selector', '', 'string');
  9062. };
  9063. var getThemeUrl = function (editor) {
  9064. return editor.getParam('theme_url');
  9065. };
  9066. var isInline = function (editor) {
  9067. return editor.getParam('inline');
  9068. };
  9069. var hasHiddenInput = function (editor) {
  9070. return editor.getParam('hidden_input');
  9071. };
  9072. var shouldPatchSubmit = function (editor) {
  9073. return editor.getParam('submit_patch');
  9074. };
  9075. var isEncodingXml = function (editor) {
  9076. return editor.getParam('encoding') === 'xml';
  9077. };
  9078. var shouldAddFormSubmitTrigger = function (editor) {
  9079. return editor.getParam('add_form_submit_trigger');
  9080. };
  9081. var shouldAddUnloadTrigger = function (editor) {
  9082. return editor.getParam('add_unload_trigger');
  9083. };
  9084. var hasForcedRootBlock = function (editor) {
  9085. return getForcedRootBlock(editor) !== '';
  9086. };
  9087. var getCustomUndoRedoLevels = function (editor) {
  9088. return editor.getParam('custom_undo_redo_levels', 0, 'number');
  9089. };
  9090. var shouldDisableNodeChange = function (editor) {
  9091. return editor.getParam('disable_nodechange');
  9092. };
  9093. var isReadOnly$1 = function (editor) {
  9094. return editor.getParam('readonly');
  9095. };
  9096. var hasContentCssCors = function (editor) {
  9097. return editor.getParam('content_css_cors');
  9098. };
  9099. var getPlugins = function (editor) {
  9100. return editor.getParam('plugins', '', 'string');
  9101. };
  9102. var getExternalPlugins$1 = function (editor) {
  9103. return editor.getParam('external_plugins');
  9104. };
  9105. var shouldBlockUnsupportedDrop = function (editor) {
  9106. return editor.getParam('block_unsupported_drop', true, 'boolean');
  9107. };
  9108. var isVisualAidsEnabled = function (editor) {
  9109. return editor.getParam('visual', true, 'boolean');
  9110. };
  9111. var getVisualAidsTableClass = function (editor) {
  9112. return editor.getParam('visual_table_class', 'mce-item-table', 'string');
  9113. };
  9114. var getVisualAidsAnchorClass = function (editor) {
  9115. return editor.getParam('visual_anchor_class', 'mce-item-anchor', 'string');
  9116. };
  9117. var getIframeAriaText = function (editor) {
  9118. return editor.getParam('iframe_aria_text', 'Rich Text Area. Press ALT-0 for help.', 'string');
  9119. };
  9120. var isElement$2 = isElement$5;
  9121. var isText$2 = isText$7;
  9122. var removeNode$1 = function (node) {
  9123. var parentNode = node.parentNode;
  9124. if (parentNode) {
  9125. parentNode.removeChild(node);
  9126. }
  9127. };
  9128. var trimCount = function (text) {
  9129. var trimmedText = trim$2(text);
  9130. return {
  9131. count: text.length - trimmedText.length,
  9132. text: trimmedText
  9133. };
  9134. };
  9135. var deleteZwspChars = function (caretContainer) {
  9136. var idx;
  9137. while ((idx = caretContainer.data.lastIndexOf(ZWSP$1)) !== -1) {
  9138. caretContainer.deleteData(idx, 1);
  9139. }
  9140. };
  9141. var removeUnchanged = function (caretContainer, pos) {
  9142. remove$2(caretContainer);
  9143. return pos;
  9144. };
  9145. var removeTextAndReposition = function (caretContainer, pos) {
  9146. var before = trimCount(caretContainer.data.substr(0, pos.offset()));
  9147. var after = trimCount(caretContainer.data.substr(pos.offset()));
  9148. var text = before.text + after.text;
  9149. if (text.length > 0) {
  9150. deleteZwspChars(caretContainer);
  9151. return CaretPosition(caretContainer, pos.offset() - before.count);
  9152. } else {
  9153. return pos;
  9154. }
  9155. };
  9156. var removeElementAndReposition = function (caretContainer, pos) {
  9157. var parentNode = pos.container();
  9158. var newPosition = indexOf$2(from(parentNode.childNodes), caretContainer).map(function (index) {
  9159. return index < pos.offset() ? CaretPosition(parentNode, pos.offset() - 1) : pos;
  9160. }).getOr(pos);
  9161. remove$2(caretContainer);
  9162. return newPosition;
  9163. };
  9164. var removeTextCaretContainer = function (caretContainer, pos) {
  9165. return isText$2(caretContainer) && pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9166. };
  9167. var removeElementCaretContainer = function (caretContainer, pos) {
  9168. return pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9169. };
  9170. var removeAndReposition = function (container, pos) {
  9171. return CaretPosition.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
  9172. };
  9173. var remove$2 = function (caretContainerNode) {
  9174. if (isElement$2(caretContainerNode) && isCaretContainer$2(caretContainerNode)) {
  9175. if (hasContent(caretContainerNode)) {
  9176. caretContainerNode.removeAttribute('data-mce-caret');
  9177. } else {
  9178. removeNode$1(caretContainerNode);
  9179. }
  9180. }
  9181. if (isText$2(caretContainerNode)) {
  9182. deleteZwspChars(caretContainerNode);
  9183. if (caretContainerNode.data.length === 0) {
  9184. removeNode$1(caretContainerNode);
  9185. }
  9186. }
  9187. };
  9188. var browser$2 = detect().browser;
  9189. var isContentEditableFalse$8 = isContentEditableFalse$b;
  9190. var isMedia$1 = isMedia$2;
  9191. var isTableCell$3 = isTableCell$5;
  9192. var inlineFakeCaretSelector = '*[contentEditable=false],video,audio,embed,object';
  9193. var getAbsoluteClientRect = function (root, element, before) {
  9194. var clientRect = collapse(element.getBoundingClientRect(), before);
  9195. var scrollX;
  9196. var scrollY;
  9197. if (root.tagName === 'BODY') {
  9198. var docElm = root.ownerDocument.documentElement;
  9199. scrollX = root.scrollLeft || docElm.scrollLeft;
  9200. scrollY = root.scrollTop || docElm.scrollTop;
  9201. } else {
  9202. var rootRect = root.getBoundingClientRect();
  9203. scrollX = root.scrollLeft - rootRect.left;
  9204. scrollY = root.scrollTop - rootRect.top;
  9205. }
  9206. clientRect.left += scrollX;
  9207. clientRect.right += scrollX;
  9208. clientRect.top += scrollY;
  9209. clientRect.bottom += scrollY;
  9210. clientRect.width = 1;
  9211. var margin = element.offsetWidth - element.clientWidth;
  9212. if (margin > 0) {
  9213. if (before) {
  9214. margin *= -1;
  9215. }
  9216. clientRect.left += margin;
  9217. clientRect.right += margin;
  9218. }
  9219. return clientRect;
  9220. };
  9221. var trimInlineCaretContainers = function (root) {
  9222. var fakeCaretTargetNodes = descendants(SugarElement.fromDom(root), inlineFakeCaretSelector);
  9223. for (var i = 0; i < fakeCaretTargetNodes.length; i++) {
  9224. var node = fakeCaretTargetNodes[i].dom;
  9225. var sibling = node.previousSibling;
  9226. if (endsWithCaretContainer$1(sibling)) {
  9227. var data = sibling.data;
  9228. if (data.length === 1) {
  9229. sibling.parentNode.removeChild(sibling);
  9230. } else {
  9231. sibling.deleteData(data.length - 1, 1);
  9232. }
  9233. }
  9234. sibling = node.nextSibling;
  9235. if (startsWithCaretContainer$1(sibling)) {
  9236. var data = sibling.data;
  9237. if (data.length === 1) {
  9238. sibling.parentNode.removeChild(sibling);
  9239. } else {
  9240. sibling.deleteData(0, 1);
  9241. }
  9242. }
  9243. }
  9244. };
  9245. var FakeCaret = function (editor, root, isBlock, hasFocus) {
  9246. var lastVisualCaret = value();
  9247. var cursorInterval;
  9248. var caretContainerNode;
  9249. var rootBlock = getForcedRootBlock(editor);
  9250. var caretBlock = rootBlock.length > 0 ? rootBlock : 'p';
  9251. var show = function (before, element) {
  9252. var rng;
  9253. hide();
  9254. if (isTableCell$3(element)) {
  9255. return null;
  9256. }
  9257. if (isBlock(element)) {
  9258. caretContainerNode = insertBlock$1(caretBlock, element, before);
  9259. var clientRect = getAbsoluteClientRect(root, element, before);
  9260. DomQuery(caretContainerNode).css('top', clientRect.top);
  9261. var caret = DomQuery('<div class="mce-visual-caret" data-mce-bogus="all"></div>').css(__assign({}, clientRect)).appendTo(root)[0];
  9262. lastVisualCaret.set({
  9263. caret: caret,
  9264. element: element,
  9265. before: before
  9266. });
  9267. if (before) {
  9268. DomQuery(caret).addClass('mce-visual-caret-before');
  9269. }
  9270. startBlink();
  9271. rng = element.ownerDocument.createRange();
  9272. rng.setStart(caretContainerNode, 0);
  9273. rng.setEnd(caretContainerNode, 0);
  9274. } else {
  9275. caretContainerNode = insertInline$1(element, before);
  9276. rng = element.ownerDocument.createRange();
  9277. if (isInlineFakeCaretTarget(caretContainerNode.nextSibling)) {
  9278. rng.setStart(caretContainerNode, 0);
  9279. rng.setEnd(caretContainerNode, 0);
  9280. } else {
  9281. rng.setStart(caretContainerNode, 1);
  9282. rng.setEnd(caretContainerNode, 1);
  9283. }
  9284. return rng;
  9285. }
  9286. return rng;
  9287. };
  9288. var hide = function () {
  9289. trimInlineCaretContainers(root);
  9290. if (caretContainerNode) {
  9291. remove$2(caretContainerNode);
  9292. caretContainerNode = null;
  9293. }
  9294. lastVisualCaret.on(function (caretState) {
  9295. DomQuery(caretState.caret).remove();
  9296. lastVisualCaret.clear();
  9297. });
  9298. if (cursorInterval) {
  9299. Delay.clearInterval(cursorInterval);
  9300. cursorInterval = undefined;
  9301. }
  9302. };
  9303. var startBlink = function () {
  9304. cursorInterval = Delay.setInterval(function () {
  9305. if (hasFocus()) {
  9306. DomQuery('div.mce-visual-caret', root).toggleClass('mce-visual-caret-hidden');
  9307. } else {
  9308. DomQuery('div.mce-visual-caret', root).addClass('mce-visual-caret-hidden');
  9309. }
  9310. }, 500);
  9311. };
  9312. var reposition = function () {
  9313. lastVisualCaret.on(function (caretState) {
  9314. var clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
  9315. DomQuery(caretState.caret).css(__assign({}, clientRect));
  9316. });
  9317. };
  9318. var destroy = function () {
  9319. return Delay.clearInterval(cursorInterval);
  9320. };
  9321. var getCss = function () {
  9322. 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;' + '}';
  9323. };
  9324. return {
  9325. show: show,
  9326. hide: hide,
  9327. getCss: getCss,
  9328. reposition: reposition,
  9329. destroy: destroy
  9330. };
  9331. };
  9332. var isFakeCaretTableBrowser = function () {
  9333. return browser$2.isIE() || browser$2.isEdge() || browser$2.isFirefox();
  9334. };
  9335. var isInlineFakeCaretTarget = function (node) {
  9336. return isContentEditableFalse$8(node) || isMedia$1(node);
  9337. };
  9338. var isFakeCaretTarget = function (node) {
  9339. return isInlineFakeCaretTarget(node) || isTable$3(node) && isFakeCaretTableBrowser();
  9340. };
  9341. var isContentEditableFalse$7 = isContentEditableFalse$b;
  9342. var isMedia = isMedia$2;
  9343. var isBlockLike = matchStyleValues('display', 'block table table-cell table-caption list-item');
  9344. var isCaretContainer = isCaretContainer$2;
  9345. var isCaretContainerBlock = isCaretContainerBlock$1;
  9346. var isElement$1 = isElement$5;
  9347. var isCaretCandidate$1 = isCaretCandidate$3;
  9348. var isForwards = function (direction) {
  9349. return direction > 0;
  9350. };
  9351. var isBackwards = function (direction) {
  9352. return direction < 0;
  9353. };
  9354. var skipCaretContainers = function (walk, shallow) {
  9355. var node;
  9356. while (node = walk(shallow)) {
  9357. if (!isCaretContainerBlock(node)) {
  9358. return node;
  9359. }
  9360. }
  9361. return null;
  9362. };
  9363. var findNode$1 = function (node, direction, predicateFn, rootNode, shallow) {
  9364. var walker = new DomTreeWalker(node, rootNode);
  9365. var isCefOrCaretContainer = isContentEditableFalse$7(node) || isCaretContainerBlock(node);
  9366. if (isBackwards(direction)) {
  9367. if (isCefOrCaretContainer) {
  9368. node = skipCaretContainers(walker.prev.bind(walker), true);
  9369. if (predicateFn(node)) {
  9370. return node;
  9371. }
  9372. }
  9373. while (node = skipCaretContainers(walker.prev.bind(walker), shallow)) {
  9374. if (predicateFn(node)) {
  9375. return node;
  9376. }
  9377. }
  9378. }
  9379. if (isForwards(direction)) {
  9380. if (isCefOrCaretContainer) {
  9381. node = skipCaretContainers(walker.next.bind(walker), true);
  9382. if (predicateFn(node)) {
  9383. return node;
  9384. }
  9385. }
  9386. while (node = skipCaretContainers(walker.next.bind(walker), shallow)) {
  9387. if (predicateFn(node)) {
  9388. return node;
  9389. }
  9390. }
  9391. }
  9392. return null;
  9393. };
  9394. var getParentBlock$2 = function (node, rootNode) {
  9395. while (node && node !== rootNode) {
  9396. if (isBlockLike(node)) {
  9397. return node;
  9398. }
  9399. node = node.parentNode;
  9400. }
  9401. return null;
  9402. };
  9403. var isInSameBlock = function (caretPosition1, caretPosition2, rootNode) {
  9404. return getParentBlock$2(caretPosition1.container(), rootNode) === getParentBlock$2(caretPosition2.container(), rootNode);
  9405. };
  9406. var getChildNodeAtRelativeOffset = function (relativeOffset, caretPosition) {
  9407. if (!caretPosition) {
  9408. return null;
  9409. }
  9410. var container = caretPosition.container();
  9411. var offset = caretPosition.offset();
  9412. if (!isElement$1(container)) {
  9413. return null;
  9414. }
  9415. return container.childNodes[offset + relativeOffset];
  9416. };
  9417. var beforeAfter = function (before, node) {
  9418. var range = node.ownerDocument.createRange();
  9419. if (before) {
  9420. range.setStartBefore(node);
  9421. range.setEndBefore(node);
  9422. } else {
  9423. range.setStartAfter(node);
  9424. range.setEndAfter(node);
  9425. }
  9426. return range;
  9427. };
  9428. var isNodesInSameBlock = function (root, node1, node2) {
  9429. return getParentBlock$2(node1, root) === getParentBlock$2(node2, root);
  9430. };
  9431. var lean = function (left, root, node) {
  9432. var siblingName = left ? 'previousSibling' : 'nextSibling';
  9433. while (node && node !== root) {
  9434. var sibling = node[siblingName];
  9435. if (isCaretContainer(sibling)) {
  9436. sibling = sibling[siblingName];
  9437. }
  9438. if (isContentEditableFalse$7(sibling) || isMedia(sibling)) {
  9439. if (isNodesInSameBlock(root, sibling, node)) {
  9440. return sibling;
  9441. }
  9442. break;
  9443. }
  9444. if (isCaretCandidate$1(sibling)) {
  9445. break;
  9446. }
  9447. node = node.parentNode;
  9448. }
  9449. return null;
  9450. };
  9451. var before$2 = curry(beforeAfter, true);
  9452. var after$2 = curry(beforeAfter, false);
  9453. var normalizeRange = function (direction, root, range) {
  9454. var node;
  9455. var leanLeft = curry(lean, true, root);
  9456. var leanRight = curry(lean, false, root);
  9457. var container = range.startContainer;
  9458. var offset = range.startOffset;
  9459. if (isCaretContainerBlock$1(container)) {
  9460. if (!isElement$1(container)) {
  9461. container = container.parentNode;
  9462. }
  9463. var location_1 = container.getAttribute('data-mce-caret');
  9464. if (location_1 === 'before') {
  9465. node = container.nextSibling;
  9466. if (isFakeCaretTarget(node)) {
  9467. return before$2(node);
  9468. }
  9469. }
  9470. if (location_1 === 'after') {
  9471. node = container.previousSibling;
  9472. if (isFakeCaretTarget(node)) {
  9473. return after$2(node);
  9474. }
  9475. }
  9476. }
  9477. if (!range.collapsed) {
  9478. return range;
  9479. }
  9480. if (isText$7(container)) {
  9481. if (isCaretContainer(container)) {
  9482. if (direction === 1) {
  9483. node = leanRight(container);
  9484. if (node) {
  9485. return before$2(node);
  9486. }
  9487. node = leanLeft(container);
  9488. if (node) {
  9489. return after$2(node);
  9490. }
  9491. }
  9492. if (direction === -1) {
  9493. node = leanLeft(container);
  9494. if (node) {
  9495. return after$2(node);
  9496. }
  9497. node = leanRight(container);
  9498. if (node) {
  9499. return before$2(node);
  9500. }
  9501. }
  9502. return range;
  9503. }
  9504. if (endsWithCaretContainer$1(container) && offset >= container.data.length - 1) {
  9505. if (direction === 1) {
  9506. node = leanRight(container);
  9507. if (node) {
  9508. return before$2(node);
  9509. }
  9510. }
  9511. return range;
  9512. }
  9513. if (startsWithCaretContainer$1(container) && offset <= 1) {
  9514. if (direction === -1) {
  9515. node = leanLeft(container);
  9516. if (node) {
  9517. return after$2(node);
  9518. }
  9519. }
  9520. return range;
  9521. }
  9522. if (offset === container.data.length) {
  9523. node = leanRight(container);
  9524. if (node) {
  9525. return before$2(node);
  9526. }
  9527. return range;
  9528. }
  9529. if (offset === 0) {
  9530. node = leanLeft(container);
  9531. if (node) {
  9532. return after$2(node);
  9533. }
  9534. return range;
  9535. }
  9536. }
  9537. return range;
  9538. };
  9539. var getRelativeCefElm = function (forward, caretPosition) {
  9540. return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition)).filter(isContentEditableFalse$7);
  9541. };
  9542. var getNormalizedRangeEndPoint = function (direction, root, range) {
  9543. var normalizedRange = normalizeRange(direction, root, range);
  9544. if (direction === -1) {
  9545. return CaretPosition.fromRangeStart(normalizedRange);
  9546. }
  9547. return CaretPosition.fromRangeEnd(normalizedRange);
  9548. };
  9549. var getElementFromPosition = function (pos) {
  9550. return Optional.from(pos.getNode()).map(SugarElement.fromDom);
  9551. };
  9552. var getElementFromPrevPosition = function (pos) {
  9553. return Optional.from(pos.getNode(true)).map(SugarElement.fromDom);
  9554. };
  9555. var getVisualCaretPosition = function (walkFn, caretPosition) {
  9556. while (caretPosition = walkFn(caretPosition)) {
  9557. if (caretPosition.isVisible()) {
  9558. return caretPosition;
  9559. }
  9560. }
  9561. return caretPosition;
  9562. };
  9563. var isMoveInsideSameBlock = function (from, to) {
  9564. var inSameBlock = isInSameBlock(from, to);
  9565. if (!inSameBlock && isBr$5(from.getNode())) {
  9566. return true;
  9567. }
  9568. return inSameBlock;
  9569. };
  9570. var HDirection;
  9571. (function (HDirection) {
  9572. HDirection[HDirection['Backwards'] = -1] = 'Backwards';
  9573. HDirection[HDirection['Forwards'] = 1] = 'Forwards';
  9574. }(HDirection || (HDirection = {})));
  9575. var isContentEditableFalse$6 = isContentEditableFalse$b;
  9576. var isText$1 = isText$7;
  9577. var isElement = isElement$5;
  9578. var isBr$1 = isBr$5;
  9579. var isCaretCandidate = isCaretCandidate$3;
  9580. var isAtomic = isAtomic$1;
  9581. var isEditableCaretCandidate = isEditableCaretCandidate$1;
  9582. var getParents$3 = function (node, root) {
  9583. var parents = [];
  9584. while (node && node !== root) {
  9585. parents.push(node);
  9586. node = node.parentNode;
  9587. }
  9588. return parents;
  9589. };
  9590. var nodeAtIndex = function (container, offset) {
  9591. if (container.hasChildNodes() && offset < container.childNodes.length) {
  9592. return container.childNodes[offset];
  9593. }
  9594. return null;
  9595. };
  9596. var getCaretCandidatePosition = function (direction, node) {
  9597. if (isForwards(direction)) {
  9598. if (isCaretCandidate(node.previousSibling) && !isText$1(node.previousSibling)) {
  9599. return CaretPosition.before(node);
  9600. }
  9601. if (isText$1(node)) {
  9602. return CaretPosition(node, 0);
  9603. }
  9604. }
  9605. if (isBackwards(direction)) {
  9606. if (isCaretCandidate(node.nextSibling) && !isText$1(node.nextSibling)) {
  9607. return CaretPosition.after(node);
  9608. }
  9609. if (isText$1(node)) {
  9610. return CaretPosition(node, node.data.length);
  9611. }
  9612. }
  9613. if (isBackwards(direction)) {
  9614. if (isBr$1(node)) {
  9615. return CaretPosition.before(node);
  9616. }
  9617. return CaretPosition.after(node);
  9618. }
  9619. return CaretPosition.before(node);
  9620. };
  9621. var moveForwardFromBr = function (root, nextNode) {
  9622. var nextSibling = nextNode.nextSibling;
  9623. if (nextSibling && isCaretCandidate(nextSibling)) {
  9624. if (isText$1(nextSibling)) {
  9625. return CaretPosition(nextSibling, 0);
  9626. } else {
  9627. return CaretPosition.before(nextSibling);
  9628. }
  9629. } else {
  9630. return findCaretPosition$1(HDirection.Forwards, CaretPosition.after(nextNode), root);
  9631. }
  9632. };
  9633. var findCaretPosition$1 = function (direction, startPos, root) {
  9634. var node;
  9635. var nextNode;
  9636. var innerNode;
  9637. var caretPosition;
  9638. if (!isElement(root) || !startPos) {
  9639. return null;
  9640. }
  9641. if (startPos.isEqual(CaretPosition.after(root)) && root.lastChild) {
  9642. caretPosition = CaretPosition.after(root.lastChild);
  9643. if (isBackwards(direction) && isCaretCandidate(root.lastChild) && isElement(root.lastChild)) {
  9644. return isBr$1(root.lastChild) ? CaretPosition.before(root.lastChild) : caretPosition;
  9645. }
  9646. } else {
  9647. caretPosition = startPos;
  9648. }
  9649. var container = caretPosition.container();
  9650. var offset = caretPosition.offset();
  9651. if (isText$1(container)) {
  9652. if (isBackwards(direction) && offset > 0) {
  9653. return CaretPosition(container, --offset);
  9654. }
  9655. if (isForwards(direction) && offset < container.length) {
  9656. return CaretPosition(container, ++offset);
  9657. }
  9658. node = container;
  9659. } else {
  9660. if (isBackwards(direction) && offset > 0) {
  9661. nextNode = nodeAtIndex(container, offset - 1);
  9662. if (isCaretCandidate(nextNode)) {
  9663. if (!isAtomic(nextNode)) {
  9664. innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
  9665. if (innerNode) {
  9666. if (isText$1(innerNode)) {
  9667. return CaretPosition(innerNode, innerNode.data.length);
  9668. }
  9669. return CaretPosition.after(innerNode);
  9670. }
  9671. }
  9672. if (isText$1(nextNode)) {
  9673. return CaretPosition(nextNode, nextNode.data.length);
  9674. }
  9675. return CaretPosition.before(nextNode);
  9676. }
  9677. }
  9678. if (isForwards(direction) && offset < container.childNodes.length) {
  9679. nextNode = nodeAtIndex(container, offset);
  9680. if (isCaretCandidate(nextNode)) {
  9681. if (isBr$1(nextNode)) {
  9682. return moveForwardFromBr(root, nextNode);
  9683. }
  9684. if (!isAtomic(nextNode)) {
  9685. innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
  9686. if (innerNode) {
  9687. if (isText$1(innerNode)) {
  9688. return CaretPosition(innerNode, 0);
  9689. }
  9690. return CaretPosition.before(innerNode);
  9691. }
  9692. }
  9693. if (isText$1(nextNode)) {
  9694. return CaretPosition(nextNode, 0);
  9695. }
  9696. return CaretPosition.after(nextNode);
  9697. }
  9698. }
  9699. node = nextNode ? nextNode : caretPosition.getNode();
  9700. }
  9701. if (isForwards(direction) && caretPosition.isAtEnd() || isBackwards(direction) && caretPosition.isAtStart()) {
  9702. node = findNode$1(node, direction, always, root, true);
  9703. if (isEditableCaretCandidate(node, root)) {
  9704. return getCaretCandidatePosition(direction, node);
  9705. }
  9706. }
  9707. nextNode = findNode$1(node, direction, isEditableCaretCandidate, root);
  9708. var rootContentEditableFalseElm = last$1(filter$4(getParents$3(container, root), isContentEditableFalse$6));
  9709. if (rootContentEditableFalseElm && (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
  9710. if (isForwards(direction)) {
  9711. caretPosition = CaretPosition.after(rootContentEditableFalseElm);
  9712. } else {
  9713. caretPosition = CaretPosition.before(rootContentEditableFalseElm);
  9714. }
  9715. return caretPosition;
  9716. }
  9717. if (nextNode) {
  9718. return getCaretCandidatePosition(direction, nextNode);
  9719. }
  9720. return null;
  9721. };
  9722. var CaretWalker = function (root) {
  9723. return {
  9724. next: function (caretPosition) {
  9725. return findCaretPosition$1(HDirection.Forwards, caretPosition, root);
  9726. },
  9727. prev: function (caretPosition) {
  9728. return findCaretPosition$1(HDirection.Backwards, caretPosition, root);
  9729. }
  9730. };
  9731. };
  9732. var walkToPositionIn = function (forward, root, start) {
  9733. var position = forward ? CaretPosition.before(start) : CaretPosition.after(start);
  9734. return fromPosition(forward, root, position);
  9735. };
  9736. var afterElement = function (node) {
  9737. return isBr$5(node) ? CaretPosition.before(node) : CaretPosition.after(node);
  9738. };
  9739. var isBeforeOrStart = function (position) {
  9740. if (CaretPosition.isTextPosition(position)) {
  9741. return position.offset() === 0;
  9742. } else {
  9743. return isCaretCandidate$3(position.getNode());
  9744. }
  9745. };
  9746. var isAfterOrEnd = function (position) {
  9747. if (CaretPosition.isTextPosition(position)) {
  9748. var container = position.container();
  9749. return position.offset() === container.data.length;
  9750. } else {
  9751. return isCaretCandidate$3(position.getNode(true));
  9752. }
  9753. };
  9754. var isBeforeAfterSameElement = function (from, to) {
  9755. return !CaretPosition.isTextPosition(from) && !CaretPosition.isTextPosition(to) && from.getNode() === to.getNode(true);
  9756. };
  9757. var isAtBr = function (position) {
  9758. return !CaretPosition.isTextPosition(position) && isBr$5(position.getNode());
  9759. };
  9760. var shouldSkipPosition = function (forward, from, to) {
  9761. if (forward) {
  9762. return !isBeforeAfterSameElement(from, to) && !isAtBr(from) && isAfterOrEnd(from) && isBeforeOrStart(to);
  9763. } else {
  9764. return !isBeforeAfterSameElement(to, from) && isBeforeOrStart(from) && isAfterOrEnd(to);
  9765. }
  9766. };
  9767. var fromPosition = function (forward, root, pos) {
  9768. var walker = CaretWalker(root);
  9769. return Optional.from(forward ? walker.next(pos) : walker.prev(pos));
  9770. };
  9771. var navigate = function (forward, root, from) {
  9772. return fromPosition(forward, root, from).bind(function (to) {
  9773. if (isInSameBlock(from, to, root) && shouldSkipPosition(forward, from, to)) {
  9774. return fromPosition(forward, root, to);
  9775. } else {
  9776. return Optional.some(to);
  9777. }
  9778. });
  9779. };
  9780. var navigateIgnore = function (forward, root, from, ignoreFilter) {
  9781. return navigate(forward, root, from).bind(function (pos) {
  9782. return ignoreFilter(pos) ? navigateIgnore(forward, root, pos, ignoreFilter) : Optional.some(pos);
  9783. });
  9784. };
  9785. var positionIn = function (forward, element) {
  9786. var startNode = forward ? element.firstChild : element.lastChild;
  9787. if (isText$7(startNode)) {
  9788. return Optional.some(CaretPosition(startNode, forward ? 0 : startNode.data.length));
  9789. } else if (startNode) {
  9790. if (isCaretCandidate$3(startNode)) {
  9791. return Optional.some(forward ? CaretPosition.before(startNode) : afterElement(startNode));
  9792. } else {
  9793. return walkToPositionIn(forward, element, startNode);
  9794. }
  9795. } else {
  9796. return Optional.none();
  9797. }
  9798. };
  9799. var nextPosition = curry(fromPosition, true);
  9800. var prevPosition = curry(fromPosition, false);
  9801. var firstPositionIn = curry(positionIn, true);
  9802. var lastPositionIn = curry(positionIn, false);
  9803. var CARET_ID$1 = '_mce_caret';
  9804. var isCaretNode = function (node) {
  9805. return isElement$5(node) && node.id === CARET_ID$1;
  9806. };
  9807. var getParentCaretContainer = function (body, node) {
  9808. while (node && node !== body) {
  9809. if (node.id === CARET_ID$1) {
  9810. return node;
  9811. }
  9812. node = node.parentNode;
  9813. }
  9814. return null;
  9815. };
  9816. var isStringPathBookmark = function (bookmark) {
  9817. return isString$1(bookmark.start);
  9818. };
  9819. var isRangeBookmark = function (bookmark) {
  9820. return has$2(bookmark, 'rng');
  9821. };
  9822. var isIdBookmark = function (bookmark) {
  9823. return has$2(bookmark, 'id');
  9824. };
  9825. var isIndexBookmark = function (bookmark) {
  9826. return has$2(bookmark, 'name');
  9827. };
  9828. var isPathBookmark = function (bookmark) {
  9829. return Tools.isArray(bookmark.start);
  9830. };
  9831. var addBogus = function (dom, node) {
  9832. if (isElement$5(node) && dom.isBlock(node) && !node.innerHTML && !Env.ie) {
  9833. node.innerHTML = '<br data-mce-bogus="1" />';
  9834. }
  9835. return node;
  9836. };
  9837. var resolveCaretPositionBookmark = function (dom, bookmark) {
  9838. var pos;
  9839. var rng = dom.createRng();
  9840. pos = resolve$2(dom.getRoot(), bookmark.start);
  9841. rng.setStart(pos.container(), pos.offset());
  9842. pos = resolve$2(dom.getRoot(), bookmark.end);
  9843. rng.setEnd(pos.container(), pos.offset());
  9844. return rng;
  9845. };
  9846. var insertZwsp = function (node, rng) {
  9847. var textNode = node.ownerDocument.createTextNode(ZWSP$1);
  9848. node.appendChild(textNode);
  9849. rng.setStart(textNode, 0);
  9850. rng.setEnd(textNode, 0);
  9851. };
  9852. var isEmpty$1 = function (node) {
  9853. return node.hasChildNodes() === false;
  9854. };
  9855. var tryFindRangePosition = function (node, rng) {
  9856. return lastPositionIn(node).fold(never, function (pos) {
  9857. rng.setStart(pos.container(), pos.offset());
  9858. rng.setEnd(pos.container(), pos.offset());
  9859. return true;
  9860. });
  9861. };
  9862. var padEmptyCaretContainer = function (root, node, rng) {
  9863. if (isEmpty$1(node) && getParentCaretContainer(root, node)) {
  9864. insertZwsp(node, rng);
  9865. return true;
  9866. } else {
  9867. return false;
  9868. }
  9869. };
  9870. var setEndPoint = function (dom, start, bookmark, rng) {
  9871. var point = bookmark[start ? 'start' : 'end'];
  9872. var i, node, offset, children;
  9873. var root = dom.getRoot();
  9874. if (point) {
  9875. offset = point[0];
  9876. for (node = root, i = point.length - 1; i >= 1; i--) {
  9877. children = node.childNodes;
  9878. if (padEmptyCaretContainer(root, node, rng)) {
  9879. return true;
  9880. }
  9881. if (point[i] > children.length - 1) {
  9882. if (padEmptyCaretContainer(root, node, rng)) {
  9883. return true;
  9884. }
  9885. return tryFindRangePosition(node, rng);
  9886. }
  9887. node = children[point[i]];
  9888. }
  9889. if (node.nodeType === 3) {
  9890. offset = Math.min(point[0], node.nodeValue.length);
  9891. }
  9892. if (node.nodeType === 1) {
  9893. offset = Math.min(point[0], node.childNodes.length);
  9894. }
  9895. if (start) {
  9896. rng.setStart(node, offset);
  9897. } else {
  9898. rng.setEnd(node, offset);
  9899. }
  9900. }
  9901. return true;
  9902. };
  9903. var isValidTextNode = function (node) {
  9904. return isText$7(node) && node.data.length > 0;
  9905. };
  9906. var restoreEndPoint = function (dom, suffix, bookmark) {
  9907. var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev;
  9908. var keep = bookmark.keep;
  9909. var container, offset;
  9910. if (marker) {
  9911. node = marker.parentNode;
  9912. if (suffix === 'start') {
  9913. if (!keep) {
  9914. idx = dom.nodeIndex(marker);
  9915. } else {
  9916. if (marker.hasChildNodes()) {
  9917. node = marker.firstChild;
  9918. idx = 1;
  9919. } else if (isValidTextNode(marker.nextSibling)) {
  9920. node = marker.nextSibling;
  9921. idx = 0;
  9922. } else if (isValidTextNode(marker.previousSibling)) {
  9923. node = marker.previousSibling;
  9924. idx = marker.previousSibling.data.length;
  9925. } else {
  9926. node = marker.parentNode;
  9927. idx = dom.nodeIndex(marker) + 1;
  9928. }
  9929. }
  9930. container = node;
  9931. offset = idx;
  9932. } else {
  9933. if (!keep) {
  9934. idx = dom.nodeIndex(marker);
  9935. } else {
  9936. if (marker.hasChildNodes()) {
  9937. node = marker.firstChild;
  9938. idx = 1;
  9939. } else if (isValidTextNode(marker.previousSibling)) {
  9940. node = marker.previousSibling;
  9941. idx = marker.previousSibling.data.length;
  9942. } else {
  9943. node = marker.parentNode;
  9944. idx = dom.nodeIndex(marker);
  9945. }
  9946. }
  9947. container = node;
  9948. offset = idx;
  9949. }
  9950. if (!keep) {
  9951. prev = marker.previousSibling;
  9952. next = marker.nextSibling;
  9953. Tools.each(Tools.grep(marker.childNodes), function (node) {
  9954. if (isText$7(node)) {
  9955. node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
  9956. }
  9957. });
  9958. while (marker = dom.get(bookmark.id + '_' + suffix)) {
  9959. dom.remove(marker, true);
  9960. }
  9961. if (prev && next && prev.nodeType === next.nodeType && isText$7(prev) && !Env.opera) {
  9962. idx = prev.nodeValue.length;
  9963. prev.appendData(next.nodeValue);
  9964. dom.remove(next);
  9965. container = prev;
  9966. offset = idx;
  9967. }
  9968. }
  9969. return Optional.some(CaretPosition(container, offset));
  9970. } else {
  9971. return Optional.none();
  9972. }
  9973. };
  9974. var resolvePaths = function (dom, bookmark) {
  9975. var rng = dom.createRng();
  9976. if (setEndPoint(dom, true, bookmark, rng) && setEndPoint(dom, false, bookmark, rng)) {
  9977. return Optional.some(rng);
  9978. } else {
  9979. return Optional.none();
  9980. }
  9981. };
  9982. var resolveId = function (dom, bookmark) {
  9983. var startPos = restoreEndPoint(dom, 'start', bookmark);
  9984. var endPos = restoreEndPoint(dom, 'end', bookmark);
  9985. return lift2(startPos, endPos.or(startPos), function (spos, epos) {
  9986. var rng = dom.createRng();
  9987. rng.setStart(addBogus(dom, spos.container()), spos.offset());
  9988. rng.setEnd(addBogus(dom, epos.container()), epos.offset());
  9989. return rng;
  9990. });
  9991. };
  9992. var resolveIndex = function (dom, bookmark) {
  9993. return Optional.from(dom.select(bookmark.name)[bookmark.index]).map(function (elm) {
  9994. var rng = dom.createRng();
  9995. rng.selectNode(elm);
  9996. return rng;
  9997. });
  9998. };
  9999. var resolve$1 = function (selection, bookmark) {
  10000. var dom = selection.dom;
  10001. if (bookmark) {
  10002. if (isPathBookmark(bookmark)) {
  10003. return resolvePaths(dom, bookmark);
  10004. } else if (isStringPathBookmark(bookmark)) {
  10005. return Optional.some(resolveCaretPositionBookmark(dom, bookmark));
  10006. } else if (isIdBookmark(bookmark)) {
  10007. return resolveId(dom, bookmark);
  10008. } else if (isIndexBookmark(bookmark)) {
  10009. return resolveIndex(dom, bookmark);
  10010. } else if (isRangeBookmark(bookmark)) {
  10011. return Optional.some(bookmark.rng);
  10012. }
  10013. }
  10014. return Optional.none();
  10015. };
  10016. var getBookmark$1 = function (selection, type, normalized) {
  10017. return getBookmark$2(selection, type, normalized);
  10018. };
  10019. var moveToBookmark = function (selection, bookmark) {
  10020. resolve$1(selection, bookmark).each(function (rng) {
  10021. selection.setRng(rng);
  10022. });
  10023. };
  10024. var isBookmarkNode$1 = function (node) {
  10025. return isElement$5(node) && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
  10026. };
  10027. var is = function (expected) {
  10028. return function (actual) {
  10029. return expected === actual;
  10030. };
  10031. };
  10032. var isNbsp = is(nbsp);
  10033. var isWhiteSpace = function (chr) {
  10034. return chr !== '' && ' \f\n\r\t\x0B'.indexOf(chr) !== -1;
  10035. };
  10036. var isContent = function (chr) {
  10037. return !isWhiteSpace(chr) && !isNbsp(chr);
  10038. };
  10039. var isNode = function (node) {
  10040. return !!node.nodeType;
  10041. };
  10042. var isInlineBlock = function (node) {
  10043. return node && /^(IMG)$/.test(node.nodeName);
  10044. };
  10045. var moveStart = function (dom, selection, rng) {
  10046. var offset = rng.startOffset;
  10047. var container = rng.startContainer;
  10048. if (container === rng.endContainer) {
  10049. if (isInlineBlock(container.childNodes[offset])) {
  10050. return;
  10051. }
  10052. }
  10053. if (isElement$5(container)) {
  10054. var nodes = container.childNodes;
  10055. var walker = void 0;
  10056. if (offset < nodes.length) {
  10057. container = nodes[offset];
  10058. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10059. } else {
  10060. container = nodes[nodes.length - 1];
  10061. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10062. walker.next(true);
  10063. }
  10064. for (var node = walker.current(); node; node = walker.next()) {
  10065. if (isText$7(node) && !isWhiteSpaceNode$1(node)) {
  10066. rng.setStart(node, 0);
  10067. selection.setRng(rng);
  10068. return;
  10069. }
  10070. }
  10071. }
  10072. };
  10073. var getNonWhiteSpaceSibling = function (node, next, inc) {
  10074. if (node) {
  10075. var nextName = next ? 'nextSibling' : 'previousSibling';
  10076. for (node = inc ? node : node[nextName]; node; node = node[nextName]) {
  10077. if (isElement$5(node) || !isWhiteSpaceNode$1(node)) {
  10078. return node;
  10079. }
  10080. }
  10081. }
  10082. };
  10083. var isTextBlock$1 = function (editor, name) {
  10084. if (isNode(name)) {
  10085. name = name.nodeName;
  10086. }
  10087. return !!editor.schema.getTextBlockElements()[name.toLowerCase()];
  10088. };
  10089. var isValid = function (ed, parent, child) {
  10090. return ed.schema.isValidChild(parent, child);
  10091. };
  10092. var isWhiteSpaceNode$1 = function (node, allowSpaces) {
  10093. if (allowSpaces === void 0) {
  10094. allowSpaces = false;
  10095. }
  10096. if (isNonNullable(node) && isText$7(node)) {
  10097. var data = allowSpaces ? node.data.replace(/ /g, '\xA0') : node.data;
  10098. return isWhitespaceText(data);
  10099. } else {
  10100. return false;
  10101. }
  10102. };
  10103. var isEmptyTextNode$1 = function (node) {
  10104. return isNonNullable(node) && isText$7(node) && node.length === 0;
  10105. };
  10106. var replaceVars = function (value, vars) {
  10107. if (isFunction(value)) {
  10108. value = value(vars);
  10109. } else if (isNonNullable(vars)) {
  10110. value = value.replace(/%(\w+)/g, function (str, name) {
  10111. return vars[name] || str;
  10112. });
  10113. }
  10114. return value;
  10115. };
  10116. var isEq$5 = function (str1, str2) {
  10117. str1 = str1 || '';
  10118. str2 = str2 || '';
  10119. str1 = '' + (str1.nodeName || str1);
  10120. str2 = '' + (str2.nodeName || str2);
  10121. return str1.toLowerCase() === str2.toLowerCase();
  10122. };
  10123. var normalizeStyleValue = function (dom, value, name) {
  10124. if (name === 'color' || name === 'backgroundColor') {
  10125. value = dom.toHex(value);
  10126. }
  10127. if (name === 'fontWeight' && value === 700) {
  10128. value = 'bold';
  10129. }
  10130. if (name === 'fontFamily') {
  10131. value = value.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
  10132. }
  10133. return '' + value;
  10134. };
  10135. var getStyle = function (dom, node, name) {
  10136. return normalizeStyleValue(dom, dom.getStyle(node, name), name);
  10137. };
  10138. var getTextDecoration = function (dom, node) {
  10139. var decoration;
  10140. dom.getParent(node, function (n) {
  10141. decoration = dom.getStyle(n, 'text-decoration');
  10142. return decoration && decoration !== 'none';
  10143. });
  10144. return decoration;
  10145. };
  10146. var getParents$2 = function (dom, node, selector) {
  10147. return dom.getParents(node, selector, dom.getRoot());
  10148. };
  10149. var isVariableFormatName = function (editor, formatName) {
  10150. var hasVariableValues = function (format) {
  10151. var isVariableValue = function (val) {
  10152. return val.length > 1 && val.charAt(0) === '%';
  10153. };
  10154. return exists([
  10155. 'styles',
  10156. 'attributes'
  10157. ], function (key) {
  10158. return get$9(format, key).exists(function (field) {
  10159. var fieldValues = isArray$1(field) ? field : values(field);
  10160. return exists(fieldValues, isVariableValue);
  10161. });
  10162. });
  10163. };
  10164. return exists(editor.formatter.get(formatName), hasVariableValues);
  10165. };
  10166. var areSimilarFormats = function (editor, formatName, otherFormatName) {
  10167. var validKeys = [
  10168. 'inline',
  10169. 'block',
  10170. 'selector',
  10171. 'attributes',
  10172. 'styles',
  10173. 'classes'
  10174. ];
  10175. var filterObj = function (format) {
  10176. return filter$3(format, function (_, key) {
  10177. return exists(validKeys, function (validKey) {
  10178. return validKey === key;
  10179. });
  10180. });
  10181. };
  10182. return exists(editor.formatter.get(formatName), function (fmt1) {
  10183. var filteredFmt1 = filterObj(fmt1);
  10184. return exists(editor.formatter.get(otherFormatName), function (fmt2) {
  10185. var filteredFmt2 = filterObj(fmt2);
  10186. return equal$1(filteredFmt1, filteredFmt2);
  10187. });
  10188. });
  10189. };
  10190. var isBlockFormat = function (format) {
  10191. return hasNonNullableKey(format, 'block');
  10192. };
  10193. var isSelectorFormat = function (format) {
  10194. return hasNonNullableKey(format, 'selector');
  10195. };
  10196. var isInlineFormat = function (format) {
  10197. return hasNonNullableKey(format, 'inline');
  10198. };
  10199. var isMixedFormat = function (format) {
  10200. return isSelectorFormat(format) && isInlineFormat(format) && is$1(get$9(format, 'mixed'), true);
  10201. };
  10202. var shouldExpandToSelector = function (format) {
  10203. return isSelectorFormat(format) && format.expand !== false && !isInlineFormat(format);
  10204. };
  10205. var isBookmarkNode = isBookmarkNode$1;
  10206. var getParents$1 = getParents$2;
  10207. var isWhiteSpaceNode = isWhiteSpaceNode$1;
  10208. var isTextBlock = isTextBlock$1;
  10209. var isBogusBr = function (node) {
  10210. return isBr$5(node) && node.getAttribute('data-mce-bogus') && !node.nextSibling;
  10211. };
  10212. var findParentContentEditable = function (dom, node) {
  10213. var parent = node;
  10214. while (parent) {
  10215. if (isElement$5(parent) && dom.getContentEditable(parent)) {
  10216. return dom.getContentEditable(parent) === 'false' ? parent : node;
  10217. }
  10218. parent = parent.parentNode;
  10219. }
  10220. return node;
  10221. };
  10222. var walkText = function (start, node, offset, predicate) {
  10223. var str = node.data;
  10224. for (var i = offset; start ? i >= 0 : i < str.length; start ? i-- : i++) {
  10225. if (predicate(str.charAt(i))) {
  10226. return start ? i + 1 : i;
  10227. }
  10228. }
  10229. return -1;
  10230. };
  10231. var findSpace = function (start, node, offset) {
  10232. return walkText(start, node, offset, function (c) {
  10233. return isNbsp(c) || isWhiteSpace(c);
  10234. });
  10235. };
  10236. var findContent = function (start, node, offset) {
  10237. return walkText(start, node, offset, isContent);
  10238. };
  10239. var findWordEndPoint = function (dom, body, container, offset, start, includeTrailingSpaces) {
  10240. var lastTextNode;
  10241. var rootNode = dom.getParent(container, dom.isBlock) || body;
  10242. var walk = function (container, offset, pred) {
  10243. var textSeeker = TextSeeker(dom);
  10244. var walker = start ? textSeeker.backwards : textSeeker.forwards;
  10245. return Optional.from(walker(container, offset, function (text, textOffset) {
  10246. if (isBookmarkNode(text.parentNode)) {
  10247. return -1;
  10248. } else {
  10249. lastTextNode = text;
  10250. return pred(start, text, textOffset);
  10251. }
  10252. }, rootNode));
  10253. };
  10254. var spaceResult = walk(container, offset, findSpace);
  10255. return spaceResult.bind(function (result) {
  10256. return includeTrailingSpaces ? walk(result.container, result.offset + (start ? -1 : 0), findContent) : Optional.some(result);
  10257. }).orThunk(function () {
  10258. return lastTextNode ? Optional.some({
  10259. container: lastTextNode,
  10260. offset: start ? 0 : lastTextNode.length
  10261. }) : Optional.none();
  10262. });
  10263. };
  10264. var findSelectorEndPoint = function (dom, formatList, rng, container, siblingName) {
  10265. if (isText$7(container) && isEmpty$3(container.data) && container[siblingName]) {
  10266. container = container[siblingName];
  10267. }
  10268. var parents = getParents$1(dom, container);
  10269. for (var i = 0; i < parents.length; i++) {
  10270. for (var y = 0; y < formatList.length; y++) {
  10271. var curFormat = formatList[y];
  10272. if (isNonNullable(curFormat.collapsed) && curFormat.collapsed !== rng.collapsed) {
  10273. continue;
  10274. }
  10275. if (isSelectorFormat(curFormat) && dom.is(parents[i], curFormat.selector)) {
  10276. return parents[i];
  10277. }
  10278. }
  10279. }
  10280. return container;
  10281. };
  10282. var findBlockEndPoint = function (editor, formatList, container, siblingName) {
  10283. var node = container;
  10284. var dom = editor.dom;
  10285. var root = dom.getRoot();
  10286. var format = formatList[0];
  10287. if (isBlockFormat(format)) {
  10288. node = format.wrapper ? null : dom.getParent(container, format.block, root);
  10289. }
  10290. if (!node) {
  10291. var scopeRoot = dom.getParent(container, 'LI,TD,TH');
  10292. node = dom.getParent(isText$7(container) ? container.parentNode : container, function (node) {
  10293. return node !== root && isTextBlock(editor, node);
  10294. }, scopeRoot);
  10295. }
  10296. if (node && isBlockFormat(format) && format.wrapper) {
  10297. node = getParents$1(dom, node, 'ul,ol').reverse()[0] || node;
  10298. }
  10299. if (!node) {
  10300. node = container;
  10301. while (node[siblingName] && !dom.isBlock(node[siblingName])) {
  10302. node = node[siblingName];
  10303. if (isEq$5(node, 'br')) {
  10304. break;
  10305. }
  10306. }
  10307. }
  10308. return node || container;
  10309. };
  10310. var isAtBlockBoundary$1 = function (dom, root, container, siblingName) {
  10311. var parent = container.parentNode;
  10312. if (isNonNullable(container[siblingName])) {
  10313. return false;
  10314. } else if (parent === root || isNullable(parent) || dom.isBlock(parent)) {
  10315. return true;
  10316. } else {
  10317. return isAtBlockBoundary$1(dom, root, parent, siblingName);
  10318. }
  10319. };
  10320. var findParentContainer = function (dom, formatList, container, offset, start) {
  10321. var parent = container;
  10322. var siblingName = start ? 'previousSibling' : 'nextSibling';
  10323. var root = dom.getRoot();
  10324. if (isText$7(container) && !isWhiteSpaceNode(container)) {
  10325. if (start ? offset > 0 : offset < container.data.length) {
  10326. return container;
  10327. }
  10328. }
  10329. while (true) {
  10330. if (!formatList[0].block_expand && dom.isBlock(parent)) {
  10331. return parent;
  10332. }
  10333. for (var sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
  10334. var allowSpaces = isText$7(sibling) && !isAtBlockBoundary$1(dom, root, sibling, siblingName);
  10335. if (!isBookmarkNode(sibling) && !isBogusBr(sibling) && !isWhiteSpaceNode(sibling, allowSpaces)) {
  10336. return parent;
  10337. }
  10338. }
  10339. if (parent === root || parent.parentNode === root) {
  10340. container = parent;
  10341. break;
  10342. }
  10343. parent = parent.parentNode;
  10344. }
  10345. return container;
  10346. };
  10347. var isSelfOrParentBookmark = function (container) {
  10348. return isBookmarkNode(container.parentNode) || isBookmarkNode(container);
  10349. };
  10350. var expandRng = function (editor, rng, formatList, includeTrailingSpace) {
  10351. if (includeTrailingSpace === void 0) {
  10352. includeTrailingSpace = false;
  10353. }
  10354. var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  10355. var dom = editor.dom;
  10356. var format = formatList[0];
  10357. if (isElement$5(startContainer) && startContainer.hasChildNodes()) {
  10358. startContainer = getNode$1(startContainer, startOffset);
  10359. if (isText$7(startContainer)) {
  10360. startOffset = 0;
  10361. }
  10362. }
  10363. if (isElement$5(endContainer) && endContainer.hasChildNodes()) {
  10364. endContainer = getNode$1(endContainer, rng.collapsed ? endOffset : endOffset - 1);
  10365. if (isText$7(endContainer)) {
  10366. endOffset = endContainer.nodeValue.length;
  10367. }
  10368. }
  10369. startContainer = findParentContentEditable(dom, startContainer);
  10370. endContainer = findParentContentEditable(dom, endContainer);
  10371. if (isSelfOrParentBookmark(startContainer)) {
  10372. startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
  10373. if (rng.collapsed) {
  10374. startContainer = startContainer.previousSibling || startContainer;
  10375. } else {
  10376. startContainer = startContainer.nextSibling || startContainer;
  10377. }
  10378. if (isText$7(startContainer)) {
  10379. startOffset = rng.collapsed ? startContainer.length : 0;
  10380. }
  10381. }
  10382. if (isSelfOrParentBookmark(endContainer)) {
  10383. endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
  10384. if (rng.collapsed) {
  10385. endContainer = endContainer.nextSibling || endContainer;
  10386. } else {
  10387. endContainer = endContainer.previousSibling || endContainer;
  10388. }
  10389. if (isText$7(endContainer)) {
  10390. endOffset = rng.collapsed ? 0 : endContainer.length;
  10391. }
  10392. }
  10393. if (rng.collapsed) {
  10394. var startPoint = findWordEndPoint(dom, editor.getBody(), startContainer, startOffset, true, includeTrailingSpace);
  10395. startPoint.each(function (_a) {
  10396. var container = _a.container, offset = _a.offset;
  10397. startContainer = container;
  10398. startOffset = offset;
  10399. });
  10400. var endPoint = findWordEndPoint(dom, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
  10401. endPoint.each(function (_a) {
  10402. var container = _a.container, offset = _a.offset;
  10403. endContainer = container;
  10404. endOffset = offset;
  10405. });
  10406. }
  10407. if (isInlineFormat(format) || format.block_expand) {
  10408. if (!isInlineFormat(format) || (!isText$7(startContainer) || startOffset === 0)) {
  10409. startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  10410. }
  10411. if (!isInlineFormat(format) || (!isText$7(endContainer) || endOffset === endContainer.nodeValue.length)) {
  10412. endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  10413. }
  10414. }
  10415. if (shouldExpandToSelector(format)) {
  10416. startContainer = findSelectorEndPoint(dom, formatList, rng, startContainer, 'previousSibling');
  10417. endContainer = findSelectorEndPoint(dom, formatList, rng, endContainer, 'nextSibling');
  10418. }
  10419. if (isBlockFormat(format) || isSelectorFormat(format)) {
  10420. startContainer = findBlockEndPoint(editor, formatList, startContainer, 'previousSibling');
  10421. endContainer = findBlockEndPoint(editor, formatList, endContainer, 'nextSibling');
  10422. if (isBlockFormat(format)) {
  10423. if (!dom.isBlock(startContainer)) {
  10424. startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  10425. }
  10426. if (!dom.isBlock(endContainer)) {
  10427. endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  10428. }
  10429. }
  10430. }
  10431. if (isElement$5(startContainer)) {
  10432. startOffset = dom.nodeIndex(startContainer);
  10433. startContainer = startContainer.parentNode;
  10434. }
  10435. if (isElement$5(endContainer)) {
  10436. endOffset = dom.nodeIndex(endContainer) + 1;
  10437. endContainer = endContainer.parentNode;
  10438. }
  10439. return {
  10440. startContainer: startContainer,
  10441. startOffset: startOffset,
  10442. endContainer: endContainer,
  10443. endOffset: endOffset
  10444. };
  10445. };
  10446. var walk$2 = function (dom, rng, callback) {
  10447. var startOffset = rng.startOffset;
  10448. var startContainer = getNode$1(rng.startContainer, startOffset);
  10449. var endOffset = rng.endOffset;
  10450. var endContainer = getNode$1(rng.endContainer, endOffset - 1);
  10451. var exclude = function (nodes) {
  10452. var firstNode = nodes[0];
  10453. if (isText$7(firstNode) && firstNode === startContainer && startOffset >= firstNode.data.length) {
  10454. nodes.splice(0, 1);
  10455. }
  10456. var lastNode = nodes[nodes.length - 1];
  10457. if (endOffset === 0 && nodes.length > 0 && lastNode === endContainer && isText$7(lastNode)) {
  10458. nodes.splice(nodes.length - 1, 1);
  10459. }
  10460. return nodes;
  10461. };
  10462. var collectSiblings = function (node, name, endNode) {
  10463. var siblings = [];
  10464. for (; node && node !== endNode; node = node[name]) {
  10465. siblings.push(node);
  10466. }
  10467. return siblings;
  10468. };
  10469. var findEndPoint = function (node, root) {
  10470. return dom.getParent(node, function (node) {
  10471. return node.parentNode === root;
  10472. }, root);
  10473. };
  10474. var walkBoundary = function (startNode, endNode, next) {
  10475. var siblingName = next ? 'nextSibling' : 'previousSibling';
  10476. for (var node = startNode, parent_1 = node.parentNode; node && node !== endNode; node = parent_1) {
  10477. parent_1 = node.parentNode;
  10478. var siblings_1 = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
  10479. if (siblings_1.length) {
  10480. if (!next) {
  10481. siblings_1.reverse();
  10482. }
  10483. callback(exclude(siblings_1));
  10484. }
  10485. }
  10486. };
  10487. if (startContainer === endContainer) {
  10488. return callback(exclude([startContainer]));
  10489. }
  10490. var ancestor = dom.findCommonAncestor(startContainer, endContainer);
  10491. if (dom.isChildOf(startContainer, endContainer)) {
  10492. return walkBoundary(startContainer, ancestor, true);
  10493. }
  10494. if (dom.isChildOf(endContainer, startContainer)) {
  10495. return walkBoundary(endContainer, ancestor);
  10496. }
  10497. var startPoint = findEndPoint(startContainer, ancestor) || startContainer;
  10498. var endPoint = findEndPoint(endContainer, ancestor) || endContainer;
  10499. walkBoundary(startContainer, startPoint, true);
  10500. var siblings = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint === endContainer ? endPoint.nextSibling : endPoint);
  10501. if (siblings.length) {
  10502. callback(exclude(siblings));
  10503. }
  10504. walkBoundary(endContainer, endPoint);
  10505. };
  10506. var getRanges = function (selection) {
  10507. var ranges = [];
  10508. if (selection) {
  10509. for (var i = 0; i < selection.rangeCount; i++) {
  10510. ranges.push(selection.getRangeAt(i));
  10511. }
  10512. }
  10513. return ranges;
  10514. };
  10515. var getSelectedNodes = function (ranges) {
  10516. return bind(ranges, function (range) {
  10517. var node = getSelectedNode(range);
  10518. return node ? [SugarElement.fromDom(node)] : [];
  10519. });
  10520. };
  10521. var hasMultipleRanges = function (selection) {
  10522. return getRanges(selection).length > 1;
  10523. };
  10524. var getCellsFromRanges = function (ranges) {
  10525. return filter$4(getSelectedNodes(ranges), isTableCell$4);
  10526. };
  10527. var getCellsFromElement = function (elm) {
  10528. return descendants(elm, 'td[data-mce-selected],th[data-mce-selected]');
  10529. };
  10530. var getCellsFromElementOrRanges = function (ranges, element) {
  10531. var selectedCells = getCellsFromElement(element);
  10532. return selectedCells.length > 0 ? selectedCells : getCellsFromRanges(ranges);
  10533. };
  10534. var getCellsFromEditor = function (editor) {
  10535. return getCellsFromElementOrRanges(getRanges(editor.selection.getSel()), SugarElement.fromDom(editor.getBody()));
  10536. };
  10537. var getClosestTable = function (cell, isRoot) {
  10538. return ancestor$2(cell, 'table', isRoot);
  10539. };
  10540. var getStartNode = function (rng) {
  10541. var sc = rng.startContainer, so = rng.startOffset;
  10542. if (isText$7(sc)) {
  10543. return so === 0 ? Optional.some(SugarElement.fromDom(sc)) : Optional.none();
  10544. } else {
  10545. return Optional.from(sc.childNodes[so]).map(SugarElement.fromDom);
  10546. }
  10547. };
  10548. var getEndNode = function (rng) {
  10549. var ec = rng.endContainer, eo = rng.endOffset;
  10550. if (isText$7(ec)) {
  10551. return eo === ec.data.length ? Optional.some(SugarElement.fromDom(ec)) : Optional.none();
  10552. } else {
  10553. return Optional.from(ec.childNodes[eo - 1]).map(SugarElement.fromDom);
  10554. }
  10555. };
  10556. var getFirstChildren = function (node) {
  10557. return firstChild(node).fold(constant([node]), function (child) {
  10558. return [node].concat(getFirstChildren(child));
  10559. });
  10560. };
  10561. var getLastChildren$1 = function (node) {
  10562. return lastChild(node).fold(constant([node]), function (child) {
  10563. if (name(child) === 'br') {
  10564. return prevSibling(child).map(function (sibling) {
  10565. return [node].concat(getLastChildren$1(sibling));
  10566. }).getOr([]);
  10567. } else {
  10568. return [node].concat(getLastChildren$1(child));
  10569. }
  10570. });
  10571. };
  10572. var hasAllContentsSelected = function (elm, rng) {
  10573. return lift2(getStartNode(rng), getEndNode(rng), function (startNode, endNode) {
  10574. var start = find$3(getFirstChildren(elm), curry(eq, startNode));
  10575. var end = find$3(getLastChildren$1(elm), curry(eq, endNode));
  10576. return start.isSome() && end.isSome();
  10577. }).getOr(false);
  10578. };
  10579. var moveEndPoint = function (dom, rng, node, start) {
  10580. var root = node, walker = new DomTreeWalker(node, root);
  10581. var moveCaretBeforeOnEnterElementsMap = filter$3(dom.schema.getMoveCaretBeforeOnEnterElements(), function (_, name) {
  10582. return !contains$3([
  10583. 'td',
  10584. 'th',
  10585. 'table'
  10586. ], name.toLowerCase());
  10587. });
  10588. do {
  10589. if (isText$7(node) && Tools.trim(node.nodeValue).length !== 0) {
  10590. if (start) {
  10591. rng.setStart(node, 0);
  10592. } else {
  10593. rng.setEnd(node, node.nodeValue.length);
  10594. }
  10595. return;
  10596. }
  10597. if (moveCaretBeforeOnEnterElementsMap[node.nodeName]) {
  10598. if (start) {
  10599. rng.setStartBefore(node);
  10600. } else {
  10601. if (node.nodeName === 'BR') {
  10602. rng.setEndBefore(node);
  10603. } else {
  10604. rng.setEndAfter(node);
  10605. }
  10606. }
  10607. return;
  10608. }
  10609. } while (node = start ? walker.next() : walker.prev());
  10610. if (root.nodeName === 'BODY') {
  10611. if (start) {
  10612. rng.setStart(root, 0);
  10613. } else {
  10614. rng.setEnd(root, root.childNodes.length);
  10615. }
  10616. }
  10617. };
  10618. var hasAnyRanges = function (editor) {
  10619. var sel = editor.selection.getSel();
  10620. return sel && sel.rangeCount > 0;
  10621. };
  10622. var runOnRanges = function (editor, executor) {
  10623. var fakeSelectionNodes = getCellsFromEditor(editor);
  10624. if (fakeSelectionNodes.length > 0) {
  10625. each$k(fakeSelectionNodes, function (elem) {
  10626. var node = elem.dom;
  10627. var fakeNodeRng = editor.dom.createRng();
  10628. fakeNodeRng.setStartBefore(node);
  10629. fakeNodeRng.setEndAfter(node);
  10630. executor(fakeNodeRng, true);
  10631. });
  10632. } else {
  10633. executor(editor.selection.getRng(), false);
  10634. }
  10635. };
  10636. var preserve = function (selection, fillBookmark, executor) {
  10637. var bookmark = getPersistentBookmark(selection, fillBookmark);
  10638. executor(bookmark);
  10639. selection.moveToBookmark(bookmark);
  10640. };
  10641. var NodeValue = function (is, name) {
  10642. var get = function (element) {
  10643. if (!is(element)) {
  10644. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  10645. }
  10646. return getOption(element).getOr('');
  10647. };
  10648. var getOption = function (element) {
  10649. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  10650. };
  10651. var set = function (element, value) {
  10652. if (!is(element)) {
  10653. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  10654. }
  10655. element.dom.nodeValue = value;
  10656. };
  10657. return {
  10658. get: get,
  10659. getOption: getOption,
  10660. set: set
  10661. };
  10662. };
  10663. var api$1 = NodeValue(isText$8, 'text');
  10664. var get$2 = function (element) {
  10665. return api$1.get(element);
  10666. };
  10667. var isZeroWidth = function (elem) {
  10668. return isText$8(elem) && get$2(elem) === ZWSP$1;
  10669. };
  10670. var context = function (editor, elem, wrapName, nodeName) {
  10671. return parent(elem).fold(function () {
  10672. return 'skipping';
  10673. }, function (parent) {
  10674. if (nodeName === 'br' || isZeroWidth(elem)) {
  10675. return 'valid';
  10676. } else if (isAnnotation(elem)) {
  10677. return 'existing';
  10678. } else if (isCaretNode(elem.dom)) {
  10679. return 'caret';
  10680. } else if (!isValid(editor, wrapName, nodeName) || !isValid(editor, name(parent), wrapName)) {
  10681. return 'invalid-child';
  10682. } else {
  10683. return 'valid';
  10684. }
  10685. });
  10686. };
  10687. var applyWordGrab = function (editor, rng) {
  10688. var r = expandRng(editor, rng, [{ inline: 'span' }]);
  10689. rng.setStart(r.startContainer, r.startOffset);
  10690. rng.setEnd(r.endContainer, r.endOffset);
  10691. editor.selection.setRng(rng);
  10692. };
  10693. var makeAnnotation = function (eDoc, _a, annotationName, decorate) {
  10694. var _b = _a.uid, uid = _b === void 0 ? generate('mce-annotation') : _b, data = __rest(_a, ['uid']);
  10695. var master = SugarElement.fromTag('span', eDoc);
  10696. add$1(master, annotation());
  10697. set$1(master, '' + dataAnnotationId(), uid);
  10698. set$1(master, '' + dataAnnotation(), annotationName);
  10699. var _c = decorate(uid, data), _d = _c.attributes, attributes = _d === void 0 ? {} : _d, _e = _c.classes, classes = _e === void 0 ? [] : _e;
  10700. setAll$1(master, attributes);
  10701. add(master, classes);
  10702. return master;
  10703. };
  10704. var annotate = function (editor, rng, annotationName, decorate, data) {
  10705. var newWrappers = [];
  10706. var master = makeAnnotation(editor.getDoc(), data, annotationName, decorate);
  10707. var wrapper = value();
  10708. var finishWrapper = function () {
  10709. wrapper.clear();
  10710. };
  10711. var getOrOpenWrapper = function () {
  10712. return wrapper.get().getOrThunk(function () {
  10713. var nu = shallow(master);
  10714. newWrappers.push(nu);
  10715. wrapper.set(nu);
  10716. return nu;
  10717. });
  10718. };
  10719. var processElements = function (elems) {
  10720. each$k(elems, processElement);
  10721. };
  10722. var processElement = function (elem) {
  10723. var ctx = context(editor, elem, 'span', name(elem));
  10724. switch (ctx) {
  10725. case 'invalid-child': {
  10726. finishWrapper();
  10727. var children$1 = children(elem);
  10728. processElements(children$1);
  10729. finishWrapper();
  10730. break;
  10731. }
  10732. case 'valid': {
  10733. var w = getOrOpenWrapper();
  10734. wrap$3(elem, w);
  10735. break;
  10736. }
  10737. }
  10738. };
  10739. var processNodes = function (nodes) {
  10740. var elems = map$3(nodes, SugarElement.fromDom);
  10741. processElements(elems);
  10742. };
  10743. walk$2(editor.dom, rng, function (nodes) {
  10744. finishWrapper();
  10745. processNodes(nodes);
  10746. });
  10747. return newWrappers;
  10748. };
  10749. var annotateWithBookmark = function (editor, name, settings, data) {
  10750. editor.undoManager.transact(function () {
  10751. var selection = editor.selection;
  10752. var initialRng = selection.getRng();
  10753. var hasFakeSelection = getCellsFromEditor(editor).length > 0;
  10754. if (initialRng.collapsed && !hasFakeSelection) {
  10755. applyWordGrab(editor, initialRng);
  10756. }
  10757. if (selection.getRng().collapsed && !hasFakeSelection) {
  10758. var wrapper = makeAnnotation(editor.getDoc(), data, name, settings.decorate);
  10759. set(wrapper, nbsp);
  10760. selection.getRng().insertNode(wrapper.dom);
  10761. selection.select(wrapper.dom);
  10762. } else {
  10763. preserve(selection, false, function () {
  10764. runOnRanges(editor, function (selectionRng) {
  10765. annotate(editor, selectionRng, name, settings.decorate, data);
  10766. });
  10767. });
  10768. }
  10769. });
  10770. };
  10771. var Annotator = function (editor) {
  10772. var registry = create$7();
  10773. setup$m(editor, registry);
  10774. var changes = setup$n(editor);
  10775. return {
  10776. register: function (name, settings) {
  10777. registry.register(name, settings);
  10778. },
  10779. annotate: function (name, data) {
  10780. registry.lookup(name).each(function (settings) {
  10781. annotateWithBookmark(editor, name, settings, data);
  10782. });
  10783. },
  10784. annotationChanged: function (name, callback) {
  10785. changes.addListener(name, callback);
  10786. },
  10787. remove: function (name) {
  10788. identify(editor, Optional.some(name)).each(function (_a) {
  10789. var elements = _a.elements;
  10790. each$k(elements, unwrap);
  10791. });
  10792. },
  10793. getAll: function (name) {
  10794. var directory = findAll(editor, name);
  10795. return map$2(directory, function (elems) {
  10796. return map$3(elems, function (elem) {
  10797. return elem.dom;
  10798. });
  10799. });
  10800. }
  10801. };
  10802. };
  10803. var BookmarkManager = function (selection) {
  10804. return {
  10805. getBookmark: curry(getBookmark$1, selection),
  10806. moveToBookmark: curry(moveToBookmark, selection)
  10807. };
  10808. };
  10809. BookmarkManager.isBookmarkNode = isBookmarkNode$1;
  10810. var getContentEditableRoot$1 = function (root, node) {
  10811. while (node && node !== root) {
  10812. if (isContentEditableTrue$4(node) || isContentEditableFalse$b(node)) {
  10813. return node;
  10814. }
  10815. node = node.parentNode;
  10816. }
  10817. return null;
  10818. };
  10819. var isXYWithinRange = function (clientX, clientY, range) {
  10820. if (range.collapsed) {
  10821. return false;
  10822. }
  10823. if (Env.browser.isIE() && range.startOffset === range.endOffset - 1 && range.startContainer === range.endContainer) {
  10824. var elm = range.startContainer.childNodes[range.startOffset];
  10825. if (isElement$5(elm)) {
  10826. return exists(elm.getClientRects(), function (rect) {
  10827. return containsXY(rect, clientX, clientY);
  10828. });
  10829. }
  10830. }
  10831. return exists(range.getClientRects(), function (rect) {
  10832. return containsXY(rect, clientX, clientY);
  10833. });
  10834. };
  10835. var firePreProcess = function (editor, args) {
  10836. return editor.fire('PreProcess', args);
  10837. };
  10838. var firePostProcess = function (editor, args) {
  10839. return editor.fire('PostProcess', args);
  10840. };
  10841. var fireRemove = function (editor) {
  10842. return editor.fire('remove');
  10843. };
  10844. var fireDetach = function (editor) {
  10845. return editor.fire('detach');
  10846. };
  10847. var fireSwitchMode = function (editor, mode) {
  10848. return editor.fire('SwitchMode', { mode: mode });
  10849. };
  10850. var fireObjectResizeStart = function (editor, target, width, height, origin) {
  10851. editor.fire('ObjectResizeStart', {
  10852. target: target,
  10853. width: width,
  10854. height: height,
  10855. origin: origin
  10856. });
  10857. };
  10858. var fireObjectResized = function (editor, target, width, height, origin) {
  10859. editor.fire('ObjectResized', {
  10860. target: target,
  10861. width: width,
  10862. height: height,
  10863. origin: origin
  10864. });
  10865. };
  10866. var firePreInit = function (editor) {
  10867. return editor.fire('PreInit');
  10868. };
  10869. var firePostRender = function (editor) {
  10870. return editor.fire('PostRender');
  10871. };
  10872. var fireInit = function (editor) {
  10873. return editor.fire('Init');
  10874. };
  10875. var firePlaceholderToggle = function (editor, state) {
  10876. return editor.fire('PlaceholderToggle', { state: state });
  10877. };
  10878. var fireError = function (editor, errorType, error) {
  10879. return editor.fire(errorType, error);
  10880. };
  10881. var fireFormatApply = function (editor, format, node, vars) {
  10882. return editor.fire('FormatApply', {
  10883. format: format,
  10884. node: node,
  10885. vars: vars
  10886. });
  10887. };
  10888. var fireFormatRemove = function (editor, format, node, vars) {
  10889. return editor.fire('FormatRemove', {
  10890. format: format,
  10891. node: node,
  10892. vars: vars
  10893. });
  10894. };
  10895. var VK = {
  10896. BACKSPACE: 8,
  10897. DELETE: 46,
  10898. DOWN: 40,
  10899. ENTER: 13,
  10900. ESC: 27,
  10901. LEFT: 37,
  10902. RIGHT: 39,
  10903. SPACEBAR: 32,
  10904. TAB: 9,
  10905. UP: 38,
  10906. PAGE_UP: 33,
  10907. PAGE_DOWN: 34,
  10908. END: 35,
  10909. HOME: 36,
  10910. modifierPressed: function (e) {
  10911. return e.shiftKey || e.ctrlKey || e.altKey || VK.metaKeyPressed(e);
  10912. },
  10913. metaKeyPressed: function (e) {
  10914. return Env.mac ? e.metaKey : e.ctrlKey && !e.altKey;
  10915. }
  10916. };
  10917. var isContentEditableFalse$5 = isContentEditableFalse$b;
  10918. var ControlSelection = function (selection, editor) {
  10919. var elementSelectionAttr = 'data-mce-selected';
  10920. var dom = editor.dom, each = Tools.each;
  10921. var selectedElm, selectedElmGhost, resizeHelper, selectedHandle, resizeBackdrop;
  10922. var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
  10923. var width, height;
  10924. var editableDoc = editor.getDoc(), rootDocument = document;
  10925. var abs = Math.abs, round = Math.round, rootElement = editor.getBody();
  10926. var startScrollWidth, startScrollHeight;
  10927. var resizeHandles = {
  10928. nw: [
  10929. 0,
  10930. 0,
  10931. -1,
  10932. -1
  10933. ],
  10934. ne: [
  10935. 1,
  10936. 0,
  10937. 1,
  10938. -1
  10939. ],
  10940. se: [
  10941. 1,
  10942. 1,
  10943. 1,
  10944. 1
  10945. ],
  10946. sw: [
  10947. 0,
  10948. 1,
  10949. -1,
  10950. 1
  10951. ]
  10952. };
  10953. var isImage = function (elm) {
  10954. return elm && (elm.nodeName === 'IMG' || editor.dom.is(elm, 'figure.image'));
  10955. };
  10956. var isMedia = function (elm) {
  10957. return isMedia$2(elm) || dom.hasClass(elm, 'mce-preview-object');
  10958. };
  10959. var isEventOnImageOutsideRange = function (evt, range) {
  10960. if (evt.type === 'longpress' || evt.type.indexOf('touch') === 0) {
  10961. var touch = evt.touches[0];
  10962. return isImage(evt.target) && !isXYWithinRange(touch.clientX, touch.clientY, range);
  10963. } else {
  10964. return isImage(evt.target) && !isXYWithinRange(evt.clientX, evt.clientY, range);
  10965. }
  10966. };
  10967. var contextMenuSelectImage = function (evt) {
  10968. var target = evt.target;
  10969. if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) && !evt.isDefaultPrevented()) {
  10970. editor.selection.select(target);
  10971. }
  10972. };
  10973. var getResizeTargets = function (elm) {
  10974. if (dom.is(elm, 'figure.image')) {
  10975. return [elm.querySelector('img')];
  10976. } else if (dom.hasClass(elm, 'mce-preview-object') && isNonNullable(elm.firstElementChild)) {
  10977. return [
  10978. elm,
  10979. elm.firstElementChild
  10980. ];
  10981. } else {
  10982. return [elm];
  10983. }
  10984. };
  10985. var isResizable = function (elm) {
  10986. var selector = getObjectResizing(editor);
  10987. if (!selector) {
  10988. return false;
  10989. }
  10990. if (elm.getAttribute('data-mce-resize') === 'false') {
  10991. return false;
  10992. }
  10993. if (elm === editor.getBody()) {
  10994. return false;
  10995. }
  10996. if (dom.hasClass(elm, 'mce-preview-object')) {
  10997. return is$2(SugarElement.fromDom(elm.firstElementChild), selector);
  10998. } else {
  10999. return is$2(SugarElement.fromDom(elm), selector);
  11000. }
  11001. };
  11002. var createGhostElement = function (elm) {
  11003. if (isMedia(elm)) {
  11004. return dom.create('img', { src: Env.transparentSrc });
  11005. } else {
  11006. return elm.cloneNode(true);
  11007. }
  11008. };
  11009. var setSizeProp = function (element, name, value) {
  11010. if (isNonNullable(value)) {
  11011. var targets = getResizeTargets(element);
  11012. each$k(targets, function (target) {
  11013. if (target.style[name] || !editor.schema.isValid(target.nodeName.toLowerCase(), name)) {
  11014. dom.setStyle(target, name, value);
  11015. } else {
  11016. dom.setAttrib(target, name, '' + value);
  11017. }
  11018. });
  11019. }
  11020. };
  11021. var setGhostElmSize = function (ghostElm, width, height) {
  11022. setSizeProp(ghostElm, 'width', width);
  11023. setSizeProp(ghostElm, 'height', height);
  11024. };
  11025. var resizeGhostElement = function (e) {
  11026. var deltaX, deltaY, proportional;
  11027. var resizeHelperX, resizeHelperY;
  11028. deltaX = e.screenX - startX;
  11029. deltaY = e.screenY - startY;
  11030. width = deltaX * selectedHandle[2] + startW;
  11031. height = deltaY * selectedHandle[3] + startH;
  11032. width = width < 5 ? 5 : width;
  11033. height = height < 5 ? 5 : height;
  11034. if ((isImage(selectedElm) || isMedia(selectedElm)) && getResizeImgProportional(editor) !== false) {
  11035. proportional = !VK.modifierPressed(e);
  11036. } else {
  11037. proportional = VK.modifierPressed(e);
  11038. }
  11039. if (proportional) {
  11040. if (abs(deltaX) > abs(deltaY)) {
  11041. height = round(width * ratio);
  11042. width = round(height / ratio);
  11043. } else {
  11044. width = round(height / ratio);
  11045. height = round(width * ratio);
  11046. }
  11047. }
  11048. setGhostElmSize(selectedElmGhost, width, height);
  11049. resizeHelperX = selectedHandle.startPos.x + deltaX;
  11050. resizeHelperY = selectedHandle.startPos.y + deltaY;
  11051. resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
  11052. resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
  11053. dom.setStyles(resizeHelper, {
  11054. left: resizeHelperX,
  11055. top: resizeHelperY,
  11056. display: 'block'
  11057. });
  11058. resizeHelper.innerHTML = width + ' &times; ' + height;
  11059. if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
  11060. dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
  11061. }
  11062. if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
  11063. dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
  11064. }
  11065. deltaX = rootElement.scrollWidth - startScrollWidth;
  11066. deltaY = rootElement.scrollHeight - startScrollHeight;
  11067. if (deltaX + deltaY !== 0) {
  11068. dom.setStyles(resizeHelper, {
  11069. left: resizeHelperX - deltaX,
  11070. top: resizeHelperY - deltaY
  11071. });
  11072. }
  11073. if (!resizeStarted) {
  11074. fireObjectResizeStart(editor, selectedElm, startW, startH, 'corner-' + selectedHandle.name);
  11075. resizeStarted = true;
  11076. }
  11077. };
  11078. var endGhostResize = function () {
  11079. var wasResizeStarted = resizeStarted;
  11080. resizeStarted = false;
  11081. if (wasResizeStarted) {
  11082. setSizeProp(selectedElm, 'width', width);
  11083. setSizeProp(selectedElm, 'height', height);
  11084. }
  11085. dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
  11086. dom.unbind(editableDoc, 'mouseup', endGhostResize);
  11087. if (rootDocument !== editableDoc) {
  11088. dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
  11089. dom.unbind(rootDocument, 'mouseup', endGhostResize);
  11090. }
  11091. dom.remove(selectedElmGhost);
  11092. dom.remove(resizeHelper);
  11093. dom.remove(resizeBackdrop);
  11094. showResizeRect(selectedElm);
  11095. if (wasResizeStarted) {
  11096. fireObjectResized(editor, selectedElm, width, height, 'corner-' + selectedHandle.name);
  11097. dom.setAttrib(selectedElm, 'style', dom.getAttrib(selectedElm, 'style'));
  11098. }
  11099. editor.nodeChanged();
  11100. };
  11101. var showResizeRect = function (targetElm) {
  11102. unbindResizeHandleEvents();
  11103. var position = dom.getPos(targetElm, rootElement);
  11104. var selectedElmX = position.x;
  11105. var selectedElmY = position.y;
  11106. var rect = targetElm.getBoundingClientRect();
  11107. var targetWidth = rect.width || rect.right - rect.left;
  11108. var targetHeight = rect.height || rect.bottom - rect.top;
  11109. if (selectedElm !== targetElm) {
  11110. hideResizeRect();
  11111. selectedElm = targetElm;
  11112. width = height = 0;
  11113. }
  11114. var e = editor.fire('ObjectSelected', { target: targetElm });
  11115. var selectedValue = dom.getAttrib(selectedElm, elementSelectionAttr, '1');
  11116. if (isResizable(targetElm) && !e.isDefaultPrevented()) {
  11117. each(resizeHandles, function (handle, name) {
  11118. var handleElm;
  11119. var startDrag = function (e) {
  11120. var target = getResizeTargets(selectedElm)[0];
  11121. startX = e.screenX;
  11122. startY = e.screenY;
  11123. startW = target.clientWidth;
  11124. startH = target.clientHeight;
  11125. ratio = startH / startW;
  11126. selectedHandle = handle;
  11127. selectedHandle.name = name;
  11128. selectedHandle.startPos = {
  11129. x: targetWidth * handle[0] + selectedElmX,
  11130. y: targetHeight * handle[1] + selectedElmY
  11131. };
  11132. startScrollWidth = rootElement.scrollWidth;
  11133. startScrollHeight = rootElement.scrollHeight;
  11134. resizeBackdrop = dom.add(rootElement, 'div', {
  11135. 'class': 'mce-resize-backdrop',
  11136. 'data-mce-bogus': 'all'
  11137. });
  11138. dom.setStyles(resizeBackdrop, {
  11139. position: 'fixed',
  11140. left: '0',
  11141. top: '0',
  11142. width: '100%',
  11143. height: '100%'
  11144. });
  11145. selectedElmGhost = createGhostElement(selectedElm);
  11146. dom.addClass(selectedElmGhost, 'mce-clonedresizable');
  11147. dom.setAttrib(selectedElmGhost, 'data-mce-bogus', 'all');
  11148. selectedElmGhost.contentEditable = 'false';
  11149. dom.setStyles(selectedElmGhost, {
  11150. left: selectedElmX,
  11151. top: selectedElmY,
  11152. margin: 0
  11153. });
  11154. setGhostElmSize(selectedElmGhost, targetWidth, targetHeight);
  11155. selectedElmGhost.removeAttribute(elementSelectionAttr);
  11156. rootElement.appendChild(selectedElmGhost);
  11157. dom.bind(editableDoc, 'mousemove', resizeGhostElement);
  11158. dom.bind(editableDoc, 'mouseup', endGhostResize);
  11159. if (rootDocument !== editableDoc) {
  11160. dom.bind(rootDocument, 'mousemove', resizeGhostElement);
  11161. dom.bind(rootDocument, 'mouseup', endGhostResize);
  11162. }
  11163. resizeHelper = dom.add(rootElement, 'div', {
  11164. 'class': 'mce-resize-helper',
  11165. 'data-mce-bogus': 'all'
  11166. }, startW + ' &times; ' + startH);
  11167. };
  11168. handleElm = dom.get('mceResizeHandle' + name);
  11169. if (handleElm) {
  11170. dom.remove(handleElm);
  11171. }
  11172. handleElm = dom.add(rootElement, 'div', {
  11173. 'id': 'mceResizeHandle' + name,
  11174. 'data-mce-bogus': 'all',
  11175. 'class': 'mce-resizehandle',
  11176. 'unselectable': true,
  11177. 'style': 'cursor:' + name + '-resize; margin:0; padding:0'
  11178. });
  11179. if (Env.ie === 11) {
  11180. handleElm.contentEditable = false;
  11181. }
  11182. dom.bind(handleElm, 'mousedown', function (e) {
  11183. e.stopImmediatePropagation();
  11184. e.preventDefault();
  11185. startDrag(e);
  11186. });
  11187. handle.elm = handleElm;
  11188. dom.setStyles(handleElm, {
  11189. left: targetWidth * handle[0] + selectedElmX - handleElm.offsetWidth / 2,
  11190. top: targetHeight * handle[1] + selectedElmY - handleElm.offsetHeight / 2
  11191. });
  11192. });
  11193. } else {
  11194. hideResizeRect();
  11195. }
  11196. if (!dom.getAttrib(selectedElm, elementSelectionAttr)) {
  11197. selectedElm.setAttribute(elementSelectionAttr, selectedValue);
  11198. }
  11199. };
  11200. var hideResizeRect = function () {
  11201. unbindResizeHandleEvents();
  11202. if (selectedElm) {
  11203. selectedElm.removeAttribute(elementSelectionAttr);
  11204. }
  11205. each$j(resizeHandles, function (value, name) {
  11206. var handleElm = dom.get('mceResizeHandle' + name);
  11207. if (handleElm) {
  11208. dom.unbind(handleElm);
  11209. dom.remove(handleElm);
  11210. }
  11211. });
  11212. };
  11213. var updateResizeRect = function (e) {
  11214. var startElm, controlElm;
  11215. var isChildOrEqual = function (node, parent) {
  11216. if (node) {
  11217. do {
  11218. if (node === parent) {
  11219. return true;
  11220. }
  11221. } while (node = node.parentNode);
  11222. }
  11223. };
  11224. if (resizeStarted || editor.removed) {
  11225. return;
  11226. }
  11227. each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function (img) {
  11228. img.removeAttribute(elementSelectionAttr);
  11229. });
  11230. controlElm = e.type === 'mousedown' ? e.target : selection.getNode();
  11231. controlElm = dom.$(controlElm).closest('table,img,figure.image,hr,video,span.mce-preview-object')[0];
  11232. if (isChildOrEqual(controlElm, rootElement)) {
  11233. disableGeckoResize();
  11234. startElm = selection.getStart(true);
  11235. if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
  11236. showResizeRect(controlElm);
  11237. return;
  11238. }
  11239. }
  11240. hideResizeRect();
  11241. };
  11242. var isWithinContentEditableFalse = function (elm) {
  11243. return isContentEditableFalse$5(getContentEditableRoot$1(editor.getBody(), elm));
  11244. };
  11245. var unbindResizeHandleEvents = function () {
  11246. each$j(resizeHandles, function (handle) {
  11247. if (handle.elm) {
  11248. dom.unbind(handle.elm);
  11249. delete handle.elm;
  11250. }
  11251. });
  11252. };
  11253. var disableGeckoResize = function () {
  11254. try {
  11255. editor.getDoc().execCommand('enableObjectResizing', false, 'false');
  11256. } catch (ex) {
  11257. }
  11258. };
  11259. editor.on('init', function () {
  11260. disableGeckoResize();
  11261. if (Env.browser.isIE() || Env.browser.isEdge()) {
  11262. editor.on('mousedown click', function (e) {
  11263. var target = e.target, nodeName = target.nodeName;
  11264. if (!resizeStarted && /^(TABLE|IMG|HR)$/.test(nodeName) && !isWithinContentEditableFalse(target)) {
  11265. if (e.button !== 2) {
  11266. editor.selection.select(target, nodeName === 'TABLE');
  11267. }
  11268. if (e.type === 'mousedown') {
  11269. editor.nodeChanged();
  11270. }
  11271. }
  11272. });
  11273. var handleMSControlSelect_1 = function (e) {
  11274. var delayedSelect = function (node) {
  11275. Delay.setEditorTimeout(editor, function () {
  11276. return editor.selection.select(node);
  11277. });
  11278. };
  11279. if (isWithinContentEditableFalse(e.target) || isMedia$2(e.target)) {
  11280. e.preventDefault();
  11281. delayedSelect(e.target);
  11282. return;
  11283. }
  11284. if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) {
  11285. e.preventDefault();
  11286. if (e.target.tagName === 'IMG') {
  11287. delayedSelect(e.target);
  11288. }
  11289. }
  11290. };
  11291. dom.bind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11292. editor.on('remove', function () {
  11293. return dom.unbind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11294. });
  11295. }
  11296. var throttledUpdateResizeRect = Delay.throttle(function (e) {
  11297. if (!editor.composing) {
  11298. updateResizeRect(e);
  11299. }
  11300. });
  11301. editor.on('nodechange ResizeEditor ResizeWindow ResizeContent drop FullscreenStateChanged', throttledUpdateResizeRect);
  11302. editor.on('keyup compositionend', function (e) {
  11303. if (selectedElm && selectedElm.nodeName === 'TABLE') {
  11304. throttledUpdateResizeRect(e);
  11305. }
  11306. });
  11307. editor.on('hide blur', hideResizeRect);
  11308. editor.on('contextmenu longpress', contextMenuSelectImage, true);
  11309. });
  11310. editor.on('remove', unbindResizeHandleEvents);
  11311. var destroy = function () {
  11312. selectedElm = selectedElmGhost = resizeBackdrop = null;
  11313. };
  11314. return {
  11315. isResizable: isResizable,
  11316. showResizeRect: showResizeRect,
  11317. hideResizeRect: hideResizeRect,
  11318. updateResizeRect: updateResizeRect,
  11319. destroy: destroy
  11320. };
  11321. };
  11322. var hasCeProperty = function (node) {
  11323. return isContentEditableTrue$4(node) || isContentEditableFalse$b(node);
  11324. };
  11325. var findParent$1 = function (node, rootNode, predicate) {
  11326. while (node && node !== rootNode) {
  11327. if (predicate(node)) {
  11328. return node;
  11329. }
  11330. node = node.parentNode;
  11331. }
  11332. return null;
  11333. };
  11334. var findClosestIeRange = function (clientX, clientY, doc) {
  11335. var rects;
  11336. var element = doc.elementFromPoint(clientX, clientY);
  11337. var rng = doc.body.createTextRange();
  11338. if (!element || element.tagName === 'HTML') {
  11339. element = doc.body;
  11340. }
  11341. rng.moveToElementText(element);
  11342. rects = Tools.toArray(rng.getClientRects());
  11343. rects = rects.sort(function (a, b) {
  11344. a = Math.abs(Math.max(a.top - clientY, a.bottom - clientY));
  11345. b = Math.abs(Math.max(b.top - clientY, b.bottom - clientY));
  11346. return a - b;
  11347. });
  11348. if (rects.length > 0) {
  11349. clientY = (rects[0].bottom + rects[0].top) / 2;
  11350. try {
  11351. rng.moveToPoint(clientX, clientY);
  11352. rng.collapse(true);
  11353. return rng;
  11354. } catch (ex) {
  11355. }
  11356. }
  11357. return null;
  11358. };
  11359. var moveOutOfContentEditableFalse = function (rng, rootNode) {
  11360. var parentElement = rng && rng.parentElement ? rng.parentElement() : null;
  11361. return isContentEditableFalse$b(findParent$1(parentElement, rootNode, hasCeProperty)) ? null : rng;
  11362. };
  11363. var fromPoint = function (clientX, clientY, doc) {
  11364. var rng, point;
  11365. var pointDoc = doc;
  11366. if (pointDoc.caretPositionFromPoint) {
  11367. point = pointDoc.caretPositionFromPoint(clientX, clientY);
  11368. if (point) {
  11369. rng = doc.createRange();
  11370. rng.setStart(point.offsetNode, point.offset);
  11371. rng.collapse(true);
  11372. }
  11373. } else if (pointDoc.caretRangeFromPoint) {
  11374. rng = pointDoc.caretRangeFromPoint(clientX, clientY);
  11375. } else if (pointDoc.body.createTextRange) {
  11376. rng = pointDoc.body.createTextRange();
  11377. try {
  11378. rng.moveToPoint(clientX, clientY);
  11379. rng.collapse(true);
  11380. } catch (ex) {
  11381. rng = findClosestIeRange(clientX, clientY, doc);
  11382. }
  11383. return moveOutOfContentEditableFalse(rng, doc.body);
  11384. }
  11385. return rng;
  11386. };
  11387. var isEq$4 = function (rng1, rng2) {
  11388. return rng1 && rng2 && (rng1.startContainer === rng2.startContainer && rng1.startOffset === rng2.startOffset) && (rng1.endContainer === rng2.endContainer && rng1.endOffset === rng2.endOffset);
  11389. };
  11390. var findParent = function (node, rootNode, predicate) {
  11391. while (node && node !== rootNode) {
  11392. if (predicate(node)) {
  11393. return node;
  11394. }
  11395. node = node.parentNode;
  11396. }
  11397. return null;
  11398. };
  11399. var hasParent$1 = function (node, rootNode, predicate) {
  11400. return findParent(node, rootNode, predicate) !== null;
  11401. };
  11402. var hasParentWithName = function (node, rootNode, name) {
  11403. return hasParent$1(node, rootNode, function (node) {
  11404. return node.nodeName === name;
  11405. });
  11406. };
  11407. var isTable = function (node) {
  11408. return node && node.nodeName === 'TABLE';
  11409. };
  11410. var isTableCell$2 = function (node) {
  11411. return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  11412. };
  11413. var isCeFalseCaretContainer = function (node, rootNode) {
  11414. return isCaretContainer$2(node) && hasParent$1(node, rootNode, isCaretNode) === false;
  11415. };
  11416. var hasBrBeforeAfter = function (dom, node, left) {
  11417. var walker = new DomTreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || dom.getRoot());
  11418. while (node = walker[left ? 'prev' : 'next']()) {
  11419. if (isBr$5(node)) {
  11420. return true;
  11421. }
  11422. }
  11423. };
  11424. var isPrevNode = function (node, name) {
  11425. return node.previousSibling && node.previousSibling.nodeName === name;
  11426. };
  11427. var hasContentEditableFalseParent = function (body, node) {
  11428. while (node && node !== body) {
  11429. if (isContentEditableFalse$b(node)) {
  11430. return true;
  11431. }
  11432. node = node.parentNode;
  11433. }
  11434. return false;
  11435. };
  11436. var findTextNodeRelative = function (dom, isAfterNode, collapsed, left, startNode) {
  11437. var lastInlineElement;
  11438. var body = dom.getRoot();
  11439. var node;
  11440. var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11441. var parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body;
  11442. if (left && isBr$5(startNode) && isAfterNode && dom.isEmpty(parentBlockContainer)) {
  11443. return Optional.some(CaretPosition(startNode.parentNode, dom.nodeIndex(startNode)));
  11444. }
  11445. var walker = new DomTreeWalker(startNode, parentBlockContainer);
  11446. while (node = walker[left ? 'prev' : 'next']()) {
  11447. if (dom.getContentEditableParent(node) === 'false' || isCeFalseCaretContainer(node, body)) {
  11448. return Optional.none();
  11449. }
  11450. if (isText$7(node) && node.nodeValue.length > 0) {
  11451. if (hasParentWithName(node, body, 'A') === false) {
  11452. return Optional.some(CaretPosition(node, left ? node.nodeValue.length : 0));
  11453. }
  11454. return Optional.none();
  11455. }
  11456. if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  11457. return Optional.none();
  11458. }
  11459. lastInlineElement = node;
  11460. }
  11461. if (collapsed && lastInlineElement) {
  11462. return Optional.some(CaretPosition(lastInlineElement, 0));
  11463. }
  11464. return Optional.none();
  11465. };
  11466. var normalizeEndPoint = function (dom, collapsed, start, rng) {
  11467. var container, offset;
  11468. var body = dom.getRoot();
  11469. var node;
  11470. var directionLeft, normalized = false;
  11471. container = rng[(start ? 'start' : 'end') + 'Container'];
  11472. offset = rng[(start ? 'start' : 'end') + 'Offset'];
  11473. var isAfterNode = isElement$5(container) && offset === container.childNodes.length;
  11474. var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11475. directionLeft = start;
  11476. if (isCaretContainer$2(container)) {
  11477. return Optional.none();
  11478. }
  11479. if (isElement$5(container) && offset > container.childNodes.length - 1) {
  11480. directionLeft = false;
  11481. }
  11482. if (isDocument$1(container)) {
  11483. container = body;
  11484. offset = 0;
  11485. }
  11486. if (container === body) {
  11487. if (directionLeft) {
  11488. node = container.childNodes[offset > 0 ? offset - 1 : 0];
  11489. if (node) {
  11490. if (isCaretContainer$2(node)) {
  11491. return Optional.none();
  11492. }
  11493. if (nonEmptyElementsMap[node.nodeName] || isTable(node)) {
  11494. return Optional.none();
  11495. }
  11496. }
  11497. }
  11498. if (container.hasChildNodes()) {
  11499. offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
  11500. container = container.childNodes[offset];
  11501. offset = isText$7(container) && isAfterNode ? container.data.length : 0;
  11502. if (!collapsed && container === body.lastChild && isTable(container)) {
  11503. return Optional.none();
  11504. }
  11505. if (hasContentEditableFalseParent(body, container) || isCaretContainer$2(container)) {
  11506. return Optional.none();
  11507. }
  11508. if (container.hasChildNodes() && isTable(container) === false) {
  11509. node = container;
  11510. var walker = new DomTreeWalker(container, body);
  11511. do {
  11512. if (isContentEditableFalse$b(node) || isCaretContainer$2(node)) {
  11513. normalized = false;
  11514. break;
  11515. }
  11516. if (isText$7(node) && node.nodeValue.length > 0) {
  11517. offset = directionLeft ? 0 : node.nodeValue.length;
  11518. container = node;
  11519. normalized = true;
  11520. break;
  11521. }
  11522. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCell$2(node)) {
  11523. offset = dom.nodeIndex(node);
  11524. container = node.parentNode;
  11525. if (!directionLeft) {
  11526. offset++;
  11527. }
  11528. normalized = true;
  11529. break;
  11530. }
  11531. } while (node = directionLeft ? walker.next() : walker.prev());
  11532. }
  11533. }
  11534. }
  11535. if (collapsed) {
  11536. if (isText$7(container) && offset === 0) {
  11537. findTextNodeRelative(dom, isAfterNode, collapsed, true, container).each(function (pos) {
  11538. container = pos.container();
  11539. offset = pos.offset();
  11540. normalized = true;
  11541. });
  11542. }
  11543. if (isElement$5(container)) {
  11544. node = container.childNodes[offset];
  11545. if (!node) {
  11546. node = container.childNodes[offset - 1];
  11547. }
  11548. if (node && isBr$5(node) && !isPrevNode(node, 'A') && !hasBrBeforeAfter(dom, node, false) && !hasBrBeforeAfter(dom, node, true)) {
  11549. findTextNodeRelative(dom, isAfterNode, collapsed, true, node).each(function (pos) {
  11550. container = pos.container();
  11551. offset = pos.offset();
  11552. normalized = true;
  11553. });
  11554. }
  11555. }
  11556. }
  11557. if (directionLeft && !collapsed && isText$7(container) && offset === container.nodeValue.length) {
  11558. findTextNodeRelative(dom, isAfterNode, collapsed, false, container).each(function (pos) {
  11559. container = pos.container();
  11560. offset = pos.offset();
  11561. normalized = true;
  11562. });
  11563. }
  11564. return normalized ? Optional.some(CaretPosition(container, offset)) : Optional.none();
  11565. };
  11566. var normalize$2 = function (dom, rng) {
  11567. var collapsed = rng.collapsed, normRng = rng.cloneRange();
  11568. var startPos = CaretPosition.fromRangeStart(rng);
  11569. normalizeEndPoint(dom, collapsed, true, normRng).each(function (pos) {
  11570. if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
  11571. normRng.setStart(pos.container(), pos.offset());
  11572. }
  11573. });
  11574. if (!collapsed) {
  11575. normalizeEndPoint(dom, collapsed, false, normRng).each(function (pos) {
  11576. normRng.setEnd(pos.container(), pos.offset());
  11577. });
  11578. }
  11579. if (collapsed) {
  11580. normRng.collapse(true);
  11581. }
  11582. return isEq$4(rng, normRng) ? Optional.none() : Optional.some(normRng);
  11583. };
  11584. var splitText = function (node, offset) {
  11585. return node.splitText(offset);
  11586. };
  11587. var split = function (rng) {
  11588. var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  11589. if (startContainer === endContainer && isText$7(startContainer)) {
  11590. if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  11591. endContainer = splitText(startContainer, startOffset);
  11592. startContainer = endContainer.previousSibling;
  11593. if (endOffset > startOffset) {
  11594. endOffset = endOffset - startOffset;
  11595. startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
  11596. endOffset = endContainer.nodeValue.length;
  11597. startOffset = 0;
  11598. } else {
  11599. endOffset = 0;
  11600. }
  11601. }
  11602. } else {
  11603. if (isText$7(startContainer) && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  11604. startContainer = splitText(startContainer, startOffset);
  11605. startOffset = 0;
  11606. }
  11607. if (isText$7(endContainer) && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
  11608. endContainer = splitText(endContainer, endOffset).previousSibling;
  11609. endOffset = endContainer.nodeValue.length;
  11610. }
  11611. }
  11612. return {
  11613. startContainer: startContainer,
  11614. startOffset: startOffset,
  11615. endContainer: endContainer,
  11616. endOffset: endOffset
  11617. };
  11618. };
  11619. var RangeUtils = function (dom) {
  11620. var walk = function (rng, callback) {
  11621. return walk$2(dom, rng, callback);
  11622. };
  11623. var split$1 = split;
  11624. var normalize = function (rng) {
  11625. return normalize$2(dom, rng).fold(never, function (normalizedRng) {
  11626. rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
  11627. rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
  11628. return true;
  11629. });
  11630. };
  11631. return {
  11632. walk: walk,
  11633. split: split$1,
  11634. normalize: normalize
  11635. };
  11636. };
  11637. RangeUtils.compareRanges = isEq$4;
  11638. RangeUtils.getCaretRangeFromPoint = fromPoint;
  11639. RangeUtils.getSelectedNode = getSelectedNode;
  11640. RangeUtils.getNode = getNode$1;
  11641. var Dimension = function (name, getOffset) {
  11642. var set = function (element, h) {
  11643. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  11644. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  11645. }
  11646. var dom = element.dom;
  11647. if (isSupported(dom)) {
  11648. dom.style[name] = h + 'px';
  11649. }
  11650. };
  11651. var get = function (element) {
  11652. var r = getOffset(element);
  11653. if (r <= 0 || r === null) {
  11654. var css = get$5(element, name);
  11655. return parseFloat(css) || 0;
  11656. }
  11657. return r;
  11658. };
  11659. var getOuter = get;
  11660. var aggregate = function (element, properties) {
  11661. return foldl(properties, function (acc, property) {
  11662. var val = get$5(element, property);
  11663. var value = val === undefined ? 0 : parseInt(val, 10);
  11664. return isNaN(value) ? acc : acc + value;
  11665. }, 0);
  11666. };
  11667. var max = function (element, value, properties) {
  11668. var cumulativeInclusions = aggregate(element, properties);
  11669. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  11670. return absoluteMax;
  11671. };
  11672. return {
  11673. set: set,
  11674. get: get,
  11675. getOuter: getOuter,
  11676. aggregate: aggregate,
  11677. max: max
  11678. };
  11679. };
  11680. var api = Dimension('height', function (element) {
  11681. var dom = element.dom;
  11682. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  11683. });
  11684. var get$1 = function (element) {
  11685. return api.get(element);
  11686. };
  11687. var walkUp = function (navigation, doc) {
  11688. var frame = navigation.view(doc);
  11689. return frame.fold(constant([]), function (f) {
  11690. var parent = navigation.owner(f);
  11691. var rest = walkUp(navigation, parent);
  11692. return [f].concat(rest);
  11693. });
  11694. };
  11695. var pathTo = function (element, navigation) {
  11696. var d = navigation.owner(element);
  11697. return walkUp(navigation, d);
  11698. };
  11699. var view = function (doc) {
  11700. var _a;
  11701. var element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  11702. return element.map(SugarElement.fromDom);
  11703. };
  11704. var owner = function (element) {
  11705. return documentOrOwner(element);
  11706. };
  11707. var Navigation = /*#__PURE__*/Object.freeze({
  11708. __proto__: null,
  11709. view: view,
  11710. owner: owner
  11711. });
  11712. var find$1 = function (element) {
  11713. var doc = SugarElement.fromDom(document);
  11714. var scroll = get$8(doc);
  11715. var frames = pathTo(element, Navigation);
  11716. var offset = viewport(element);
  11717. var r = foldr(frames, function (b, a) {
  11718. var loc = viewport(a);
  11719. return {
  11720. left: b.left + loc.left,
  11721. top: b.top + loc.top
  11722. };
  11723. }, {
  11724. left: 0,
  11725. top: 0
  11726. });
  11727. return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  11728. };
  11729. var excludeFromDescend = function (element) {
  11730. return name(element) === 'textarea';
  11731. };
  11732. var fireScrollIntoViewEvent = function (editor, data) {
  11733. var scrollEvent = editor.fire('ScrollIntoView', data);
  11734. return scrollEvent.isDefaultPrevented();
  11735. };
  11736. var fireAfterScrollIntoViewEvent = function (editor, data) {
  11737. editor.fire('AfterScrollIntoView', data);
  11738. };
  11739. var descend = function (element, offset) {
  11740. var children$1 = children(element);
  11741. if (children$1.length === 0 || excludeFromDescend(element)) {
  11742. return {
  11743. element: element,
  11744. offset: offset
  11745. };
  11746. } else if (offset < children$1.length && !excludeFromDescend(children$1[offset])) {
  11747. return {
  11748. element: children$1[offset],
  11749. offset: 0
  11750. };
  11751. } else {
  11752. var last = children$1[children$1.length - 1];
  11753. if (excludeFromDescend(last)) {
  11754. return {
  11755. element: element,
  11756. offset: offset
  11757. };
  11758. } else {
  11759. if (name(last) === 'img') {
  11760. return {
  11761. element: last,
  11762. offset: 1
  11763. };
  11764. } else if (isText$8(last)) {
  11765. return {
  11766. element: last,
  11767. offset: get$2(last).length
  11768. };
  11769. } else {
  11770. return {
  11771. element: last,
  11772. offset: children(last).length
  11773. };
  11774. }
  11775. }
  11776. }
  11777. };
  11778. var markerInfo = function (element, cleanupFun) {
  11779. var pos = absolute(element);
  11780. var height = get$1(element);
  11781. return {
  11782. element: element,
  11783. bottom: pos.top + height,
  11784. height: height,
  11785. pos: pos,
  11786. cleanup: cleanupFun
  11787. };
  11788. };
  11789. var createMarker = function (element, offset) {
  11790. var startPoint = descend(element, offset);
  11791. var span = SugarElement.fromHtml('<span data-mce-bogus="all" style="display: inline-block;">' + ZWSP$1 + '</span>');
  11792. before$4(startPoint.element, span);
  11793. return markerInfo(span, function () {
  11794. return remove$7(span);
  11795. });
  11796. };
  11797. var elementMarker = function (element) {
  11798. return markerInfo(SugarElement.fromDom(element), noop);
  11799. };
  11800. var withMarker = function (editor, f, rng, alignToTop) {
  11801. preserveWith(editor, function (_s, _e) {
  11802. return applyWithMarker(editor, f, rng, alignToTop);
  11803. }, rng);
  11804. };
  11805. var withScrollEvents = function (editor, doc, f, marker, alignToTop) {
  11806. var data = {
  11807. elm: marker.element.dom,
  11808. alignToTop: alignToTop
  11809. };
  11810. if (fireScrollIntoViewEvent(editor, data)) {
  11811. return;
  11812. }
  11813. var scrollTop = get$8(doc).top;
  11814. f(doc, scrollTop, marker, alignToTop);
  11815. fireAfterScrollIntoViewEvent(editor, data);
  11816. };
  11817. var applyWithMarker = function (editor, f, rng, alignToTop) {
  11818. var body = SugarElement.fromDom(editor.getBody());
  11819. var doc = SugarElement.fromDom(editor.getDoc());
  11820. reflow(body);
  11821. var marker = createMarker(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  11822. withScrollEvents(editor, doc, f, marker, alignToTop);
  11823. marker.cleanup();
  11824. };
  11825. var withElement = function (editor, element, f, alignToTop) {
  11826. var doc = SugarElement.fromDom(editor.getDoc());
  11827. withScrollEvents(editor, doc, f, elementMarker(element), alignToTop);
  11828. };
  11829. var preserveWith = function (editor, f, rng) {
  11830. var startElement = rng.startContainer;
  11831. var startOffset = rng.startOffset;
  11832. var endElement = rng.endContainer;
  11833. var endOffset = rng.endOffset;
  11834. f(SugarElement.fromDom(startElement), SugarElement.fromDom(endElement));
  11835. var newRng = editor.dom.createRng();
  11836. newRng.setStart(startElement, startOffset);
  11837. newRng.setEnd(endElement, endOffset);
  11838. editor.selection.setRng(rng);
  11839. };
  11840. var scrollToMarker = function (marker, viewHeight, alignToTop, doc) {
  11841. var pos = marker.pos;
  11842. if (alignToTop) {
  11843. to(pos.left, pos.top, doc);
  11844. } else {
  11845. var y = pos.top - viewHeight + marker.height;
  11846. to(pos.left, y, doc);
  11847. }
  11848. };
  11849. var intoWindowIfNeeded = function (doc, scrollTop, viewHeight, marker, alignToTop) {
  11850. var viewportBottom = viewHeight + scrollTop;
  11851. var markerTop = marker.pos.top;
  11852. var markerBottom = marker.bottom;
  11853. var largerThanViewport = markerBottom - markerTop >= viewHeight;
  11854. if (markerTop < scrollTop) {
  11855. scrollToMarker(marker, viewHeight, alignToTop !== false, doc);
  11856. } else if (markerTop > viewportBottom) {
  11857. var align = largerThanViewport ? alignToTop !== false : alignToTop === true;
  11858. scrollToMarker(marker, viewHeight, align, doc);
  11859. } else if (markerBottom > viewportBottom && !largerThanViewport) {
  11860. scrollToMarker(marker, viewHeight, alignToTop === true, doc);
  11861. }
  11862. };
  11863. var intoWindow = function (doc, scrollTop, marker, alignToTop) {
  11864. var viewHeight = doc.dom.defaultView.innerHeight;
  11865. intoWindowIfNeeded(doc, scrollTop, viewHeight, marker, alignToTop);
  11866. };
  11867. var intoFrame = function (doc, scrollTop, marker, alignToTop) {
  11868. var frameViewHeight = doc.dom.defaultView.innerHeight;
  11869. intoWindowIfNeeded(doc, scrollTop, frameViewHeight, marker, alignToTop);
  11870. var op = find$1(marker.element);
  11871. var viewportBounds = getBounds(window);
  11872. if (op.top < viewportBounds.y) {
  11873. intoView(marker.element, alignToTop !== false);
  11874. } else if (op.top > viewportBounds.bottom) {
  11875. intoView(marker.element, alignToTop === true);
  11876. }
  11877. };
  11878. var rangeIntoWindow = function (editor, rng, alignToTop) {
  11879. return withMarker(editor, intoWindow, rng, alignToTop);
  11880. };
  11881. var elementIntoWindow = function (editor, element, alignToTop) {
  11882. return withElement(editor, element, intoWindow, alignToTop);
  11883. };
  11884. var rangeIntoFrame = function (editor, rng, alignToTop) {
  11885. return withMarker(editor, intoFrame, rng, alignToTop);
  11886. };
  11887. var elementIntoFrame = function (editor, element, alignToTop) {
  11888. return withElement(editor, element, intoFrame, alignToTop);
  11889. };
  11890. var scrollElementIntoView = function (editor, element, alignToTop) {
  11891. var scroller = editor.inline ? elementIntoWindow : elementIntoFrame;
  11892. scroller(editor, element, alignToTop);
  11893. };
  11894. var scrollRangeIntoView = function (editor, rng, alignToTop) {
  11895. var scroller = editor.inline ? rangeIntoWindow : rangeIntoFrame;
  11896. scroller(editor, rng, alignToTop);
  11897. };
  11898. var getDocument = function () {
  11899. return SugarElement.fromDom(document);
  11900. };
  11901. var focus$1 = function (element) {
  11902. return element.dom.focus();
  11903. };
  11904. var hasFocus$1 = function (element) {
  11905. var root = getRootNode(element).dom;
  11906. return element.dom === root.activeElement;
  11907. };
  11908. var active = function (root) {
  11909. if (root === void 0) {
  11910. root = getDocument();
  11911. }
  11912. return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  11913. };
  11914. var search = function (element) {
  11915. return active(getRootNode(element)).filter(function (e) {
  11916. return element.dom.contains(e.dom);
  11917. });
  11918. };
  11919. var create$5 = function (start, soffset, finish, foffset) {
  11920. return {
  11921. start: start,
  11922. soffset: soffset,
  11923. finish: finish,
  11924. foffset: foffset
  11925. };
  11926. };
  11927. var SimRange = { create: create$5 };
  11928. var adt$1 = Adt.generate([
  11929. { before: ['element'] },
  11930. {
  11931. on: [
  11932. 'element',
  11933. 'offset'
  11934. ]
  11935. },
  11936. { after: ['element'] }
  11937. ]);
  11938. var cata = function (subject, onBefore, onOn, onAfter) {
  11939. return subject.fold(onBefore, onOn, onAfter);
  11940. };
  11941. var getStart$2 = function (situ) {
  11942. return situ.fold(identity, identity, identity);
  11943. };
  11944. var before$1 = adt$1.before;
  11945. var on = adt$1.on;
  11946. var after$1 = adt$1.after;
  11947. var Situ = {
  11948. before: before$1,
  11949. on: on,
  11950. after: after$1,
  11951. cata: cata,
  11952. getStart: getStart$2
  11953. };
  11954. var adt = Adt.generate([
  11955. { domRange: ['rng'] },
  11956. {
  11957. relative: [
  11958. 'startSitu',
  11959. 'finishSitu'
  11960. ]
  11961. },
  11962. {
  11963. exact: [
  11964. 'start',
  11965. 'soffset',
  11966. 'finish',
  11967. 'foffset'
  11968. ]
  11969. }
  11970. ]);
  11971. var exactFromRange = function (simRange) {
  11972. return adt.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  11973. };
  11974. var getStart$1 = function (selection) {
  11975. return selection.match({
  11976. domRange: function (rng) {
  11977. return SugarElement.fromDom(rng.startContainer);
  11978. },
  11979. relative: function (startSitu, _finishSitu) {
  11980. return Situ.getStart(startSitu);
  11981. },
  11982. exact: function (start, _soffset, _finish, _foffset) {
  11983. return start;
  11984. }
  11985. });
  11986. };
  11987. var domRange = adt.domRange;
  11988. var relative = adt.relative;
  11989. var exact = adt.exact;
  11990. var getWin = function (selection) {
  11991. var start = getStart$1(selection);
  11992. return defaultView(start);
  11993. };
  11994. var range = SimRange.create;
  11995. var SimSelection = {
  11996. domRange: domRange,
  11997. relative: relative,
  11998. exact: exact,
  11999. exactFromRange: exactFromRange,
  12000. getWin: getWin,
  12001. range: range
  12002. };
  12003. var browser$1 = detect().browser;
  12004. var clamp$1 = function (offset, element) {
  12005. var max = isText$8(element) ? get$2(element).length : children(element).length + 1;
  12006. if (offset > max) {
  12007. return max;
  12008. } else if (offset < 0) {
  12009. return 0;
  12010. }
  12011. return offset;
  12012. };
  12013. var normalizeRng = function (rng) {
  12014. return SimSelection.range(rng.start, clamp$1(rng.soffset, rng.start), rng.finish, clamp$1(rng.foffset, rng.finish));
  12015. };
  12016. var isOrContains = function (root, elm) {
  12017. return !isRestrictedNode(elm.dom) && (contains$1(root, elm) || eq(root, elm));
  12018. };
  12019. var isRngInRoot = function (root) {
  12020. return function (rng) {
  12021. return isOrContains(root, rng.start) && isOrContains(root, rng.finish);
  12022. };
  12023. };
  12024. var shouldStore = function (editor) {
  12025. return editor.inline === true || browser$1.isIE();
  12026. };
  12027. var nativeRangeToSelectionRange = function (r) {
  12028. return SimSelection.range(SugarElement.fromDom(r.startContainer), r.startOffset, SugarElement.fromDom(r.endContainer), r.endOffset);
  12029. };
  12030. var readRange = function (win) {
  12031. var selection = win.getSelection();
  12032. var rng = !selection || selection.rangeCount === 0 ? Optional.none() : Optional.from(selection.getRangeAt(0));
  12033. return rng.map(nativeRangeToSelectionRange);
  12034. };
  12035. var getBookmark = function (root) {
  12036. var win = defaultView(root);
  12037. return readRange(win.dom).filter(isRngInRoot(root));
  12038. };
  12039. var validate = function (root, bookmark) {
  12040. return Optional.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
  12041. };
  12042. var bookmarkToNativeRng = function (bookmark) {
  12043. var rng = document.createRange();
  12044. try {
  12045. rng.setStart(bookmark.start.dom, bookmark.soffset);
  12046. rng.setEnd(bookmark.finish.dom, bookmark.foffset);
  12047. return Optional.some(rng);
  12048. } catch (_) {
  12049. return Optional.none();
  12050. }
  12051. };
  12052. var store = function (editor) {
  12053. var newBookmark = shouldStore(editor) ? getBookmark(SugarElement.fromDom(editor.getBody())) : Optional.none();
  12054. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12055. };
  12056. var storeNative = function (editor, rng) {
  12057. var root = SugarElement.fromDom(editor.getBody());
  12058. var range = shouldStore(editor) ? Optional.from(rng) : Optional.none();
  12059. var newBookmark = range.map(nativeRangeToSelectionRange).filter(isRngInRoot(root));
  12060. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12061. };
  12062. var getRng = function (editor) {
  12063. var bookmark = editor.bookmark ? editor.bookmark : Optional.none();
  12064. return bookmark.bind(function (x) {
  12065. return validate(SugarElement.fromDom(editor.getBody()), x);
  12066. }).bind(bookmarkToNativeRng);
  12067. };
  12068. var restore = function (editor) {
  12069. getRng(editor).each(function (rng) {
  12070. return editor.selection.setRng(rng);
  12071. });
  12072. };
  12073. var isEditorUIElement$1 = function (elm) {
  12074. var className = elm.className.toString();
  12075. return className.indexOf('tox-') !== -1 || className.indexOf('mce-') !== -1;
  12076. };
  12077. var FocusManager = { isEditorUIElement: isEditorUIElement$1 };
  12078. var isManualNodeChange = function (e) {
  12079. return e.type === 'nodechange' && e.selectionChange;
  12080. };
  12081. var registerPageMouseUp = function (editor, throttledStore) {
  12082. var mouseUpPage = function () {
  12083. throttledStore.throttle();
  12084. };
  12085. DOMUtils.DOM.bind(document, 'mouseup', mouseUpPage);
  12086. editor.on('remove', function () {
  12087. DOMUtils.DOM.unbind(document, 'mouseup', mouseUpPage);
  12088. });
  12089. };
  12090. var registerFocusOut = function (editor) {
  12091. editor.on('focusout', function () {
  12092. store(editor);
  12093. });
  12094. };
  12095. var registerMouseUp = function (editor, throttledStore) {
  12096. editor.on('mouseup touchend', function (_e) {
  12097. throttledStore.throttle();
  12098. });
  12099. };
  12100. var registerEditorEvents = function (editor, throttledStore) {
  12101. var browser = detect().browser;
  12102. if (browser.isIE()) {
  12103. registerFocusOut(editor);
  12104. } else {
  12105. registerMouseUp(editor, throttledStore);
  12106. }
  12107. editor.on('keyup NodeChange', function (e) {
  12108. if (!isManualNodeChange(e)) {
  12109. store(editor);
  12110. }
  12111. });
  12112. };
  12113. var register$3 = function (editor) {
  12114. var throttledStore = first(function () {
  12115. store(editor);
  12116. }, 0);
  12117. editor.on('init', function () {
  12118. if (editor.inline) {
  12119. registerPageMouseUp(editor, throttledStore);
  12120. }
  12121. registerEditorEvents(editor, throttledStore);
  12122. });
  12123. editor.on('remove', function () {
  12124. throttledStore.cancel();
  12125. });
  12126. };
  12127. var documentFocusInHandler;
  12128. var DOM$8 = DOMUtils.DOM;
  12129. var isEditorUIElement = function (elm) {
  12130. return FocusManager.isEditorUIElement(elm);
  12131. };
  12132. var isEditorContentAreaElement = function (elm) {
  12133. var classList = elm.classList;
  12134. if (classList !== undefined) {
  12135. return classList.contains('tox-edit-area') || classList.contains('tox-edit-area__iframe') || classList.contains('mce-content-body');
  12136. } else {
  12137. return false;
  12138. }
  12139. };
  12140. var isUIElement = function (editor, elm) {
  12141. var customSelector = getCustomUiSelector(editor);
  12142. var parent = DOM$8.getParent(elm, function (elm) {
  12143. return isEditorUIElement(elm) || (customSelector ? editor.dom.is(elm, customSelector) : false);
  12144. });
  12145. return parent !== null;
  12146. };
  12147. var getActiveElement = function (editor) {
  12148. try {
  12149. var root = getRootNode(SugarElement.fromDom(editor.getElement()));
  12150. return active(root).fold(function () {
  12151. return document.body;
  12152. }, function (x) {
  12153. return x.dom;
  12154. });
  12155. } catch (ex) {
  12156. return document.body;
  12157. }
  12158. };
  12159. var registerEvents$1 = function (editorManager, e) {
  12160. var editor = e.editor;
  12161. register$3(editor);
  12162. editor.on('focusin', function () {
  12163. var focusedEditor = editorManager.focusedEditor;
  12164. if (focusedEditor !== editor) {
  12165. if (focusedEditor) {
  12166. focusedEditor.fire('blur', { focusedEditor: editor });
  12167. }
  12168. editorManager.setActive(editor);
  12169. editorManager.focusedEditor = editor;
  12170. editor.fire('focus', { blurredEditor: focusedEditor });
  12171. editor.focus(true);
  12172. }
  12173. });
  12174. editor.on('focusout', function () {
  12175. Delay.setEditorTimeout(editor, function () {
  12176. var focusedEditor = editorManager.focusedEditor;
  12177. if (!isUIElement(editor, getActiveElement(editor)) && focusedEditor === editor) {
  12178. editor.fire('blur', { focusedEditor: null });
  12179. editorManager.focusedEditor = null;
  12180. }
  12181. });
  12182. });
  12183. if (!documentFocusInHandler) {
  12184. documentFocusInHandler = function (e) {
  12185. var activeEditor = editorManager.activeEditor;
  12186. if (activeEditor) {
  12187. getOriginalEventTarget(e).each(function (target) {
  12188. if (target.ownerDocument === document) {
  12189. if (target !== document.body && !isUIElement(activeEditor, target) && editorManager.focusedEditor === activeEditor) {
  12190. activeEditor.fire('blur', { focusedEditor: null });
  12191. editorManager.focusedEditor = null;
  12192. }
  12193. }
  12194. });
  12195. }
  12196. };
  12197. DOM$8.bind(document, 'focusin', documentFocusInHandler);
  12198. }
  12199. };
  12200. var unregisterDocumentEvents = function (editorManager, e) {
  12201. if (editorManager.focusedEditor === e.editor) {
  12202. editorManager.focusedEditor = null;
  12203. }
  12204. if (!editorManager.activeEditor) {
  12205. DOM$8.unbind(document, 'focusin', documentFocusInHandler);
  12206. documentFocusInHandler = null;
  12207. }
  12208. };
  12209. var setup$l = function (editorManager) {
  12210. editorManager.on('AddEditor', curry(registerEvents$1, editorManager));
  12211. editorManager.on('RemoveEditor', curry(unregisterDocumentEvents, editorManager));
  12212. };
  12213. var getContentEditableHost = function (editor, node) {
  12214. return editor.dom.getParent(node, function (node) {
  12215. return editor.dom.getContentEditable(node) === 'true';
  12216. });
  12217. };
  12218. var getCollapsedNode = function (rng) {
  12219. return rng.collapsed ? Optional.from(getNode$1(rng.startContainer, rng.startOffset)).map(SugarElement.fromDom) : Optional.none();
  12220. };
  12221. var getFocusInElement = function (root, rng) {
  12222. return getCollapsedNode(rng).bind(function (node) {
  12223. if (isTableSection(node)) {
  12224. return Optional.some(node);
  12225. } else if (contains$1(root, node) === false) {
  12226. return Optional.some(root);
  12227. } else {
  12228. return Optional.none();
  12229. }
  12230. });
  12231. };
  12232. var normalizeSelection$1 = function (editor, rng) {
  12233. getFocusInElement(SugarElement.fromDom(editor.getBody()), rng).bind(function (elm) {
  12234. return firstPositionIn(elm.dom);
  12235. }).fold(function () {
  12236. editor.selection.normalize();
  12237. return;
  12238. }, function (caretPos) {
  12239. return editor.selection.setRng(caretPos.toRange());
  12240. });
  12241. };
  12242. var focusBody = function (body) {
  12243. if (body.setActive) {
  12244. try {
  12245. body.setActive();
  12246. } catch (ex) {
  12247. body.focus();
  12248. }
  12249. } else {
  12250. body.focus();
  12251. }
  12252. };
  12253. var hasElementFocus = function (elm) {
  12254. return hasFocus$1(elm) || search(elm).isSome();
  12255. };
  12256. var hasIframeFocus = function (editor) {
  12257. return editor.iframeElement && hasFocus$1(SugarElement.fromDom(editor.iframeElement));
  12258. };
  12259. var hasInlineFocus = function (editor) {
  12260. var rawBody = editor.getBody();
  12261. return rawBody && hasElementFocus(SugarElement.fromDom(rawBody));
  12262. };
  12263. var hasUiFocus = function (editor) {
  12264. var dos = getRootNode(SugarElement.fromDom(editor.getElement()));
  12265. return active(dos).filter(function (elem) {
  12266. return !isEditorContentAreaElement(elem.dom) && isUIElement(editor, elem.dom);
  12267. }).isSome();
  12268. };
  12269. var hasFocus = function (editor) {
  12270. return editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
  12271. };
  12272. var hasEditorOrUiFocus = function (editor) {
  12273. return hasFocus(editor) || hasUiFocus(editor);
  12274. };
  12275. var focusEditor = function (editor) {
  12276. var selection = editor.selection;
  12277. var body = editor.getBody();
  12278. var rng = selection.getRng();
  12279. editor.quirks.refreshContentEditable();
  12280. if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  12281. getRng(editor).each(function (bookmarkRng) {
  12282. editor.selection.setRng(bookmarkRng);
  12283. rng = bookmarkRng;
  12284. });
  12285. }
  12286. var contentEditableHost = getContentEditableHost(editor, selection.getNode());
  12287. if (editor.$.contains(body, contentEditableHost)) {
  12288. focusBody(contentEditableHost);
  12289. normalizeSelection$1(editor, rng);
  12290. activateEditor(editor);
  12291. return;
  12292. }
  12293. if (!editor.inline) {
  12294. if (!Env.opera) {
  12295. focusBody(body);
  12296. }
  12297. editor.getWin().focus();
  12298. }
  12299. if (Env.gecko || editor.inline) {
  12300. focusBody(body);
  12301. normalizeSelection$1(editor, rng);
  12302. }
  12303. activateEditor(editor);
  12304. };
  12305. var activateEditor = function (editor) {
  12306. return editor.editorManager.setActive(editor);
  12307. };
  12308. var focus = function (editor, skipFocus) {
  12309. if (editor.removed) {
  12310. return;
  12311. }
  12312. if (skipFocus) {
  12313. activateEditor(editor);
  12314. } else {
  12315. focusEditor(editor);
  12316. }
  12317. };
  12318. var getEndpointElement = function (root, rng, start, real, resolve) {
  12319. var container = start ? rng.startContainer : rng.endContainer;
  12320. var offset = start ? rng.startOffset : rng.endOffset;
  12321. return Optional.from(container).map(SugarElement.fromDom).map(function (elm) {
  12322. return !real || !rng.collapsed ? child$1(elm, resolve(elm, offset)).getOr(elm) : elm;
  12323. }).bind(function (elm) {
  12324. return isElement$6(elm) ? Optional.some(elm) : parent(elm).filter(isElement$6);
  12325. }).map(function (elm) {
  12326. return elm.dom;
  12327. }).getOr(root);
  12328. };
  12329. var getStart = function (root, rng, real) {
  12330. return getEndpointElement(root, rng, true, real, function (elm, offset) {
  12331. return Math.min(childNodesCount(elm), offset);
  12332. });
  12333. };
  12334. var getEnd = function (root, rng, real) {
  12335. return getEndpointElement(root, rng, false, real, function (elm, offset) {
  12336. return offset > 0 ? offset - 1 : offset;
  12337. });
  12338. };
  12339. var skipEmptyTextNodes = function (node, forwards) {
  12340. var orig = node;
  12341. while (node && isText$7(node) && node.length === 0) {
  12342. node = forwards ? node.nextSibling : node.previousSibling;
  12343. }
  12344. return node || orig;
  12345. };
  12346. var getNode = function (root, rng) {
  12347. var elm, startContainer, endContainer;
  12348. if (!rng) {
  12349. return root;
  12350. }
  12351. startContainer = rng.startContainer;
  12352. endContainer = rng.endContainer;
  12353. var startOffset = rng.startOffset;
  12354. var endOffset = rng.endOffset;
  12355. elm = rng.commonAncestorContainer;
  12356. if (!rng.collapsed) {
  12357. if (startContainer === endContainer) {
  12358. if (endOffset - startOffset < 2) {
  12359. if (startContainer.hasChildNodes()) {
  12360. elm = startContainer.childNodes[startOffset];
  12361. }
  12362. }
  12363. }
  12364. if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
  12365. if (startContainer.length === startOffset) {
  12366. startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
  12367. } else {
  12368. startContainer = startContainer.parentNode;
  12369. }
  12370. if (endOffset === 0) {
  12371. endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
  12372. } else {
  12373. endContainer = endContainer.parentNode;
  12374. }
  12375. if (startContainer && startContainer === endContainer) {
  12376. return startContainer;
  12377. }
  12378. }
  12379. }
  12380. if (elm && elm.nodeType === 3) {
  12381. return elm.parentNode;
  12382. }
  12383. return elm;
  12384. };
  12385. var getSelectedBlocks = function (dom, rng, startElm, endElm) {
  12386. var node;
  12387. var selectedBlocks = [];
  12388. var root = dom.getRoot();
  12389. startElm = dom.getParent(startElm || getStart(root, rng, rng.collapsed), dom.isBlock);
  12390. endElm = dom.getParent(endElm || getEnd(root, rng, rng.collapsed), dom.isBlock);
  12391. if (startElm && startElm !== root) {
  12392. selectedBlocks.push(startElm);
  12393. }
  12394. if (startElm && endElm && startElm !== endElm) {
  12395. node = startElm;
  12396. var walker = new DomTreeWalker(startElm, root);
  12397. while ((node = walker.next()) && node !== endElm) {
  12398. if (dom.isBlock(node)) {
  12399. selectedBlocks.push(node);
  12400. }
  12401. }
  12402. }
  12403. if (endElm && startElm !== endElm && endElm !== root) {
  12404. selectedBlocks.push(endElm);
  12405. }
  12406. return selectedBlocks;
  12407. };
  12408. var select = function (dom, node, content) {
  12409. return Optional.from(node).map(function (node) {
  12410. var idx = dom.nodeIndex(node);
  12411. var rng = dom.createRng();
  12412. rng.setStart(node.parentNode, idx);
  12413. rng.setEnd(node.parentNode, idx + 1);
  12414. if (content) {
  12415. moveEndPoint(dom, rng, node, true);
  12416. moveEndPoint(dom, rng, node, false);
  12417. }
  12418. return rng;
  12419. });
  12420. };
  12421. var processRanges = function (editor, ranges) {
  12422. return map$3(ranges, function (range) {
  12423. var evt = editor.fire('GetSelectionRange', { range: range });
  12424. return evt.range !== range ? evt.range : range;
  12425. });
  12426. };
  12427. var typeLookup = {
  12428. '#text': 3,
  12429. '#comment': 8,
  12430. '#cdata': 4,
  12431. '#pi': 7,
  12432. '#doctype': 10,
  12433. '#document-fragment': 11
  12434. };
  12435. var walk$1 = function (node, root, prev) {
  12436. var startName = prev ? 'lastChild' : 'firstChild';
  12437. var siblingName = prev ? 'prev' : 'next';
  12438. if (node[startName]) {
  12439. return node[startName];
  12440. }
  12441. if (node !== root) {
  12442. var sibling = node[siblingName];
  12443. if (sibling) {
  12444. return sibling;
  12445. }
  12446. for (var parent_1 = node.parent; parent_1 && parent_1 !== root; parent_1 = parent_1.parent) {
  12447. sibling = parent_1[siblingName];
  12448. if (sibling) {
  12449. return sibling;
  12450. }
  12451. }
  12452. }
  12453. };
  12454. var isEmptyTextNode = function (node) {
  12455. if (!isWhitespaceText(node.value)) {
  12456. return false;
  12457. }
  12458. var parentNode = node.parent;
  12459. if (parentNode && (parentNode.name !== 'span' || parentNode.attr('style')) && /^[ ]+$/.test(node.value)) {
  12460. return false;
  12461. }
  12462. return true;
  12463. };
  12464. var isNonEmptyElement = function (node) {
  12465. var isNamedAnchor = node.name === 'a' && !node.attr('href') && node.attr('id');
  12466. return node.attr('name') || node.attr('id') && !node.firstChild || node.attr('data-mce-bookmark') || isNamedAnchor;
  12467. };
  12468. var AstNode = function () {
  12469. function AstNode(name, type) {
  12470. this.name = name;
  12471. this.type = type;
  12472. if (type === 1) {
  12473. this.attributes = [];
  12474. this.attributes.map = {};
  12475. }
  12476. }
  12477. AstNode.create = function (name, attrs) {
  12478. var node = new AstNode(name, typeLookup[name] || 1);
  12479. if (attrs) {
  12480. each$j(attrs, function (value, attrName) {
  12481. node.attr(attrName, value);
  12482. });
  12483. }
  12484. return node;
  12485. };
  12486. AstNode.prototype.replace = function (node) {
  12487. var self = this;
  12488. if (node.parent) {
  12489. node.remove();
  12490. }
  12491. self.insert(node, self);
  12492. self.remove();
  12493. return self;
  12494. };
  12495. AstNode.prototype.attr = function (name, value) {
  12496. var self = this;
  12497. var attrs;
  12498. if (typeof name !== 'string') {
  12499. if (name !== undefined && name !== null) {
  12500. each$j(name, function (value, key) {
  12501. self.attr(key, value);
  12502. });
  12503. }
  12504. return self;
  12505. }
  12506. if (attrs = self.attributes) {
  12507. if (value !== undefined) {
  12508. if (value === null) {
  12509. if (name in attrs.map) {
  12510. delete attrs.map[name];
  12511. var i = attrs.length;
  12512. while (i--) {
  12513. if (attrs[i].name === name) {
  12514. attrs.splice(i, 1);
  12515. return self;
  12516. }
  12517. }
  12518. }
  12519. return self;
  12520. }
  12521. if (name in attrs.map) {
  12522. var i = attrs.length;
  12523. while (i--) {
  12524. if (attrs[i].name === name) {
  12525. attrs[i].value = value;
  12526. break;
  12527. }
  12528. }
  12529. } else {
  12530. attrs.push({
  12531. name: name,
  12532. value: value
  12533. });
  12534. }
  12535. attrs.map[name] = value;
  12536. return self;
  12537. }
  12538. return attrs.map[name];
  12539. }
  12540. };
  12541. AstNode.prototype.clone = function () {
  12542. var self = this;
  12543. var clone = new AstNode(self.name, self.type);
  12544. var selfAttrs;
  12545. if (selfAttrs = self.attributes) {
  12546. var cloneAttrs = [];
  12547. cloneAttrs.map = {};
  12548. for (var i = 0, l = selfAttrs.length; i < l; i++) {
  12549. var selfAttr = selfAttrs[i];
  12550. if (selfAttr.name !== 'id') {
  12551. cloneAttrs[cloneAttrs.length] = {
  12552. name: selfAttr.name,
  12553. value: selfAttr.value
  12554. };
  12555. cloneAttrs.map[selfAttr.name] = selfAttr.value;
  12556. }
  12557. }
  12558. clone.attributes = cloneAttrs;
  12559. }
  12560. clone.value = self.value;
  12561. clone.shortEnded = self.shortEnded;
  12562. return clone;
  12563. };
  12564. AstNode.prototype.wrap = function (wrapper) {
  12565. var self = this;
  12566. self.parent.insert(wrapper, self);
  12567. wrapper.append(self);
  12568. return self;
  12569. };
  12570. AstNode.prototype.unwrap = function () {
  12571. var self = this;
  12572. for (var node = self.firstChild; node;) {
  12573. var next = node.next;
  12574. self.insert(node, self, true);
  12575. node = next;
  12576. }
  12577. self.remove();
  12578. };
  12579. AstNode.prototype.remove = function () {
  12580. var self = this, parent = self.parent, next = self.next, prev = self.prev;
  12581. if (parent) {
  12582. if (parent.firstChild === self) {
  12583. parent.firstChild = next;
  12584. if (next) {
  12585. next.prev = null;
  12586. }
  12587. } else {
  12588. prev.next = next;
  12589. }
  12590. if (parent.lastChild === self) {
  12591. parent.lastChild = prev;
  12592. if (prev) {
  12593. prev.next = null;
  12594. }
  12595. } else {
  12596. next.prev = prev;
  12597. }
  12598. self.parent = self.next = self.prev = null;
  12599. }
  12600. return self;
  12601. };
  12602. AstNode.prototype.append = function (node) {
  12603. var self = this;
  12604. if (node.parent) {
  12605. node.remove();
  12606. }
  12607. var last = self.lastChild;
  12608. if (last) {
  12609. last.next = node;
  12610. node.prev = last;
  12611. self.lastChild = node;
  12612. } else {
  12613. self.lastChild = self.firstChild = node;
  12614. }
  12615. node.parent = self;
  12616. return node;
  12617. };
  12618. AstNode.prototype.insert = function (node, refNode, before) {
  12619. if (node.parent) {
  12620. node.remove();
  12621. }
  12622. var parent = refNode.parent || this;
  12623. if (before) {
  12624. if (refNode === parent.firstChild) {
  12625. parent.firstChild = node;
  12626. } else {
  12627. refNode.prev.next = node;
  12628. }
  12629. node.prev = refNode.prev;
  12630. node.next = refNode;
  12631. refNode.prev = node;
  12632. } else {
  12633. if (refNode === parent.lastChild) {
  12634. parent.lastChild = node;
  12635. } else {
  12636. refNode.next.prev = node;
  12637. }
  12638. node.next = refNode.next;
  12639. node.prev = refNode;
  12640. refNode.next = node;
  12641. }
  12642. node.parent = parent;
  12643. return node;
  12644. };
  12645. AstNode.prototype.getAll = function (name) {
  12646. var self = this;
  12647. var collection = [];
  12648. for (var node = self.firstChild; node; node = walk$1(node, self)) {
  12649. if (node.name === name) {
  12650. collection.push(node);
  12651. }
  12652. }
  12653. return collection;
  12654. };
  12655. AstNode.prototype.children = function () {
  12656. var self = this;
  12657. var collection = [];
  12658. for (var node = self.firstChild; node; node = node.next) {
  12659. collection.push(node);
  12660. }
  12661. return collection;
  12662. };
  12663. AstNode.prototype.empty = function () {
  12664. var self = this;
  12665. if (self.firstChild) {
  12666. var nodes = [];
  12667. for (var node = self.firstChild; node; node = walk$1(node, self)) {
  12668. nodes.push(node);
  12669. }
  12670. var i = nodes.length;
  12671. while (i--) {
  12672. var node = nodes[i];
  12673. node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
  12674. }
  12675. }
  12676. self.firstChild = self.lastChild = null;
  12677. return self;
  12678. };
  12679. AstNode.prototype.isEmpty = function (elements, whitespace, predicate) {
  12680. if (whitespace === void 0) {
  12681. whitespace = {};
  12682. }
  12683. var self = this;
  12684. var node = self.firstChild;
  12685. if (isNonEmptyElement(self)) {
  12686. return false;
  12687. }
  12688. if (node) {
  12689. do {
  12690. if (node.type === 1) {
  12691. if (node.attr('data-mce-bogus')) {
  12692. continue;
  12693. }
  12694. if (elements[node.name]) {
  12695. return false;
  12696. }
  12697. if (isNonEmptyElement(node)) {
  12698. return false;
  12699. }
  12700. }
  12701. if (node.type === 8) {
  12702. return false;
  12703. }
  12704. if (node.type === 3 && !isEmptyTextNode(node)) {
  12705. return false;
  12706. }
  12707. if (node.type === 3 && node.parent && whitespace[node.parent.name] && isWhitespaceText(node.value)) {
  12708. return false;
  12709. }
  12710. if (predicate && predicate(node)) {
  12711. return false;
  12712. }
  12713. } while (node = walk$1(node, self));
  12714. }
  12715. return true;
  12716. };
  12717. AstNode.prototype.walk = function (prev) {
  12718. return walk$1(this, null, prev);
  12719. };
  12720. return AstNode;
  12721. }();
  12722. var extractBase64DataUris = function (html) {
  12723. var dataImageUri = /data:[^;<"'\s]+;base64,([a-z0-9\+\/=\s]+)/gi;
  12724. var chunks = [];
  12725. var uris = {};
  12726. var prefix = generate('img');
  12727. var matches;
  12728. var index = 0;
  12729. var count = 0;
  12730. while (matches = dataImageUri.exec(html)) {
  12731. var uri = matches[0];
  12732. var imageId = prefix + '_' + count++;
  12733. uris[imageId] = uri;
  12734. if (index < matches.index) {
  12735. chunks.push(html.substr(index, matches.index - index));
  12736. }
  12737. chunks.push(imageId);
  12738. index = matches.index + uri.length;
  12739. }
  12740. var re = new RegExp(prefix + '_[0-9]+', 'g');
  12741. if (index === 0) {
  12742. return {
  12743. prefix: prefix,
  12744. uris: uris,
  12745. html: html,
  12746. re: re
  12747. };
  12748. } else {
  12749. if (index < html.length) {
  12750. chunks.push(html.substr(index));
  12751. }
  12752. return {
  12753. prefix: prefix,
  12754. uris: uris,
  12755. html: chunks.join(''),
  12756. re: re
  12757. };
  12758. }
  12759. };
  12760. var restoreDataUris = function (html, result) {
  12761. return html.replace(result.re, function (imageId) {
  12762. return get$9(result.uris, imageId).getOr(imageId);
  12763. });
  12764. };
  12765. var parseDataUri$1 = function (uri) {
  12766. var matches = /data:([^;]+);base64,([a-z0-9\+\/=\s]+)/i.exec(uri);
  12767. if (matches) {
  12768. return Optional.some({
  12769. type: matches[1],
  12770. data: decodeURIComponent(matches[2])
  12771. });
  12772. } else {
  12773. return Optional.none();
  12774. }
  12775. };
  12776. var each$d = Tools.each, trim = Tools.trim;
  12777. var queryParts = 'source protocol authority userInfo user password host port relative path directory file query anchor'.split(' ');
  12778. var DEFAULT_PORTS = {
  12779. ftp: 21,
  12780. http: 80,
  12781. https: 443,
  12782. mailto: 25
  12783. };
  12784. var safeSvgDataUrlElements = [
  12785. 'img',
  12786. 'video'
  12787. ];
  12788. var blockSvgDataUris = function (allowSvgDataUrls, tagName) {
  12789. if (isNonNullable(allowSvgDataUrls)) {
  12790. return !allowSvgDataUrls;
  12791. } else {
  12792. return isNonNullable(tagName) ? !contains$3(safeSvgDataUrlElements, tagName) : true;
  12793. }
  12794. };
  12795. var isInvalidUri = function (settings, uri, tagName) {
  12796. if (settings.allow_html_data_urls) {
  12797. return false;
  12798. } else if (/^data:image\//i.test(uri)) {
  12799. return blockSvgDataUris(settings.allow_svg_data_urls, tagName) && /^data:image\/svg\+xml/i.test(uri);
  12800. } else {
  12801. return /^data:/i.test(uri);
  12802. }
  12803. };
  12804. var URI = function () {
  12805. function URI(url, settings) {
  12806. url = trim(url);
  12807. this.settings = settings || {};
  12808. var baseUri = this.settings.base_uri;
  12809. var self = this;
  12810. if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
  12811. self.source = url;
  12812. return;
  12813. }
  12814. var isProtocolRelative = url.indexOf('//') === 0;
  12815. if (url.indexOf('/') === 0 && !isProtocolRelative) {
  12816. url = (baseUri ? baseUri.protocol || 'http' : 'http') + '://mce_host' + url;
  12817. }
  12818. if (!/^[\w\-]*:?\/\//.test(url)) {
  12819. var baseUrl = this.settings.base_uri ? this.settings.base_uri.path : new URI(document.location.href).directory;
  12820. if (this.settings.base_uri && this.settings.base_uri.protocol == '') {
  12821. url = '//mce_host' + self.toAbsPath(baseUrl, url);
  12822. } else {
  12823. var match = /([^#?]*)([#?]?.*)/.exec(url);
  12824. url = (baseUri && baseUri.protocol || 'http') + '://mce_host' + self.toAbsPath(baseUrl, match[1]) + match[2];
  12825. }
  12826. }
  12827. url = url.replace(/@@/g, '(mce_at)');
  12828. var urlMatch = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?(\[[a-zA-Z0-9:.%]+\]|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
  12829. each$d(queryParts, function (v, i) {
  12830. var part = urlMatch[i];
  12831. if (part) {
  12832. part = part.replace(/\(mce_at\)/g, '@@');
  12833. }
  12834. self[v] = part;
  12835. });
  12836. if (baseUri) {
  12837. if (!self.protocol) {
  12838. self.protocol = baseUri.protocol;
  12839. }
  12840. if (!self.userInfo) {
  12841. self.userInfo = baseUri.userInfo;
  12842. }
  12843. if (!self.port && self.host === 'mce_host') {
  12844. self.port = baseUri.port;
  12845. }
  12846. if (!self.host || self.host === 'mce_host') {
  12847. self.host = baseUri.host;
  12848. }
  12849. self.source = '';
  12850. }
  12851. if (isProtocolRelative) {
  12852. self.protocol = '';
  12853. }
  12854. }
  12855. URI.parseDataUri = function (uri) {
  12856. var type;
  12857. var uriComponents = decodeURIComponent(uri).split(',');
  12858. var matches = /data:([^;]+)/.exec(uriComponents[0]);
  12859. if (matches) {
  12860. type = matches[1];
  12861. }
  12862. return {
  12863. type: type,
  12864. data: uriComponents[1]
  12865. };
  12866. };
  12867. URI.isDomSafe = function (uri, context, options) {
  12868. if (options === void 0) {
  12869. options = {};
  12870. }
  12871. if (options.allow_script_urls) {
  12872. return true;
  12873. } else {
  12874. var decodedUri = Entities.decode(uri).replace(/[\s\u0000-\u001F]+/g, '');
  12875. try {
  12876. decodedUri = decodeURIComponent(decodedUri);
  12877. } catch (ex) {
  12878. decodedUri = unescape(decodedUri);
  12879. }
  12880. if (/((java|vb)script|mhtml):/i.test(decodedUri)) {
  12881. return false;
  12882. }
  12883. return !isInvalidUri(options, decodedUri, context);
  12884. }
  12885. };
  12886. URI.getDocumentBaseUrl = function (loc) {
  12887. var baseUrl;
  12888. if (loc.protocol.indexOf('http') !== 0 && loc.protocol !== 'file:') {
  12889. baseUrl = loc.href;
  12890. } else {
  12891. baseUrl = loc.protocol + '//' + loc.host + loc.pathname;
  12892. }
  12893. if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
  12894. baseUrl = baseUrl.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  12895. if (!/[\/\\]$/.test(baseUrl)) {
  12896. baseUrl += '/';
  12897. }
  12898. }
  12899. return baseUrl;
  12900. };
  12901. URI.prototype.setPath = function (path) {
  12902. var pathMatch = /^(.*?)\/?(\w+)?$/.exec(path);
  12903. this.path = pathMatch[0];
  12904. this.directory = pathMatch[1];
  12905. this.file = pathMatch[2];
  12906. this.source = '';
  12907. this.getURI();
  12908. };
  12909. URI.prototype.toRelative = function (uri) {
  12910. var output;
  12911. if (uri === './') {
  12912. return uri;
  12913. }
  12914. var relativeUri = new URI(uri, { base_uri: this });
  12915. if (relativeUri.host !== 'mce_host' && this.host !== relativeUri.host && relativeUri.host || this.port !== relativeUri.port || this.protocol !== relativeUri.protocol && relativeUri.protocol !== '') {
  12916. return relativeUri.getURI();
  12917. }
  12918. var tu = this.getURI(), uu = relativeUri.getURI();
  12919. if (tu === uu || tu.charAt(tu.length - 1) === '/' && tu.substr(0, tu.length - 1) === uu) {
  12920. return tu;
  12921. }
  12922. output = this.toRelPath(this.path, relativeUri.path);
  12923. if (relativeUri.query) {
  12924. output += '?' + relativeUri.query;
  12925. }
  12926. if (relativeUri.anchor) {
  12927. output += '#' + relativeUri.anchor;
  12928. }
  12929. return output;
  12930. };
  12931. URI.prototype.toAbsolute = function (uri, noHost) {
  12932. var absoluteUri = new URI(uri, { base_uri: this });
  12933. return absoluteUri.getURI(noHost && this.isSameOrigin(absoluteUri));
  12934. };
  12935. URI.prototype.isSameOrigin = function (uri) {
  12936. if (this.host == uri.host && this.protocol == uri.protocol) {
  12937. if (this.port == uri.port) {
  12938. return true;
  12939. }
  12940. var defaultPort = DEFAULT_PORTS[this.protocol];
  12941. if (defaultPort && (this.port || defaultPort) == (uri.port || defaultPort)) {
  12942. return true;
  12943. }
  12944. }
  12945. return false;
  12946. };
  12947. URI.prototype.toRelPath = function (base, path) {
  12948. var breakPoint = 0, out = '', i, l;
  12949. var normalizedBase = base.substring(0, base.lastIndexOf('/')).split('/');
  12950. var items = path.split('/');
  12951. if (normalizedBase.length >= items.length) {
  12952. for (i = 0, l = normalizedBase.length; i < l; i++) {
  12953. if (i >= items.length || normalizedBase[i] !== items[i]) {
  12954. breakPoint = i + 1;
  12955. break;
  12956. }
  12957. }
  12958. }
  12959. if (normalizedBase.length < items.length) {
  12960. for (i = 0, l = items.length; i < l; i++) {
  12961. if (i >= normalizedBase.length || normalizedBase[i] !== items[i]) {
  12962. breakPoint = i + 1;
  12963. break;
  12964. }
  12965. }
  12966. }
  12967. if (breakPoint === 1) {
  12968. return path;
  12969. }
  12970. for (i = 0, l = normalizedBase.length - (breakPoint - 1); i < l; i++) {
  12971. out += '../';
  12972. }
  12973. for (i = breakPoint - 1, l = items.length; i < l; i++) {
  12974. if (i !== breakPoint - 1) {
  12975. out += '/' + items[i];
  12976. } else {
  12977. out += items[i];
  12978. }
  12979. }
  12980. return out;
  12981. };
  12982. URI.prototype.toAbsPath = function (base, path) {
  12983. var i, nb = 0, o = [], outPath;
  12984. var tr = /\/$/.test(path) ? '/' : '';
  12985. var normalizedBase = base.split('/');
  12986. var normalizedPath = path.split('/');
  12987. each$d(normalizedBase, function (k) {
  12988. if (k) {
  12989. o.push(k);
  12990. }
  12991. });
  12992. normalizedBase = o;
  12993. for (i = normalizedPath.length - 1, o = []; i >= 0; i--) {
  12994. if (normalizedPath[i].length === 0 || normalizedPath[i] === '.') {
  12995. continue;
  12996. }
  12997. if (normalizedPath[i] === '..') {
  12998. nb++;
  12999. continue;
  13000. }
  13001. if (nb > 0) {
  13002. nb--;
  13003. continue;
  13004. }
  13005. o.push(normalizedPath[i]);
  13006. }
  13007. i = normalizedBase.length - nb;
  13008. if (i <= 0) {
  13009. outPath = reverse(o).join('/');
  13010. } else {
  13011. outPath = normalizedBase.slice(0, i).join('/') + '/' + reverse(o).join('/');
  13012. }
  13013. if (outPath.indexOf('/') !== 0) {
  13014. outPath = '/' + outPath;
  13015. }
  13016. if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) {
  13017. outPath += tr;
  13018. }
  13019. return outPath;
  13020. };
  13021. URI.prototype.getURI = function (noProtoHost) {
  13022. if (noProtoHost === void 0) {
  13023. noProtoHost = false;
  13024. }
  13025. var s;
  13026. if (!this.source || noProtoHost) {
  13027. s = '';
  13028. if (!noProtoHost) {
  13029. if (this.protocol) {
  13030. s += this.protocol + '://';
  13031. } else {
  13032. s += '//';
  13033. }
  13034. if (this.userInfo) {
  13035. s += this.userInfo + '@';
  13036. }
  13037. if (this.host) {
  13038. s += this.host;
  13039. }
  13040. if (this.port) {
  13041. s += ':' + this.port;
  13042. }
  13043. }
  13044. if (this.path) {
  13045. s += this.path;
  13046. }
  13047. if (this.query) {
  13048. s += '?' + this.query;
  13049. }
  13050. if (this.anchor) {
  13051. s += '#' + this.anchor;
  13052. }
  13053. this.source = s;
  13054. }
  13055. return this.source;
  13056. };
  13057. return URI;
  13058. }();
  13059. var filteredClobberElements = Tools.makeMap('button,fieldset,form,iframe,img,image,input,object,output,select,textarea');
  13060. var isValidPrefixAttrName = function (name) {
  13061. return name.indexOf('data-') === 0 || name.indexOf('aria-') === 0;
  13062. };
  13063. var findMatchingEndTagIndex = function (schema, html, startIndex) {
  13064. var startTagRegExp = /<([!?\/])?([A-Za-z0-9\-_:.]+)/g;
  13065. var endTagRegExp = /(?:\s(?:[^'">]+(?:"[^"]*"|'[^']*'))*[^"'>]*(?:"[^">]*|'[^'>]*)?|\s*|\/)>/g;
  13066. var shortEndedElements = schema.getShortEndedElements();
  13067. var count = 1, index = startIndex;
  13068. while (count !== 0) {
  13069. startTagRegExp.lastIndex = index;
  13070. while (true) {
  13071. var startMatch = startTagRegExp.exec(html);
  13072. if (startMatch === null) {
  13073. return index;
  13074. } else if (startMatch[1] === '!') {
  13075. if (startsWith(startMatch[2], '--')) {
  13076. index = findCommentEndIndex(html, false, startMatch.index + '!--'.length);
  13077. } else {
  13078. index = findCommentEndIndex(html, true, startMatch.index + 1);
  13079. }
  13080. break;
  13081. } else {
  13082. endTagRegExp.lastIndex = startTagRegExp.lastIndex;
  13083. var endMatch = endTagRegExp.exec(html);
  13084. if (isNull(endMatch) || endMatch.index !== startTagRegExp.lastIndex) {
  13085. continue;
  13086. }
  13087. if (startMatch[1] === '/') {
  13088. count -= 1;
  13089. } else if (!has$2(shortEndedElements, startMatch[2])) {
  13090. count += 1;
  13091. }
  13092. index = startTagRegExp.lastIndex + endMatch[0].length;
  13093. break;
  13094. }
  13095. }
  13096. }
  13097. return index;
  13098. };
  13099. var isConditionalComment = function (html, startIndex) {
  13100. return /^\s*\[if [\w\W]+\]>.*<!\[endif\](--!?)?>/.test(html.substr(startIndex));
  13101. };
  13102. var findCommentEndIndex = function (html, isBogus, startIndex) {
  13103. if (startIndex === void 0) {
  13104. startIndex = 0;
  13105. }
  13106. var lcHtml = html.toLowerCase();
  13107. if (lcHtml.indexOf('[if ', startIndex) !== -1 && isConditionalComment(lcHtml, startIndex)) {
  13108. var endIfIndex = lcHtml.indexOf('[endif]', startIndex);
  13109. return lcHtml.indexOf('>', endIfIndex);
  13110. } else {
  13111. if (isBogus) {
  13112. var endIndex = lcHtml.indexOf('>', startIndex);
  13113. return endIndex !== -1 ? endIndex : lcHtml.length;
  13114. } else {
  13115. var endCommentRegexp = /--!?>/g;
  13116. endCommentRegexp.lastIndex = startIndex;
  13117. var match = endCommentRegexp.exec(html);
  13118. return match ? match.index + match[0].length : lcHtml.length;
  13119. }
  13120. }
  13121. };
  13122. var checkBogusAttribute = function (regExp, attrString) {
  13123. var matches = regExp.exec(attrString);
  13124. if (matches) {
  13125. var name_1 = matches[1];
  13126. var value = matches[2];
  13127. return typeof name_1 === 'string' && name_1.toLowerCase() === 'data-mce-bogus' ? value : null;
  13128. } else {
  13129. return null;
  13130. }
  13131. };
  13132. var SaxParser = function (settings, schema) {
  13133. var _a;
  13134. if (schema === void 0) {
  13135. schema = Schema();
  13136. }
  13137. settings = settings || {};
  13138. var doc = (_a = settings.document) !== null && _a !== void 0 ? _a : document;
  13139. var form = doc.createElement('form');
  13140. if (settings.fix_self_closing !== false) {
  13141. settings.fix_self_closing = true;
  13142. }
  13143. var comment = settings.comment ? settings.comment : noop;
  13144. var cdata = settings.cdata ? settings.cdata : noop;
  13145. var text = settings.text ? settings.text : noop;
  13146. var start = settings.start ? settings.start : noop;
  13147. var end = settings.end ? settings.end : noop;
  13148. var pi = settings.pi ? settings.pi : noop;
  13149. var doctype = settings.doctype ? settings.doctype : noop;
  13150. var parseInternal = function (base64Extract, format) {
  13151. if (format === void 0) {
  13152. format = 'html';
  13153. }
  13154. var html = base64Extract.html;
  13155. var matches, index = 0, value, endRegExp;
  13156. var stack = [];
  13157. var attrList, i, textData, name;
  13158. var isInternalElement, isShortEnded;
  13159. var elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns;
  13160. var attributesRequired, attributesDefault, attributesForced;
  13161. var anyAttributesRequired, attrValue, idCount = 0;
  13162. var decode = Entities.decode;
  13163. var filteredUrlAttrs = Tools.makeMap('src,href,data,background,action,formaction,poster,xlink:href');
  13164. var parsingMode = format === 'html' ? 0 : 1;
  13165. var processEndTag = function (name) {
  13166. var pos, i;
  13167. pos = stack.length;
  13168. while (pos--) {
  13169. if (stack[pos].name === name) {
  13170. break;
  13171. }
  13172. }
  13173. if (pos >= 0) {
  13174. for (i = stack.length - 1; i >= pos; i--) {
  13175. name = stack[i];
  13176. if (name.valid) {
  13177. end(name.name);
  13178. }
  13179. }
  13180. stack.length = pos;
  13181. }
  13182. };
  13183. var processText = function (value, raw) {
  13184. return text(restoreDataUris(value, base64Extract), raw);
  13185. };
  13186. var processComment = function (value) {
  13187. if (value === '') {
  13188. return;
  13189. }
  13190. if (value.charAt(0) === '>') {
  13191. value = ' ' + value;
  13192. }
  13193. if (!settings.allow_conditional_comments && value.substr(0, 3).toLowerCase() === '[if') {
  13194. value = ' ' + value;
  13195. }
  13196. comment(restoreDataUris(value, base64Extract));
  13197. };
  13198. var processAttr = function (value) {
  13199. return restoreDataUris(value, base64Extract);
  13200. };
  13201. var processMalformedComment = function (value, startIndex) {
  13202. var startTag = value || '';
  13203. var isBogus = !startsWith(startTag, '--');
  13204. var endIndex = findCommentEndIndex(html, isBogus, startIndex);
  13205. value = html.substr(startIndex, endIndex - startIndex);
  13206. processComment(isBogus ? startTag + value : value);
  13207. return endIndex + 1;
  13208. };
  13209. var parseAttribute = function (tagName, name, value, val2, val3) {
  13210. name = name.toLowerCase();
  13211. value = processAttr(name in fillAttrsMap ? name : decode(value || val2 || val3 || ''));
  13212. if (validate && !isInternalElement && isValidPrefixAttrName(name) === false) {
  13213. var attrRule = validAttributesMap[name];
  13214. if (!attrRule && validAttributePatterns) {
  13215. var i_1 = validAttributePatterns.length;
  13216. while (i_1--) {
  13217. attrRule = validAttributePatterns[i_1];
  13218. if (attrRule.pattern.test(name)) {
  13219. break;
  13220. }
  13221. }
  13222. if (i_1 === -1) {
  13223. attrRule = null;
  13224. }
  13225. }
  13226. if (!attrRule) {
  13227. return;
  13228. }
  13229. if (attrRule.validValues && !(value in attrRule.validValues)) {
  13230. return;
  13231. }
  13232. }
  13233. var isNameOrId = name === 'name' || name === 'id';
  13234. if (isNameOrId && tagName in filteredClobberElements && (value in doc || value in form)) {
  13235. return;
  13236. }
  13237. if (filteredUrlAttrs[name] && !URI.isDomSafe(value, tagName, settings)) {
  13238. return;
  13239. }
  13240. if (isInternalElement && (name in filteredUrlAttrs || name.indexOf('on') === 0)) {
  13241. return;
  13242. }
  13243. attrList.map[name] = value;
  13244. attrList.push({
  13245. name: name,
  13246. value: value
  13247. });
  13248. };
  13249. 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');
  13250. var attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g;
  13251. var shortEndedElements = schema.getShortEndedElements();
  13252. var selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
  13253. var fillAttrsMap = schema.getBoolAttrs();
  13254. var validate = settings.validate;
  13255. var removeInternalElements = settings.remove_internals;
  13256. var fixSelfClosing = settings.fix_self_closing;
  13257. var specialElements = schema.getSpecialElements();
  13258. var processHtml = html + '>';
  13259. while (matches = tokenRegExp.exec(processHtml)) {
  13260. var matchText = matches[0];
  13261. if (index < matches.index) {
  13262. processText(decode(html.substr(index, matches.index - index)));
  13263. }
  13264. if (value = matches[7]) {
  13265. value = value.toLowerCase();
  13266. if (value.charAt(0) === ':') {
  13267. value = value.substr(1);
  13268. }
  13269. processEndTag(value);
  13270. } else if (value = matches[8]) {
  13271. if (matches.index + matchText.length > html.length) {
  13272. processText(decode(html.substr(matches.index)));
  13273. index = matches.index + matchText.length;
  13274. continue;
  13275. }
  13276. value = value.toLowerCase();
  13277. if (value.charAt(0) === ':') {
  13278. value = value.substr(1);
  13279. }
  13280. isShortEnded = value in shortEndedElements;
  13281. if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value) {
  13282. processEndTag(value);
  13283. }
  13284. var bogusValue = checkBogusAttribute(attrRegExp, matches[9]);
  13285. if (bogusValue !== null) {
  13286. if (bogusValue === 'all') {
  13287. index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
  13288. tokenRegExp.lastIndex = index;
  13289. continue;
  13290. }
  13291. isValidElement = false;
  13292. }
  13293. if (!validate || (elementRule = schema.getElementRule(value))) {
  13294. isValidElement = true;
  13295. if (validate) {
  13296. validAttributesMap = elementRule.attributes;
  13297. validAttributePatterns = elementRule.attributePatterns;
  13298. }
  13299. if (attribsValue = matches[9]) {
  13300. isInternalElement = attribsValue.indexOf('data-mce-type') !== -1;
  13301. if (isInternalElement && removeInternalElements) {
  13302. isValidElement = false;
  13303. }
  13304. attrList = [];
  13305. attrList.map = {};
  13306. attribsValue.replace(attrRegExp, function (match, name, val, val2, val3) {
  13307. parseAttribute(value, name, val, val2, val3);
  13308. return '';
  13309. });
  13310. } else {
  13311. attrList = [];
  13312. attrList.map = {};
  13313. }
  13314. if (validate && !isInternalElement) {
  13315. attributesRequired = elementRule.attributesRequired;
  13316. attributesDefault = elementRule.attributesDefault;
  13317. attributesForced = elementRule.attributesForced;
  13318. anyAttributesRequired = elementRule.removeEmptyAttrs;
  13319. if (anyAttributesRequired && !attrList.length) {
  13320. isValidElement = false;
  13321. }
  13322. if (attributesForced) {
  13323. i = attributesForced.length;
  13324. while (i--) {
  13325. attr = attributesForced[i];
  13326. name = attr.name;
  13327. attrValue = attr.value;
  13328. if (attrValue === '{$uid}') {
  13329. attrValue = 'mce_' + idCount++;
  13330. }
  13331. attrList.map[name] = attrValue;
  13332. attrList.push({
  13333. name: name,
  13334. value: attrValue
  13335. });
  13336. }
  13337. }
  13338. if (attributesDefault) {
  13339. i = attributesDefault.length;
  13340. while (i--) {
  13341. attr = attributesDefault[i];
  13342. name = attr.name;
  13343. if (!(name in attrList.map)) {
  13344. attrValue = attr.value;
  13345. if (attrValue === '{$uid}') {
  13346. attrValue = 'mce_' + idCount++;
  13347. }
  13348. attrList.map[name] = attrValue;
  13349. attrList.push({
  13350. name: name,
  13351. value: attrValue
  13352. });
  13353. }
  13354. }
  13355. }
  13356. if (attributesRequired) {
  13357. i = attributesRequired.length;
  13358. while (i--) {
  13359. if (attributesRequired[i] in attrList.map) {
  13360. break;
  13361. }
  13362. }
  13363. if (i === -1) {
  13364. isValidElement = false;
  13365. }
  13366. }
  13367. if (attr = attrList.map['data-mce-bogus']) {
  13368. if (attr === 'all') {
  13369. index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
  13370. tokenRegExp.lastIndex = index;
  13371. continue;
  13372. }
  13373. isValidElement = false;
  13374. }
  13375. }
  13376. if (isValidElement) {
  13377. start(value, attrList, isShortEnded);
  13378. }
  13379. } else {
  13380. isValidElement = false;
  13381. }
  13382. if (endRegExp = specialElements[value]) {
  13383. endRegExp.lastIndex = index = matches.index + matchText.length;
  13384. if (matches = endRegExp.exec(html)) {
  13385. if (isValidElement) {
  13386. textData = html.substr(index, matches.index - index);
  13387. }
  13388. index = matches.index + matches[0].length;
  13389. } else {
  13390. textData = html.substr(index);
  13391. index = html.length;
  13392. }
  13393. if (isValidElement) {
  13394. if (textData.length > 0) {
  13395. processText(textData, true);
  13396. }
  13397. end(value);
  13398. }
  13399. tokenRegExp.lastIndex = index;
  13400. continue;
  13401. }
  13402. if (!isShortEnded) {
  13403. if (!attribsValue || attribsValue.indexOf('/') !== attribsValue.length - 1) {
  13404. stack.push({
  13405. name: value,
  13406. valid: isValidElement
  13407. });
  13408. } else if (isValidElement) {
  13409. end(value);
  13410. }
  13411. }
  13412. } else if (value = matches[1]) {
  13413. processComment(value);
  13414. } else if (value = matches[2]) {
  13415. var isValidCdataSection = parsingMode === 1 || settings.preserve_cdata || stack.length > 0 && schema.isValidChild(stack[stack.length - 1].name, '#cdata');
  13416. if (isValidCdataSection) {
  13417. cdata(value);
  13418. } else {
  13419. index = processMalformedComment('', matches.index + 2);
  13420. tokenRegExp.lastIndex = index;
  13421. continue;
  13422. }
  13423. } else if (value = matches[3]) {
  13424. doctype(value);
  13425. } else if ((value = matches[4]) || matchText === '<!') {
  13426. index = processMalformedComment(value, matches.index + matchText.length);
  13427. tokenRegExp.lastIndex = index;
  13428. continue;
  13429. } else if (value = matches[5]) {
  13430. if (parsingMode === 1) {
  13431. pi(value, matches[6]);
  13432. } else {
  13433. index = processMalformedComment('?', matches.index + 2);
  13434. tokenRegExp.lastIndex = index;
  13435. continue;
  13436. }
  13437. }
  13438. index = matches.index + matchText.length;
  13439. }
  13440. if (index < html.length) {
  13441. processText(decode(html.substr(index)));
  13442. }
  13443. for (i = stack.length - 1; i >= 0; i--) {
  13444. value = stack[i];
  13445. if (value.valid) {
  13446. end(value.name);
  13447. }
  13448. }
  13449. };
  13450. var parse = function (html, format) {
  13451. if (format === void 0) {
  13452. format = 'html';
  13453. }
  13454. parseInternal(extractBase64DataUris(html), format);
  13455. };
  13456. return { parse: parse };
  13457. };
  13458. SaxParser.findEndTag = findMatchingEndTagIndex;
  13459. var trimHtml = function (tempAttrs, html) {
  13460. var trimContentRegExp = new RegExp(['\\s?(' + tempAttrs.join('|') + ')="[^"]+"'].join('|'), 'gi');
  13461. return html.replace(trimContentRegExp, '');
  13462. };
  13463. var trimInternal = function (serializer, html) {
  13464. var bogusAllRegExp = /<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g;
  13465. var schema = serializer.schema;
  13466. var content = trimHtml(serializer.getTempAttrs(), html);
  13467. var shortEndedElements = schema.getShortEndedElements();
  13468. var matches;
  13469. while (matches = bogusAllRegExp.exec(content)) {
  13470. var index = bogusAllRegExp.lastIndex;
  13471. var matchLength = matches[0].length;
  13472. var endTagIndex = void 0;
  13473. if (shortEndedElements[matches[1]]) {
  13474. endTagIndex = index;
  13475. } else {
  13476. endTagIndex = SaxParser.findEndTag(schema, content, index);
  13477. }
  13478. content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
  13479. bogusAllRegExp.lastIndex = index - matchLength;
  13480. }
  13481. return trim$2(content);
  13482. };
  13483. var trimExternal = trimInternal;
  13484. var trimEmptyContents = function (editor, html) {
  13485. var blockName = getForcedRootBlock(editor);
  13486. var emptyRegExp = new RegExp('^(<' + blockName + '[^>]*>(&nbsp;|&#160;|\\s|\xA0|<br \\/>|)<\\/' + blockName + '>[\r\n]*|<br \\/>[\r\n]*)$');
  13487. return html.replace(emptyRegExp, '');
  13488. };
  13489. var setupArgs$3 = function (args, format) {
  13490. return __assign(__assign({}, args), {
  13491. format: format,
  13492. get: true,
  13493. getInner: true
  13494. });
  13495. };
  13496. var getContentFromBody = function (editor, args, format, body) {
  13497. var defaultedArgs = setupArgs$3(args, format);
  13498. var updatedArgs = args.no_events ? defaultedArgs : editor.fire('BeforeGetContent', defaultedArgs);
  13499. var content;
  13500. if (updatedArgs.format === 'raw') {
  13501. content = Tools.trim(trimExternal(editor.serializer, body.innerHTML));
  13502. } else if (updatedArgs.format === 'text') {
  13503. content = editor.dom.isEmpty(body) ? '' : trim$2(body.innerText || body.textContent);
  13504. } else if (updatedArgs.format === 'tree') {
  13505. content = editor.serializer.serialize(body, updatedArgs);
  13506. } else {
  13507. content = trimEmptyContents(editor, editor.serializer.serialize(body, updatedArgs));
  13508. }
  13509. if (!contains$3([
  13510. 'text',
  13511. 'tree'
  13512. ], updatedArgs.format) && !isWsPreserveElement(SugarElement.fromDom(body))) {
  13513. updatedArgs.content = Tools.trim(content);
  13514. } else {
  13515. updatedArgs.content = content;
  13516. }
  13517. if (updatedArgs.no_events) {
  13518. return updatedArgs.content;
  13519. } else {
  13520. return editor.fire('GetContent', updatedArgs).content;
  13521. }
  13522. };
  13523. var getContentInternal = function (editor, args, format) {
  13524. return Optional.from(editor.getBody()).fold(constant(args.format === 'tree' ? new AstNode('body', 11) : ''), function (body) {
  13525. return getContentFromBody(editor, args, format, body);
  13526. });
  13527. };
  13528. var each$c = Tools.each;
  13529. var ElementUtils = function (dom) {
  13530. var compare = function (node1, node2) {
  13531. if (node1.nodeName !== node2.nodeName) {
  13532. return false;
  13533. }
  13534. var getAttribs = function (node) {
  13535. var attribs = {};
  13536. each$c(dom.getAttribs(node), function (attr) {
  13537. var name = attr.nodeName.toLowerCase();
  13538. if (name.indexOf('_') !== 0 && name !== 'style' && name.indexOf('data-') !== 0) {
  13539. attribs[name] = dom.getAttrib(node, name);
  13540. }
  13541. });
  13542. return attribs;
  13543. };
  13544. var compareObjects = function (obj1, obj2) {
  13545. var value, name;
  13546. for (name in obj1) {
  13547. if (has$2(obj1, name)) {
  13548. value = obj2[name];
  13549. if (typeof value === 'undefined') {
  13550. return false;
  13551. }
  13552. if (obj1[name] !== value) {
  13553. return false;
  13554. }
  13555. delete obj2[name];
  13556. }
  13557. }
  13558. for (name in obj2) {
  13559. if (has$2(obj2, name)) {
  13560. return false;
  13561. }
  13562. }
  13563. return true;
  13564. };
  13565. if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
  13566. return false;
  13567. }
  13568. if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
  13569. return false;
  13570. }
  13571. return !isBookmarkNode$1(node1) && !isBookmarkNode$1(node2);
  13572. };
  13573. return { compare: compare };
  13574. };
  13575. var makeMap$1 = Tools.makeMap;
  13576. var Writer = function (settings) {
  13577. var html = [];
  13578. settings = settings || {};
  13579. var indent = settings.indent;
  13580. var indentBefore = makeMap$1(settings.indent_before || '');
  13581. var indentAfter = makeMap$1(settings.indent_after || '');
  13582. var encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
  13583. var htmlOutput = settings.element_format === 'html';
  13584. return {
  13585. start: function (name, attrs, empty) {
  13586. var i, l, attr, value;
  13587. if (indent && indentBefore[name] && html.length > 0) {
  13588. value = html[html.length - 1];
  13589. if (value.length > 0 && value !== '\n') {
  13590. html.push('\n');
  13591. }
  13592. }
  13593. html.push('<', name);
  13594. if (attrs) {
  13595. for (i = 0, l = attrs.length; i < l; i++) {
  13596. attr = attrs[i];
  13597. html.push(' ', attr.name, '="', encode(attr.value, true), '"');
  13598. }
  13599. }
  13600. if (!empty || htmlOutput) {
  13601. html[html.length] = '>';
  13602. } else {
  13603. html[html.length] = ' />';
  13604. }
  13605. if (empty && indent && indentAfter[name] && html.length > 0) {
  13606. value = html[html.length - 1];
  13607. if (value.length > 0 && value !== '\n') {
  13608. html.push('\n');
  13609. }
  13610. }
  13611. },
  13612. end: function (name) {
  13613. var value;
  13614. html.push('</', name, '>');
  13615. if (indent && indentAfter[name] && html.length > 0) {
  13616. value = html[html.length - 1];
  13617. if (value.length > 0 && value !== '\n') {
  13618. html.push('\n');
  13619. }
  13620. }
  13621. },
  13622. text: function (text, raw) {
  13623. if (text.length > 0) {
  13624. html[html.length] = raw ? text : encode(text);
  13625. }
  13626. },
  13627. cdata: function (text) {
  13628. html.push('<![CDATA[', text, ']]>');
  13629. },
  13630. comment: function (text) {
  13631. html.push('<!--', text, '-->');
  13632. },
  13633. pi: function (name, text) {
  13634. if (text) {
  13635. html.push('<?', name, ' ', encode(text), '?>');
  13636. } else {
  13637. html.push('<?', name, '?>');
  13638. }
  13639. if (indent) {
  13640. html.push('\n');
  13641. }
  13642. },
  13643. doctype: function (text) {
  13644. html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
  13645. },
  13646. reset: function () {
  13647. html.length = 0;
  13648. },
  13649. getContent: function () {
  13650. return html.join('').replace(/\n$/, '');
  13651. }
  13652. };
  13653. };
  13654. var HtmlSerializer = function (settings, schema) {
  13655. if (schema === void 0) {
  13656. schema = Schema();
  13657. }
  13658. var writer = Writer(settings);
  13659. settings = settings || {};
  13660. settings.validate = 'validate' in settings ? settings.validate : true;
  13661. var serialize = function (node) {
  13662. var validate = settings.validate;
  13663. var handlers = {
  13664. 3: function (node) {
  13665. writer.text(node.value, node.raw);
  13666. },
  13667. 8: function (node) {
  13668. writer.comment(node.value);
  13669. },
  13670. 7: function (node) {
  13671. writer.pi(node.name, node.value);
  13672. },
  13673. 10: function (node) {
  13674. writer.doctype(node.value);
  13675. },
  13676. 4: function (node) {
  13677. writer.cdata(node.value);
  13678. },
  13679. 11: function (node) {
  13680. if (node = node.firstChild) {
  13681. do {
  13682. walk(node);
  13683. } while (node = node.next);
  13684. }
  13685. }
  13686. };
  13687. writer.reset();
  13688. var walk = function (node) {
  13689. var handler = handlers[node.type];
  13690. if (!handler) {
  13691. var name_1 = node.name;
  13692. var isEmpty = node.shortEnded;
  13693. var attrs = node.attributes;
  13694. if (validate && attrs && attrs.length > 1) {
  13695. var sortedAttrs = [];
  13696. sortedAttrs.map = {};
  13697. var elementRule = schema.getElementRule(node.name);
  13698. if (elementRule) {
  13699. for (var i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
  13700. var attrName = elementRule.attributesOrder[i];
  13701. if (attrName in attrs.map) {
  13702. var attrValue = attrs.map[attrName];
  13703. sortedAttrs.map[attrName] = attrValue;
  13704. sortedAttrs.push({
  13705. name: attrName,
  13706. value: attrValue
  13707. });
  13708. }
  13709. }
  13710. for (var i = 0, l = attrs.length; i < l; i++) {
  13711. var attrName = attrs[i].name;
  13712. if (!(attrName in sortedAttrs.map)) {
  13713. var attrValue = attrs.map[attrName];
  13714. sortedAttrs.map[attrName] = attrValue;
  13715. sortedAttrs.push({
  13716. name: attrName,
  13717. value: attrValue
  13718. });
  13719. }
  13720. }
  13721. attrs = sortedAttrs;
  13722. }
  13723. }
  13724. writer.start(node.name, attrs, isEmpty);
  13725. if (!isEmpty) {
  13726. if (node = node.firstChild) {
  13727. do {
  13728. walk(node);
  13729. } while (node = node.next);
  13730. }
  13731. writer.end(name_1);
  13732. }
  13733. } else {
  13734. handler(node);
  13735. }
  13736. };
  13737. if (node.type === 1 && !settings.inner) {
  13738. walk(node);
  13739. } else {
  13740. handlers[11](node);
  13741. }
  13742. return writer.getContent();
  13743. };
  13744. return { serialize: serialize };
  13745. };
  13746. var nonInheritableStyles = new Set();
  13747. (function () {
  13748. var nonInheritableStylesArr = [
  13749. 'margin',
  13750. 'margin-left',
  13751. 'margin-right',
  13752. 'margin-top',
  13753. 'margin-bottom',
  13754. 'padding',
  13755. 'padding-left',
  13756. 'padding-right',
  13757. 'padding-top',
  13758. 'padding-bottom',
  13759. 'border',
  13760. 'border-width',
  13761. 'border-style',
  13762. 'border-color',
  13763. 'background',
  13764. 'background-attachment',
  13765. 'background-clip',
  13766. 'background-color',
  13767. 'background-image',
  13768. 'background-origin',
  13769. 'background-position',
  13770. 'background-repeat',
  13771. 'background-size',
  13772. 'float',
  13773. 'position',
  13774. 'left',
  13775. 'right',
  13776. 'top',
  13777. 'bottom',
  13778. 'z-index',
  13779. 'display',
  13780. 'transform',
  13781. 'width',
  13782. 'max-width',
  13783. 'min-width',
  13784. 'height',
  13785. 'max-height',
  13786. 'min-height',
  13787. 'overflow',
  13788. 'overflow-x',
  13789. 'overflow-y',
  13790. 'text-overflow',
  13791. 'vertical-align',
  13792. 'transition',
  13793. 'transition-delay',
  13794. 'transition-duration',
  13795. 'transition-property',
  13796. 'transition-timing-function'
  13797. ];
  13798. each$k(nonInheritableStylesArr, function (style) {
  13799. nonInheritableStyles.add(style);
  13800. });
  13801. }());
  13802. var shorthandStyleProps = [
  13803. 'font',
  13804. 'text-decoration',
  13805. 'text-emphasis'
  13806. ];
  13807. var getStyleProps = function (dom, node) {
  13808. return keys(dom.parseStyle(dom.getAttrib(node, 'style')));
  13809. };
  13810. var isNonInheritableStyle = function (style) {
  13811. return nonInheritableStyles.has(style);
  13812. };
  13813. var hasInheritableStyles = function (dom, node) {
  13814. return forall(getStyleProps(dom, node), function (style) {
  13815. return !isNonInheritableStyle(style);
  13816. });
  13817. };
  13818. var getLonghandStyleProps = function (styles) {
  13819. return filter$4(styles, function (style) {
  13820. return exists(shorthandStyleProps, function (prop) {
  13821. return startsWith(style, prop);
  13822. });
  13823. });
  13824. };
  13825. var hasStyleConflict = function (dom, node, parentNode) {
  13826. var nodeStyleProps = getStyleProps(dom, node);
  13827. var parentNodeStyleProps = getStyleProps(dom, parentNode);
  13828. var valueMismatch = function (prop) {
  13829. var nodeValue = dom.getStyle(node, prop);
  13830. var parentValue = dom.getStyle(parentNode, prop);
  13831. return isNotEmpty(nodeValue) && isNotEmpty(parentValue) && nodeValue !== parentValue;
  13832. };
  13833. return exists(nodeStyleProps, function (nodeStyleProp) {
  13834. var propExists = function (props) {
  13835. return exists(props, function (prop) {
  13836. return prop === nodeStyleProp;
  13837. });
  13838. };
  13839. if (!propExists(parentNodeStyleProps) && propExists(shorthandStyleProps)) {
  13840. var longhandProps = getLonghandStyleProps(parentNodeStyleProps);
  13841. return exists(longhandProps, valueMismatch);
  13842. } else {
  13843. return valueMismatch(nodeStyleProp);
  13844. }
  13845. });
  13846. };
  13847. var isChar = function (forward, predicate, pos) {
  13848. return Optional.from(pos.container()).filter(isText$7).exists(function (text) {
  13849. var delta = forward ? 0 : -1;
  13850. return predicate(text.data.charAt(pos.offset() + delta));
  13851. });
  13852. };
  13853. var isBeforeSpace = curry(isChar, true, isWhiteSpace);
  13854. var isAfterSpace = curry(isChar, false, isWhiteSpace);
  13855. var isEmptyText = function (pos) {
  13856. var container = pos.container();
  13857. return isText$7(container) && (container.data.length === 0 || isZwsp(container.data) && BookmarkManager.isBookmarkNode(container.parentNode));
  13858. };
  13859. var matchesElementPosition = function (before, predicate) {
  13860. return function (pos) {
  13861. return Optional.from(getChildNodeAtRelativeOffset(before ? 0 : -1, pos)).filter(predicate).isSome();
  13862. };
  13863. };
  13864. var isImageBlock = function (node) {
  13865. return isImg(node) && get$5(SugarElement.fromDom(node), 'display') === 'block';
  13866. };
  13867. var isCefNode = function (node) {
  13868. return isContentEditableFalse$b(node) && !isBogusAll$1(node);
  13869. };
  13870. var isBeforeImageBlock = matchesElementPosition(true, isImageBlock);
  13871. var isAfterImageBlock = matchesElementPosition(false, isImageBlock);
  13872. var isBeforeMedia = matchesElementPosition(true, isMedia$2);
  13873. var isAfterMedia = matchesElementPosition(false, isMedia$2);
  13874. var isBeforeTable = matchesElementPosition(true, isTable$3);
  13875. var isAfterTable = matchesElementPosition(false, isTable$3);
  13876. var isBeforeContentEditableFalse = matchesElementPosition(true, isCefNode);
  13877. var isAfterContentEditableFalse = matchesElementPosition(false, isCefNode);
  13878. var getLastChildren = function (elm) {
  13879. var children = [];
  13880. var rawNode = elm.dom;
  13881. while (rawNode) {
  13882. children.push(SugarElement.fromDom(rawNode));
  13883. rawNode = rawNode.lastChild;
  13884. }
  13885. return children;
  13886. };
  13887. var removeTrailingBr = function (elm) {
  13888. var allBrs = descendants(elm, 'br');
  13889. var brs = filter$4(getLastChildren(elm).slice(-1), isBr$4);
  13890. if (allBrs.length === brs.length) {
  13891. each$k(brs, remove$7);
  13892. }
  13893. };
  13894. var fillWithPaddingBr = function (elm) {
  13895. empty(elm);
  13896. append$1(elm, SugarElement.fromHtml('<br data-mce-bogus="1">'));
  13897. };
  13898. var trimBlockTrailingBr = function (elm) {
  13899. lastChild(elm).each(function (lastChild) {
  13900. prevSibling(lastChild).each(function (lastChildPrevSibling) {
  13901. if (isBlock$2(elm) && isBr$4(lastChild) && isBlock$2(lastChildPrevSibling)) {
  13902. remove$7(lastChild);
  13903. }
  13904. });
  13905. });
  13906. };
  13907. var dropLast = function (xs) {
  13908. return xs.slice(0, -1);
  13909. };
  13910. var parentsUntil = function (start, root, predicate) {
  13911. if (contains$1(root, start)) {
  13912. return dropLast(parents$1(start, function (elm) {
  13913. return predicate(elm) || eq(elm, root);
  13914. }));
  13915. } else {
  13916. return [];
  13917. }
  13918. };
  13919. var parents = function (start, root) {
  13920. return parentsUntil(start, root, never);
  13921. };
  13922. var parentsAndSelf = function (start, root) {
  13923. return [start].concat(parents(start, root));
  13924. };
  13925. var navigateIgnoreEmptyTextNodes = function (forward, root, from) {
  13926. return navigateIgnore(forward, root, from, isEmptyText);
  13927. };
  13928. var getClosestBlock$1 = function (root, pos) {
  13929. return find$3(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  13930. };
  13931. var isAtBeforeAfterBlockBoundary = function (forward, root, pos) {
  13932. return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  13933. return getClosestBlock$1(root, pos).fold(function () {
  13934. return isInSameBlock(newPos, pos, root.dom) === false;
  13935. }, function (fromBlock) {
  13936. return isInSameBlock(newPos, pos, root.dom) === false && contains$1(fromBlock, SugarElement.fromDom(newPos.container()));
  13937. });
  13938. });
  13939. };
  13940. var isAtBlockBoundary = function (forward, root, pos) {
  13941. return getClosestBlock$1(root, pos).fold(function () {
  13942. return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  13943. return isInSameBlock(newPos, pos, root.dom) === false;
  13944. });
  13945. }, function (parent) {
  13946. return navigateIgnoreEmptyTextNodes(forward, parent.dom, pos).isNone();
  13947. });
  13948. };
  13949. var isAtStartOfBlock = curry(isAtBlockBoundary, false);
  13950. var isAtEndOfBlock = curry(isAtBlockBoundary, true);
  13951. var isBeforeBlock = curry(isAtBeforeAfterBlockBoundary, false);
  13952. var isAfterBlock = curry(isAtBeforeAfterBlockBoundary, true);
  13953. var isBr = function (pos) {
  13954. return getElementFromPosition(pos).exists(isBr$4);
  13955. };
  13956. var findBr = function (forward, root, pos) {
  13957. var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  13958. var scope = head(parentBlocks).getOr(root);
  13959. return fromPosition(forward, scope.dom, pos).filter(isBr);
  13960. };
  13961. var isBeforeBr$1 = function (root, pos) {
  13962. return getElementFromPosition(pos).exists(isBr$4) || findBr(true, root, pos).isSome();
  13963. };
  13964. var isAfterBr = function (root, pos) {
  13965. return getElementFromPrevPosition(pos).exists(isBr$4) || findBr(false, root, pos).isSome();
  13966. };
  13967. var findPreviousBr = curry(findBr, false);
  13968. var findNextBr = curry(findBr, true);
  13969. var isInMiddleOfText = function (pos) {
  13970. return CaretPosition.isTextPosition(pos) && !pos.isAtStart() && !pos.isAtEnd();
  13971. };
  13972. var getClosestBlock = function (root, pos) {
  13973. var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  13974. return head(parentBlocks).getOr(root);
  13975. };
  13976. var hasSpaceBefore = function (root, pos) {
  13977. if (isInMiddleOfText(pos)) {
  13978. return isAfterSpace(pos);
  13979. } else {
  13980. return isAfterSpace(pos) || prevPosition(getClosestBlock(root, pos).dom, pos).exists(isAfterSpace);
  13981. }
  13982. };
  13983. var hasSpaceAfter = function (root, pos) {
  13984. if (isInMiddleOfText(pos)) {
  13985. return isBeforeSpace(pos);
  13986. } else {
  13987. return isBeforeSpace(pos) || nextPosition(getClosestBlock(root, pos).dom, pos).exists(isBeforeSpace);
  13988. }
  13989. };
  13990. var isPreValue = function (value) {
  13991. return contains$3([
  13992. 'pre',
  13993. 'pre-wrap'
  13994. ], value);
  13995. };
  13996. var isInPre = function (pos) {
  13997. return getElementFromPosition(pos).bind(function (elm) {
  13998. return closest$3(elm, isElement$6);
  13999. }).exists(function (elm) {
  14000. return isPreValue(get$5(elm, 'white-space'));
  14001. });
  14002. };
  14003. var isAtBeginningOfBody = function (root, pos) {
  14004. return prevPosition(root.dom, pos).isNone();
  14005. };
  14006. var isAtEndOfBody = function (root, pos) {
  14007. return nextPosition(root.dom, pos).isNone();
  14008. };
  14009. var isAtLineBoundary = function (root, pos) {
  14010. return isAtBeginningOfBody(root, pos) || isAtEndOfBody(root, pos) || isAtStartOfBlock(root, pos) || isAtEndOfBlock(root, pos) || isAfterBr(root, pos) || isBeforeBr$1(root, pos);
  14011. };
  14012. var needsToHaveNbsp = function (root, pos) {
  14013. if (isInPre(pos)) {
  14014. return false;
  14015. } else {
  14016. return isAtLineBoundary(root, pos) || hasSpaceBefore(root, pos) || hasSpaceAfter(root, pos);
  14017. }
  14018. };
  14019. var needsToBeNbspLeft = function (root, pos) {
  14020. if (isInPre(pos)) {
  14021. return false;
  14022. } else {
  14023. return isAtStartOfBlock(root, pos) || isBeforeBlock(root, pos) || isAfterBr(root, pos) || hasSpaceBefore(root, pos);
  14024. }
  14025. };
  14026. var leanRight = function (pos) {
  14027. var container = pos.container();
  14028. var offset = pos.offset();
  14029. if (isText$7(container) && offset < container.data.length) {
  14030. return CaretPosition(container, offset + 1);
  14031. } else {
  14032. return pos;
  14033. }
  14034. };
  14035. var needsToBeNbspRight = function (root, pos) {
  14036. if (isInPre(pos)) {
  14037. return false;
  14038. } else {
  14039. return isAtEndOfBlock(root, pos) || isAfterBlock(root, pos) || isBeforeBr$1(root, pos) || hasSpaceAfter(root, pos);
  14040. }
  14041. };
  14042. var needsToBeNbsp = function (root, pos) {
  14043. return needsToBeNbspLeft(root, pos) || needsToBeNbspRight(root, leanRight(pos));
  14044. };
  14045. var isNbspAt = function (text, offset) {
  14046. return isNbsp(text.charAt(offset));
  14047. };
  14048. var hasNbsp = function (pos) {
  14049. var container = pos.container();
  14050. return isText$7(container) && contains$2(container.data, nbsp);
  14051. };
  14052. var normalizeNbspMiddle = function (text) {
  14053. var chars = text.split('');
  14054. return map$3(chars, function (chr, i) {
  14055. if (isNbsp(chr) && i > 0 && i < chars.length - 1 && isContent(chars[i - 1]) && isContent(chars[i + 1])) {
  14056. return ' ';
  14057. } else {
  14058. return chr;
  14059. }
  14060. }).join('');
  14061. };
  14062. var normalizeNbspAtStart = function (root, node) {
  14063. var text = node.data;
  14064. var firstPos = CaretPosition(node, 0);
  14065. if (isNbspAt(text, 0) && !needsToBeNbsp(root, firstPos)) {
  14066. node.data = ' ' + text.slice(1);
  14067. return true;
  14068. } else {
  14069. return false;
  14070. }
  14071. };
  14072. var normalizeNbspInMiddleOfTextNode = function (node) {
  14073. var text = node.data;
  14074. var newText = normalizeNbspMiddle(text);
  14075. if (newText !== text) {
  14076. node.data = newText;
  14077. return true;
  14078. } else {
  14079. return false;
  14080. }
  14081. };
  14082. var normalizeNbspAtEnd = function (root, node) {
  14083. var text = node.data;
  14084. var lastPos = CaretPosition(node, text.length - 1);
  14085. if (isNbspAt(text, text.length - 1) && !needsToBeNbsp(root, lastPos)) {
  14086. node.data = text.slice(0, -1) + ' ';
  14087. return true;
  14088. } else {
  14089. return false;
  14090. }
  14091. };
  14092. var normalizeNbsps = function (root, pos) {
  14093. return Optional.some(pos).filter(hasNbsp).bind(function (pos) {
  14094. var container = pos.container();
  14095. var normalized = normalizeNbspAtStart(root, container) || normalizeNbspInMiddleOfTextNode(container) || normalizeNbspAtEnd(root, container);
  14096. return normalized ? Optional.some(pos) : Optional.none();
  14097. });
  14098. };
  14099. var normalizeNbspsInEditor = function (editor) {
  14100. var root = SugarElement.fromDom(editor.getBody());
  14101. if (editor.selection.isCollapsed()) {
  14102. normalizeNbsps(root, CaretPosition.fromRangeStart(editor.selection.getRng())).each(function (pos) {
  14103. editor.selection.setRng(pos.toRange());
  14104. });
  14105. }
  14106. };
  14107. var normalizeContent = function (content, isStartOfContent, isEndOfContent) {
  14108. var result = foldl(content, function (acc, c) {
  14109. if (isWhiteSpace(c) || isNbsp(c)) {
  14110. if (acc.previousCharIsSpace || acc.str === '' && isStartOfContent || acc.str.length === content.length - 1 && isEndOfContent) {
  14111. return {
  14112. previousCharIsSpace: false,
  14113. str: acc.str + nbsp
  14114. };
  14115. } else {
  14116. return {
  14117. previousCharIsSpace: true,
  14118. str: acc.str + ' '
  14119. };
  14120. }
  14121. } else {
  14122. return {
  14123. previousCharIsSpace: false,
  14124. str: acc.str + c
  14125. };
  14126. }
  14127. }, {
  14128. previousCharIsSpace: false,
  14129. str: ''
  14130. });
  14131. return result.str;
  14132. };
  14133. var normalize$1 = function (node, offset, count) {
  14134. if (count === 0) {
  14135. return;
  14136. }
  14137. var elm = SugarElement.fromDom(node);
  14138. var root = ancestor$3(elm, isBlock$2).getOr(elm);
  14139. var whitespace = node.data.slice(offset, offset + count);
  14140. var isEndOfContent = offset + count >= node.data.length && needsToBeNbspRight(root, CaretPosition(node, node.data.length));
  14141. var isStartOfContent = offset === 0 && needsToBeNbspLeft(root, CaretPosition(node, 0));
  14142. node.replaceData(offset, count, normalizeContent(whitespace, isStartOfContent, isEndOfContent));
  14143. };
  14144. var normalizeWhitespaceAfter = function (node, offset) {
  14145. var content = node.data.slice(offset);
  14146. var whitespaceCount = content.length - lTrim(content).length;
  14147. normalize$1(node, offset, whitespaceCount);
  14148. };
  14149. var normalizeWhitespaceBefore = function (node, offset) {
  14150. var content = node.data.slice(0, offset);
  14151. var whitespaceCount = content.length - rTrim(content).length;
  14152. normalize$1(node, offset - whitespaceCount, whitespaceCount);
  14153. };
  14154. var mergeTextNodes = function (prevNode, nextNode, normalizeWhitespace, mergeToPrev) {
  14155. if (mergeToPrev === void 0) {
  14156. mergeToPrev = true;
  14157. }
  14158. var whitespaceOffset = rTrim(prevNode.data).length;
  14159. var newNode = mergeToPrev ? prevNode : nextNode;
  14160. var removeNode = mergeToPrev ? nextNode : prevNode;
  14161. if (mergeToPrev) {
  14162. newNode.appendData(removeNode.data);
  14163. } else {
  14164. newNode.insertData(0, removeNode.data);
  14165. }
  14166. remove$7(SugarElement.fromDom(removeNode));
  14167. if (normalizeWhitespace) {
  14168. normalizeWhitespaceAfter(newNode, whitespaceOffset);
  14169. }
  14170. return newNode;
  14171. };
  14172. var needsReposition = function (pos, elm) {
  14173. var container = pos.container();
  14174. var offset = pos.offset();
  14175. return CaretPosition.isTextPosition(pos) === false && container === elm.parentNode && offset > CaretPosition.before(elm).offset();
  14176. };
  14177. var reposition = function (elm, pos) {
  14178. return needsReposition(pos, elm) ? CaretPosition(pos.container(), pos.offset() - 1) : pos;
  14179. };
  14180. var beforeOrStartOf = function (node) {
  14181. return isText$7(node) ? CaretPosition(node, 0) : CaretPosition.before(node);
  14182. };
  14183. var afterOrEndOf = function (node) {
  14184. return isText$7(node) ? CaretPosition(node, node.data.length) : CaretPosition.after(node);
  14185. };
  14186. var getPreviousSiblingCaretPosition = function (elm) {
  14187. if (isCaretCandidate$3(elm.previousSibling)) {
  14188. return Optional.some(afterOrEndOf(elm.previousSibling));
  14189. } else {
  14190. return elm.previousSibling ? lastPositionIn(elm.previousSibling) : Optional.none();
  14191. }
  14192. };
  14193. var getNextSiblingCaretPosition = function (elm) {
  14194. if (isCaretCandidate$3(elm.nextSibling)) {
  14195. return Optional.some(beforeOrStartOf(elm.nextSibling));
  14196. } else {
  14197. return elm.nextSibling ? firstPositionIn(elm.nextSibling) : Optional.none();
  14198. }
  14199. };
  14200. var findCaretPositionBackwardsFromElm = function (rootElement, elm) {
  14201. var startPosition = CaretPosition.before(elm.previousSibling ? elm.previousSibling : elm.parentNode);
  14202. return prevPosition(rootElement, startPosition).fold(function () {
  14203. return nextPosition(rootElement, CaretPosition.after(elm));
  14204. }, Optional.some);
  14205. };
  14206. var findCaretPositionForwardsFromElm = function (rootElement, elm) {
  14207. return nextPosition(rootElement, CaretPosition.after(elm)).fold(function () {
  14208. return prevPosition(rootElement, CaretPosition.before(elm));
  14209. }, Optional.some);
  14210. };
  14211. var findCaretPositionBackwards = function (rootElement, elm) {
  14212. return getPreviousSiblingCaretPosition(elm).orThunk(function () {
  14213. return getNextSiblingCaretPosition(elm);
  14214. }).orThunk(function () {
  14215. return findCaretPositionBackwardsFromElm(rootElement, elm);
  14216. });
  14217. };
  14218. var findCaretPositionForward = function (rootElement, elm) {
  14219. return getNextSiblingCaretPosition(elm).orThunk(function () {
  14220. return getPreviousSiblingCaretPosition(elm);
  14221. }).orThunk(function () {
  14222. return findCaretPositionForwardsFromElm(rootElement, elm);
  14223. });
  14224. };
  14225. var findCaretPosition = function (forward, rootElement, elm) {
  14226. return forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
  14227. };
  14228. var findCaretPosOutsideElmAfterDelete = function (forward, rootElement, elm) {
  14229. return findCaretPosition(forward, rootElement, elm).map(curry(reposition, elm));
  14230. };
  14231. var setSelection$1 = function (editor, forward, pos) {
  14232. pos.fold(function () {
  14233. editor.focus();
  14234. }, function (pos) {
  14235. editor.selection.setRng(pos.toRange(), forward);
  14236. });
  14237. };
  14238. var eqRawNode = function (rawNode) {
  14239. return function (elm) {
  14240. return elm.dom === rawNode;
  14241. };
  14242. };
  14243. var isBlock = function (editor, elm) {
  14244. return elm && has$2(editor.schema.getBlockElements(), name(elm));
  14245. };
  14246. var paddEmptyBlock = function (elm) {
  14247. if (isEmpty$2(elm)) {
  14248. var br = SugarElement.fromHtml('<br data-mce-bogus="1">');
  14249. empty(elm);
  14250. append$1(elm, br);
  14251. return Optional.some(CaretPosition.before(br.dom));
  14252. } else {
  14253. return Optional.none();
  14254. }
  14255. };
  14256. var deleteNormalized = function (elm, afterDeletePosOpt, normalizeWhitespace) {
  14257. var prevTextOpt = prevSibling(elm).filter(isText$8);
  14258. var nextTextOpt = nextSibling(elm).filter(isText$8);
  14259. remove$7(elm);
  14260. return lift3(prevTextOpt, nextTextOpt, afterDeletePosOpt, function (prev, next, pos) {
  14261. var prevNode = prev.dom, nextNode = next.dom;
  14262. var offset = prevNode.data.length;
  14263. mergeTextNodes(prevNode, nextNode, normalizeWhitespace);
  14264. return pos.container() === nextNode ? CaretPosition(prevNode, offset) : pos;
  14265. }).orThunk(function () {
  14266. if (normalizeWhitespace) {
  14267. prevTextOpt.each(function (elm) {
  14268. return normalizeWhitespaceBefore(elm.dom, elm.dom.length);
  14269. });
  14270. nextTextOpt.each(function (elm) {
  14271. return normalizeWhitespaceAfter(elm.dom, 0);
  14272. });
  14273. }
  14274. return afterDeletePosOpt;
  14275. });
  14276. };
  14277. var isInlineElement = function (editor, element) {
  14278. return has$2(editor.schema.getTextInlineElements(), name(element));
  14279. };
  14280. var deleteElement$2 = function (editor, forward, elm, moveCaret) {
  14281. if (moveCaret === void 0) {
  14282. moveCaret = true;
  14283. }
  14284. var afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom);
  14285. var parentBlock = ancestor$3(elm, curry(isBlock, editor), eqRawNode(editor.getBody()));
  14286. var normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos, isInlineElement(editor, elm));
  14287. if (editor.dom.isEmpty(editor.getBody())) {
  14288. editor.setContent('');
  14289. editor.selection.setCursorLocation();
  14290. } else {
  14291. parentBlock.bind(paddEmptyBlock).fold(function () {
  14292. if (moveCaret) {
  14293. setSelection$1(editor, forward, normalizedAfterDeletePos);
  14294. }
  14295. }, function (paddPos) {
  14296. if (moveCaret) {
  14297. setSelection$1(editor, forward, Optional.some(paddPos));
  14298. }
  14299. });
  14300. }
  14301. };
  14302. var isRootFromElement = function (root) {
  14303. return function (cur) {
  14304. return eq(root, cur);
  14305. };
  14306. };
  14307. var getTableCells = function (table) {
  14308. return descendants(table, 'td,th');
  14309. };
  14310. var getTableDetailsFromRange = function (rng, isRoot) {
  14311. var getTable = function (node) {
  14312. return getClosestTable(SugarElement.fromDom(node), isRoot);
  14313. };
  14314. var startTable = getTable(rng.startContainer);
  14315. var endTable = getTable(rng.endContainer);
  14316. var isStartInTable = startTable.isSome();
  14317. var isEndInTable = endTable.isSome();
  14318. var isSameTable = lift2(startTable, endTable, eq).getOr(false);
  14319. var isMultiTable = !isSameTable && isStartInTable && isEndInTable;
  14320. return {
  14321. startTable: startTable,
  14322. endTable: endTable,
  14323. isStartInTable: isStartInTable,
  14324. isEndInTable: isEndInTable,
  14325. isSameTable: isSameTable,
  14326. isMultiTable: isMultiTable
  14327. };
  14328. };
  14329. var tableCellRng = function (start, end) {
  14330. return {
  14331. start: start,
  14332. end: end
  14333. };
  14334. };
  14335. var tableSelection = function (rng, table, cells) {
  14336. return {
  14337. rng: rng,
  14338. table: table,
  14339. cells: cells
  14340. };
  14341. };
  14342. var deleteAction = Adt.generate([
  14343. {
  14344. singleCellTable: [
  14345. 'rng',
  14346. 'cell'
  14347. ]
  14348. },
  14349. { fullTable: ['table'] },
  14350. {
  14351. partialTable: [
  14352. 'cells',
  14353. 'outsideDetails'
  14354. ]
  14355. },
  14356. {
  14357. multiTable: [
  14358. 'startTableCells',
  14359. 'endTableCells',
  14360. 'betweenRng'
  14361. ]
  14362. }
  14363. ]);
  14364. var getClosestCell$1 = function (container, isRoot) {
  14365. return closest$2(SugarElement.fromDom(container), 'td,th', isRoot);
  14366. };
  14367. var isExpandedCellRng = function (cellRng) {
  14368. return !eq(cellRng.start, cellRng.end);
  14369. };
  14370. var getTableFromCellRng = function (cellRng, isRoot) {
  14371. return getClosestTable(cellRng.start, isRoot).bind(function (startParentTable) {
  14372. return getClosestTable(cellRng.end, isRoot).bind(function (endParentTable) {
  14373. return someIf(eq(startParentTable, endParentTable), startParentTable);
  14374. });
  14375. });
  14376. };
  14377. var isSingleCellTable = function (cellRng, isRoot) {
  14378. return !isExpandedCellRng(cellRng) && getTableFromCellRng(cellRng, isRoot).exists(function (table) {
  14379. var rows = table.dom.rows;
  14380. return rows.length === 1 && rows[0].cells.length === 1;
  14381. });
  14382. };
  14383. var getCellRng = function (rng, isRoot) {
  14384. var startCell = getClosestCell$1(rng.startContainer, isRoot);
  14385. var endCell = getClosestCell$1(rng.endContainer, isRoot);
  14386. return lift2(startCell, endCell, tableCellRng);
  14387. };
  14388. var getCellRangeFromStartTable = function (isRoot) {
  14389. return function (startCell) {
  14390. return getClosestTable(startCell, isRoot).bind(function (table) {
  14391. return last$2(getTableCells(table)).map(function (endCell) {
  14392. return tableCellRng(startCell, endCell);
  14393. });
  14394. });
  14395. };
  14396. };
  14397. var getCellRangeFromEndTable = function (isRoot) {
  14398. return function (endCell) {
  14399. return getClosestTable(endCell, isRoot).bind(function (table) {
  14400. return head(getTableCells(table)).map(function (startCell) {
  14401. return tableCellRng(startCell, endCell);
  14402. });
  14403. });
  14404. };
  14405. };
  14406. var getTableSelectionFromCellRng = function (isRoot) {
  14407. return function (cellRng) {
  14408. return getTableFromCellRng(cellRng, isRoot).map(function (table) {
  14409. return tableSelection(cellRng, table, getTableCells(table));
  14410. });
  14411. };
  14412. };
  14413. var getTableSelections = function (cellRng, selectionDetails, rng, isRoot) {
  14414. if (rng.collapsed || !cellRng.forall(isExpandedCellRng)) {
  14415. return Optional.none();
  14416. } else if (selectionDetails.isSameTable) {
  14417. var sameTableSelection = cellRng.bind(getTableSelectionFromCellRng(isRoot));
  14418. return Optional.some({
  14419. start: sameTableSelection,
  14420. end: sameTableSelection
  14421. });
  14422. } else {
  14423. var startCell = getClosestCell$1(rng.startContainer, isRoot);
  14424. var endCell = getClosestCell$1(rng.endContainer, isRoot);
  14425. var startTableSelection = startCell.bind(getCellRangeFromStartTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  14426. var endTableSelection = endCell.bind(getCellRangeFromEndTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  14427. return Optional.some({
  14428. start: startTableSelection,
  14429. end: endTableSelection
  14430. });
  14431. }
  14432. };
  14433. var getCellIndex = function (cells, cell) {
  14434. return findIndex$2(cells, function (x) {
  14435. return eq(x, cell);
  14436. });
  14437. };
  14438. var getSelectedCells = function (tableSelection) {
  14439. return lift2(getCellIndex(tableSelection.cells, tableSelection.rng.start), getCellIndex(tableSelection.cells, tableSelection.rng.end), function (startIndex, endIndex) {
  14440. return tableSelection.cells.slice(startIndex, endIndex + 1);
  14441. });
  14442. };
  14443. var isSingleCellTableContentSelected = function (optCellRng, rng, isRoot) {
  14444. return optCellRng.exists(function (cellRng) {
  14445. return isSingleCellTable(cellRng, isRoot) && hasAllContentsSelected(cellRng.start, rng);
  14446. });
  14447. };
  14448. var unselectCells = function (rng, selectionDetails) {
  14449. var startTable = selectionDetails.startTable, endTable = selectionDetails.endTable;
  14450. var otherContentRng = rng.cloneRange();
  14451. startTable.each(function (table) {
  14452. return otherContentRng.setStartAfter(table.dom);
  14453. });
  14454. endTable.each(function (table) {
  14455. return otherContentRng.setEndBefore(table.dom);
  14456. });
  14457. return otherContentRng;
  14458. };
  14459. var handleSingleTable = function (cellRng, selectionDetails, rng, isRoot) {
  14460. return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function (_a) {
  14461. var start = _a.start, end = _a.end;
  14462. return start.or(end);
  14463. }).bind(function (tableSelection) {
  14464. var isSameTable = selectionDetails.isSameTable;
  14465. var selectedCells = getSelectedCells(tableSelection).getOr([]);
  14466. if (isSameTable && tableSelection.cells.length === selectedCells.length) {
  14467. return Optional.some(deleteAction.fullTable(tableSelection.table));
  14468. } else if (selectedCells.length > 0) {
  14469. if (isSameTable) {
  14470. return Optional.some(deleteAction.partialTable(selectedCells, Optional.none()));
  14471. } else {
  14472. var otherContentRng = unselectCells(rng, selectionDetails);
  14473. return Optional.some(deleteAction.partialTable(selectedCells, Optional.some(__assign(__assign({}, selectionDetails), { rng: otherContentRng }))));
  14474. }
  14475. } else {
  14476. return Optional.none();
  14477. }
  14478. });
  14479. };
  14480. var handleMultiTable = function (cellRng, selectionDetails, rng, isRoot) {
  14481. return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function (_a) {
  14482. var start = _a.start, end = _a.end;
  14483. var startTableSelectedCells = start.bind(getSelectedCells).getOr([]);
  14484. var endTableSelectedCells = end.bind(getSelectedCells).getOr([]);
  14485. if (startTableSelectedCells.length > 0 && endTableSelectedCells.length > 0) {
  14486. var otherContentRng = unselectCells(rng, selectionDetails);
  14487. return Optional.some(deleteAction.multiTable(startTableSelectedCells, endTableSelectedCells, otherContentRng));
  14488. } else {
  14489. return Optional.none();
  14490. }
  14491. });
  14492. };
  14493. var getActionFromRange = function (root, rng) {
  14494. var isRoot = isRootFromElement(root);
  14495. var optCellRng = getCellRng(rng, isRoot);
  14496. var selectionDetails = getTableDetailsFromRange(rng, isRoot);
  14497. if (isSingleCellTableContentSelected(optCellRng, rng, isRoot)) {
  14498. return optCellRng.map(function (cellRng) {
  14499. return deleteAction.singleCellTable(rng, cellRng.start);
  14500. });
  14501. } else if (selectionDetails.isMultiTable) {
  14502. return handleMultiTable(optCellRng, selectionDetails, rng, isRoot);
  14503. } else {
  14504. return handleSingleTable(optCellRng, selectionDetails, rng, isRoot);
  14505. }
  14506. };
  14507. var freefallRtl = function (root) {
  14508. var child = isComment$1(root) ? prevSibling(root) : lastChild(root);
  14509. return child.bind(freefallRtl).orThunk(function () {
  14510. return Optional.some(root);
  14511. });
  14512. };
  14513. var cleanCells = function (cells) {
  14514. return each$k(cells, function (cell) {
  14515. remove$6(cell, 'contenteditable');
  14516. fillWithPaddingBr(cell);
  14517. });
  14518. };
  14519. var getOutsideBlock = function (editor, container) {
  14520. return Optional.from(editor.dom.getParent(container, editor.dom.isBlock)).map(SugarElement.fromDom);
  14521. };
  14522. var handleEmptyBlock = function (editor, startInTable, emptyBlock) {
  14523. emptyBlock.each(function (block) {
  14524. if (startInTable) {
  14525. remove$7(block);
  14526. } else {
  14527. fillWithPaddingBr(block);
  14528. editor.selection.setCursorLocation(block.dom, 0);
  14529. }
  14530. });
  14531. };
  14532. var deleteContentInsideCell = function (editor, cell, rng, isFirstCellInSelection) {
  14533. var insideTableRng = rng.cloneRange();
  14534. if (isFirstCellInSelection) {
  14535. insideTableRng.setStart(rng.startContainer, rng.startOffset);
  14536. insideTableRng.setEndAfter(cell.dom.lastChild);
  14537. } else {
  14538. insideTableRng.setStartBefore(cell.dom.firstChild);
  14539. insideTableRng.setEnd(rng.endContainer, rng.endOffset);
  14540. }
  14541. deleteCellContents(editor, insideTableRng, cell, false);
  14542. };
  14543. var collapseAndRestoreCellSelection = function (editor) {
  14544. var selectedCells = getCellsFromEditor(editor);
  14545. var selectedNode = SugarElement.fromDom(editor.selection.getNode());
  14546. if (isTableCell$5(selectedNode.dom) && isEmpty$2(selectedNode)) {
  14547. editor.selection.setCursorLocation(selectedNode.dom, 0);
  14548. } else {
  14549. editor.selection.collapse(true);
  14550. }
  14551. if (selectedCells.length > 1 && exists(selectedCells, function (cell) {
  14552. return eq(cell, selectedNode);
  14553. })) {
  14554. set$1(selectedNode, 'data-mce-selected', '1');
  14555. }
  14556. };
  14557. var emptySingleTableCells = function (editor, cells, outsideDetails) {
  14558. var editorRng = editor.selection.getRng();
  14559. var cellsToClean = outsideDetails.bind(function (_a) {
  14560. var rng = _a.rng, isStartInTable = _a.isStartInTable;
  14561. var outsideBlock = getOutsideBlock(editor, isStartInTable ? rng.endContainer : rng.startContainer);
  14562. rng.deleteContents();
  14563. handleEmptyBlock(editor, isStartInTable, outsideBlock.filter(isEmpty$2));
  14564. var endPointCell = isStartInTable ? cells[0] : cells[cells.length - 1];
  14565. deleteContentInsideCell(editor, endPointCell, editorRng, isStartInTable);
  14566. if (!isEmpty$2(endPointCell)) {
  14567. return Optional.some(isStartInTable ? cells.slice(1) : cells.slice(0, -1));
  14568. } else {
  14569. return Optional.none();
  14570. }
  14571. }).getOr(cells);
  14572. cleanCells(cellsToClean);
  14573. collapseAndRestoreCellSelection(editor);
  14574. return true;
  14575. };
  14576. var emptyMultiTableCells = function (editor, startTableCells, endTableCells, betweenRng) {
  14577. var rng = editor.selection.getRng();
  14578. var startCell = startTableCells[0];
  14579. var endCell = endTableCells[endTableCells.length - 1];
  14580. deleteContentInsideCell(editor, startCell, rng, true);
  14581. deleteContentInsideCell(editor, endCell, rng, false);
  14582. var startTableCellsToClean = isEmpty$2(startCell) ? startTableCells : startTableCells.slice(1);
  14583. var endTableCellsToClean = isEmpty$2(endCell) ? endTableCells : endTableCells.slice(0, -1);
  14584. cleanCells(startTableCellsToClean.concat(endTableCellsToClean));
  14585. betweenRng.deleteContents();
  14586. collapseAndRestoreCellSelection(editor);
  14587. return true;
  14588. };
  14589. var deleteCellContents = function (editor, rng, cell, moveSelection) {
  14590. if (moveSelection === void 0) {
  14591. moveSelection = true;
  14592. }
  14593. rng.deleteContents();
  14594. var lastNode = freefallRtl(cell).getOr(cell);
  14595. var lastBlock = SugarElement.fromDom(editor.dom.getParent(lastNode.dom, editor.dom.isBlock));
  14596. if (isEmpty$2(lastBlock)) {
  14597. fillWithPaddingBr(lastBlock);
  14598. if (moveSelection) {
  14599. editor.selection.setCursorLocation(lastBlock.dom, 0);
  14600. }
  14601. }
  14602. if (!eq(cell, lastBlock)) {
  14603. var additionalCleanupNodes = is$1(parent(lastBlock), cell) ? [] : siblings(lastBlock);
  14604. each$k(additionalCleanupNodes.concat(children(cell)), function (node) {
  14605. if (!eq(node, lastBlock) && !contains$1(node, lastBlock) && isEmpty$2(node)) {
  14606. remove$7(node);
  14607. }
  14608. });
  14609. }
  14610. return true;
  14611. };
  14612. var deleteTableElement = function (editor, table) {
  14613. deleteElement$2(editor, false, table);
  14614. return true;
  14615. };
  14616. var deleteCellRange = function (editor, rootElm, rng) {
  14617. return getActionFromRange(rootElm, rng).map(function (action) {
  14618. return action.fold(curry(deleteCellContents, editor), curry(deleteTableElement, editor), curry(emptySingleTableCells, editor), curry(emptyMultiTableCells, editor));
  14619. });
  14620. };
  14621. var deleteCaptionRange = function (editor, caption) {
  14622. return emptyElement(editor, caption);
  14623. };
  14624. var deleteTableRange = function (editor, rootElm, rng, startElm) {
  14625. return getParentCaption(rootElm, startElm).fold(function () {
  14626. return deleteCellRange(editor, rootElm, rng);
  14627. }, function (caption) {
  14628. return deleteCaptionRange(editor, caption);
  14629. }).getOr(false);
  14630. };
  14631. var deleteRange$2 = function (editor, startElm, selectedCells) {
  14632. var rootNode = SugarElement.fromDom(editor.getBody());
  14633. var rng = editor.selection.getRng();
  14634. return selectedCells.length !== 0 ? emptySingleTableCells(editor, selectedCells, Optional.none()) : deleteTableRange(editor, rootNode, rng, startElm);
  14635. };
  14636. var getParentCell = function (rootElm, elm) {
  14637. return find$3(parentsAndSelf(elm, rootElm), isTableCell$4);
  14638. };
  14639. var getParentCaption = function (rootElm, elm) {
  14640. return find$3(parentsAndSelf(elm, rootElm), isTag('caption'));
  14641. };
  14642. var deleteBetweenCells = function (editor, rootElm, forward, fromCell, from) {
  14643. return navigate(forward, editor.getBody(), from).bind(function (to) {
  14644. return getParentCell(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCell) {
  14645. return eq(toCell, fromCell) === false;
  14646. });
  14647. });
  14648. };
  14649. var emptyElement = function (editor, elm) {
  14650. fillWithPaddingBr(elm);
  14651. editor.selection.setCursorLocation(elm.dom, 0);
  14652. return Optional.some(true);
  14653. };
  14654. var isDeleteOfLastCharPos = function (fromCaption, forward, from, to) {
  14655. return firstPositionIn(fromCaption.dom).bind(function (first) {
  14656. return lastPositionIn(fromCaption.dom).map(function (last) {
  14657. return forward ? from.isEqual(first) && to.isEqual(last) : from.isEqual(last) && to.isEqual(first);
  14658. });
  14659. }).getOr(true);
  14660. };
  14661. var emptyCaretCaption = function (editor, elm) {
  14662. return emptyElement(editor, elm);
  14663. };
  14664. var validateCaretCaption = function (rootElm, fromCaption, to) {
  14665. return getParentCaption(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCaption) {
  14666. return eq(toCaption, fromCaption) === false;
  14667. });
  14668. };
  14669. var deleteCaretInsideCaption = function (editor, rootElm, forward, fromCaption, from) {
  14670. return navigate(forward, editor.getBody(), from).bind(function (to) {
  14671. return isDeleteOfLastCharPos(fromCaption, forward, from, to) ? emptyCaretCaption(editor, fromCaption) : validateCaretCaption(rootElm, fromCaption, to);
  14672. }).or(Optional.some(true));
  14673. };
  14674. var deleteCaretCells = function (editor, forward, rootElm, startElm) {
  14675. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  14676. return getParentCell(rootElm, startElm).bind(function (fromCell) {
  14677. return isEmpty$2(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from);
  14678. }).getOr(false);
  14679. };
  14680. var deleteCaretCaption = function (editor, forward, rootElm, fromCaption) {
  14681. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  14682. return isEmpty$2(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from);
  14683. };
  14684. var isNearTable = function (forward, pos) {
  14685. return forward ? isBeforeTable(pos) : isAfterTable(pos);
  14686. };
  14687. var isBeforeOrAfterTable = function (editor, forward) {
  14688. var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  14689. return isNearTable(forward, fromPos) || fromPosition(forward, editor.getBody(), fromPos).exists(function (pos) {
  14690. return isNearTable(forward, pos);
  14691. });
  14692. };
  14693. var deleteCaret$3 = function (editor, forward, startElm) {
  14694. var rootElm = SugarElement.fromDom(editor.getBody());
  14695. return getParentCaption(rootElm, startElm).fold(function () {
  14696. return deleteCaretCells(editor, forward, rootElm, startElm) || isBeforeOrAfterTable(editor, forward);
  14697. }, function (fromCaption) {
  14698. return deleteCaretCaption(editor, forward, rootElm, fromCaption).getOr(false);
  14699. });
  14700. };
  14701. var backspaceDelete$9 = function (editor, forward) {
  14702. var startElm = SugarElement.fromDom(editor.selection.getStart(true));
  14703. var cells = getCellsFromEditor(editor);
  14704. return editor.selection.isCollapsed() && cells.length === 0 ? deleteCaret$3(editor, forward, startElm) : deleteRange$2(editor, startElm, cells);
  14705. };
  14706. var createRange = function (sc, so, ec, eo) {
  14707. var rng = document.createRange();
  14708. rng.setStart(sc, so);
  14709. rng.setEnd(ec, eo);
  14710. return rng;
  14711. };
  14712. var normalizeBlockSelectionRange = function (rng) {
  14713. var startPos = CaretPosition.fromRangeStart(rng);
  14714. var endPos = CaretPosition.fromRangeEnd(rng);
  14715. var rootNode = rng.commonAncestorContainer;
  14716. return fromPosition(false, rootNode, endPos).map(function (newEndPos) {
  14717. if (!isInSameBlock(startPos, endPos, rootNode) && isInSameBlock(startPos, newEndPos, rootNode)) {
  14718. return createRange(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
  14719. } else {
  14720. return rng;
  14721. }
  14722. }).getOr(rng);
  14723. };
  14724. var normalize = function (rng) {
  14725. return rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
  14726. };
  14727. var hasOnlyOneChild$1 = function (node) {
  14728. return node.firstChild && node.firstChild === node.lastChild;
  14729. };
  14730. var isPaddingNode = function (node) {
  14731. return node.name === 'br' || node.value === nbsp;
  14732. };
  14733. var isPaddedEmptyBlock = function (schema, node) {
  14734. var blockElements = schema.getBlockElements();
  14735. return blockElements[node.name] && hasOnlyOneChild$1(node) && isPaddingNode(node.firstChild);
  14736. };
  14737. var isEmptyFragmentElement = function (schema, node) {
  14738. var nonEmptyElements = schema.getNonEmptyElements();
  14739. return node && (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
  14740. };
  14741. var isListFragment = function (schema, fragment) {
  14742. var firstChild = fragment.firstChild;
  14743. var lastChild = fragment.lastChild;
  14744. if (firstChild && firstChild.name === 'meta') {
  14745. firstChild = firstChild.next;
  14746. }
  14747. if (lastChild && lastChild.attr('id') === 'mce_marker') {
  14748. lastChild = lastChild.prev;
  14749. }
  14750. if (isEmptyFragmentElement(schema, lastChild)) {
  14751. lastChild = lastChild.prev;
  14752. }
  14753. if (!firstChild || firstChild !== lastChild) {
  14754. return false;
  14755. }
  14756. return firstChild.name === 'ul' || firstChild.name === 'ol';
  14757. };
  14758. var cleanupDomFragment = function (domFragment) {
  14759. var firstChild = domFragment.firstChild;
  14760. var lastChild = domFragment.lastChild;
  14761. if (firstChild && firstChild.nodeName === 'META') {
  14762. firstChild.parentNode.removeChild(firstChild);
  14763. }
  14764. if (lastChild && lastChild.id === 'mce_marker') {
  14765. lastChild.parentNode.removeChild(lastChild);
  14766. }
  14767. return domFragment;
  14768. };
  14769. var toDomFragment = function (dom, serializer, fragment) {
  14770. var html = serializer.serialize(fragment);
  14771. var domFragment = dom.createFragment(html);
  14772. return cleanupDomFragment(domFragment);
  14773. };
  14774. var listItems = function (elm) {
  14775. return filter$4(elm.childNodes, function (child) {
  14776. return child.nodeName === 'LI';
  14777. });
  14778. };
  14779. var isPadding = function (node) {
  14780. return node.data === nbsp || isBr$5(node);
  14781. };
  14782. var isListItemPadded = function (node) {
  14783. return node && node.firstChild && node.firstChild === node.lastChild && isPadding(node.firstChild);
  14784. };
  14785. var isEmptyOrPadded = function (elm) {
  14786. return !elm.firstChild || isListItemPadded(elm);
  14787. };
  14788. var trimListItems = function (elms) {
  14789. return elms.length > 0 && isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
  14790. };
  14791. var getParentLi = function (dom, node) {
  14792. var parentBlock = dom.getParent(node, dom.isBlock);
  14793. return parentBlock && parentBlock.nodeName === 'LI' ? parentBlock : null;
  14794. };
  14795. var isParentBlockLi = function (dom, node) {
  14796. return !!getParentLi(dom, node);
  14797. };
  14798. var getSplit = function (parentNode, rng) {
  14799. var beforeRng = rng.cloneRange();
  14800. var afterRng = rng.cloneRange();
  14801. beforeRng.setStartBefore(parentNode);
  14802. afterRng.setEndAfter(parentNode);
  14803. return [
  14804. beforeRng.cloneContents(),
  14805. afterRng.cloneContents()
  14806. ];
  14807. };
  14808. var findFirstIn = function (node, rootNode) {
  14809. var caretPos = CaretPosition.before(node);
  14810. var caretWalker = CaretWalker(rootNode);
  14811. var newCaretPos = caretWalker.next(caretPos);
  14812. return newCaretPos ? newCaretPos.toRange() : null;
  14813. };
  14814. var findLastOf = function (node, rootNode) {
  14815. var caretPos = CaretPosition.after(node);
  14816. var caretWalker = CaretWalker(rootNode);
  14817. var newCaretPos = caretWalker.prev(caretPos);
  14818. return newCaretPos ? newCaretPos.toRange() : null;
  14819. };
  14820. var insertMiddle = function (target, elms, rootNode, rng) {
  14821. var parts = getSplit(target, rng);
  14822. var parentElm = target.parentNode;
  14823. parentElm.insertBefore(parts[0], target);
  14824. Tools.each(elms, function (li) {
  14825. parentElm.insertBefore(li, target);
  14826. });
  14827. parentElm.insertBefore(parts[1], target);
  14828. parentElm.removeChild(target);
  14829. return findLastOf(elms[elms.length - 1], rootNode);
  14830. };
  14831. var insertBefore$1 = function (target, elms, rootNode) {
  14832. var parentElm = target.parentNode;
  14833. Tools.each(elms, function (elm) {
  14834. parentElm.insertBefore(elm, target);
  14835. });
  14836. return findFirstIn(target, rootNode);
  14837. };
  14838. var insertAfter$1 = function (target, elms, rootNode, dom) {
  14839. dom.insertAfter(elms.reverse(), target);
  14840. return findLastOf(elms[0], rootNode);
  14841. };
  14842. var insertAtCaret$1 = function (serializer, dom, rng, fragment) {
  14843. var domFragment = toDomFragment(dom, serializer, fragment);
  14844. var liTarget = getParentLi(dom, rng.startContainer);
  14845. var liElms = trimListItems(listItems(domFragment.firstChild));
  14846. var BEGINNING = 1, END = 2;
  14847. var rootNode = dom.getRoot();
  14848. var isAt = function (location) {
  14849. var caretPos = CaretPosition.fromRangeStart(rng);
  14850. var caretWalker = CaretWalker(dom.getRoot());
  14851. var newPos = location === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
  14852. return newPos ? getParentLi(dom, newPos.getNode()) !== liTarget : true;
  14853. };
  14854. if (isAt(BEGINNING)) {
  14855. return insertBefore$1(liTarget, liElms, rootNode);
  14856. } else if (isAt(END)) {
  14857. return insertAfter$1(liTarget, liElms, rootNode, dom);
  14858. }
  14859. return insertMiddle(liTarget, liElms, rootNode, rng);
  14860. };
  14861. var trimOrPadLeftRight = function (dom, rng, html) {
  14862. var root = SugarElement.fromDom(dom.getRoot());
  14863. if (needsToBeNbspLeft(root, CaretPosition.fromRangeStart(rng))) {
  14864. html = html.replace(/^ /, '&nbsp;');
  14865. } else {
  14866. html = html.replace(/^&nbsp;/, ' ');
  14867. }
  14868. if (needsToBeNbspRight(root, CaretPosition.fromRangeEnd(rng))) {
  14869. html = html.replace(/(&nbsp;| )(<br( \/)>)?$/, '&nbsp;');
  14870. } else {
  14871. html = html.replace(/&nbsp;(<br( \/)?>)?$/, ' ');
  14872. }
  14873. return html;
  14874. };
  14875. var isTableCell$1 = isTableCell$5;
  14876. var isTableCellContentSelected = function (dom, rng, cell) {
  14877. if (cell !== null) {
  14878. var endCell = dom.getParent(rng.endContainer, isTableCell$1);
  14879. return cell === endCell && hasAllContentsSelected(SugarElement.fromDom(cell), rng);
  14880. } else {
  14881. return false;
  14882. }
  14883. };
  14884. var validInsertion = function (editor, value, parentNode) {
  14885. if (parentNode.getAttribute('data-mce-bogus') === 'all') {
  14886. parentNode.parentNode.insertBefore(editor.dom.createFragment(value), parentNode);
  14887. } else {
  14888. var node = parentNode.firstChild;
  14889. var node2 = parentNode.lastChild;
  14890. if (!node || node === node2 && node.nodeName === 'BR') {
  14891. editor.dom.setHTML(parentNode, value);
  14892. } else {
  14893. editor.selection.setContent(value);
  14894. }
  14895. }
  14896. };
  14897. var trimBrsFromTableCell = function (dom, elm) {
  14898. Optional.from(dom.getParent(elm, 'td,th')).map(SugarElement.fromDom).each(trimBlockTrailingBr);
  14899. };
  14900. var reduceInlineTextElements = function (editor, merge) {
  14901. var textInlineElements = editor.schema.getTextInlineElements();
  14902. var dom = editor.dom;
  14903. if (merge) {
  14904. var root_1 = editor.getBody();
  14905. var elementUtils_1 = ElementUtils(dom);
  14906. Tools.each(dom.select('*[data-mce-fragment]'), function (node) {
  14907. var isInline = isNonNullable(textInlineElements[node.nodeName.toLowerCase()]);
  14908. if (isInline && hasInheritableStyles(dom, node)) {
  14909. for (var parentNode = node.parentNode; isNonNullable(parentNode) && parentNode !== root_1; parentNode = parentNode.parentNode) {
  14910. var styleConflict = hasStyleConflict(dom, node, parentNode);
  14911. if (styleConflict) {
  14912. break;
  14913. }
  14914. if (elementUtils_1.compare(parentNode, node)) {
  14915. dom.remove(node, true);
  14916. break;
  14917. }
  14918. }
  14919. }
  14920. });
  14921. }
  14922. };
  14923. var markFragmentElements = function (fragment) {
  14924. var node = fragment;
  14925. while (node = node.walk()) {
  14926. if (node.type === 1) {
  14927. node.attr('data-mce-fragment', '1');
  14928. }
  14929. }
  14930. };
  14931. var unmarkFragmentElements = function (elm) {
  14932. Tools.each(elm.getElementsByTagName('*'), function (elm) {
  14933. elm.removeAttribute('data-mce-fragment');
  14934. });
  14935. };
  14936. var isPartOfFragment = function (node) {
  14937. return !!node.getAttribute('data-mce-fragment');
  14938. };
  14939. var canHaveChildren = function (editor, node) {
  14940. return node && !editor.schema.getShortEndedElements()[node.nodeName];
  14941. };
  14942. var moveSelectionToMarker = function (editor, marker) {
  14943. var nextRng;
  14944. var dom = editor.dom;
  14945. var selection = editor.selection;
  14946. if (!marker) {
  14947. return;
  14948. }
  14949. selection.scrollIntoView(marker);
  14950. var parentEditableElm = getContentEditableRoot$1(editor.getBody(), marker);
  14951. if (dom.getContentEditable(parentEditableElm) === 'false') {
  14952. dom.remove(marker);
  14953. selection.select(parentEditableElm);
  14954. return;
  14955. }
  14956. var rng = dom.createRng();
  14957. var node = marker.previousSibling;
  14958. if (isText$7(node)) {
  14959. rng.setStart(node, node.nodeValue.length);
  14960. if (!Env.ie) {
  14961. var node2 = marker.nextSibling;
  14962. if (isText$7(node2)) {
  14963. node.appendData(node2.data);
  14964. node2.parentNode.removeChild(node2);
  14965. }
  14966. }
  14967. } else {
  14968. rng.setStartBefore(marker);
  14969. rng.setEndBefore(marker);
  14970. }
  14971. var findNextCaretRng = function (rng) {
  14972. var caretPos = CaretPosition.fromRangeStart(rng);
  14973. var caretWalker = CaretWalker(editor.getBody());
  14974. caretPos = caretWalker.next(caretPos);
  14975. if (caretPos) {
  14976. return caretPos.toRange();
  14977. }
  14978. };
  14979. var parentBlock = dom.getParent(marker, dom.isBlock);
  14980. dom.remove(marker);
  14981. if (parentBlock && dom.isEmpty(parentBlock)) {
  14982. editor.$(parentBlock).empty();
  14983. rng.setStart(parentBlock, 0);
  14984. rng.setEnd(parentBlock, 0);
  14985. if (!isTableCell$1(parentBlock) && !isPartOfFragment(parentBlock) && (nextRng = findNextCaretRng(rng))) {
  14986. rng = nextRng;
  14987. dom.remove(parentBlock);
  14988. } else {
  14989. dom.add(parentBlock, dom.create('br', { 'data-mce-bogus': '1' }));
  14990. }
  14991. }
  14992. selection.setRng(rng);
  14993. };
  14994. var deleteSelectedContent = function (editor) {
  14995. var dom = editor.dom;
  14996. var rng = normalize(editor.selection.getRng());
  14997. editor.selection.setRng(rng);
  14998. var startCell = dom.getParent(rng.startContainer, isTableCell$1);
  14999. if (isTableCellContentSelected(dom, rng, startCell)) {
  15000. deleteCellContents(editor, rng, SugarElement.fromDom(startCell));
  15001. } else {
  15002. editor.getDoc().execCommand('Delete', false, null);
  15003. }
  15004. };
  15005. var insertHtmlAtCaret = function (editor, value, details) {
  15006. var parentNode;
  15007. var rng, node;
  15008. var selection = editor.selection;
  15009. var dom = editor.dom;
  15010. if (/^ | $/.test(value)) {
  15011. value = trimOrPadLeftRight(dom, selection.getRng(), value);
  15012. }
  15013. var parser = editor.parser;
  15014. var merge = details.merge;
  15015. var serializer = HtmlSerializer({ validate: shouldValidate(editor) }, editor.schema);
  15016. var bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>';
  15017. var args = editor.fire('BeforeSetContent', {
  15018. content: value,
  15019. format: 'html',
  15020. selection: true,
  15021. paste: details.paste
  15022. });
  15023. if (args.isDefaultPrevented()) {
  15024. editor.fire('SetContent', {
  15025. content: args.content,
  15026. format: 'html',
  15027. selection: true,
  15028. paste: details.paste
  15029. });
  15030. return;
  15031. }
  15032. value = args.content;
  15033. if (value.indexOf('{$caret}') === -1) {
  15034. value += '{$caret}';
  15035. }
  15036. value = value.replace(/\{\$caret\}/, bookmarkHtml);
  15037. rng = selection.getRng();
  15038. var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
  15039. var body = editor.getBody();
  15040. if (caretElement === body && selection.isCollapsed()) {
  15041. if (dom.isBlock(body.firstChild) && canHaveChildren(editor, body.firstChild) && dom.isEmpty(body.firstChild)) {
  15042. rng = dom.createRng();
  15043. rng.setStart(body.firstChild, 0);
  15044. rng.setEnd(body.firstChild, 0);
  15045. selection.setRng(rng);
  15046. }
  15047. }
  15048. if (!selection.isCollapsed()) {
  15049. deleteSelectedContent(editor);
  15050. }
  15051. parentNode = selection.getNode();
  15052. var parserArgs = {
  15053. context: parentNode.nodeName.toLowerCase(),
  15054. data: details.data,
  15055. insert: true
  15056. };
  15057. var fragment = parser.parse(value, parserArgs);
  15058. if (details.paste === true && isListFragment(editor.schema, fragment) && isParentBlockLi(dom, parentNode)) {
  15059. rng = insertAtCaret$1(serializer, dom, selection.getRng(), fragment);
  15060. selection.setRng(rng);
  15061. editor.fire('SetContent', args);
  15062. return;
  15063. }
  15064. markFragmentElements(fragment);
  15065. node = fragment.lastChild;
  15066. if (node.attr('id') === 'mce_marker') {
  15067. var marker = node;
  15068. for (node = node.prev; node; node = node.walk(true)) {
  15069. if (node.type === 3 || !dom.isBlock(node.name)) {
  15070. if (editor.schema.isValidChild(node.parent.name, 'span')) {
  15071. node.parent.insert(marker, node, node.name === 'br');
  15072. }
  15073. break;
  15074. }
  15075. }
  15076. }
  15077. editor._selectionOverrides.showBlockCaretContainer(parentNode);
  15078. if (!parserArgs.invalid) {
  15079. value = serializer.serialize(fragment);
  15080. validInsertion(editor, value, parentNode);
  15081. } else {
  15082. editor.selection.setContent(bookmarkHtml);
  15083. parentNode = selection.getNode();
  15084. var rootNode = editor.getBody();
  15085. if (parentNode.nodeType === 9) {
  15086. parentNode = node = rootNode;
  15087. } else {
  15088. node = parentNode;
  15089. }
  15090. while (node !== rootNode) {
  15091. parentNode = node;
  15092. node = node.parentNode;
  15093. }
  15094. value = parentNode === rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
  15095. value = serializer.serialize(parser.parse(value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function () {
  15096. return serializer.serialize(fragment);
  15097. })));
  15098. if (parentNode === rootNode) {
  15099. dom.setHTML(rootNode, value);
  15100. } else {
  15101. dom.setOuterHTML(parentNode, value);
  15102. }
  15103. }
  15104. reduceInlineTextElements(editor, merge);
  15105. moveSelectionToMarker(editor, dom.get('mce_marker'));
  15106. unmarkFragmentElements(editor.getBody());
  15107. trimBrsFromTableCell(dom, selection.getStart());
  15108. editor.fire('SetContent', args);
  15109. editor.addVisual();
  15110. };
  15111. var traverse = function (node, fn) {
  15112. fn(node);
  15113. if (node.firstChild) {
  15114. traverse(node.firstChild, fn);
  15115. }
  15116. if (node.next) {
  15117. traverse(node.next, fn);
  15118. }
  15119. };
  15120. var findMatchingNodes = function (nodeFilters, attributeFilters, node) {
  15121. var nodeMatches = {};
  15122. var attrMatches = {};
  15123. var matches = [];
  15124. if (node.firstChild) {
  15125. traverse(node.firstChild, function (node) {
  15126. each$k(nodeFilters, function (filter) {
  15127. if (filter.name === node.name) {
  15128. if (nodeMatches[filter.name]) {
  15129. nodeMatches[filter.name].nodes.push(node);
  15130. } else {
  15131. nodeMatches[filter.name] = {
  15132. filter: filter,
  15133. nodes: [node]
  15134. };
  15135. }
  15136. }
  15137. });
  15138. each$k(attributeFilters, function (filter) {
  15139. if (typeof node.attr(filter.name) === 'string') {
  15140. if (attrMatches[filter.name]) {
  15141. attrMatches[filter.name].nodes.push(node);
  15142. } else {
  15143. attrMatches[filter.name] = {
  15144. filter: filter,
  15145. nodes: [node]
  15146. };
  15147. }
  15148. }
  15149. });
  15150. });
  15151. }
  15152. for (var name_1 in nodeMatches) {
  15153. if (has$2(nodeMatches, name_1)) {
  15154. matches.push(nodeMatches[name_1]);
  15155. }
  15156. }
  15157. for (var name_2 in attrMatches) {
  15158. if (has$2(attrMatches, name_2)) {
  15159. matches.push(attrMatches[name_2]);
  15160. }
  15161. }
  15162. return matches;
  15163. };
  15164. var filter$1 = function (nodeFilters, attributeFilters, node) {
  15165. var matches = findMatchingNodes(nodeFilters, attributeFilters, node);
  15166. each$k(matches, function (match) {
  15167. each$k(match.filter.callbacks, function (callback) {
  15168. callback(match.nodes, match.filter.name, {});
  15169. });
  15170. });
  15171. };
  15172. var defaultFormat$1 = 'html';
  15173. var isTreeNode = function (content) {
  15174. return content instanceof AstNode;
  15175. };
  15176. var moveSelection = function (editor) {
  15177. if (hasFocus(editor)) {
  15178. firstPositionIn(editor.getBody()).each(function (pos) {
  15179. var node = pos.getNode();
  15180. var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  15181. editor.selection.setRng(caretPos.toRange());
  15182. });
  15183. }
  15184. };
  15185. var setEditorHtml = function (editor, html, noSelection) {
  15186. editor.dom.setHTML(editor.getBody(), html);
  15187. if (noSelection !== true) {
  15188. moveSelection(editor);
  15189. }
  15190. };
  15191. var setContentString = function (editor, body, content, args) {
  15192. if (content.length === 0 || /^\s+$/.test(content)) {
  15193. var padd = '<br data-mce-bogus="1">';
  15194. if (body.nodeName === 'TABLE') {
  15195. content = '<tr><td>' + padd + '</td></tr>';
  15196. } else if (/^(UL|OL)$/.test(body.nodeName)) {
  15197. content = '<li>' + padd + '</li>';
  15198. }
  15199. var forcedRootBlockName = getForcedRootBlock(editor);
  15200. if (forcedRootBlockName && editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
  15201. content = padd;
  15202. content = editor.dom.createHTML(forcedRootBlockName, getForcedRootBlockAttrs(editor), content);
  15203. } else if (!content) {
  15204. content = '<br data-mce-bogus="1">';
  15205. }
  15206. setEditorHtml(editor, content, args.no_selection);
  15207. editor.fire('SetContent', args);
  15208. } else {
  15209. if (args.format !== 'raw') {
  15210. content = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(editor.parser.parse(content, {
  15211. isRootContent: true,
  15212. insert: true
  15213. }));
  15214. }
  15215. args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? content : Tools.trim(content);
  15216. setEditorHtml(editor, args.content, args.no_selection);
  15217. if (!args.no_events) {
  15218. editor.fire('SetContent', args);
  15219. }
  15220. }
  15221. return args.content;
  15222. };
  15223. var setContentTree = function (editor, body, content, args) {
  15224. filter$1(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
  15225. var html = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(content);
  15226. args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? html : Tools.trim(html);
  15227. setEditorHtml(editor, args.content, args.no_selection);
  15228. if (!args.no_events) {
  15229. editor.fire('SetContent', args);
  15230. }
  15231. return content;
  15232. };
  15233. var setupArgs$2 = function (args, content) {
  15234. return __assign(__assign({ format: defaultFormat$1 }, args), {
  15235. set: true,
  15236. content: isTreeNode(content) ? '' : content
  15237. });
  15238. };
  15239. var setContentInternal = function (editor, content, args) {
  15240. var defaultedArgs = setupArgs$2(args, content);
  15241. var updatedArgs = args.no_events ? defaultedArgs : editor.fire('BeforeSetContent', defaultedArgs);
  15242. if (!isTreeNode(content)) {
  15243. content = updatedArgs.content;
  15244. }
  15245. return Optional.from(editor.getBody()).fold(constant(content), function (body) {
  15246. return isTreeNode(content) ? setContentTree(editor, body, content, updatedArgs) : setContentString(editor, body, content, updatedArgs);
  15247. });
  15248. };
  15249. var sibling = function (scope, predicate) {
  15250. return sibling$2(scope, predicate).isSome();
  15251. };
  15252. var ensureIsRoot = function (isRoot) {
  15253. return isFunction(isRoot) ? isRoot : never;
  15254. };
  15255. var ancestor = function (scope, transform, isRoot) {
  15256. var element = scope.dom;
  15257. var stop = ensureIsRoot(isRoot);
  15258. while (element.parentNode) {
  15259. element = element.parentNode;
  15260. var el = SugarElement.fromDom(element);
  15261. var transformed = transform(el);
  15262. if (transformed.isSome()) {
  15263. return transformed;
  15264. } else if (stop(el)) {
  15265. break;
  15266. }
  15267. }
  15268. return Optional.none();
  15269. };
  15270. var closest$1 = function (scope, transform, isRoot) {
  15271. var current = transform(scope);
  15272. var stop = ensureIsRoot(isRoot);
  15273. return current.orThunk(function () {
  15274. return stop(scope) ? Optional.none() : ancestor(scope, transform, stop);
  15275. });
  15276. };
  15277. var isEq$3 = isEq$5;
  15278. var matchesUnInheritedFormatSelector = function (ed, node, name) {
  15279. var formatList = ed.formatter.get(name);
  15280. if (formatList) {
  15281. for (var i = 0; i < formatList.length; i++) {
  15282. var format = formatList[i];
  15283. if (isSelectorFormat(format) && format.inherit === false && ed.dom.is(node, format.selector)) {
  15284. return true;
  15285. }
  15286. }
  15287. }
  15288. return false;
  15289. };
  15290. var matchParents = function (editor, node, name, vars, similar) {
  15291. var root = editor.dom.getRoot();
  15292. if (node === root) {
  15293. return false;
  15294. }
  15295. node = editor.dom.getParent(node, function (node) {
  15296. if (matchesUnInheritedFormatSelector(editor, node, name)) {
  15297. return true;
  15298. }
  15299. return node.parentNode === root || !!matchNode(editor, node, name, vars, true);
  15300. });
  15301. return !!matchNode(editor, node, name, vars, similar);
  15302. };
  15303. var matchName$1 = function (dom, node, format) {
  15304. if (isEq$3(node, format.inline)) {
  15305. return true;
  15306. }
  15307. if (isEq$3(node, format.block)) {
  15308. return true;
  15309. }
  15310. if (format.selector) {
  15311. return node.nodeType === 1 && dom.is(node, format.selector);
  15312. }
  15313. };
  15314. var matchItems = function (dom, node, format, itemName, similar, vars) {
  15315. var items = format[itemName];
  15316. if (isFunction(format.onmatch)) {
  15317. return format.onmatch(node, format, itemName);
  15318. }
  15319. if (items) {
  15320. if (isUndefined(items.length)) {
  15321. for (var key in items) {
  15322. if (has$2(items, key)) {
  15323. var value = itemName === 'attributes' ? dom.getAttrib(node, key) : getStyle(dom, node, key);
  15324. var expectedValue = replaceVars(items[key], vars);
  15325. var isEmptyValue = isNullable(value) || isEmpty$3(value);
  15326. if (isEmptyValue && isNullable(expectedValue)) {
  15327. continue;
  15328. }
  15329. if (similar && isEmptyValue && !format.exact) {
  15330. return false;
  15331. }
  15332. if ((!similar || format.exact) && !isEq$3(value, normalizeStyleValue(dom, expectedValue, key))) {
  15333. return false;
  15334. }
  15335. }
  15336. }
  15337. } else {
  15338. for (var i = 0; i < items.length; i++) {
  15339. if (itemName === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(dom, node, items[i])) {
  15340. return true;
  15341. }
  15342. }
  15343. }
  15344. }
  15345. return true;
  15346. };
  15347. var matchNode = function (ed, node, name, vars, similar) {
  15348. var formatList = ed.formatter.get(name);
  15349. var dom = ed.dom;
  15350. if (formatList && node) {
  15351. for (var i = 0; i < formatList.length; i++) {
  15352. var format = formatList[i];
  15353. if (matchName$1(ed.dom, node, format) && matchItems(dom, node, format, 'attributes', similar, vars) && matchItems(dom, node, format, 'styles', similar, vars)) {
  15354. var classes = format.classes;
  15355. if (classes) {
  15356. for (var x = 0; x < classes.length; x++) {
  15357. if (!ed.dom.hasClass(node, replaceVars(classes[x], vars))) {
  15358. return;
  15359. }
  15360. }
  15361. }
  15362. return format;
  15363. }
  15364. }
  15365. }
  15366. };
  15367. var match$2 = function (editor, name, vars, node, similar) {
  15368. if (node) {
  15369. return matchParents(editor, node, name, vars, similar);
  15370. }
  15371. node = editor.selection.getNode();
  15372. if (matchParents(editor, node, name, vars, similar)) {
  15373. return true;
  15374. }
  15375. var startNode = editor.selection.getStart();
  15376. if (startNode !== node) {
  15377. if (matchParents(editor, startNode, name, vars, similar)) {
  15378. return true;
  15379. }
  15380. }
  15381. return false;
  15382. };
  15383. var matchAll = function (editor, names, vars) {
  15384. var matchedFormatNames = [];
  15385. var checkedMap = {};
  15386. var startElement = editor.selection.getStart();
  15387. editor.dom.getParent(startElement, function (node) {
  15388. for (var i = 0; i < names.length; i++) {
  15389. var name_1 = names[i];
  15390. if (!checkedMap[name_1] && matchNode(editor, node, name_1, vars)) {
  15391. checkedMap[name_1] = true;
  15392. matchedFormatNames.push(name_1);
  15393. }
  15394. }
  15395. }, editor.dom.getRoot());
  15396. return matchedFormatNames;
  15397. };
  15398. var closest = function (editor, names) {
  15399. var isRoot = function (elm) {
  15400. return eq(elm, SugarElement.fromDom(editor.getBody()));
  15401. };
  15402. var match = function (elm, name) {
  15403. return matchNode(editor, elm.dom, name) ? Optional.some(name) : Optional.none();
  15404. };
  15405. return Optional.from(editor.selection.getStart(true)).bind(function (rawElm) {
  15406. return closest$1(SugarElement.fromDom(rawElm), function (elm) {
  15407. return findMap(names, function (name) {
  15408. return match(elm, name);
  15409. });
  15410. }, isRoot);
  15411. }).getOrNull();
  15412. };
  15413. var canApply = function (editor, name) {
  15414. var formatList = editor.formatter.get(name);
  15415. var dom = editor.dom;
  15416. if (formatList) {
  15417. var startNode = editor.selection.getStart();
  15418. var parents = getParents$2(dom, startNode);
  15419. for (var x = formatList.length - 1; x >= 0; x--) {
  15420. var format = formatList[x];
  15421. if (!isSelectorFormat(format) || isNonNullable(format.defaultBlock)) {
  15422. return true;
  15423. }
  15424. for (var i = parents.length - 1; i >= 0; i--) {
  15425. if (dom.is(parents[i], format.selector)) {
  15426. return true;
  15427. }
  15428. }
  15429. }
  15430. }
  15431. return false;
  15432. };
  15433. var matchAllOnNode = function (editor, node, formatNames) {
  15434. return foldl(formatNames, function (acc, name) {
  15435. var matchSimilar = isVariableFormatName(editor, name);
  15436. if (editor.formatter.matchNode(node, name, {}, matchSimilar)) {
  15437. return acc.concat([name]);
  15438. } else {
  15439. return acc;
  15440. }
  15441. }, []);
  15442. };
  15443. var ZWSP = ZWSP$1, CARET_ID = '_mce_caret';
  15444. var importNode = function (ownerDocument, node) {
  15445. return ownerDocument.importNode(node, true);
  15446. };
  15447. var getEmptyCaretContainers = function (node) {
  15448. var nodes = [];
  15449. while (node) {
  15450. if (node.nodeType === 3 && node.nodeValue !== ZWSP || node.childNodes.length > 1) {
  15451. return [];
  15452. }
  15453. if (node.nodeType === 1) {
  15454. nodes.push(node);
  15455. }
  15456. node = node.firstChild;
  15457. }
  15458. return nodes;
  15459. };
  15460. var isCaretContainerEmpty = function (node) {
  15461. return getEmptyCaretContainers(node).length > 0;
  15462. };
  15463. var findFirstTextNode = function (node) {
  15464. if (node) {
  15465. var walker = new DomTreeWalker(node, node);
  15466. for (node = walker.current(); node; node = walker.next()) {
  15467. if (isText$7(node)) {
  15468. return node;
  15469. }
  15470. }
  15471. }
  15472. return null;
  15473. };
  15474. var createCaretContainer = function (fill) {
  15475. var caretContainer = SugarElement.fromTag('span');
  15476. setAll$1(caretContainer, {
  15477. 'id': CARET_ID,
  15478. 'data-mce-bogus': '1',
  15479. 'data-mce-type': 'format-caret'
  15480. });
  15481. if (fill) {
  15482. append$1(caretContainer, SugarElement.fromText(ZWSP));
  15483. }
  15484. return caretContainer;
  15485. };
  15486. var trimZwspFromCaretContainer = function (caretContainerNode) {
  15487. var textNode = findFirstTextNode(caretContainerNode);
  15488. if (textNode && textNode.nodeValue.charAt(0) === ZWSP) {
  15489. textNode.deleteData(0, 1);
  15490. }
  15491. return textNode;
  15492. };
  15493. var removeCaretContainerNode = function (editor, node, moveCaret) {
  15494. if (moveCaret === void 0) {
  15495. moveCaret = true;
  15496. }
  15497. var dom = editor.dom, selection = editor.selection;
  15498. if (isCaretContainerEmpty(node)) {
  15499. deleteElement$2(editor, false, SugarElement.fromDom(node), moveCaret);
  15500. } else {
  15501. var rng = selection.getRng();
  15502. var block = dom.getParent(node, dom.isBlock);
  15503. var startContainer = rng.startContainer;
  15504. var startOffset = rng.startOffset;
  15505. var endContainer = rng.endContainer;
  15506. var endOffset = rng.endOffset;
  15507. var textNode = trimZwspFromCaretContainer(node);
  15508. dom.remove(node, true);
  15509. if (startContainer === textNode && startOffset > 0) {
  15510. rng.setStart(textNode, startOffset - 1);
  15511. }
  15512. if (endContainer === textNode && endOffset > 0) {
  15513. rng.setEnd(textNode, endOffset - 1);
  15514. }
  15515. if (block && dom.isEmpty(block)) {
  15516. fillWithPaddingBr(SugarElement.fromDom(block));
  15517. }
  15518. selection.setRng(rng);
  15519. }
  15520. };
  15521. var removeCaretContainer = function (editor, node, moveCaret) {
  15522. if (moveCaret === void 0) {
  15523. moveCaret = true;
  15524. }
  15525. var dom = editor.dom, selection = editor.selection;
  15526. if (!node) {
  15527. node = getParentCaretContainer(editor.getBody(), selection.getStart());
  15528. if (!node) {
  15529. while (node = dom.get(CARET_ID)) {
  15530. removeCaretContainerNode(editor, node, false);
  15531. }
  15532. }
  15533. } else {
  15534. removeCaretContainerNode(editor, node, moveCaret);
  15535. }
  15536. };
  15537. var insertCaretContainerNode = function (editor, caretContainer, formatNode) {
  15538. var dom = editor.dom, block = dom.getParent(formatNode, curry(isTextBlock$1, editor));
  15539. if (block && dom.isEmpty(block)) {
  15540. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15541. } else {
  15542. removeTrailingBr(SugarElement.fromDom(formatNode));
  15543. if (dom.isEmpty(formatNode)) {
  15544. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15545. } else {
  15546. dom.insertAfter(caretContainer, formatNode);
  15547. }
  15548. }
  15549. };
  15550. var appendNode = function (parentNode, node) {
  15551. parentNode.appendChild(node);
  15552. return node;
  15553. };
  15554. var insertFormatNodesIntoCaretContainer = function (formatNodes, caretContainer) {
  15555. var innerMostFormatNode = foldr(formatNodes, function (parentNode, formatNode) {
  15556. return appendNode(parentNode, formatNode.cloneNode(false));
  15557. }, caretContainer);
  15558. return appendNode(innerMostFormatNode, innerMostFormatNode.ownerDocument.createTextNode(ZWSP));
  15559. };
  15560. var cleanFormatNode = function (editor, caretContainer, formatNode, name, vars, similar) {
  15561. var formatter = editor.formatter;
  15562. var dom = editor.dom;
  15563. var validFormats = filter$4(keys(formatter.get()), function (formatName) {
  15564. return formatName !== name && !contains$2(formatName, 'removeformat');
  15565. });
  15566. var matchedFormats = matchAllOnNode(editor, formatNode, validFormats);
  15567. var uniqueFormats = filter$4(matchedFormats, function (fmtName) {
  15568. return !areSimilarFormats(editor, fmtName, name);
  15569. });
  15570. if (uniqueFormats.length > 0) {
  15571. var clonedFormatNode = formatNode.cloneNode(false);
  15572. dom.add(caretContainer, clonedFormatNode);
  15573. formatter.remove(name, vars, clonedFormatNode, similar);
  15574. dom.remove(clonedFormatNode);
  15575. return Optional.some(clonedFormatNode);
  15576. } else {
  15577. return Optional.none();
  15578. }
  15579. };
  15580. var applyCaretFormat = function (editor, name, vars) {
  15581. var caretContainer, textNode;
  15582. var selection = editor.selection;
  15583. var selectionRng = selection.getRng();
  15584. var offset = selectionRng.startOffset;
  15585. var container = selectionRng.startContainer;
  15586. var text = container.nodeValue;
  15587. caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
  15588. if (caretContainer) {
  15589. textNode = findFirstTextNode(caretContainer);
  15590. }
  15591. var wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
  15592. if (text && offset > 0 && offset < text.length && wordcharRegex.test(text.charAt(offset)) && wordcharRegex.test(text.charAt(offset - 1))) {
  15593. var bookmark = selection.getBookmark();
  15594. selectionRng.collapse(true);
  15595. var rng = expandRng(editor, selectionRng, editor.formatter.get(name));
  15596. rng = split(rng);
  15597. editor.formatter.apply(name, vars, rng);
  15598. selection.moveToBookmark(bookmark);
  15599. } else {
  15600. if (!caretContainer || textNode.nodeValue !== ZWSP) {
  15601. caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom);
  15602. textNode = caretContainer.firstChild;
  15603. selectionRng.insertNode(caretContainer);
  15604. offset = 1;
  15605. editor.formatter.apply(name, vars, caretContainer);
  15606. } else {
  15607. editor.formatter.apply(name, vars, caretContainer);
  15608. }
  15609. selection.setCursorLocation(textNode, offset);
  15610. }
  15611. };
  15612. var removeCaretFormat = function (editor, name, vars, similar) {
  15613. var dom = editor.dom;
  15614. var selection = editor.selection;
  15615. var hasContentAfter, node, formatNode;
  15616. var parents = [];
  15617. var rng = selection.getRng();
  15618. var container = rng.startContainer;
  15619. var offset = rng.startOffset;
  15620. node = container;
  15621. if (container.nodeType === 3) {
  15622. if (offset !== container.nodeValue.length) {
  15623. hasContentAfter = true;
  15624. }
  15625. node = node.parentNode;
  15626. }
  15627. while (node) {
  15628. if (matchNode(editor, node, name, vars, similar)) {
  15629. formatNode = node;
  15630. break;
  15631. }
  15632. if (node.nextSibling) {
  15633. hasContentAfter = true;
  15634. }
  15635. parents.push(node);
  15636. node = node.parentNode;
  15637. }
  15638. if (!formatNode) {
  15639. return;
  15640. }
  15641. if (hasContentAfter) {
  15642. var bookmark = selection.getBookmark();
  15643. rng.collapse(true);
  15644. var expandedRng = expandRng(editor, rng, editor.formatter.get(name), true);
  15645. expandedRng = split(expandedRng);
  15646. editor.formatter.remove(name, vars, expandedRng, similar);
  15647. selection.moveToBookmark(bookmark);
  15648. } else {
  15649. var caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
  15650. var newCaretContainer = createCaretContainer(false).dom;
  15651. insertCaretContainerNode(editor, newCaretContainer, caretContainer !== null ? caretContainer : formatNode);
  15652. var cleanedFormatNode = cleanFormatNode(editor, newCaretContainer, formatNode, name, vars, similar);
  15653. var caretTextNode = insertFormatNodesIntoCaretContainer(parents.concat(cleanedFormatNode.toArray()), newCaretContainer);
  15654. removeCaretContainerNode(editor, caretContainer, false);
  15655. selection.setCursorLocation(caretTextNode, 1);
  15656. if (dom.isEmpty(formatNode)) {
  15657. dom.remove(formatNode);
  15658. }
  15659. }
  15660. };
  15661. var disableCaretContainer = function (editor, keyCode) {
  15662. var selection = editor.selection, body = editor.getBody();
  15663. removeCaretContainer(editor, null, false);
  15664. if ((keyCode === 8 || keyCode === 46) && selection.isCollapsed() && selection.getStart().innerHTML === ZWSP) {
  15665. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15666. }
  15667. if (keyCode === 37 || keyCode === 39) {
  15668. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15669. }
  15670. };
  15671. var setup$k = function (editor) {
  15672. editor.on('mouseup keydown', function (e) {
  15673. disableCaretContainer(editor, e.keyCode);
  15674. });
  15675. };
  15676. var replaceWithCaretFormat = function (targetNode, formatNodes) {
  15677. var caretContainer = createCaretContainer(false);
  15678. var innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom);
  15679. before$4(SugarElement.fromDom(targetNode), caretContainer);
  15680. remove$7(SugarElement.fromDom(targetNode));
  15681. return CaretPosition(innerMost, 0);
  15682. };
  15683. var isFormatElement = function (editor, element) {
  15684. var inlineElements = editor.schema.getTextInlineElements();
  15685. return has$2(inlineElements, name(element)) && !isCaretNode(element.dom) && !isBogus$2(element.dom);
  15686. };
  15687. var isEmptyCaretFormatElement = function (element) {
  15688. return isCaretNode(element.dom) && isCaretContainerEmpty(element.dom);
  15689. };
  15690. var postProcessHooks = {};
  15691. var filter = filter$2;
  15692. var each$b = each$i;
  15693. var addPostProcessHook = function (name, hook) {
  15694. var hooks = postProcessHooks[name];
  15695. if (!hooks) {
  15696. postProcessHooks[name] = [];
  15697. }
  15698. postProcessHooks[name].push(hook);
  15699. };
  15700. var postProcess$1 = function (name, editor) {
  15701. each$b(postProcessHooks[name], function (hook) {
  15702. hook(editor);
  15703. });
  15704. };
  15705. addPostProcessHook('pre', function (editor) {
  15706. var rng = editor.selection.getRng();
  15707. var blocks;
  15708. var hasPreSibling = function (pre) {
  15709. return isPre(pre.previousSibling) && indexOf$1(blocks, pre.previousSibling) !== -1;
  15710. };
  15711. var joinPre = function (pre1, pre2) {
  15712. DomQuery(pre2).remove();
  15713. DomQuery(pre1).append('<br><br>').append(pre2.childNodes);
  15714. };
  15715. var isPre = matchNodeNames(['pre']);
  15716. if (!rng.collapsed) {
  15717. blocks = editor.selection.getSelectedBlocks();
  15718. each$b(filter(filter(blocks, isPre), hasPreSibling), function (pre) {
  15719. joinPre(pre.previousSibling, pre);
  15720. });
  15721. }
  15722. });
  15723. var each$a = Tools.each;
  15724. var isElementNode$1 = function (node) {
  15725. return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  15726. };
  15727. var findElementSibling = function (node, siblingName) {
  15728. for (var sibling = node; sibling; sibling = sibling[siblingName]) {
  15729. if (isText$7(sibling) && isNotEmpty(sibling.data)) {
  15730. return node;
  15731. }
  15732. if (isElement$5(sibling) && !isBookmarkNode$1(sibling)) {
  15733. return sibling;
  15734. }
  15735. }
  15736. return node;
  15737. };
  15738. var mergeSiblingsNodes = function (dom, prev, next) {
  15739. var elementUtils = ElementUtils(dom);
  15740. if (prev && next) {
  15741. prev = findElementSibling(prev, 'previousSibling');
  15742. next = findElementSibling(next, 'nextSibling');
  15743. if (elementUtils.compare(prev, next)) {
  15744. for (var sibling = prev.nextSibling; sibling && sibling !== next;) {
  15745. var tmpSibling = sibling;
  15746. sibling = sibling.nextSibling;
  15747. prev.appendChild(tmpSibling);
  15748. }
  15749. dom.remove(next);
  15750. Tools.each(Tools.grep(next.childNodes), function (node) {
  15751. prev.appendChild(node);
  15752. });
  15753. return prev;
  15754. }
  15755. }
  15756. return next;
  15757. };
  15758. var mergeSiblings = function (dom, format, vars, node) {
  15759. if (node && format.merge_siblings !== false) {
  15760. var newNode = mergeSiblingsNodes(dom, getNonWhiteSpaceSibling(node), node);
  15761. mergeSiblingsNodes(dom, newNode, getNonWhiteSpaceSibling(newNode, true));
  15762. }
  15763. };
  15764. var clearChildStyles = function (dom, format, node) {
  15765. if (format.clear_child_styles) {
  15766. var selector = format.links ? '*:not(a)' : '*';
  15767. each$a(dom.select(selector, node), function (node) {
  15768. if (isElementNode$1(node)) {
  15769. each$a(format.styles, function (value, name) {
  15770. dom.setStyle(node, name, '');
  15771. });
  15772. }
  15773. });
  15774. }
  15775. };
  15776. var processChildElements = function (node, filter, process) {
  15777. each$a(node.childNodes, function (node) {
  15778. if (isElementNode$1(node)) {
  15779. if (filter(node)) {
  15780. process(node);
  15781. }
  15782. if (node.hasChildNodes()) {
  15783. processChildElements(node, filter, process);
  15784. }
  15785. }
  15786. });
  15787. };
  15788. var unwrapEmptySpan = function (dom, node) {
  15789. if (node.nodeName === 'SPAN' && dom.getAttribs(node).length === 0) {
  15790. dom.remove(node, true);
  15791. }
  15792. };
  15793. var hasStyle = function (dom, name) {
  15794. return function (node) {
  15795. return !!(node && getStyle(dom, node, name));
  15796. };
  15797. };
  15798. var applyStyle = function (dom, name, value) {
  15799. return function (node) {
  15800. dom.setStyle(node, name, value);
  15801. if (node.getAttribute('style') === '') {
  15802. node.removeAttribute('style');
  15803. }
  15804. unwrapEmptySpan(dom, node);
  15805. };
  15806. };
  15807. var removeResult = Adt.generate([
  15808. { keep: [] },
  15809. { rename: ['name'] },
  15810. { removed: [] }
  15811. ]);
  15812. var MCE_ATTR_RE = /^(src|href|style)$/;
  15813. var each$9 = Tools.each;
  15814. var isEq$2 = isEq$5;
  15815. var isTableCellOrRow = function (node) {
  15816. return /^(TR|TH|TD)$/.test(node.nodeName);
  15817. };
  15818. var isChildOfInlineParent = function (dom, node, parent) {
  15819. return dom.isChildOf(node, parent) && node !== parent && !dom.isBlock(parent);
  15820. };
  15821. var getContainer = function (ed, rng, start) {
  15822. var container = rng[start ? 'startContainer' : 'endContainer'];
  15823. var offset = rng[start ? 'startOffset' : 'endOffset'];
  15824. if (isElement$5(container)) {
  15825. var lastIdx = container.childNodes.length - 1;
  15826. if (!start && offset) {
  15827. offset--;
  15828. }
  15829. container = container.childNodes[offset > lastIdx ? lastIdx : offset];
  15830. }
  15831. if (isText$7(container) && start && offset >= container.nodeValue.length) {
  15832. container = new DomTreeWalker(container, ed.getBody()).next() || container;
  15833. }
  15834. if (isText$7(container) && !start && offset === 0) {
  15835. container = new DomTreeWalker(container, ed.getBody()).prev() || container;
  15836. }
  15837. return container;
  15838. };
  15839. var normalizeTableSelection = function (node, start) {
  15840. var prop = start ? 'firstChild' : 'lastChild';
  15841. if (isTableCellOrRow(node) && node[prop]) {
  15842. var childNode = node[prop];
  15843. if (node.nodeName === 'TR') {
  15844. return childNode[prop] || childNode;
  15845. } else {
  15846. return childNode;
  15847. }
  15848. }
  15849. return node;
  15850. };
  15851. var wrap$1 = function (dom, node, name, attrs) {
  15852. var wrapper = dom.create(name, attrs);
  15853. node.parentNode.insertBefore(wrapper, node);
  15854. wrapper.appendChild(node);
  15855. return wrapper;
  15856. };
  15857. var wrapWithSiblings = function (dom, node, next, name, attrs) {
  15858. var start = SugarElement.fromDom(node);
  15859. var wrapper = SugarElement.fromDom(dom.create(name, attrs));
  15860. var siblings = next ? nextSiblings(start) : prevSiblings(start);
  15861. append(wrapper, siblings);
  15862. if (next) {
  15863. before$4(start, wrapper);
  15864. prepend(wrapper, start);
  15865. } else {
  15866. after$3(start, wrapper);
  15867. append$1(wrapper, start);
  15868. }
  15869. return wrapper.dom;
  15870. };
  15871. var matchName = function (dom, node, format) {
  15872. if (isInlineFormat(format) && isEq$2(node, format.inline)) {
  15873. return true;
  15874. }
  15875. if (isBlockFormat(format) && isEq$2(node, format.block)) {
  15876. return true;
  15877. }
  15878. if (isSelectorFormat(format)) {
  15879. return isElement$5(node) && dom.is(node, format.selector);
  15880. }
  15881. };
  15882. var isColorFormatAndAnchor = function (node, format) {
  15883. return format.links && node.nodeName === 'A';
  15884. };
  15885. var find = function (dom, node, next, inc) {
  15886. var sibling = getNonWhiteSpaceSibling(node, next, inc);
  15887. return isNullable(sibling) || sibling.nodeName === 'BR' || dom.isBlock(sibling);
  15888. };
  15889. var removeNode = function (ed, node, format) {
  15890. var parentNode = node.parentNode;
  15891. var rootBlockElm;
  15892. var dom = ed.dom, forcedRootBlock = getForcedRootBlock(ed);
  15893. if (isBlockFormat(format)) {
  15894. if (!forcedRootBlock) {
  15895. if (dom.isBlock(node) && !dom.isBlock(parentNode)) {
  15896. if (!find(dom, node, false) && !find(dom, node.firstChild, true, true)) {
  15897. node.insertBefore(dom.create('br'), node.firstChild);
  15898. }
  15899. if (!find(dom, node, true) && !find(dom, node.lastChild, false, true)) {
  15900. node.appendChild(dom.create('br'));
  15901. }
  15902. }
  15903. } else {
  15904. if (parentNode === dom.getRoot()) {
  15905. if (!format.list_block || !isEq$2(node, format.list_block)) {
  15906. each$k(from(node.childNodes), function (node) {
  15907. if (isValid(ed, forcedRootBlock, node.nodeName.toLowerCase())) {
  15908. if (!rootBlockElm) {
  15909. rootBlockElm = wrap$1(dom, node, forcedRootBlock);
  15910. dom.setAttribs(rootBlockElm, ed.settings.forced_root_block_attrs);
  15911. } else {
  15912. rootBlockElm.appendChild(node);
  15913. }
  15914. } else {
  15915. rootBlockElm = null;
  15916. }
  15917. });
  15918. }
  15919. }
  15920. }
  15921. }
  15922. if (isMixedFormat(format) && !isEq$2(format.inline, node)) {
  15923. return;
  15924. }
  15925. dom.remove(node, true);
  15926. };
  15927. var removeFormatInternal = function (ed, format, vars, node, compareNode) {
  15928. var stylesModified;
  15929. var dom = ed.dom;
  15930. if (!matchName(dom, node, format) && !isColorFormatAndAnchor(node, format)) {
  15931. return removeResult.keep();
  15932. }
  15933. var elm = node;
  15934. if (isInlineFormat(format) && format.remove === 'all' && isArray$1(format.preserve_attributes)) {
  15935. var attrsToPreserve = filter$4(dom.getAttribs(elm), function (attr) {
  15936. return contains$3(format.preserve_attributes, attr.name.toLowerCase());
  15937. });
  15938. dom.removeAllAttribs(elm);
  15939. each$k(attrsToPreserve, function (attr) {
  15940. return dom.setAttrib(elm, attr.name, attr.value);
  15941. });
  15942. if (attrsToPreserve.length > 0) {
  15943. return removeResult.rename('span');
  15944. }
  15945. }
  15946. if (format.remove !== 'all') {
  15947. each$9(format.styles, function (value, name) {
  15948. value = normalizeStyleValue(dom, replaceVars(value, vars), name + '');
  15949. if (isNumber(name)) {
  15950. name = value;
  15951. compareNode = null;
  15952. }
  15953. if (format.remove_similar || (!compareNode || isEq$2(getStyle(dom, compareNode, name), value))) {
  15954. dom.setStyle(elm, name, '');
  15955. }
  15956. stylesModified = true;
  15957. });
  15958. if (stylesModified && dom.getAttrib(elm, 'style') === '') {
  15959. elm.removeAttribute('style');
  15960. elm.removeAttribute('data-mce-style');
  15961. }
  15962. each$9(format.attributes, function (value, name) {
  15963. var valueOut;
  15964. value = replaceVars(value, vars);
  15965. if (isNumber(name)) {
  15966. name = value;
  15967. compareNode = null;
  15968. }
  15969. if (format.remove_similar || (!compareNode || isEq$2(dom.getAttrib(compareNode, name), value))) {
  15970. if (name === 'class') {
  15971. value = dom.getAttrib(elm, name);
  15972. if (value) {
  15973. valueOut = '';
  15974. each$k(value.split(/\s+/), function (cls) {
  15975. if (/mce\-\w+/.test(cls)) {
  15976. valueOut += (valueOut ? ' ' : '') + cls;
  15977. }
  15978. });
  15979. if (valueOut) {
  15980. dom.setAttrib(elm, name, valueOut);
  15981. return;
  15982. }
  15983. }
  15984. }
  15985. if (MCE_ATTR_RE.test(name)) {
  15986. elm.removeAttribute('data-mce-' + name);
  15987. }
  15988. if (name === 'style' && matchNodeNames(['li'])(elm) && dom.getStyle(elm, 'list-style-type') === 'none') {
  15989. elm.removeAttribute(name);
  15990. dom.setStyle(elm, 'list-style-type', 'none');
  15991. return;
  15992. }
  15993. if (name === 'class') {
  15994. elm.removeAttribute('className');
  15995. }
  15996. elm.removeAttribute(name);
  15997. }
  15998. });
  15999. each$9(format.classes, function (value) {
  16000. value = replaceVars(value, vars);
  16001. if (!compareNode || dom.hasClass(compareNode, value)) {
  16002. dom.removeClass(elm, value);
  16003. }
  16004. });
  16005. var attrs = dom.getAttribs(elm);
  16006. for (var i = 0; i < attrs.length; i++) {
  16007. var attrName = attrs[i].nodeName;
  16008. if (attrName.indexOf('_') !== 0 && attrName.indexOf('data-') !== 0) {
  16009. return removeResult.keep();
  16010. }
  16011. }
  16012. }
  16013. if (format.remove !== 'none') {
  16014. removeNode(ed, elm, format);
  16015. return removeResult.removed();
  16016. }
  16017. return removeResult.keep();
  16018. };
  16019. var removeFormat$1 = function (ed, format, vars, node, compareNode) {
  16020. return removeFormatInternal(ed, format, vars, node, compareNode).fold(never, function (newName) {
  16021. ed.dom.rename(node, newName);
  16022. return true;
  16023. }, always);
  16024. };
  16025. var findFormatRoot = function (editor, container, name, vars, similar) {
  16026. var formatRoot;
  16027. each$k(getParents$2(editor.dom, container.parentNode).reverse(), function (parent) {
  16028. if (!formatRoot && parent.id !== '_start' && parent.id !== '_end') {
  16029. var format = matchNode(editor, parent, name, vars, similar);
  16030. if (format && format.split !== false) {
  16031. formatRoot = parent;
  16032. }
  16033. }
  16034. });
  16035. return formatRoot;
  16036. };
  16037. var removeFormatFromClone = function (editor, format, vars, clone) {
  16038. return removeFormatInternal(editor, format, vars, clone, clone).fold(constant(clone), function (newName) {
  16039. var fragment = editor.dom.createFragment();
  16040. fragment.appendChild(clone);
  16041. return editor.dom.rename(clone, newName);
  16042. }, constant(null));
  16043. };
  16044. var wrapAndSplit = function (editor, formatList, formatRoot, container, target, split, format, vars) {
  16045. var clone, lastClone, firstClone;
  16046. var dom = editor.dom;
  16047. if (formatRoot) {
  16048. var formatRootParent = formatRoot.parentNode;
  16049. for (var parent_1 = container.parentNode; parent_1 && parent_1 !== formatRootParent; parent_1 = parent_1.parentNode) {
  16050. clone = dom.clone(parent_1, false);
  16051. for (var i = 0; i < formatList.length; i++) {
  16052. clone = removeFormatFromClone(editor, formatList[i], vars, clone);
  16053. if (clone === null) {
  16054. break;
  16055. }
  16056. }
  16057. if (clone) {
  16058. if (lastClone) {
  16059. clone.appendChild(lastClone);
  16060. }
  16061. if (!firstClone) {
  16062. firstClone = clone;
  16063. }
  16064. lastClone = clone;
  16065. }
  16066. }
  16067. if (split && (!format.mixed || !dom.isBlock(formatRoot))) {
  16068. container = dom.split(formatRoot, container);
  16069. }
  16070. if (lastClone) {
  16071. target.parentNode.insertBefore(lastClone, target);
  16072. firstClone.appendChild(target);
  16073. if (isInlineFormat(format)) {
  16074. mergeSiblings(dom, format, vars, lastClone);
  16075. }
  16076. }
  16077. }
  16078. return container;
  16079. };
  16080. var remove$1 = function (ed, name, vars, node, similar) {
  16081. var formatList = ed.formatter.get(name);
  16082. var format = formatList[0];
  16083. var contentEditable = true;
  16084. var dom = ed.dom;
  16085. var selection = ed.selection;
  16086. var splitToFormatRoot = function (container) {
  16087. var formatRoot = findFormatRoot(ed, container, name, vars, similar);
  16088. return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format, vars);
  16089. };
  16090. var isRemoveBookmarkNode = function (node) {
  16091. return isBookmarkNode$1(node) && isElement$5(node) && (node.id === '_start' || node.id === '_end');
  16092. };
  16093. var removeNodeFormat = function (node) {
  16094. return exists(formatList, function (fmt) {
  16095. return removeFormat$1(ed, fmt, vars, node, node);
  16096. });
  16097. };
  16098. var process = function (node) {
  16099. var lastContentEditable = true;
  16100. var hasContentEditableState = false;
  16101. if (isElement$5(node) && dom.getContentEditable(node)) {
  16102. lastContentEditable = contentEditable;
  16103. contentEditable = dom.getContentEditable(node) === 'true';
  16104. hasContentEditableState = true;
  16105. }
  16106. var children = from(node.childNodes);
  16107. if (contentEditable && !hasContentEditableState) {
  16108. var removed = removeNodeFormat(node);
  16109. var currentNodeMatches = removed || exists(formatList, function (f) {
  16110. return matchName$1(dom, node, f);
  16111. });
  16112. var parentNode = node.parentNode;
  16113. if (!currentNodeMatches && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  16114. removeNodeFormat(parentNode);
  16115. }
  16116. }
  16117. if (format.deep) {
  16118. if (children.length) {
  16119. for (var i = 0; i < children.length; i++) {
  16120. process(children[i]);
  16121. }
  16122. if (hasContentEditableState) {
  16123. contentEditable = lastContentEditable;
  16124. }
  16125. }
  16126. }
  16127. var textDecorations = [
  16128. 'underline',
  16129. 'line-through',
  16130. 'overline'
  16131. ];
  16132. each$k(textDecorations, function (decoration) {
  16133. if (isElement$5(node) && ed.dom.getStyle(node, 'text-decoration') === decoration && node.parentNode && getTextDecoration(dom, node.parentNode) === decoration) {
  16134. removeFormat$1(ed, {
  16135. deep: false,
  16136. exact: true,
  16137. inline: 'span',
  16138. styles: { textDecoration: decoration }
  16139. }, null, node);
  16140. }
  16141. });
  16142. };
  16143. var unwrap = function (start) {
  16144. var node = dom.get(start ? '_start' : '_end');
  16145. var out = node[start ? 'firstChild' : 'lastChild'];
  16146. if (isRemoveBookmarkNode(out)) {
  16147. out = out[start ? 'firstChild' : 'lastChild'];
  16148. }
  16149. if (isText$7(out) && out.data.length === 0) {
  16150. out = start ? node.previousSibling || node.nextSibling : node.nextSibling || node.previousSibling;
  16151. }
  16152. dom.remove(node, true);
  16153. return out;
  16154. };
  16155. var removeRngStyle = function (rng) {
  16156. var startContainer, endContainer;
  16157. var expandedRng = expandRng(ed, rng, formatList, rng.collapsed);
  16158. if (format.split) {
  16159. expandedRng = split(expandedRng);
  16160. startContainer = getContainer(ed, expandedRng, true);
  16161. endContainer = getContainer(ed, expandedRng);
  16162. if (startContainer !== endContainer) {
  16163. startContainer = normalizeTableSelection(startContainer, true);
  16164. endContainer = normalizeTableSelection(endContainer, false);
  16165. if (isChildOfInlineParent(dom, startContainer, endContainer)) {
  16166. var marker = Optional.from(startContainer.firstChild).getOr(startContainer);
  16167. splitToFormatRoot(wrapWithSiblings(dom, marker, true, 'span', {
  16168. 'id': '_start',
  16169. 'data-mce-type': 'bookmark'
  16170. }));
  16171. unwrap(true);
  16172. return;
  16173. }
  16174. if (isChildOfInlineParent(dom, endContainer, startContainer)) {
  16175. var marker = Optional.from(endContainer.lastChild).getOr(endContainer);
  16176. splitToFormatRoot(wrapWithSiblings(dom, marker, false, 'span', {
  16177. 'id': '_end',
  16178. 'data-mce-type': 'bookmark'
  16179. }));
  16180. unwrap(false);
  16181. return;
  16182. }
  16183. startContainer = wrap$1(dom, startContainer, 'span', {
  16184. 'id': '_start',
  16185. 'data-mce-type': 'bookmark'
  16186. });
  16187. endContainer = wrap$1(dom, endContainer, 'span', {
  16188. 'id': '_end',
  16189. 'data-mce-type': 'bookmark'
  16190. });
  16191. var newRng = dom.createRng();
  16192. newRng.setStartAfter(startContainer);
  16193. newRng.setEndBefore(endContainer);
  16194. walk$2(dom, newRng, function (nodes) {
  16195. each$k(nodes, function (n) {
  16196. if (!isBookmarkNode$1(n) && !isBookmarkNode$1(n.parentNode)) {
  16197. splitToFormatRoot(n);
  16198. }
  16199. });
  16200. });
  16201. splitToFormatRoot(startContainer);
  16202. splitToFormatRoot(endContainer);
  16203. startContainer = unwrap(true);
  16204. endContainer = unwrap();
  16205. } else {
  16206. startContainer = endContainer = splitToFormatRoot(startContainer);
  16207. }
  16208. expandedRng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
  16209. expandedRng.startOffset = dom.nodeIndex(startContainer);
  16210. expandedRng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
  16211. expandedRng.endOffset = dom.nodeIndex(endContainer) + 1;
  16212. }
  16213. walk$2(dom, expandedRng, function (nodes) {
  16214. each$k(nodes, process);
  16215. });
  16216. };
  16217. if (node) {
  16218. if (isNode(node)) {
  16219. var rng = dom.createRng();
  16220. rng.setStartBefore(node);
  16221. rng.setEndAfter(node);
  16222. removeRngStyle(rng);
  16223. } else {
  16224. removeRngStyle(node);
  16225. }
  16226. fireFormatRemove(ed, name, node, vars);
  16227. return;
  16228. }
  16229. if (dom.getContentEditable(selection.getNode()) === 'false') {
  16230. node = selection.getNode();
  16231. for (var i = 0; i < formatList.length; i++) {
  16232. if (formatList[i].ceFalseOverride) {
  16233. if (removeFormat$1(ed, formatList[i], vars, node, node)) {
  16234. break;
  16235. }
  16236. }
  16237. }
  16238. fireFormatRemove(ed, name, node, vars);
  16239. return;
  16240. }
  16241. if (!selection.isCollapsed() || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  16242. preserve(selection, true, function () {
  16243. runOnRanges(ed, removeRngStyle);
  16244. });
  16245. if (isInlineFormat(format) && match$2(ed, name, vars, selection.getStart())) {
  16246. moveStart(dom, selection, selection.getRng());
  16247. }
  16248. ed.nodeChanged();
  16249. } else {
  16250. removeCaretFormat(ed, name, vars, similar);
  16251. }
  16252. fireFormatRemove(ed, name, node, vars);
  16253. };
  16254. var each$8 = Tools.each;
  16255. var mergeTextDecorationsAndColor = function (dom, format, vars, node) {
  16256. var processTextDecorationsAndColor = function (n) {
  16257. if (n.nodeType === 1 && n.parentNode && n.parentNode.nodeType === 1) {
  16258. var textDecoration = getTextDecoration(dom, n.parentNode);
  16259. if (dom.getStyle(n, 'color') && textDecoration) {
  16260. dom.setStyle(n, 'text-decoration', textDecoration);
  16261. } else if (dom.getStyle(n, 'text-decoration') === textDecoration) {
  16262. dom.setStyle(n, 'text-decoration', null);
  16263. }
  16264. }
  16265. };
  16266. if (format.styles && (format.styles.color || format.styles.textDecoration)) {
  16267. Tools.walk(node, processTextDecorationsAndColor, 'childNodes');
  16268. processTextDecorationsAndColor(node);
  16269. }
  16270. };
  16271. var mergeBackgroundColorAndFontSize = function (dom, format, vars, node) {
  16272. if (format.styles && format.styles.backgroundColor) {
  16273. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'backgroundColor', replaceVars(format.styles.backgroundColor, vars)));
  16274. }
  16275. };
  16276. var mergeSubSup = function (dom, format, vars, node) {
  16277. if (isInlineFormat(format) && (format.inline === 'sub' || format.inline === 'sup')) {
  16278. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'fontSize', ''));
  16279. dom.remove(dom.select(format.inline === 'sup' ? 'sub' : 'sup', node), true);
  16280. }
  16281. };
  16282. var mergeWithChildren = function (editor, formatList, vars, node) {
  16283. each$8(formatList, function (format) {
  16284. if (isInlineFormat(format)) {
  16285. each$8(editor.dom.select(format.inline, node), function (child) {
  16286. if (!isElementNode$1(child)) {
  16287. return;
  16288. }
  16289. removeFormat$1(editor, format, vars, child, format.exact ? child : null);
  16290. });
  16291. }
  16292. clearChildStyles(editor.dom, format, node);
  16293. });
  16294. };
  16295. var mergeWithParents = function (editor, format, name, vars, node) {
  16296. if (matchNode(editor, node.parentNode, name, vars)) {
  16297. if (removeFormat$1(editor, format, vars, node)) {
  16298. return;
  16299. }
  16300. }
  16301. if (format.merge_with_parents) {
  16302. editor.dom.getParent(node.parentNode, function (parent) {
  16303. if (matchNode(editor, parent, name, vars)) {
  16304. removeFormat$1(editor, format, vars, node);
  16305. return true;
  16306. }
  16307. });
  16308. }
  16309. };
  16310. var each$7 = Tools.each;
  16311. var isElementNode = function (node) {
  16312. return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  16313. };
  16314. var canFormatBR = function (editor, format, node, parentName) {
  16315. if (canFormatEmptyLines(editor) && isInlineFormat(format)) {
  16316. var validBRParentElements = getTextRootBlockElements(editor.schema);
  16317. var hasCaretNodeSibling = sibling(SugarElement.fromDom(node), function (sibling) {
  16318. return isCaretNode(sibling.dom);
  16319. });
  16320. return hasNonNullableKey(validBRParentElements, parentName) && isEmpty$2(SugarElement.fromDom(node.parentNode), false) && !hasCaretNodeSibling;
  16321. } else {
  16322. return false;
  16323. }
  16324. };
  16325. var applyFormat$1 = function (ed, name, vars, node) {
  16326. var formatList = ed.formatter.get(name);
  16327. var format = formatList[0];
  16328. var isCollapsed = !node && ed.selection.isCollapsed();
  16329. var dom = ed.dom;
  16330. var selection = ed.selection;
  16331. var setElementFormat = function (elm, fmt) {
  16332. if (fmt === void 0) {
  16333. fmt = format;
  16334. }
  16335. if (isFunction(fmt.onformat)) {
  16336. fmt.onformat(elm, fmt, vars, node);
  16337. }
  16338. each$7(fmt.styles, function (value, name) {
  16339. dom.setStyle(elm, name, replaceVars(value, vars));
  16340. });
  16341. if (fmt.styles) {
  16342. var styleVal = dom.getAttrib(elm, 'style');
  16343. if (styleVal) {
  16344. dom.setAttrib(elm, 'data-mce-style', styleVal);
  16345. }
  16346. }
  16347. each$7(fmt.attributes, function (value, name) {
  16348. dom.setAttrib(elm, name, replaceVars(value, vars));
  16349. });
  16350. each$7(fmt.classes, function (value) {
  16351. value = replaceVars(value, vars);
  16352. if (!dom.hasClass(elm, value)) {
  16353. dom.addClass(elm, value);
  16354. }
  16355. });
  16356. };
  16357. var applyNodeStyle = function (formatList, node) {
  16358. var found = false;
  16359. each$7(formatList, function (format) {
  16360. if (!isSelectorFormat(format)) {
  16361. return false;
  16362. }
  16363. if (isNonNullable(format.collapsed) && format.collapsed !== isCollapsed) {
  16364. return;
  16365. }
  16366. if (dom.is(node, format.selector) && !isCaretNode(node)) {
  16367. setElementFormat(node, format);
  16368. found = true;
  16369. return false;
  16370. }
  16371. });
  16372. return found;
  16373. };
  16374. var createWrapElement = function (wrapName) {
  16375. if (isString$1(wrapName)) {
  16376. var wrapElm = dom.create(wrapName);
  16377. setElementFormat(wrapElm);
  16378. return wrapElm;
  16379. } else {
  16380. return null;
  16381. }
  16382. };
  16383. var applyRngStyle = function (dom, rng, nodeSpecific) {
  16384. var newWrappers = [];
  16385. var contentEditable = true;
  16386. var wrapName = format.inline || format.block;
  16387. var wrapElm = createWrapElement(wrapName);
  16388. walk$2(dom, rng, function (nodes) {
  16389. var currentWrapElm;
  16390. var process = function (node) {
  16391. var hasContentEditableState = false;
  16392. var lastContentEditable = contentEditable;
  16393. var nodeName = node.nodeName.toLowerCase();
  16394. var parentNode = node.parentNode;
  16395. var parentName = parentNode.nodeName.toLowerCase();
  16396. if (isElement$5(node) && dom.getContentEditable(node)) {
  16397. lastContentEditable = contentEditable;
  16398. contentEditable = dom.getContentEditable(node) === 'true';
  16399. hasContentEditableState = true;
  16400. }
  16401. if (isBr$5(node) && !canFormatBR(ed, format, node, parentName)) {
  16402. currentWrapElm = null;
  16403. if (isBlockFormat(format)) {
  16404. dom.remove(node);
  16405. }
  16406. return;
  16407. }
  16408. if (isBlockFormat(format) && format.wrapper && matchNode(ed, node, name, vars)) {
  16409. currentWrapElm = null;
  16410. return;
  16411. }
  16412. if (contentEditable && !hasContentEditableState && isBlockFormat(format) && !format.wrapper && isTextBlock$1(ed, nodeName) && isValid(ed, parentName, wrapName)) {
  16413. var elm = dom.rename(node, wrapName);
  16414. setElementFormat(elm);
  16415. newWrappers.push(elm);
  16416. currentWrapElm = null;
  16417. return;
  16418. }
  16419. if (isSelectorFormat(format)) {
  16420. var found = applyNodeStyle(formatList, node);
  16421. if (!found && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  16422. found = applyNodeStyle(formatList, parentNode);
  16423. }
  16424. if (!isInlineFormat(format) || found) {
  16425. currentWrapElm = null;
  16426. return;
  16427. }
  16428. }
  16429. 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))) {
  16430. if (!currentWrapElm) {
  16431. currentWrapElm = dom.clone(wrapElm, false);
  16432. node.parentNode.insertBefore(currentWrapElm, node);
  16433. newWrappers.push(currentWrapElm);
  16434. }
  16435. currentWrapElm.appendChild(node);
  16436. } else {
  16437. currentWrapElm = null;
  16438. each$k(from(node.childNodes), process);
  16439. if (hasContentEditableState) {
  16440. contentEditable = lastContentEditable;
  16441. }
  16442. currentWrapElm = null;
  16443. }
  16444. };
  16445. each$k(nodes, process);
  16446. });
  16447. if (format.links === true) {
  16448. each$k(newWrappers, function (node) {
  16449. var process = function (node) {
  16450. if (node.nodeName === 'A') {
  16451. setElementFormat(node, format);
  16452. }
  16453. each$k(from(node.childNodes), process);
  16454. };
  16455. process(node);
  16456. });
  16457. }
  16458. each$k(newWrappers, function (node) {
  16459. var getChildCount = function (node) {
  16460. var count = 0;
  16461. each$k(node.childNodes, function (node) {
  16462. if (!isEmptyTextNode$1(node) && !isBookmarkNode$1(node)) {
  16463. count++;
  16464. }
  16465. });
  16466. return count;
  16467. };
  16468. var mergeStyles = function (node) {
  16469. var childElement = find$3(node.childNodes, isElementNode).filter(function (child) {
  16470. return matchName$1(dom, child, format);
  16471. });
  16472. return childElement.map(function (child) {
  16473. var clone = dom.clone(child, false);
  16474. setElementFormat(clone);
  16475. dom.replace(clone, node, true);
  16476. dom.remove(child, true);
  16477. return clone;
  16478. }).getOr(node);
  16479. };
  16480. var childCount = getChildCount(node);
  16481. if ((newWrappers.length > 1 || !dom.isBlock(node)) && childCount === 0) {
  16482. dom.remove(node, true);
  16483. return;
  16484. }
  16485. if (isInlineFormat(format) || isBlockFormat(format) && format.wrapper) {
  16486. if (!format.exact && childCount === 1) {
  16487. node = mergeStyles(node);
  16488. }
  16489. mergeWithChildren(ed, formatList, vars, node);
  16490. mergeWithParents(ed, format, name, vars, node);
  16491. mergeBackgroundColorAndFontSize(dom, format, vars, node);
  16492. mergeTextDecorationsAndColor(dom, format, vars, node);
  16493. mergeSubSup(dom, format, vars, node);
  16494. mergeSiblings(dom, format, vars, node);
  16495. }
  16496. });
  16497. };
  16498. if (dom.getContentEditable(selection.getNode()) === 'false') {
  16499. node = selection.getNode();
  16500. for (var i = 0, l = formatList.length; i < l; i++) {
  16501. var formatItem = formatList[i];
  16502. if (formatItem.ceFalseOverride && isSelectorFormat(formatItem) && dom.is(node, formatItem.selector)) {
  16503. setElementFormat(node, formatItem);
  16504. break;
  16505. }
  16506. }
  16507. fireFormatApply(ed, name, node, vars);
  16508. return;
  16509. }
  16510. if (format) {
  16511. if (node) {
  16512. if (isNode(node)) {
  16513. if (!applyNodeStyle(formatList, node)) {
  16514. var rng = dom.createRng();
  16515. rng.setStartBefore(node);
  16516. rng.setEndAfter(node);
  16517. applyRngStyle(dom, expandRng(ed, rng, formatList), true);
  16518. }
  16519. } else {
  16520. applyRngStyle(dom, node, true);
  16521. }
  16522. } else {
  16523. if (!isCollapsed || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  16524. var curSelNode = selection.getNode();
  16525. var firstFormat = formatList[0];
  16526. if (!ed.settings.forced_root_block && firstFormat.defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) {
  16527. applyFormat$1(ed, firstFormat.defaultBlock);
  16528. }
  16529. selection.setRng(normalize(selection.getRng()));
  16530. preserve(selection, true, function () {
  16531. runOnRanges(ed, function (selectionRng, fake) {
  16532. var expandedRng = fake ? selectionRng : expandRng(ed, selectionRng, formatList);
  16533. applyRngStyle(dom, expandedRng, false);
  16534. });
  16535. });
  16536. moveStart(dom, selection, selection.getRng());
  16537. ed.nodeChanged();
  16538. } else {
  16539. applyCaretFormat(ed, name, vars);
  16540. }
  16541. }
  16542. postProcess$1(name, ed);
  16543. }
  16544. fireFormatApply(ed, name, node, vars);
  16545. };
  16546. var hasVars = function (value) {
  16547. return has$2(value, 'vars');
  16548. };
  16549. var setup$j = function (registeredFormatListeners, editor) {
  16550. registeredFormatListeners.set({});
  16551. editor.on('NodeChange', function (e) {
  16552. updateAndFireChangeCallbacks(editor, e.element, registeredFormatListeners.get());
  16553. });
  16554. editor.on('FormatApply FormatRemove', function (e) {
  16555. var element = Optional.from(e.node).map(function (nodeOrRange) {
  16556. return isNode(nodeOrRange) ? nodeOrRange : nodeOrRange.startContainer;
  16557. }).bind(function (node) {
  16558. return isElement$5(node) ? Optional.some(node) : Optional.from(node.parentElement);
  16559. }).getOrThunk(function () {
  16560. return fallbackElement(editor);
  16561. });
  16562. updateAndFireChangeCallbacks(editor, element, registeredFormatListeners.get());
  16563. });
  16564. };
  16565. var fallbackElement = function (editor) {
  16566. return editor.selection.getStart();
  16567. };
  16568. var matchingNode = function (editor, parents, format, similar, vars) {
  16569. var isMatchingNode = function (node) {
  16570. var matchingFormat = editor.formatter.matchNode(node, format, vars !== null && vars !== void 0 ? vars : {}, similar);
  16571. return !isUndefined(matchingFormat);
  16572. };
  16573. var isUnableToMatch = function (node) {
  16574. if (matchesUnInheritedFormatSelector(editor, node, format)) {
  16575. return true;
  16576. } else {
  16577. if (!similar) {
  16578. return isNonNullable(editor.formatter.matchNode(node, format, vars, true));
  16579. } else {
  16580. return false;
  16581. }
  16582. }
  16583. };
  16584. return findUntil$1(parents, isMatchingNode, isUnableToMatch);
  16585. };
  16586. var getParents = function (editor, elm) {
  16587. var element = elm !== null && elm !== void 0 ? elm : fallbackElement(editor);
  16588. return filter$4(getParents$2(editor.dom, element), function (node) {
  16589. return isElement$5(node) && !isBogus$2(node);
  16590. });
  16591. };
  16592. var updateAndFireChangeCallbacks = function (editor, elm, registeredCallbacks) {
  16593. var parents = getParents(editor, elm);
  16594. each$j(registeredCallbacks, function (data, format) {
  16595. var runIfChanged = function (spec) {
  16596. var match = matchingNode(editor, parents, format, spec.similar, hasVars(spec) ? spec.vars : undefined);
  16597. var isSet = match.isSome();
  16598. if (spec.state.get() !== isSet) {
  16599. spec.state.set(isSet);
  16600. var node_1 = match.getOr(elm);
  16601. if (hasVars(spec)) {
  16602. spec.callback(isSet, {
  16603. node: node_1,
  16604. format: format,
  16605. parents: parents
  16606. });
  16607. } else {
  16608. each$k(spec.callbacks, function (callback) {
  16609. return callback(isSet, {
  16610. node: node_1,
  16611. format: format,
  16612. parents: parents
  16613. });
  16614. });
  16615. }
  16616. }
  16617. };
  16618. each$k([
  16619. data.withSimilar,
  16620. data.withoutSimilar
  16621. ], runIfChanged);
  16622. each$k(data.withVars, runIfChanged);
  16623. });
  16624. };
  16625. var addListeners = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  16626. var formatChangeItems = registeredFormatListeners.get();
  16627. each$k(formats.split(','), function (format) {
  16628. var group = get$9(formatChangeItems, format).getOrThunk(function () {
  16629. var base = {
  16630. withSimilar: {
  16631. state: Cell(false),
  16632. similar: true,
  16633. callbacks: []
  16634. },
  16635. withoutSimilar: {
  16636. state: Cell(false),
  16637. similar: false,
  16638. callbacks: []
  16639. },
  16640. withVars: []
  16641. };
  16642. formatChangeItems[format] = base;
  16643. return base;
  16644. });
  16645. var getCurrent = function () {
  16646. var parents = getParents(editor);
  16647. return matchingNode(editor, parents, format, similar, vars).isSome();
  16648. };
  16649. if (isUndefined(vars)) {
  16650. var toAppendTo = similar ? group.withSimilar : group.withoutSimilar;
  16651. toAppendTo.callbacks.push(callback);
  16652. if (toAppendTo.callbacks.length === 1) {
  16653. toAppendTo.state.set(getCurrent());
  16654. }
  16655. } else {
  16656. group.withVars.push({
  16657. state: Cell(getCurrent()),
  16658. similar: similar,
  16659. vars: vars,
  16660. callback: callback
  16661. });
  16662. }
  16663. });
  16664. registeredFormatListeners.set(formatChangeItems);
  16665. };
  16666. var removeListeners = function (registeredFormatListeners, formats, callback) {
  16667. var formatChangeItems = registeredFormatListeners.get();
  16668. each$k(formats.split(','), function (format) {
  16669. return get$9(formatChangeItems, format).each(function (group) {
  16670. formatChangeItems[format] = {
  16671. withSimilar: __assign(__assign({}, group.withSimilar), {
  16672. callbacks: filter$4(group.withSimilar.callbacks, function (cb) {
  16673. return cb !== callback;
  16674. })
  16675. }),
  16676. withoutSimilar: __assign(__assign({}, group.withoutSimilar), {
  16677. callbacks: filter$4(group.withoutSimilar.callbacks, function (cb) {
  16678. return cb !== callback;
  16679. })
  16680. }),
  16681. withVars: filter$4(group.withVars, function (item) {
  16682. return item.callback !== callback;
  16683. })
  16684. };
  16685. });
  16686. });
  16687. registeredFormatListeners.set(formatChangeItems);
  16688. };
  16689. var formatChangedInternal = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  16690. if (registeredFormatListeners.get() === null) {
  16691. setup$j(registeredFormatListeners, editor);
  16692. }
  16693. addListeners(editor, registeredFormatListeners, formats, callback, similar, vars);
  16694. return {
  16695. unbind: function () {
  16696. return removeListeners(registeredFormatListeners, formats, callback);
  16697. }
  16698. };
  16699. };
  16700. var toggle = function (editor, name, vars, node) {
  16701. var fmt = editor.formatter.get(name);
  16702. if (match$2(editor, name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) {
  16703. remove$1(editor, name, vars, node);
  16704. } else {
  16705. applyFormat$1(editor, name, vars, node);
  16706. }
  16707. };
  16708. var fromElements = function (elements, scope) {
  16709. var doc = scope || document;
  16710. var fragment = doc.createDocumentFragment();
  16711. each$k(elements, function (element) {
  16712. fragment.appendChild(element.dom);
  16713. });
  16714. return SugarElement.fromDom(fragment);
  16715. };
  16716. var tableModel = function (element, width, rows) {
  16717. return {
  16718. element: element,
  16719. width: width,
  16720. rows: rows
  16721. };
  16722. };
  16723. var tableRow = function (element, cells) {
  16724. return {
  16725. element: element,
  16726. cells: cells
  16727. };
  16728. };
  16729. var cellPosition = function (x, y) {
  16730. return {
  16731. x: x,
  16732. y: y
  16733. };
  16734. };
  16735. var getSpan = function (td, key) {
  16736. var value = parseInt(get$6(td, key), 10);
  16737. return isNaN(value) ? 1 : value;
  16738. };
  16739. var fillout = function (table, x, y, tr, td) {
  16740. var rowspan = getSpan(td, 'rowspan');
  16741. var colspan = getSpan(td, 'colspan');
  16742. var rows = table.rows;
  16743. for (var y2 = y; y2 < y + rowspan; y2++) {
  16744. if (!rows[y2]) {
  16745. rows[y2] = tableRow(deep$1(tr), []);
  16746. }
  16747. for (var x2 = x; x2 < x + colspan; x2++) {
  16748. var cells = rows[y2].cells;
  16749. cells[x2] = y2 === y && x2 === x ? td : shallow(td);
  16750. }
  16751. }
  16752. };
  16753. var cellExists = function (table, x, y) {
  16754. var rows = table.rows;
  16755. var cells = rows[y] ? rows[y].cells : [];
  16756. return !!cells[x];
  16757. };
  16758. var skipCellsX = function (table, x, y) {
  16759. while (cellExists(table, x, y)) {
  16760. x++;
  16761. }
  16762. return x;
  16763. };
  16764. var getWidth = function (rows) {
  16765. return foldl(rows, function (acc, row) {
  16766. return row.cells.length > acc ? row.cells.length : acc;
  16767. }, 0);
  16768. };
  16769. var findElementPos = function (table, element) {
  16770. var rows = table.rows;
  16771. for (var y = 0; y < rows.length; y++) {
  16772. var cells = rows[y].cells;
  16773. for (var x = 0; x < cells.length; x++) {
  16774. if (eq(cells[x], element)) {
  16775. return Optional.some(cellPosition(x, y));
  16776. }
  16777. }
  16778. }
  16779. return Optional.none();
  16780. };
  16781. var extractRows = function (table, sx, sy, ex, ey) {
  16782. var newRows = [];
  16783. var rows = table.rows;
  16784. for (var y = sy; y <= ey; y++) {
  16785. var cells = rows[y].cells;
  16786. var slice = sx < ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
  16787. newRows.push(tableRow(rows[y].element, slice));
  16788. }
  16789. return newRows;
  16790. };
  16791. var subTable = function (table, startPos, endPos) {
  16792. var sx = startPos.x, sy = startPos.y;
  16793. var ex = endPos.x, ey = endPos.y;
  16794. var newRows = sy < ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
  16795. return tableModel(table.element, getWidth(newRows), newRows);
  16796. };
  16797. var createDomTable = function (table, rows) {
  16798. var tableElement = shallow(table.element);
  16799. var tableBody = SugarElement.fromTag('tbody');
  16800. append(tableBody, rows);
  16801. append$1(tableElement, tableBody);
  16802. return tableElement;
  16803. };
  16804. var modelRowsToDomRows = function (table) {
  16805. return map$3(table.rows, function (row) {
  16806. var cells = map$3(row.cells, function (cell) {
  16807. var td = deep$1(cell);
  16808. remove$6(td, 'colspan');
  16809. remove$6(td, 'rowspan');
  16810. return td;
  16811. });
  16812. var tr = shallow(row.element);
  16813. append(tr, cells);
  16814. return tr;
  16815. });
  16816. };
  16817. var fromDom = function (tableElm) {
  16818. var table = tableModel(shallow(tableElm), 0, []);
  16819. each$k(descendants(tableElm, 'tr'), function (tr, y) {
  16820. each$k(descendants(tr, 'td,th'), function (td, x) {
  16821. fillout(table, skipCellsX(table, x, y), y, tr, td);
  16822. });
  16823. });
  16824. return tableModel(table.element, getWidth(table.rows), table.rows);
  16825. };
  16826. var toDom = function (table) {
  16827. return createDomTable(table, modelRowsToDomRows(table));
  16828. };
  16829. var subsection = function (table, startElement, endElement) {
  16830. return findElementPos(table, startElement).bind(function (startPos) {
  16831. return findElementPos(table, endElement).map(function (endPos) {
  16832. return subTable(table, startPos, endPos);
  16833. });
  16834. });
  16835. };
  16836. var findParentListContainer = function (parents) {
  16837. return find$3(parents, function (elm) {
  16838. return name(elm) === 'ul' || name(elm) === 'ol';
  16839. });
  16840. };
  16841. var getFullySelectedListWrappers = function (parents, rng) {
  16842. return find$3(parents, function (elm) {
  16843. return name(elm) === 'li' && hasAllContentsSelected(elm, rng);
  16844. }).fold(constant([]), function (_li) {
  16845. return findParentListContainer(parents).map(function (listCont) {
  16846. var listElm = SugarElement.fromTag(name(listCont));
  16847. var listStyles = filter$3(getAllRaw(listCont), function (_style, name) {
  16848. return startsWith(name, 'list-style');
  16849. });
  16850. setAll(listElm, listStyles);
  16851. return [
  16852. SugarElement.fromTag('li'),
  16853. listElm
  16854. ];
  16855. }).getOr([]);
  16856. });
  16857. };
  16858. var wrap = function (innerElm, elms) {
  16859. var wrapped = foldl(elms, function (acc, elm) {
  16860. append$1(elm, acc);
  16861. return elm;
  16862. }, innerElm);
  16863. return elms.length > 0 ? fromElements([wrapped]) : wrapped;
  16864. };
  16865. var directListWrappers = function (commonAnchorContainer) {
  16866. if (isListItem(commonAnchorContainer)) {
  16867. return parent(commonAnchorContainer).filter(isList).fold(constant([]), function (listElm) {
  16868. return [
  16869. commonAnchorContainer,
  16870. listElm
  16871. ];
  16872. });
  16873. } else {
  16874. return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
  16875. }
  16876. };
  16877. var getWrapElements = function (rootNode, rng) {
  16878. var commonAnchorContainer = SugarElement.fromDom(rng.commonAncestorContainer);
  16879. var parents = parentsAndSelf(commonAnchorContainer, rootNode);
  16880. var wrapElements = filter$4(parents, function (elm) {
  16881. return isInline$1(elm) || isHeading(elm);
  16882. });
  16883. var listWrappers = getFullySelectedListWrappers(parents, rng);
  16884. var allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
  16885. return map$3(allWrappers, shallow);
  16886. };
  16887. var emptyFragment = function () {
  16888. return fromElements([]);
  16889. };
  16890. var getFragmentFromRange = function (rootNode, rng) {
  16891. return wrap(SugarElement.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
  16892. };
  16893. var getParentTable = function (rootElm, cell) {
  16894. return ancestor$2(cell, 'table', curry(eq, rootElm));
  16895. };
  16896. var getTableFragment = function (rootNode, selectedTableCells) {
  16897. return getParentTable(rootNode, selectedTableCells[0]).bind(function (tableElm) {
  16898. var firstCell = selectedTableCells[0];
  16899. var lastCell = selectedTableCells[selectedTableCells.length - 1];
  16900. var fullTableModel = fromDom(tableElm);
  16901. return subsection(fullTableModel, firstCell, lastCell).map(function (sectionedTableModel) {
  16902. return fromElements([toDom(sectionedTableModel)]);
  16903. });
  16904. }).getOrThunk(emptyFragment);
  16905. };
  16906. var getSelectionFragment = function (rootNode, ranges) {
  16907. return ranges.length > 0 && ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
  16908. };
  16909. var read$3 = function (rootNode, ranges) {
  16910. var selectedCells = getCellsFromElementOrRanges(ranges, rootNode);
  16911. return selectedCells.length > 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
  16912. };
  16913. var trimLeadingCollapsibleText = function (text) {
  16914. return text.replace(/^[ \f\n\r\t\v]+/, '');
  16915. };
  16916. var isCollapsibleWhitespace = function (text, index) {
  16917. return index >= 0 && index < text.length && isWhiteSpace(text.charAt(index));
  16918. };
  16919. var getInnerText = function (bin, shouldTrim) {
  16920. var text = trim$2(bin.innerText);
  16921. return shouldTrim ? trimLeadingCollapsibleText(text) : text;
  16922. };
  16923. var getContextNodeName = function (parentBlockOpt) {
  16924. return parentBlockOpt.map(function (block) {
  16925. return block.nodeName;
  16926. }).getOr('div').toLowerCase();
  16927. };
  16928. var getTextContent = function (editor) {
  16929. return Optional.from(editor.selection.getRng()).map(function (rng) {
  16930. var parentBlockOpt = Optional.from(editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock));
  16931. var body = editor.getBody();
  16932. var contextNodeName = getContextNodeName(parentBlockOpt);
  16933. var shouldTrimSpaces = Env.browser.isIE() && contextNodeName !== 'pre';
  16934. var bin = editor.dom.add(body, contextNodeName, {
  16935. 'data-mce-bogus': 'all',
  16936. 'style': 'overflow: hidden; opacity: 0;'
  16937. }, rng.cloneContents());
  16938. var text = getInnerText(bin, shouldTrimSpaces);
  16939. var nonRenderedText = trim$2(bin.textContent);
  16940. editor.dom.remove(bin);
  16941. if (isCollapsibleWhitespace(nonRenderedText, 0) || isCollapsibleWhitespace(nonRenderedText, nonRenderedText.length - 1)) {
  16942. var parentBlock = parentBlockOpt.getOr(body);
  16943. var parentBlockText = getInnerText(parentBlock, shouldTrimSpaces);
  16944. var textIndex = parentBlockText.indexOf(text);
  16945. if (textIndex === -1) {
  16946. return text;
  16947. } else {
  16948. var hasProceedingSpace = isCollapsibleWhitespace(parentBlockText, textIndex - 1);
  16949. var hasTrailingSpace = isCollapsibleWhitespace(parentBlockText, textIndex + text.length);
  16950. return (hasProceedingSpace ? ' ' : '') + text + (hasTrailingSpace ? ' ' : '');
  16951. }
  16952. } else {
  16953. return text;
  16954. }
  16955. }).getOr('');
  16956. };
  16957. var getSerializedContent = function (editor, args) {
  16958. var rng = editor.selection.getRng(), tmpElm = editor.dom.create('body');
  16959. var sel = editor.selection.getSel();
  16960. var ranges = processRanges(editor, getRanges(sel));
  16961. var fragment = args.contextual ? read$3(SugarElement.fromDom(editor.getBody()), ranges).dom : rng.cloneContents();
  16962. if (fragment) {
  16963. tmpElm.appendChild(fragment);
  16964. }
  16965. return editor.selection.serializer.serialize(tmpElm, args);
  16966. };
  16967. var setupArgs$1 = function (args, format) {
  16968. return __assign(__assign({}, args), {
  16969. format: format,
  16970. get: true,
  16971. selection: true
  16972. });
  16973. };
  16974. var getSelectedContentInternal = function (editor, format, args) {
  16975. if (args === void 0) {
  16976. args = {};
  16977. }
  16978. var defaultedArgs = setupArgs$1(args, format);
  16979. var updatedArgs = editor.fire('BeforeGetContent', defaultedArgs);
  16980. if (updatedArgs.isDefaultPrevented()) {
  16981. editor.fire('GetContent', updatedArgs);
  16982. return updatedArgs.content;
  16983. }
  16984. if (updatedArgs.format === 'text') {
  16985. return getTextContent(editor);
  16986. } else {
  16987. updatedArgs.getInner = true;
  16988. var content = getSerializedContent(editor, updatedArgs);
  16989. if (updatedArgs.format === 'tree') {
  16990. return content;
  16991. } else {
  16992. updatedArgs.content = editor.selection.isCollapsed() ? '' : content;
  16993. editor.fire('GetContent', updatedArgs);
  16994. return updatedArgs.content;
  16995. }
  16996. }
  16997. };
  16998. var KEEP = 0, INSERT = 1, DELETE = 2;
  16999. var diff = function (left, right) {
  17000. var size = left.length + right.length + 2;
  17001. var vDown = new Array(size);
  17002. var vUp = new Array(size);
  17003. var snake = function (start, end, diag) {
  17004. return {
  17005. start: start,
  17006. end: end,
  17007. diag: diag
  17008. };
  17009. };
  17010. var buildScript = function (start1, end1, start2, end2, script) {
  17011. var middle = getMiddleSnake(start1, end1, start2, end2);
  17012. if (middle === null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) {
  17013. var i = start1;
  17014. var j = start2;
  17015. while (i < end1 || j < end2) {
  17016. if (i < end1 && j < end2 && left[i] === right[j]) {
  17017. script.push([
  17018. KEEP,
  17019. left[i]
  17020. ]);
  17021. ++i;
  17022. ++j;
  17023. } else {
  17024. if (end1 - start1 > end2 - start2) {
  17025. script.push([
  17026. DELETE,
  17027. left[i]
  17028. ]);
  17029. ++i;
  17030. } else {
  17031. script.push([
  17032. INSERT,
  17033. right[j]
  17034. ]);
  17035. ++j;
  17036. }
  17037. }
  17038. }
  17039. } else {
  17040. buildScript(start1, middle.start, start2, middle.start - middle.diag, script);
  17041. for (var i2 = middle.start; i2 < middle.end; ++i2) {
  17042. script.push([
  17043. KEEP,
  17044. left[i2]
  17045. ]);
  17046. }
  17047. buildScript(middle.end, end1, middle.end - middle.diag, end2, script);
  17048. }
  17049. };
  17050. var buildSnake = function (start, diag, end1, end2) {
  17051. var end = start;
  17052. while (end - diag < end2 && end < end1 && left[end] === right[end - diag]) {
  17053. ++end;
  17054. }
  17055. return snake(start, end, diag);
  17056. };
  17057. var getMiddleSnake = function (start1, end1, start2, end2) {
  17058. var m = end1 - start1;
  17059. var n = end2 - start2;
  17060. if (m === 0 || n === 0) {
  17061. return null;
  17062. }
  17063. var delta = m - n;
  17064. var sum = n + m;
  17065. var offset = (sum % 2 === 0 ? sum : sum + 1) / 2;
  17066. vDown[1 + offset] = start1;
  17067. vUp[1 + offset] = end1 + 1;
  17068. var d, k, i, x, y;
  17069. for (d = 0; d <= offset; ++d) {
  17070. for (k = -d; k <= d; k += 2) {
  17071. i = k + offset;
  17072. if (k === -d || k !== d && vDown[i - 1] < vDown[i + 1]) {
  17073. vDown[i] = vDown[i + 1];
  17074. } else {
  17075. vDown[i] = vDown[i - 1] + 1;
  17076. }
  17077. x = vDown[i];
  17078. y = x - start1 + start2 - k;
  17079. while (x < end1 && y < end2 && left[x] === right[y]) {
  17080. vDown[i] = ++x;
  17081. ++y;
  17082. }
  17083. if (delta % 2 !== 0 && delta - d <= k && k <= delta + d) {
  17084. if (vUp[i - delta] <= vDown[i]) {
  17085. return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2);
  17086. }
  17087. }
  17088. }
  17089. for (k = delta - d; k <= delta + d; k += 2) {
  17090. i = k + offset - delta;
  17091. if (k === delta - d || k !== delta + d && vUp[i + 1] <= vUp[i - 1]) {
  17092. vUp[i] = vUp[i + 1] - 1;
  17093. } else {
  17094. vUp[i] = vUp[i - 1];
  17095. }
  17096. x = vUp[i] - 1;
  17097. y = x - start1 + start2 - k;
  17098. while (x >= start1 && y >= start2 && left[x] === right[y]) {
  17099. vUp[i] = x--;
  17100. y--;
  17101. }
  17102. if (delta % 2 === 0 && -d <= k && k <= d) {
  17103. if (vUp[i] <= vDown[i + delta]) {
  17104. return buildSnake(vUp[i], k + start1 - start2, end1, end2);
  17105. }
  17106. }
  17107. }
  17108. }
  17109. };
  17110. var script = [];
  17111. buildScript(0, left.length, 0, right.length, script);
  17112. return script;
  17113. };
  17114. var getOuterHtml = function (elm) {
  17115. if (isElement$5(elm)) {
  17116. return elm.outerHTML;
  17117. } else if (isText$7(elm)) {
  17118. return Entities.encodeRaw(elm.data, false);
  17119. } else if (isComment(elm)) {
  17120. return '<!--' + elm.data + '-->';
  17121. }
  17122. return '';
  17123. };
  17124. var createFragment = function (html) {
  17125. var node;
  17126. var container = document.createElement('div');
  17127. var frag = document.createDocumentFragment();
  17128. if (html) {
  17129. container.innerHTML = html;
  17130. }
  17131. while (node = container.firstChild) {
  17132. frag.appendChild(node);
  17133. }
  17134. return frag;
  17135. };
  17136. var insertAt = function (elm, html, index) {
  17137. var fragment = createFragment(html);
  17138. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  17139. var target = elm.childNodes[index];
  17140. target.parentNode.insertBefore(fragment, target);
  17141. } else {
  17142. elm.appendChild(fragment);
  17143. }
  17144. };
  17145. var removeAt = function (elm, index) {
  17146. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  17147. var target = elm.childNodes[index];
  17148. target.parentNode.removeChild(target);
  17149. }
  17150. };
  17151. var applyDiff = function (diff, elm) {
  17152. var index = 0;
  17153. each$k(diff, function (action) {
  17154. if (action[0] === KEEP) {
  17155. index++;
  17156. } else if (action[0] === INSERT) {
  17157. insertAt(elm, action[1], index);
  17158. index++;
  17159. } else if (action[0] === DELETE) {
  17160. removeAt(elm, index);
  17161. }
  17162. });
  17163. };
  17164. var read$2 = function (elm) {
  17165. return filter$4(map$3(from(elm.childNodes), getOuterHtml), function (item) {
  17166. return item.length > 0;
  17167. });
  17168. };
  17169. var write = function (fragments, elm) {
  17170. var currentFragments = map$3(from(elm.childNodes), getOuterHtml);
  17171. applyDiff(diff(currentFragments, fragments), elm);
  17172. return elm;
  17173. };
  17174. var lazyTempDocument = cached(function () {
  17175. return document.implementation.createHTMLDocument('undo');
  17176. });
  17177. var hasIframes = function (html) {
  17178. return html.indexOf('</iframe>') !== -1;
  17179. };
  17180. var createFragmentedLevel = function (fragments) {
  17181. return {
  17182. type: 'fragmented',
  17183. fragments: fragments,
  17184. content: '',
  17185. bookmark: null,
  17186. beforeBookmark: null
  17187. };
  17188. };
  17189. var createCompleteLevel = function (content) {
  17190. return {
  17191. type: 'complete',
  17192. fragments: null,
  17193. content: content,
  17194. bookmark: null,
  17195. beforeBookmark: null
  17196. };
  17197. };
  17198. var createFromEditor = function (editor) {
  17199. var fragments = read$2(editor.getBody());
  17200. var trimmedFragments = bind(fragments, function (html) {
  17201. var trimmed = trimInternal(editor.serializer, html);
  17202. return trimmed.length > 0 ? [trimmed] : [];
  17203. });
  17204. var content = trimmedFragments.join('');
  17205. return hasIframes(content) ? createFragmentedLevel(trimmedFragments) : createCompleteLevel(content);
  17206. };
  17207. var applyToEditor = function (editor, level, before) {
  17208. var bookmark = before ? level.beforeBookmark : level.bookmark;
  17209. if (level.type === 'fragmented') {
  17210. write(level.fragments, editor.getBody());
  17211. } else {
  17212. editor.setContent(level.content, {
  17213. format: 'raw',
  17214. no_selection: isNonNullable(bookmark) && isPathBookmark(bookmark) ? !bookmark.isFakeCaret : true
  17215. });
  17216. }
  17217. editor.selection.moveToBookmark(bookmark);
  17218. };
  17219. var getLevelContent = function (level) {
  17220. return level.type === 'fragmented' ? level.fragments.join('') : level.content;
  17221. };
  17222. var getCleanLevelContent = function (level) {
  17223. var elm = SugarElement.fromTag('body', lazyTempDocument());
  17224. set(elm, getLevelContent(level));
  17225. each$k(descendants(elm, '*[data-mce-bogus]'), unwrap);
  17226. return get$3(elm);
  17227. };
  17228. var hasEqualContent = function (level1, level2) {
  17229. return getLevelContent(level1) === getLevelContent(level2);
  17230. };
  17231. var hasEqualCleanedContent = function (level1, level2) {
  17232. return getCleanLevelContent(level1) === getCleanLevelContent(level2);
  17233. };
  17234. var isEq$1 = function (level1, level2) {
  17235. if (!level1 || !level2) {
  17236. return false;
  17237. } else if (hasEqualContent(level1, level2)) {
  17238. return true;
  17239. } else {
  17240. return hasEqualCleanedContent(level1, level2);
  17241. }
  17242. };
  17243. var isUnlocked = function (locks) {
  17244. return locks.get() === 0;
  17245. };
  17246. var setTyping = function (undoManager, typing, locks) {
  17247. if (isUnlocked(locks)) {
  17248. undoManager.typing = typing;
  17249. }
  17250. };
  17251. var endTyping = function (undoManager, locks) {
  17252. if (undoManager.typing) {
  17253. setTyping(undoManager, false, locks);
  17254. undoManager.add();
  17255. }
  17256. };
  17257. var endTypingLevelIgnoreLocks = function (undoManager) {
  17258. if (undoManager.typing) {
  17259. undoManager.typing = false;
  17260. undoManager.add();
  17261. }
  17262. };
  17263. var beforeChange$1 = function (editor, locks, beforeBookmark) {
  17264. if (isUnlocked(locks)) {
  17265. beforeBookmark.set(getUndoBookmark(editor.selection));
  17266. }
  17267. };
  17268. var addUndoLevel$1 = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  17269. var currentLevel = createFromEditor(editor);
  17270. level = level || {};
  17271. level = Tools.extend(level, currentLevel);
  17272. if (isUnlocked(locks) === false || editor.removed) {
  17273. return null;
  17274. }
  17275. var lastLevel = undoManager.data[index.get()];
  17276. if (editor.fire('BeforeAddUndo', {
  17277. level: level,
  17278. lastLevel: lastLevel,
  17279. originalEvent: event
  17280. }).isDefaultPrevented()) {
  17281. return null;
  17282. }
  17283. if (lastLevel && isEq$1(lastLevel, level)) {
  17284. return null;
  17285. }
  17286. if (undoManager.data[index.get()]) {
  17287. beforeBookmark.get().each(function (bm) {
  17288. undoManager.data[index.get()].beforeBookmark = bm;
  17289. });
  17290. }
  17291. var customUndoRedoLevels = getCustomUndoRedoLevels(editor);
  17292. if (customUndoRedoLevels) {
  17293. if (undoManager.data.length > customUndoRedoLevels) {
  17294. for (var i = 0; i < undoManager.data.length - 1; i++) {
  17295. undoManager.data[i] = undoManager.data[i + 1];
  17296. }
  17297. undoManager.data.length--;
  17298. index.set(undoManager.data.length);
  17299. }
  17300. }
  17301. level.bookmark = getUndoBookmark(editor.selection);
  17302. if (index.get() < undoManager.data.length - 1) {
  17303. undoManager.data.length = index.get() + 1;
  17304. }
  17305. undoManager.data.push(level);
  17306. index.set(undoManager.data.length - 1);
  17307. var args = {
  17308. level: level,
  17309. lastLevel: lastLevel,
  17310. originalEvent: event
  17311. };
  17312. if (index.get() > 0) {
  17313. editor.setDirty(true);
  17314. editor.fire('AddUndo', args);
  17315. editor.fire('change', args);
  17316. } else {
  17317. editor.fire('AddUndo', args);
  17318. }
  17319. return level;
  17320. };
  17321. var clear$1 = function (editor, undoManager, index) {
  17322. undoManager.data = [];
  17323. index.set(0);
  17324. undoManager.typing = false;
  17325. editor.fire('ClearUndos');
  17326. };
  17327. var extra$1 = function (editor, undoManager, index, callback1, callback2) {
  17328. if (undoManager.transact(callback1)) {
  17329. var bookmark = undoManager.data[index.get()].bookmark;
  17330. var lastLevel = undoManager.data[index.get() - 1];
  17331. applyToEditor(editor, lastLevel, true);
  17332. if (undoManager.transact(callback2)) {
  17333. undoManager.data[index.get() - 1].beforeBookmark = bookmark;
  17334. }
  17335. }
  17336. };
  17337. var redo$1 = function (editor, index, data) {
  17338. var level;
  17339. if (index.get() < data.length - 1) {
  17340. index.set(index.get() + 1);
  17341. level = data[index.get()];
  17342. applyToEditor(editor, level, false);
  17343. editor.setDirty(true);
  17344. editor.fire('Redo', { level: level });
  17345. }
  17346. return level;
  17347. };
  17348. var undo$1 = function (editor, undoManager, locks, index) {
  17349. var level;
  17350. if (undoManager.typing) {
  17351. undoManager.add();
  17352. undoManager.typing = false;
  17353. setTyping(undoManager, false, locks);
  17354. }
  17355. if (index.get() > 0) {
  17356. index.set(index.get() - 1);
  17357. level = undoManager.data[index.get()];
  17358. applyToEditor(editor, level, true);
  17359. editor.setDirty(true);
  17360. editor.fire('Undo', { level: level });
  17361. }
  17362. return level;
  17363. };
  17364. var reset$1 = function (undoManager) {
  17365. undoManager.clear();
  17366. undoManager.add();
  17367. };
  17368. var hasUndo$1 = function (editor, undoManager, index) {
  17369. return index.get() > 0 || undoManager.typing && undoManager.data[0] && !isEq$1(createFromEditor(editor), undoManager.data[0]);
  17370. };
  17371. var hasRedo$1 = function (undoManager, index) {
  17372. return index.get() < undoManager.data.length - 1 && !undoManager.typing;
  17373. };
  17374. var transact$1 = function (undoManager, locks, callback) {
  17375. endTyping(undoManager, locks);
  17376. undoManager.beforeChange();
  17377. undoManager.ignore(callback);
  17378. return undoManager.add();
  17379. };
  17380. var ignore$1 = function (locks, callback) {
  17381. try {
  17382. locks.set(locks.get() + 1);
  17383. callback();
  17384. } finally {
  17385. locks.set(locks.get() - 1);
  17386. }
  17387. };
  17388. var addVisualInternal = function (editor, elm) {
  17389. var dom = editor.dom;
  17390. var scope = isNonNullable(elm) ? elm : editor.getBody();
  17391. if (isUndefined(editor.hasVisual)) {
  17392. editor.hasVisual = isVisualAidsEnabled(editor);
  17393. }
  17394. each$k(dom.select('table,a', scope), function (matchedElm) {
  17395. switch (matchedElm.nodeName) {
  17396. case 'TABLE':
  17397. var cls = getVisualAidsTableClass(editor);
  17398. var value = dom.getAttrib(matchedElm, 'border');
  17399. if ((!value || value === '0') && editor.hasVisual) {
  17400. dom.addClass(matchedElm, cls);
  17401. } else {
  17402. dom.removeClass(matchedElm, cls);
  17403. }
  17404. break;
  17405. case 'A':
  17406. if (!dom.getAttrib(matchedElm, 'href')) {
  17407. var value_1 = dom.getAttrib(matchedElm, 'name') || matchedElm.id;
  17408. var cls_1 = getVisualAidsAnchorClass(editor);
  17409. if (value_1 && editor.hasVisual) {
  17410. dom.addClass(matchedElm, cls_1);
  17411. } else {
  17412. dom.removeClass(matchedElm, cls_1);
  17413. }
  17414. }
  17415. break;
  17416. }
  17417. });
  17418. editor.fire('VisualAid', {
  17419. element: elm,
  17420. hasVisual: editor.hasVisual
  17421. });
  17422. };
  17423. var makePlainAdaptor = function (editor) {
  17424. return {
  17425. undoManager: {
  17426. beforeChange: function (locks, beforeBookmark) {
  17427. return beforeChange$1(editor, locks, beforeBookmark);
  17428. },
  17429. add: function (undoManager, index, locks, beforeBookmark, level, event) {
  17430. return addUndoLevel$1(editor, undoManager, index, locks, beforeBookmark, level, event);
  17431. },
  17432. undo: function (undoManager, locks, index) {
  17433. return undo$1(editor, undoManager, locks, index);
  17434. },
  17435. redo: function (index, data) {
  17436. return redo$1(editor, index, data);
  17437. },
  17438. clear: function (undoManager, index) {
  17439. return clear$1(editor, undoManager, index);
  17440. },
  17441. reset: function (undoManager) {
  17442. return reset$1(undoManager);
  17443. },
  17444. hasUndo: function (undoManager, index) {
  17445. return hasUndo$1(editor, undoManager, index);
  17446. },
  17447. hasRedo: function (undoManager, index) {
  17448. return hasRedo$1(undoManager, index);
  17449. },
  17450. transact: function (undoManager, locks, callback) {
  17451. return transact$1(undoManager, locks, callback);
  17452. },
  17453. ignore: function (locks, callback) {
  17454. return ignore$1(locks, callback);
  17455. },
  17456. extra: function (undoManager, index, callback1, callback2) {
  17457. return extra$1(editor, undoManager, index, callback1, callback2);
  17458. }
  17459. },
  17460. formatter: {
  17461. match: function (name, vars, node, similar) {
  17462. return match$2(editor, name, vars, node, similar);
  17463. },
  17464. matchAll: function (names, vars) {
  17465. return matchAll(editor, names, vars);
  17466. },
  17467. matchNode: function (node, name, vars, similar) {
  17468. return matchNode(editor, node, name, vars, similar);
  17469. },
  17470. canApply: function (name) {
  17471. return canApply(editor, name);
  17472. },
  17473. closest: function (names) {
  17474. return closest(editor, names);
  17475. },
  17476. apply: function (name, vars, node) {
  17477. return applyFormat$1(editor, name, vars, node);
  17478. },
  17479. remove: function (name, vars, node, similar) {
  17480. return remove$1(editor, name, vars, node, similar);
  17481. },
  17482. toggle: function (name, vars, node) {
  17483. return toggle(editor, name, vars, node);
  17484. },
  17485. formatChanged: function (registeredFormatListeners, formats, callback, similar, vars) {
  17486. return formatChangedInternal(editor, registeredFormatListeners, formats, callback, similar, vars);
  17487. }
  17488. },
  17489. editor: {
  17490. getContent: function (args, format) {
  17491. return getContentInternal(editor, args, format);
  17492. },
  17493. setContent: function (content, args) {
  17494. return setContentInternal(editor, content, args);
  17495. },
  17496. insertContent: function (value, details) {
  17497. return insertHtmlAtCaret(editor, value, details);
  17498. },
  17499. addVisual: function (elm) {
  17500. return addVisualInternal(editor, elm);
  17501. }
  17502. },
  17503. selection: {
  17504. getContent: function (format, args) {
  17505. return getSelectedContentInternal(editor, format, args);
  17506. }
  17507. },
  17508. raw: {
  17509. getModel: function () {
  17510. return Optional.none();
  17511. }
  17512. }
  17513. };
  17514. };
  17515. var makeRtcAdaptor = function (rtcEditor) {
  17516. var defaultVars = function (vars) {
  17517. return isObject(vars) ? vars : {};
  17518. };
  17519. var undoManager = rtcEditor.undoManager, formatter = rtcEditor.formatter, editor = rtcEditor.editor, selection = rtcEditor.selection, raw = rtcEditor.raw;
  17520. return {
  17521. undoManager: {
  17522. beforeChange: undoManager.beforeChange,
  17523. add: undoManager.add,
  17524. undo: undoManager.undo,
  17525. redo: undoManager.redo,
  17526. clear: undoManager.clear,
  17527. reset: undoManager.reset,
  17528. hasUndo: undoManager.hasUndo,
  17529. hasRedo: undoManager.hasRedo,
  17530. transact: function (_undoManager, _locks, fn) {
  17531. return undoManager.transact(fn);
  17532. },
  17533. ignore: function (_locks, callback) {
  17534. return undoManager.ignore(callback);
  17535. },
  17536. extra: function (_undoManager, _index, callback1, callback2) {
  17537. return undoManager.extra(callback1, callback2);
  17538. }
  17539. },
  17540. formatter: {
  17541. match: function (name, vars, _node, similar) {
  17542. return formatter.match(name, defaultVars(vars), similar);
  17543. },
  17544. matchAll: formatter.matchAll,
  17545. matchNode: formatter.matchNode,
  17546. canApply: function (name) {
  17547. return formatter.canApply(name);
  17548. },
  17549. closest: function (names) {
  17550. return formatter.closest(names);
  17551. },
  17552. apply: function (name, vars, _node) {
  17553. return formatter.apply(name, defaultVars(vars));
  17554. },
  17555. remove: function (name, vars, _node, _similar) {
  17556. return formatter.remove(name, defaultVars(vars));
  17557. },
  17558. toggle: function (name, vars, _node) {
  17559. return formatter.toggle(name, defaultVars(vars));
  17560. },
  17561. formatChanged: function (_rfl, formats, callback, similar, vars) {
  17562. return formatter.formatChanged(formats, callback, similar, vars);
  17563. }
  17564. },
  17565. editor: {
  17566. getContent: function (args, _format) {
  17567. return editor.getContent(args);
  17568. },
  17569. setContent: function (content, args) {
  17570. return editor.setContent(content, args);
  17571. },
  17572. insertContent: function (content, _details) {
  17573. return editor.insertContent(content);
  17574. },
  17575. addVisual: editor.addVisual
  17576. },
  17577. selection: {
  17578. getContent: function (_format, args) {
  17579. return selection.getContent(args);
  17580. }
  17581. },
  17582. raw: {
  17583. getModel: function () {
  17584. return Optional.some(raw.getRawModel());
  17585. }
  17586. }
  17587. };
  17588. };
  17589. var makeNoopAdaptor = function () {
  17590. var nul = constant(null);
  17591. var empty = constant('');
  17592. return {
  17593. undoManager: {
  17594. beforeChange: noop,
  17595. add: nul,
  17596. undo: nul,
  17597. redo: nul,
  17598. clear: noop,
  17599. reset: noop,
  17600. hasUndo: never,
  17601. hasRedo: never,
  17602. transact: nul,
  17603. ignore: noop,
  17604. extra: noop
  17605. },
  17606. formatter: {
  17607. match: never,
  17608. matchAll: constant([]),
  17609. matchNode: constant(undefined),
  17610. canApply: never,
  17611. closest: empty,
  17612. apply: noop,
  17613. remove: noop,
  17614. toggle: noop,
  17615. formatChanged: constant({ unbind: noop })
  17616. },
  17617. editor: {
  17618. getContent: empty,
  17619. setContent: empty,
  17620. insertContent: noop,
  17621. addVisual: noop
  17622. },
  17623. selection: { getContent: empty },
  17624. raw: { getModel: constant(Optional.none()) }
  17625. };
  17626. };
  17627. var isRtc = function (editor) {
  17628. return has$2(editor.plugins, 'rtc');
  17629. };
  17630. var getRtcSetup = function (editor) {
  17631. return get$9(editor.plugins, 'rtc').bind(function (rtcPlugin) {
  17632. return Optional.from(rtcPlugin.setup);
  17633. });
  17634. };
  17635. var setup$i = function (editor) {
  17636. var editorCast = editor;
  17637. return getRtcSetup(editor).fold(function () {
  17638. editorCast.rtcInstance = makePlainAdaptor(editor);
  17639. return Optional.none();
  17640. }, function (setup) {
  17641. editorCast.rtcInstance = makeNoopAdaptor();
  17642. return Optional.some(function () {
  17643. return setup().then(function (rtcEditor) {
  17644. editorCast.rtcInstance = makeRtcAdaptor(rtcEditor);
  17645. return rtcEditor.rtc.isRemote;
  17646. });
  17647. });
  17648. });
  17649. };
  17650. var getRtcInstanceWithFallback = function (editor) {
  17651. return editor.rtcInstance ? editor.rtcInstance : makePlainAdaptor(editor);
  17652. };
  17653. var getRtcInstanceWithError = function (editor) {
  17654. var rtcInstance = editor.rtcInstance;
  17655. if (!rtcInstance) {
  17656. throw new Error('Failed to get RTC instance not yet initialized.');
  17657. } else {
  17658. return rtcInstance;
  17659. }
  17660. };
  17661. var beforeChange = function (editor, locks, beforeBookmark) {
  17662. getRtcInstanceWithError(editor).undoManager.beforeChange(locks, beforeBookmark);
  17663. };
  17664. var addUndoLevel = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  17665. return getRtcInstanceWithError(editor).undoManager.add(undoManager, index, locks, beforeBookmark, level, event);
  17666. };
  17667. var undo = function (editor, undoManager, locks, index) {
  17668. return getRtcInstanceWithError(editor).undoManager.undo(undoManager, locks, index);
  17669. };
  17670. var redo = function (editor, index, data) {
  17671. return getRtcInstanceWithError(editor).undoManager.redo(index, data);
  17672. };
  17673. var clear = function (editor, undoManager, index) {
  17674. getRtcInstanceWithError(editor).undoManager.clear(undoManager, index);
  17675. };
  17676. var reset = function (editor, undoManager) {
  17677. getRtcInstanceWithError(editor).undoManager.reset(undoManager);
  17678. };
  17679. var hasUndo = function (editor, undoManager, index) {
  17680. return getRtcInstanceWithError(editor).undoManager.hasUndo(undoManager, index);
  17681. };
  17682. var hasRedo = function (editor, undoManager, index) {
  17683. return getRtcInstanceWithError(editor).undoManager.hasRedo(undoManager, index);
  17684. };
  17685. var transact = function (editor, undoManager, locks, callback) {
  17686. return getRtcInstanceWithError(editor).undoManager.transact(undoManager, locks, callback);
  17687. };
  17688. var ignore = function (editor, locks, callback) {
  17689. getRtcInstanceWithError(editor).undoManager.ignore(locks, callback);
  17690. };
  17691. var extra = function (editor, undoManager, index, callback1, callback2) {
  17692. getRtcInstanceWithError(editor).undoManager.extra(undoManager, index, callback1, callback2);
  17693. };
  17694. var matchFormat = function (editor, name, vars, node, similar) {
  17695. return getRtcInstanceWithError(editor).formatter.match(name, vars, node, similar);
  17696. };
  17697. var matchAllFormats = function (editor, names, vars) {
  17698. return getRtcInstanceWithError(editor).formatter.matchAll(names, vars);
  17699. };
  17700. var matchNodeFormat = function (editor, node, name, vars, similar) {
  17701. return getRtcInstanceWithError(editor).formatter.matchNode(node, name, vars, similar);
  17702. };
  17703. var canApplyFormat = function (editor, name) {
  17704. return getRtcInstanceWithError(editor).formatter.canApply(name);
  17705. };
  17706. var closestFormat = function (editor, names) {
  17707. return getRtcInstanceWithError(editor).formatter.closest(names);
  17708. };
  17709. var applyFormat = function (editor, name, vars, node) {
  17710. getRtcInstanceWithError(editor).formatter.apply(name, vars, node);
  17711. };
  17712. var removeFormat = function (editor, name, vars, node, similar) {
  17713. getRtcInstanceWithError(editor).formatter.remove(name, vars, node, similar);
  17714. };
  17715. var toggleFormat = function (editor, name, vars, node) {
  17716. getRtcInstanceWithError(editor).formatter.toggle(name, vars, node);
  17717. };
  17718. var formatChanged = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  17719. return getRtcInstanceWithError(editor).formatter.formatChanged(registeredFormatListeners, formats, callback, similar, vars);
  17720. };
  17721. var getContent$2 = function (editor, args, format) {
  17722. return getRtcInstanceWithFallback(editor).editor.getContent(args, format);
  17723. };
  17724. var setContent$2 = function (editor, content, args) {
  17725. return getRtcInstanceWithFallback(editor).editor.setContent(content, args);
  17726. };
  17727. var insertContent = function (editor, value, details) {
  17728. return getRtcInstanceWithFallback(editor).editor.insertContent(value, details);
  17729. };
  17730. var getSelectedContent = function (editor, format, args) {
  17731. return getRtcInstanceWithError(editor).selection.getContent(format, args);
  17732. };
  17733. var addVisual$1 = function (editor, elm) {
  17734. return getRtcInstanceWithError(editor).editor.addVisual(elm);
  17735. };
  17736. var getContent$1 = function (editor, args) {
  17737. if (args === void 0) {
  17738. args = {};
  17739. }
  17740. var format = args.format ? args.format : 'html';
  17741. return getSelectedContent(editor, format, args);
  17742. };
  17743. var removeEmpty = function (text) {
  17744. if (text.dom.length === 0) {
  17745. remove$7(text);
  17746. return Optional.none();
  17747. } else {
  17748. return Optional.some(text);
  17749. }
  17750. };
  17751. var walkPastBookmark = function (node, start) {
  17752. return node.filter(function (elm) {
  17753. return BookmarkManager.isBookmarkNode(elm.dom);
  17754. }).bind(start ? nextSibling : prevSibling);
  17755. };
  17756. var merge = function (outer, inner, rng, start) {
  17757. var outerElm = outer.dom;
  17758. var innerElm = inner.dom;
  17759. var oldLength = start ? outerElm.length : innerElm.length;
  17760. if (start) {
  17761. mergeTextNodes(outerElm, innerElm, false, !start);
  17762. rng.setStart(innerElm, oldLength);
  17763. } else {
  17764. mergeTextNodes(innerElm, outerElm, false, !start);
  17765. rng.setEnd(innerElm, oldLength);
  17766. }
  17767. };
  17768. var normalizeTextIfRequired = function (inner, start) {
  17769. parent(inner).each(function (root) {
  17770. var text = inner.dom;
  17771. if (start && needsToBeNbspLeft(root, CaretPosition(text, 0))) {
  17772. normalizeWhitespaceAfter(text, 0);
  17773. } else if (!start && needsToBeNbspRight(root, CaretPosition(text, text.length))) {
  17774. normalizeWhitespaceBefore(text, text.length);
  17775. }
  17776. });
  17777. };
  17778. var mergeAndNormalizeText = function (outerNode, innerNode, rng, start) {
  17779. outerNode.bind(function (outer) {
  17780. var normalizer = start ? normalizeWhitespaceBefore : normalizeWhitespaceAfter;
  17781. normalizer(outer.dom, start ? outer.dom.length : 0);
  17782. return innerNode.filter(isText$8).map(function (inner) {
  17783. return merge(outer, inner, rng, start);
  17784. });
  17785. }).orThunk(function () {
  17786. var innerTextNode = walkPastBookmark(innerNode, start).or(innerNode).filter(isText$8);
  17787. return innerTextNode.map(function (inner) {
  17788. return normalizeTextIfRequired(inner, start);
  17789. });
  17790. });
  17791. };
  17792. var rngSetContent = function (rng, fragment) {
  17793. var firstChild = Optional.from(fragment.firstChild).map(SugarElement.fromDom);
  17794. var lastChild = Optional.from(fragment.lastChild).map(SugarElement.fromDom);
  17795. rng.deleteContents();
  17796. rng.insertNode(fragment);
  17797. var prevText = firstChild.bind(prevSibling).filter(isText$8).bind(removeEmpty);
  17798. var nextText = lastChild.bind(nextSibling).filter(isText$8).bind(removeEmpty);
  17799. mergeAndNormalizeText(prevText, firstChild, rng, true);
  17800. mergeAndNormalizeText(nextText, lastChild, rng, false);
  17801. rng.collapse(false);
  17802. };
  17803. var setupArgs = function (args, content) {
  17804. return __assign(__assign({ format: 'html' }, args), {
  17805. set: true,
  17806. selection: true,
  17807. content: content
  17808. });
  17809. };
  17810. var cleanContent = function (editor, args) {
  17811. if (args.format !== 'raw') {
  17812. var rng = editor.selection.getRng();
  17813. var contextBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
  17814. var contextArgs = contextBlock ? { context: contextBlock.nodeName.toLowerCase() } : {};
  17815. var node = editor.parser.parse(args.content, __assign(__assign({
  17816. isRootContent: true,
  17817. forced_root_block: false
  17818. }, contextArgs), args));
  17819. return HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(node);
  17820. } else {
  17821. return args.content;
  17822. }
  17823. };
  17824. var setContent$1 = function (editor, content, args) {
  17825. if (args === void 0) {
  17826. args = {};
  17827. }
  17828. var defaultedArgs = setupArgs(args, content);
  17829. var updatedArgs = defaultedArgs;
  17830. if (!defaultedArgs.no_events) {
  17831. var eventArgs = editor.fire('BeforeSetContent', defaultedArgs);
  17832. if (eventArgs.isDefaultPrevented()) {
  17833. editor.fire('SetContent', eventArgs);
  17834. return;
  17835. } else {
  17836. updatedArgs = eventArgs;
  17837. }
  17838. }
  17839. updatedArgs.content = cleanContent(editor, updatedArgs);
  17840. var rng = editor.selection.getRng();
  17841. rngSetContent(rng, rng.createContextualFragment(updatedArgs.content));
  17842. editor.selection.setRng(rng);
  17843. scrollRangeIntoView(editor, rng);
  17844. if (!updatedArgs.no_events) {
  17845. editor.fire('SetContent', updatedArgs);
  17846. }
  17847. };
  17848. var deleteFromCallbackMap = function (callbackMap, selector, callback) {
  17849. if (callbackMap && has$2(callbackMap, selector)) {
  17850. var newCallbacks = filter$4(callbackMap[selector], function (cb) {
  17851. return cb !== callback;
  17852. });
  17853. if (newCallbacks.length === 0) {
  17854. delete callbackMap[selector];
  17855. } else {
  17856. callbackMap[selector] = newCallbacks;
  17857. }
  17858. }
  17859. };
  17860. function SelectorChanged (dom, editor) {
  17861. var selectorChangedData;
  17862. var currentSelectors;
  17863. var findMatchingNode = function (selector, nodes) {
  17864. return find$3(nodes, function (node) {
  17865. return dom.is(node, selector);
  17866. });
  17867. };
  17868. var getParents = function (elem) {
  17869. return dom.getParents(elem, null, dom.getRoot());
  17870. };
  17871. return {
  17872. selectorChangedWithUnbind: function (selector, callback) {
  17873. if (!selectorChangedData) {
  17874. selectorChangedData = {};
  17875. currentSelectors = {};
  17876. editor.on('NodeChange', function (e) {
  17877. var node = e.element;
  17878. var parents = getParents(node);
  17879. var matchedSelectors = {};
  17880. Tools.each(selectorChangedData, function (callbacks, selector) {
  17881. findMatchingNode(selector, parents).each(function (node) {
  17882. if (!currentSelectors[selector]) {
  17883. each$k(callbacks, function (callback) {
  17884. callback(true, {
  17885. node: node,
  17886. selector: selector,
  17887. parents: parents
  17888. });
  17889. });
  17890. currentSelectors[selector] = callbacks;
  17891. }
  17892. matchedSelectors[selector] = callbacks;
  17893. });
  17894. });
  17895. Tools.each(currentSelectors, function (callbacks, selector) {
  17896. if (!matchedSelectors[selector]) {
  17897. delete currentSelectors[selector];
  17898. Tools.each(callbacks, function (callback) {
  17899. callback(false, {
  17900. node: node,
  17901. selector: selector,
  17902. parents: parents
  17903. });
  17904. });
  17905. }
  17906. });
  17907. });
  17908. }
  17909. if (!selectorChangedData[selector]) {
  17910. selectorChangedData[selector] = [];
  17911. }
  17912. selectorChangedData[selector].push(callback);
  17913. findMatchingNode(selector, getParents(editor.selection.getStart())).each(function () {
  17914. currentSelectors[selector] = selectorChangedData[selector];
  17915. });
  17916. return {
  17917. unbind: function () {
  17918. deleteFromCallbackMap(selectorChangedData, selector, callback);
  17919. deleteFromCallbackMap(currentSelectors, selector, callback);
  17920. }
  17921. };
  17922. }
  17923. };
  17924. }
  17925. var isNativeIeSelection = function (rng) {
  17926. return !!rng.select;
  17927. };
  17928. var isAttachedToDom = function (node) {
  17929. return !!(node && node.ownerDocument) && contains$1(SugarElement.fromDom(node.ownerDocument), SugarElement.fromDom(node));
  17930. };
  17931. var isValidRange = function (rng) {
  17932. if (!rng) {
  17933. return false;
  17934. } else if (isNativeIeSelection(rng)) {
  17935. return true;
  17936. } else {
  17937. return isAttachedToDom(rng.startContainer) && isAttachedToDom(rng.endContainer);
  17938. }
  17939. };
  17940. var EditorSelection = function (dom, win, serializer, editor) {
  17941. var selectedRange;
  17942. var explicitRange;
  17943. var selectorChangedWithUnbind = SelectorChanged(dom, editor).selectorChangedWithUnbind;
  17944. var setCursorLocation = function (node, offset) {
  17945. var rng = dom.createRng();
  17946. if (isNonNullable(node) && isNonNullable(offset)) {
  17947. rng.setStart(node, offset);
  17948. rng.setEnd(node, offset);
  17949. setRng(rng);
  17950. collapse(false);
  17951. } else {
  17952. moveEndPoint(dom, rng, editor.getBody(), true);
  17953. setRng(rng);
  17954. }
  17955. };
  17956. var getContent = function (args) {
  17957. return getContent$1(editor, args);
  17958. };
  17959. var setContent = function (content, args) {
  17960. return setContent$1(editor, content, args);
  17961. };
  17962. var getStart$1 = function (real) {
  17963. return getStart(editor.getBody(), getRng$1(), real);
  17964. };
  17965. var getEnd$1 = function (real) {
  17966. return getEnd(editor.getBody(), getRng$1(), real);
  17967. };
  17968. var getBookmark = function (type, normalized) {
  17969. return bookmarkManager.getBookmark(type, normalized);
  17970. };
  17971. var moveToBookmark = function (bookmark) {
  17972. return bookmarkManager.moveToBookmark(bookmark);
  17973. };
  17974. var select$1 = function (node, content) {
  17975. select(dom, node, content).each(setRng);
  17976. return node;
  17977. };
  17978. var isCollapsed = function () {
  17979. var rng = getRng$1(), sel = getSel();
  17980. if (!rng || rng.item) {
  17981. return false;
  17982. }
  17983. if (rng.compareEndPoints) {
  17984. return rng.compareEndPoints('StartToEnd', rng) === 0;
  17985. }
  17986. return !sel || rng.collapsed;
  17987. };
  17988. var collapse = function (toStart) {
  17989. var rng = getRng$1();
  17990. rng.collapse(!!toStart);
  17991. setRng(rng);
  17992. };
  17993. var getSel = function () {
  17994. return win.getSelection ? win.getSelection() : win.document.selection;
  17995. };
  17996. var getRng$1 = function () {
  17997. var selection, rng, elm;
  17998. var tryCompareBoundaryPoints = function (how, sourceRange, destinationRange) {
  17999. try {
  18000. return sourceRange.compareBoundaryPoints(how, destinationRange);
  18001. } catch (ex) {
  18002. return -1;
  18003. }
  18004. };
  18005. var doc = win.document;
  18006. if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  18007. var bookmark = getRng(editor);
  18008. if (bookmark.isSome()) {
  18009. return bookmark.map(function (r) {
  18010. return processRanges(editor, [r])[0];
  18011. }).getOr(doc.createRange());
  18012. }
  18013. }
  18014. try {
  18015. if ((selection = getSel()) && !isRestrictedNode(selection.anchorNode)) {
  18016. if (selection.rangeCount > 0) {
  18017. rng = selection.getRangeAt(0);
  18018. } else {
  18019. rng = selection.createRange ? selection.createRange() : doc.createRange();
  18020. }
  18021. rng = processRanges(editor, [rng])[0];
  18022. }
  18023. } catch (ex) {
  18024. }
  18025. if (!rng) {
  18026. rng = doc.createRange ? doc.createRange() : doc.body.createTextRange();
  18027. }
  18028. if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
  18029. elm = dom.getRoot();
  18030. rng.setStart(elm, 0);
  18031. rng.setEnd(elm, 0);
  18032. }
  18033. if (selectedRange && explicitRange) {
  18034. if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 && tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
  18035. rng = explicitRange;
  18036. } else {
  18037. selectedRange = null;
  18038. explicitRange = null;
  18039. }
  18040. }
  18041. return rng;
  18042. };
  18043. var setRng = function (rng, forward) {
  18044. var node;
  18045. if (!isValidRange(rng)) {
  18046. return;
  18047. }
  18048. var ieRange = isNativeIeSelection(rng) ? rng : null;
  18049. if (ieRange) {
  18050. explicitRange = null;
  18051. try {
  18052. ieRange.select();
  18053. } catch (ex) {
  18054. }
  18055. return;
  18056. }
  18057. var sel = getSel();
  18058. var evt = editor.fire('SetSelectionRange', {
  18059. range: rng,
  18060. forward: forward
  18061. });
  18062. rng = evt.range;
  18063. if (sel) {
  18064. explicitRange = rng;
  18065. try {
  18066. sel.removeAllRanges();
  18067. sel.addRange(rng);
  18068. } catch (ex) {
  18069. }
  18070. if (forward === false && sel.extend) {
  18071. sel.collapse(rng.endContainer, rng.endOffset);
  18072. sel.extend(rng.startContainer, rng.startOffset);
  18073. }
  18074. selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
  18075. }
  18076. if (!rng.collapsed && rng.startContainer === rng.endContainer && sel.setBaseAndExtent && !Env.ie) {
  18077. if (rng.endOffset - rng.startOffset < 2) {
  18078. if (rng.startContainer.hasChildNodes()) {
  18079. node = rng.startContainer.childNodes[rng.startOffset];
  18080. if (node && node.tagName === 'IMG') {
  18081. sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
  18082. if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
  18083. sel.setBaseAndExtent(node, 0, node, 1);
  18084. }
  18085. }
  18086. }
  18087. }
  18088. }
  18089. editor.fire('AfterSetSelectionRange', {
  18090. range: rng,
  18091. forward: forward
  18092. });
  18093. };
  18094. var setNode = function (elm) {
  18095. setContent(dom.getOuterHTML(elm));
  18096. return elm;
  18097. };
  18098. var getNode$1 = function () {
  18099. return getNode(editor.getBody(), getRng$1());
  18100. };
  18101. var getSelectedBlocks$1 = function (startElm, endElm) {
  18102. return getSelectedBlocks(dom, getRng$1(), startElm, endElm);
  18103. };
  18104. var isForward = function () {
  18105. var sel = getSel();
  18106. var anchorNode = sel === null || sel === void 0 ? void 0 : sel.anchorNode;
  18107. var focusNode = sel === null || sel === void 0 ? void 0 : sel.focusNode;
  18108. if (!sel || !anchorNode || !focusNode || isRestrictedNode(anchorNode) || isRestrictedNode(focusNode)) {
  18109. return true;
  18110. }
  18111. var anchorRange = dom.createRng();
  18112. anchorRange.setStart(anchorNode, sel.anchorOffset);
  18113. anchorRange.collapse(true);
  18114. var focusRange = dom.createRng();
  18115. focusRange.setStart(focusNode, sel.focusOffset);
  18116. focusRange.collapse(true);
  18117. return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
  18118. };
  18119. var normalize = function () {
  18120. var rng = getRng$1();
  18121. var sel = getSel();
  18122. if (!hasMultipleRanges(sel) && hasAnyRanges(editor)) {
  18123. var normRng = normalize$2(dom, rng);
  18124. normRng.each(function (normRng) {
  18125. setRng(normRng, isForward());
  18126. });
  18127. return normRng.getOr(rng);
  18128. }
  18129. return rng;
  18130. };
  18131. var selectorChanged = function (selector, callback) {
  18132. selectorChangedWithUnbind(selector, callback);
  18133. return exports;
  18134. };
  18135. var getScrollContainer = function () {
  18136. var scrollContainer;
  18137. var node = dom.getRoot();
  18138. while (node && node.nodeName !== 'BODY') {
  18139. if (node.scrollHeight > node.clientHeight) {
  18140. scrollContainer = node;
  18141. break;
  18142. }
  18143. node = node.parentNode;
  18144. }
  18145. return scrollContainer;
  18146. };
  18147. var scrollIntoView = function (elm, alignToTop) {
  18148. if (isNonNullable(elm)) {
  18149. scrollElementIntoView(editor, elm, alignToTop);
  18150. } else {
  18151. scrollRangeIntoView(editor, getRng$1(), alignToTop);
  18152. }
  18153. };
  18154. var placeCaretAt = function (clientX, clientY) {
  18155. return setRng(fromPoint(clientX, clientY, editor.getDoc()));
  18156. };
  18157. var getBoundingClientRect = function () {
  18158. var rng = getRng$1();
  18159. return rng.collapsed ? CaretPosition.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
  18160. };
  18161. var destroy = function () {
  18162. win = selectedRange = explicitRange = null;
  18163. controlSelection.destroy();
  18164. };
  18165. var exports = {
  18166. bookmarkManager: null,
  18167. controlSelection: null,
  18168. dom: dom,
  18169. win: win,
  18170. serializer: serializer,
  18171. editor: editor,
  18172. collapse: collapse,
  18173. setCursorLocation: setCursorLocation,
  18174. getContent: getContent,
  18175. setContent: setContent,
  18176. getBookmark: getBookmark,
  18177. moveToBookmark: moveToBookmark,
  18178. select: select$1,
  18179. isCollapsed: isCollapsed,
  18180. isForward: isForward,
  18181. setNode: setNode,
  18182. getNode: getNode$1,
  18183. getSel: getSel,
  18184. setRng: setRng,
  18185. getRng: getRng$1,
  18186. getStart: getStart$1,
  18187. getEnd: getEnd$1,
  18188. getSelectedBlocks: getSelectedBlocks$1,
  18189. normalize: normalize,
  18190. selectorChanged: selectorChanged,
  18191. selectorChangedWithUnbind: selectorChangedWithUnbind,
  18192. getScrollContainer: getScrollContainer,
  18193. scrollIntoView: scrollIntoView,
  18194. placeCaretAt: placeCaretAt,
  18195. getBoundingClientRect: getBoundingClientRect,
  18196. destroy: destroy
  18197. };
  18198. var bookmarkManager = BookmarkManager(exports);
  18199. var controlSelection = ControlSelection(exports, editor);
  18200. exports.bookmarkManager = bookmarkManager;
  18201. exports.controlSelection = controlSelection;
  18202. return exports;
  18203. };
  18204. var removeAttrs = function (node, names) {
  18205. each$k(names, function (name) {
  18206. node.attr(name, null);
  18207. });
  18208. };
  18209. var addFontToSpansFilter = function (domParser, styles, fontSizes) {
  18210. domParser.addNodeFilter('font', function (nodes) {
  18211. each$k(nodes, function (node) {
  18212. var props = styles.parse(node.attr('style'));
  18213. var color = node.attr('color');
  18214. var face = node.attr('face');
  18215. var size = node.attr('size');
  18216. if (color) {
  18217. props.color = color;
  18218. }
  18219. if (face) {
  18220. props['font-family'] = face;
  18221. }
  18222. if (size) {
  18223. props['font-size'] = fontSizes[parseInt(node.attr('size'), 10) - 1];
  18224. }
  18225. node.name = 'span';
  18226. node.attr('style', styles.serialize(props));
  18227. removeAttrs(node, [
  18228. 'color',
  18229. 'face',
  18230. 'size'
  18231. ]);
  18232. });
  18233. });
  18234. };
  18235. var addStrikeToSpanFilter = function (domParser, styles) {
  18236. domParser.addNodeFilter('strike', function (nodes) {
  18237. each$k(nodes, function (node) {
  18238. var props = styles.parse(node.attr('style'));
  18239. props['text-decoration'] = 'line-through';
  18240. node.name = 'span';
  18241. node.attr('style', styles.serialize(props));
  18242. });
  18243. });
  18244. };
  18245. var addFilters = function (domParser, settings) {
  18246. var styles = Styles();
  18247. if (settings.convert_fonts_to_spans) {
  18248. addFontToSpansFilter(domParser, styles, Tools.explode(settings.font_size_legacy_values));
  18249. }
  18250. addStrikeToSpanFilter(domParser, styles);
  18251. };
  18252. var register$2 = function (domParser, settings) {
  18253. if (settings.inline_styles) {
  18254. addFilters(domParser, settings);
  18255. }
  18256. };
  18257. var blobUriToBlob = function (url) {
  18258. return new promiseObj(function (resolve, reject) {
  18259. var rejectWithError = function () {
  18260. reject('Cannot convert ' + url + ' to Blob. Resource might not exist or is inaccessible.');
  18261. };
  18262. try {
  18263. var xhr_1 = new XMLHttpRequest();
  18264. xhr_1.open('GET', url, true);
  18265. xhr_1.responseType = 'blob';
  18266. xhr_1.onload = function () {
  18267. if (xhr_1.status === 200) {
  18268. resolve(xhr_1.response);
  18269. } else {
  18270. rejectWithError();
  18271. }
  18272. };
  18273. xhr_1.onerror = rejectWithError;
  18274. xhr_1.send();
  18275. } catch (ex) {
  18276. rejectWithError();
  18277. }
  18278. });
  18279. };
  18280. var parseDataUri = function (uri) {
  18281. var type;
  18282. var uriParts = decodeURIComponent(uri).split(',');
  18283. var matches = /data:([^;]+)/.exec(uriParts[0]);
  18284. if (matches) {
  18285. type = matches[1];
  18286. }
  18287. return {
  18288. type: type,
  18289. data: uriParts[1]
  18290. };
  18291. };
  18292. var buildBlob = function (type, data) {
  18293. var str;
  18294. try {
  18295. str = atob(data);
  18296. } catch (e) {
  18297. return Optional.none();
  18298. }
  18299. var arr = new Uint8Array(str.length);
  18300. for (var i = 0; i < arr.length; i++) {
  18301. arr[i] = str.charCodeAt(i);
  18302. }
  18303. return Optional.some(new Blob([arr], { type: type }));
  18304. };
  18305. var dataUriToBlob = function (uri) {
  18306. return new promiseObj(function (resolve) {
  18307. var _a = parseDataUri(uri), type = _a.type, data = _a.data;
  18308. buildBlob(type, data).fold(function () {
  18309. return resolve(new Blob([]));
  18310. }, resolve);
  18311. });
  18312. };
  18313. var uriToBlob = function (url) {
  18314. if (url.indexOf('blob:') === 0) {
  18315. return blobUriToBlob(url);
  18316. }
  18317. if (url.indexOf('data:') === 0) {
  18318. return dataUriToBlob(url);
  18319. }
  18320. return null;
  18321. };
  18322. var blobToDataUri = function (blob) {
  18323. return new promiseObj(function (resolve) {
  18324. var reader = new FileReader();
  18325. reader.onloadend = function () {
  18326. resolve(reader.result);
  18327. };
  18328. reader.readAsDataURL(blob);
  18329. });
  18330. };
  18331. var count$1 = 0;
  18332. var uniqueId = function (prefix) {
  18333. return (prefix || 'blobid') + count$1++;
  18334. };
  18335. var imageToBlobInfo = function (blobCache, img, resolve, reject) {
  18336. var base64, blobInfo;
  18337. if (img.src.indexOf('blob:') === 0) {
  18338. blobInfo = blobCache.getByUri(img.src);
  18339. if (blobInfo) {
  18340. resolve({
  18341. image: img,
  18342. blobInfo: blobInfo
  18343. });
  18344. } else {
  18345. uriToBlob(img.src).then(function (blob) {
  18346. blobToDataUri(blob).then(function (dataUri) {
  18347. base64 = parseDataUri(dataUri).data;
  18348. blobInfo = blobCache.create(uniqueId(), blob, base64);
  18349. blobCache.add(blobInfo);
  18350. resolve({
  18351. image: img,
  18352. blobInfo: blobInfo
  18353. });
  18354. });
  18355. }, function (err) {
  18356. reject(err);
  18357. });
  18358. }
  18359. return;
  18360. }
  18361. var _a = parseDataUri(img.src), data = _a.data, type = _a.type;
  18362. base64 = data;
  18363. blobInfo = blobCache.getByData(base64, type);
  18364. if (blobInfo) {
  18365. resolve({
  18366. image: img,
  18367. blobInfo: blobInfo
  18368. });
  18369. } else {
  18370. uriToBlob(img.src).then(function (blob) {
  18371. blobInfo = blobCache.create(uniqueId(), blob, base64);
  18372. blobCache.add(blobInfo);
  18373. resolve({
  18374. image: img,
  18375. blobInfo: blobInfo
  18376. });
  18377. }, function (err) {
  18378. reject(err);
  18379. });
  18380. }
  18381. };
  18382. var getAllImages = function (elm) {
  18383. return elm ? from(elm.getElementsByTagName('img')) : [];
  18384. };
  18385. var ImageScanner = function (uploadStatus, blobCache) {
  18386. var cachedPromises = {};
  18387. var findAll = function (elm, predicate) {
  18388. if (!predicate) {
  18389. predicate = always;
  18390. }
  18391. var images = filter$4(getAllImages(elm), function (img) {
  18392. var src = img.src;
  18393. if (!Env.fileApi) {
  18394. return false;
  18395. }
  18396. if (img.hasAttribute('data-mce-bogus')) {
  18397. return false;
  18398. }
  18399. if (img.hasAttribute('data-mce-placeholder')) {
  18400. return false;
  18401. }
  18402. if (!src || src === Env.transparentSrc) {
  18403. return false;
  18404. }
  18405. if (src.indexOf('blob:') === 0) {
  18406. return !uploadStatus.isUploaded(src) && predicate(img);
  18407. }
  18408. if (src.indexOf('data:') === 0) {
  18409. return predicate(img);
  18410. }
  18411. return false;
  18412. });
  18413. var promises = map$3(images, function (img) {
  18414. if (cachedPromises[img.src] !== undefined) {
  18415. return new promiseObj(function (resolve) {
  18416. cachedPromises[img.src].then(function (imageInfo) {
  18417. if (typeof imageInfo === 'string') {
  18418. return imageInfo;
  18419. }
  18420. resolve({
  18421. image: img,
  18422. blobInfo: imageInfo.blobInfo
  18423. });
  18424. });
  18425. });
  18426. }
  18427. var newPromise = new promiseObj(function (resolve, reject) {
  18428. imageToBlobInfo(blobCache, img, resolve, reject);
  18429. }).then(function (result) {
  18430. delete cachedPromises[result.image.src];
  18431. return result;
  18432. }).catch(function (error) {
  18433. delete cachedPromises[img.src];
  18434. return error;
  18435. });
  18436. cachedPromises[img.src] = newPromise;
  18437. return newPromise;
  18438. });
  18439. return promiseObj.all(promises);
  18440. };
  18441. return { findAll: findAll };
  18442. };
  18443. var paddEmptyNode = function (settings, args, blockElements, node) {
  18444. var brPreferred = settings.padd_empty_with_br || args.insert;
  18445. if (brPreferred && blockElements[node.name]) {
  18446. node.empty().append(new AstNode('br', 1)).shortEnded = true;
  18447. } else {
  18448. node.empty().append(new AstNode('#text', 3)).value = nbsp;
  18449. }
  18450. };
  18451. var isPaddedWithNbsp = function (node) {
  18452. return hasOnlyChild(node, '#text') && node.firstChild.value === nbsp;
  18453. };
  18454. var hasOnlyChild = function (node, name) {
  18455. return node && node.firstChild && node.firstChild === node.lastChild && node.firstChild.name === name;
  18456. };
  18457. var isPadded = function (schema, node) {
  18458. var rule = schema.getElementRule(node.name);
  18459. return rule && rule.paddEmpty;
  18460. };
  18461. var isEmpty = function (schema, nonEmptyElements, whitespaceElements, node) {
  18462. return node.isEmpty(nonEmptyElements, whitespaceElements, function (node) {
  18463. return isPadded(schema, node);
  18464. });
  18465. };
  18466. var isLineBreakNode = function (node, blockElements) {
  18467. return node && (has$2(blockElements, node.name) || node.name === 'br');
  18468. };
  18469. var isBogusImage = function (img) {
  18470. return isNonNullable(img.attr('data-mce-bogus'));
  18471. };
  18472. var isInternalImageSource = function (img) {
  18473. return img.attr('src') === Env.transparentSrc || isNonNullable(img.attr('data-mce-placeholder'));
  18474. };
  18475. var isValidDataImg = function (img, settings) {
  18476. if (settings.images_dataimg_filter) {
  18477. var imgElem_1 = new Image();
  18478. imgElem_1.src = img.attr('src');
  18479. each$j(img.attributes.map, function (value, key) {
  18480. imgElem_1.setAttribute(key, value);
  18481. });
  18482. return settings.images_dataimg_filter(imgElem_1);
  18483. } else {
  18484. return true;
  18485. }
  18486. };
  18487. var registerBase64ImageFilter = function (parser, settings) {
  18488. var blobCache = settings.blob_cache;
  18489. var processImage = function (img) {
  18490. var inputSrc = img.attr('src');
  18491. if (isInternalImageSource(img) || isBogusImage(img)) {
  18492. return;
  18493. }
  18494. parseDataUri$1(inputSrc).filter(function () {
  18495. return isValidDataImg(img, settings);
  18496. }).bind(function (_a) {
  18497. var type = _a.type, data = _a.data;
  18498. return Optional.from(blobCache.getByData(data, type)).orThunk(function () {
  18499. return buildBlob(type, data).map(function (blob) {
  18500. var blobInfo = blobCache.create(uniqueId(), blob, data);
  18501. blobCache.add(blobInfo);
  18502. return blobInfo;
  18503. });
  18504. });
  18505. }).each(function (blobInfo) {
  18506. img.attr('src', blobInfo.blobUri());
  18507. });
  18508. };
  18509. if (blobCache) {
  18510. parser.addAttributeFilter('src', function (nodes) {
  18511. return each$k(nodes, processImage);
  18512. });
  18513. }
  18514. };
  18515. var register$1 = function (parser, settings) {
  18516. var schema = parser.schema;
  18517. if (settings.remove_trailing_brs) {
  18518. parser.addNodeFilter('br', function (nodes, _, args) {
  18519. var i;
  18520. var l = nodes.length;
  18521. var node;
  18522. var blockElements = Tools.extend({}, schema.getBlockElements());
  18523. var nonEmptyElements = schema.getNonEmptyElements();
  18524. var parent, lastParent, prev, prevName;
  18525. var whiteSpaceElements = schema.getWhiteSpaceElements();
  18526. var elementRule, textNode;
  18527. blockElements.body = 1;
  18528. for (i = 0; i < l; i++) {
  18529. node = nodes[i];
  18530. parent = node.parent;
  18531. if (blockElements[node.parent.name] && node === parent.lastChild) {
  18532. prev = node.prev;
  18533. while (prev) {
  18534. prevName = prev.name;
  18535. if (prevName !== 'span' || prev.attr('data-mce-type') !== 'bookmark') {
  18536. if (prevName === 'br') {
  18537. node = null;
  18538. }
  18539. break;
  18540. }
  18541. prev = prev.prev;
  18542. }
  18543. if (node) {
  18544. node.remove();
  18545. if (isEmpty(schema, nonEmptyElements, whiteSpaceElements, parent)) {
  18546. elementRule = schema.getElementRule(parent.name);
  18547. if (elementRule) {
  18548. if (elementRule.removeEmpty) {
  18549. parent.remove();
  18550. } else if (elementRule.paddEmpty) {
  18551. paddEmptyNode(settings, args, blockElements, parent);
  18552. }
  18553. }
  18554. }
  18555. }
  18556. } else {
  18557. lastParent = node;
  18558. while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) {
  18559. lastParent = parent;
  18560. if (blockElements[parent.name]) {
  18561. break;
  18562. }
  18563. parent = parent.parent;
  18564. }
  18565. if (lastParent === parent && settings.padd_empty_with_br !== true) {
  18566. textNode = new AstNode('#text', 3);
  18567. textNode.value = nbsp;
  18568. node.replace(textNode);
  18569. }
  18570. }
  18571. }
  18572. });
  18573. }
  18574. parser.addAttributeFilter('href', function (nodes) {
  18575. var i = nodes.length;
  18576. var appendRel = function (rel) {
  18577. var parts = rel.split(' ').filter(function (p) {
  18578. return p.length > 0;
  18579. });
  18580. return parts.concat(['noopener']).sort().join(' ');
  18581. };
  18582. var addNoOpener = function (rel) {
  18583. var newRel = rel ? Tools.trim(rel) : '';
  18584. if (!/\b(noopener)\b/g.test(newRel)) {
  18585. return appendRel(newRel);
  18586. } else {
  18587. return newRel;
  18588. }
  18589. };
  18590. if (!settings.allow_unsafe_link_target) {
  18591. while (i--) {
  18592. var node = nodes[i];
  18593. if (node.name === 'a' && node.attr('target') === '_blank') {
  18594. node.attr('rel', addNoOpener(node.attr('rel')));
  18595. }
  18596. }
  18597. }
  18598. });
  18599. if (!settings.allow_html_in_named_anchor) {
  18600. parser.addAttributeFilter('id,name', function (nodes) {
  18601. var i = nodes.length, sibling, prevSibling, parent, node;
  18602. while (i--) {
  18603. node = nodes[i];
  18604. if (node.name === 'a' && node.firstChild && !node.attr('href')) {
  18605. parent = node.parent;
  18606. sibling = node.lastChild;
  18607. do {
  18608. prevSibling = sibling.prev;
  18609. parent.insert(sibling, node);
  18610. sibling = prevSibling;
  18611. } while (sibling);
  18612. }
  18613. }
  18614. });
  18615. }
  18616. if (settings.fix_list_elements) {
  18617. parser.addNodeFilter('ul,ol', function (nodes) {
  18618. var i = nodes.length, node, parentNode;
  18619. while (i--) {
  18620. node = nodes[i];
  18621. parentNode = node.parent;
  18622. if (parentNode.name === 'ul' || parentNode.name === 'ol') {
  18623. if (node.prev && node.prev.name === 'li') {
  18624. node.prev.append(node);
  18625. } else {
  18626. var li = new AstNode('li', 1);
  18627. li.attr('style', 'list-style-type: none');
  18628. node.wrap(li);
  18629. }
  18630. }
  18631. }
  18632. });
  18633. }
  18634. if (settings.validate && schema.getValidClasses()) {
  18635. parser.addAttributeFilter('class', function (nodes) {
  18636. var validClasses = schema.getValidClasses();
  18637. var i = nodes.length;
  18638. while (i--) {
  18639. var node = nodes[i];
  18640. var classList = node.attr('class').split(' ');
  18641. var classValue = '';
  18642. for (var ci = 0; ci < classList.length; ci++) {
  18643. var className = classList[ci];
  18644. var valid = false;
  18645. var validClassesMap = validClasses['*'];
  18646. if (validClassesMap && validClassesMap[className]) {
  18647. valid = true;
  18648. }
  18649. validClassesMap = validClasses[node.name];
  18650. if (!valid && validClassesMap && validClassesMap[className]) {
  18651. valid = true;
  18652. }
  18653. if (valid) {
  18654. if (classValue) {
  18655. classValue += ' ';
  18656. }
  18657. classValue += className;
  18658. }
  18659. }
  18660. if (!classValue.length) {
  18661. classValue = null;
  18662. }
  18663. node.attr('class', classValue);
  18664. }
  18665. });
  18666. }
  18667. registerBase64ImageFilter(parser, settings);
  18668. };
  18669. var makeMap = Tools.makeMap, each$6 = Tools.each, explode$2 = Tools.explode, extend$4 = Tools.extend;
  18670. var DomParser = function (settings, schema) {
  18671. if (schema === void 0) {
  18672. schema = Schema();
  18673. }
  18674. var nodeFilters = {};
  18675. var attributeFilters = [];
  18676. var matchedNodes = {};
  18677. var matchedAttributes = {};
  18678. settings = settings || {};
  18679. settings.validate = 'validate' in settings ? settings.validate : true;
  18680. settings.root_name = settings.root_name || 'body';
  18681. var fixInvalidChildren = function (nodes) {
  18682. var nonSplitableElements = makeMap('tr,td,th,tbody,thead,tfoot,table');
  18683. var nonEmptyElements = schema.getNonEmptyElements();
  18684. var whitespaceElements = schema.getWhiteSpaceElements();
  18685. var textBlockElements = schema.getTextBlockElements();
  18686. var specialElements = schema.getSpecialElements();
  18687. var removeOrUnwrapInvalidNode = function (node, originalNodeParent) {
  18688. if (originalNodeParent === void 0) {
  18689. originalNodeParent = node.parent;
  18690. }
  18691. if (specialElements[node.name]) {
  18692. node.empty().remove();
  18693. } else {
  18694. var children = node.children();
  18695. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  18696. var childNode = children_1[_i];
  18697. if (!schema.isValidChild(originalNodeParent.name, childNode.name)) {
  18698. removeOrUnwrapInvalidNode(childNode, originalNodeParent);
  18699. }
  18700. }
  18701. node.unwrap();
  18702. }
  18703. };
  18704. for (var ni = 0; ni < nodes.length; ni++) {
  18705. var node = nodes[ni];
  18706. var parent_1 = void 0, newParent = void 0, tempNode = void 0;
  18707. if (!node.parent || node.fixed) {
  18708. continue;
  18709. }
  18710. if (textBlockElements[node.name] && node.parent.name === 'li') {
  18711. var sibling = node.next;
  18712. while (sibling) {
  18713. if (textBlockElements[sibling.name]) {
  18714. sibling.name = 'li';
  18715. sibling.fixed = true;
  18716. node.parent.insert(sibling, node.parent);
  18717. } else {
  18718. break;
  18719. }
  18720. sibling = sibling.next;
  18721. }
  18722. node.unwrap();
  18723. continue;
  18724. }
  18725. var parents = [node];
  18726. for (parent_1 = node.parent; parent_1 && !schema.isValidChild(parent_1.name, node.name) && !nonSplitableElements[parent_1.name]; parent_1 = parent_1.parent) {
  18727. parents.push(parent_1);
  18728. }
  18729. if (parent_1 && parents.length > 1) {
  18730. if (schema.isValidChild(parent_1.name, node.name)) {
  18731. parents.reverse();
  18732. newParent = filterNode(parents[0].clone());
  18733. var currentNode = newParent;
  18734. for (var i = 0; i < parents.length - 1; i++) {
  18735. if (schema.isValidChild(currentNode.name, parents[i].name)) {
  18736. tempNode = filterNode(parents[i].clone());
  18737. currentNode.append(tempNode);
  18738. } else {
  18739. tempNode = currentNode;
  18740. }
  18741. for (var childNode = parents[i].firstChild; childNode && childNode !== parents[i + 1];) {
  18742. var nextNode = childNode.next;
  18743. tempNode.append(childNode);
  18744. childNode = nextNode;
  18745. }
  18746. currentNode = tempNode;
  18747. }
  18748. if (!isEmpty(schema, nonEmptyElements, whitespaceElements, newParent)) {
  18749. parent_1.insert(newParent, parents[0], true);
  18750. parent_1.insert(node, newParent);
  18751. } else {
  18752. parent_1.insert(node, parents[0], true);
  18753. }
  18754. parent_1 = parents[0];
  18755. if (isEmpty(schema, nonEmptyElements, whitespaceElements, parent_1) || hasOnlyChild(parent_1, 'br')) {
  18756. parent_1.empty().remove();
  18757. }
  18758. } else {
  18759. removeOrUnwrapInvalidNode(node);
  18760. }
  18761. } else if (node.parent) {
  18762. if (node.name === 'li') {
  18763. var sibling = node.prev;
  18764. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  18765. sibling.append(node);
  18766. continue;
  18767. }
  18768. sibling = node.next;
  18769. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  18770. sibling.insert(node, sibling.firstChild, true);
  18771. continue;
  18772. }
  18773. node.wrap(filterNode(new AstNode('ul', 1)));
  18774. continue;
  18775. }
  18776. if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
  18777. node.wrap(filterNode(new AstNode('div', 1)));
  18778. } else {
  18779. removeOrUnwrapInvalidNode(node);
  18780. }
  18781. }
  18782. }
  18783. };
  18784. var filterNode = function (node) {
  18785. var name = node.name;
  18786. if (name in nodeFilters) {
  18787. var list = matchedNodes[name];
  18788. if (list) {
  18789. list.push(node);
  18790. } else {
  18791. matchedNodes[name] = [node];
  18792. }
  18793. }
  18794. var i = attributeFilters.length;
  18795. while (i--) {
  18796. var attrName = attributeFilters[i].name;
  18797. if (attrName in node.attributes.map) {
  18798. var list = matchedAttributes[attrName];
  18799. if (list) {
  18800. list.push(node);
  18801. } else {
  18802. matchedAttributes[attrName] = [node];
  18803. }
  18804. }
  18805. }
  18806. return node;
  18807. };
  18808. var addNodeFilter = function (name, callback) {
  18809. each$6(explode$2(name), function (name) {
  18810. var list = nodeFilters[name];
  18811. if (!list) {
  18812. nodeFilters[name] = list = [];
  18813. }
  18814. list.push(callback);
  18815. });
  18816. };
  18817. var getNodeFilters = function () {
  18818. var out = [];
  18819. for (var name_1 in nodeFilters) {
  18820. if (has$2(nodeFilters, name_1)) {
  18821. out.push({
  18822. name: name_1,
  18823. callbacks: nodeFilters[name_1]
  18824. });
  18825. }
  18826. }
  18827. return out;
  18828. };
  18829. var addAttributeFilter = function (name, callback) {
  18830. each$6(explode$2(name), function (name) {
  18831. var i;
  18832. for (i = 0; i < attributeFilters.length; i++) {
  18833. if (attributeFilters[i].name === name) {
  18834. attributeFilters[i].callbacks.push(callback);
  18835. return;
  18836. }
  18837. }
  18838. attributeFilters.push({
  18839. name: name,
  18840. callbacks: [callback]
  18841. });
  18842. });
  18843. };
  18844. var getAttributeFilters = function () {
  18845. return [].concat(attributeFilters);
  18846. };
  18847. var parse = function (html, args) {
  18848. var nodes, i, l, fi, fl, list, name;
  18849. var invalidChildren = [];
  18850. var node;
  18851. var getRootBlockName = function (name) {
  18852. if (name === false) {
  18853. return '';
  18854. } else if (name === true) {
  18855. return 'p';
  18856. } else {
  18857. return name;
  18858. }
  18859. };
  18860. args = args || {};
  18861. matchedNodes = {};
  18862. matchedAttributes = {};
  18863. var blockElements = extend$4(makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  18864. var textRootBlockElements = getTextRootBlockElements(schema);
  18865. var nonEmptyElements = schema.getNonEmptyElements();
  18866. var children = schema.children;
  18867. var validate = settings.validate;
  18868. var forcedRootBlockName = 'forced_root_block' in args ? args.forced_root_block : settings.forced_root_block;
  18869. var rootBlockName = getRootBlockName(forcedRootBlockName);
  18870. var whiteSpaceElements = schema.getWhiteSpaceElements();
  18871. var startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  18872. var endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  18873. var allWhiteSpaceRegExp = /[ \t\r\n]+/g;
  18874. var isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/;
  18875. var isInWhiteSpacePreservedElement = has$2(whiteSpaceElements, args.context) || has$2(whiteSpaceElements, settings.root_name);
  18876. var addRootBlocks = function () {
  18877. var node = rootNode.firstChild, rootBlockNode = null;
  18878. var trim = function (rootBlock) {
  18879. if (rootBlock) {
  18880. node = rootBlock.firstChild;
  18881. if (node && node.type === 3) {
  18882. node.value = node.value.replace(startWhiteSpaceRegExp, '');
  18883. }
  18884. node = rootBlock.lastChild;
  18885. if (node && node.type === 3) {
  18886. node.value = node.value.replace(endWhiteSpaceRegExp, '');
  18887. }
  18888. }
  18889. };
  18890. if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
  18891. return;
  18892. }
  18893. while (node) {
  18894. var next = node.next;
  18895. if (node.type === 3 || node.type === 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type')) {
  18896. if (!rootBlockNode) {
  18897. rootBlockNode = createNode(rootBlockName, 1);
  18898. rootBlockNode.attr(settings.forced_root_block_attrs);
  18899. rootNode.insert(rootBlockNode, node);
  18900. rootBlockNode.append(node);
  18901. } else {
  18902. rootBlockNode.append(node);
  18903. }
  18904. } else {
  18905. trim(rootBlockNode);
  18906. rootBlockNode = null;
  18907. }
  18908. node = next;
  18909. }
  18910. trim(rootBlockNode);
  18911. };
  18912. var createNode = function (name, type) {
  18913. var node = new AstNode(name, type);
  18914. var list;
  18915. if (name in nodeFilters) {
  18916. list = matchedNodes[name];
  18917. if (list) {
  18918. list.push(node);
  18919. } else {
  18920. matchedNodes[name] = [node];
  18921. }
  18922. }
  18923. return node;
  18924. };
  18925. var removeWhitespaceBefore = function (node) {
  18926. var blockElements = schema.getBlockElements();
  18927. for (var textNode = node.prev; textNode && textNode.type === 3;) {
  18928. var textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
  18929. if (textVal.length > 0) {
  18930. textNode.value = textVal;
  18931. return;
  18932. }
  18933. var textNodeNext = textNode.next;
  18934. if (textNodeNext) {
  18935. if (textNodeNext.type === 3 && textNodeNext.value.length) {
  18936. textNode = textNode.prev;
  18937. continue;
  18938. }
  18939. if (!blockElements[textNodeNext.name] && textNodeNext.name !== 'script' && textNodeNext.name !== 'style') {
  18940. textNode = textNode.prev;
  18941. continue;
  18942. }
  18943. }
  18944. var sibling = textNode.prev;
  18945. textNode.remove();
  18946. textNode = sibling;
  18947. }
  18948. };
  18949. var cloneAndExcludeBlocks = function (input) {
  18950. var output = {};
  18951. for (var name_2 in input) {
  18952. if (name_2 !== 'li' && name_2 !== 'p') {
  18953. output[name_2] = input[name_2];
  18954. }
  18955. }
  18956. return output;
  18957. };
  18958. var isTextRootBlockEmpty = function (node) {
  18959. var tempNode = node;
  18960. while (isNonNullable(tempNode)) {
  18961. if (tempNode.name in textRootBlockElements) {
  18962. return isEmpty(schema, nonEmptyElements, whiteSpaceElements, tempNode);
  18963. } else {
  18964. tempNode = tempNode.parent;
  18965. }
  18966. }
  18967. return false;
  18968. };
  18969. var parser = SaxParser({
  18970. validate: validate,
  18971. document: settings.document,
  18972. allow_html_data_urls: settings.allow_html_data_urls,
  18973. allow_svg_data_urls: settings.allow_svg_data_urls,
  18974. allow_script_urls: settings.allow_script_urls,
  18975. allow_conditional_comments: settings.allow_conditional_comments,
  18976. preserve_cdata: settings.preserve_cdata,
  18977. self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()),
  18978. cdata: function (text) {
  18979. node.append(createNode('#cdata', 4)).value = text;
  18980. },
  18981. text: function (text, raw) {
  18982. var textNode;
  18983. if (!isInWhiteSpacePreservedElement) {
  18984. text = text.replace(allWhiteSpaceRegExp, ' ');
  18985. if (isLineBreakNode(node.lastChild, blockElements)) {
  18986. text = text.replace(startWhiteSpaceRegExp, '');
  18987. }
  18988. }
  18989. if (text.length !== 0) {
  18990. textNode = createNode('#text', 3);
  18991. textNode.raw = !!raw;
  18992. node.append(textNode).value = text;
  18993. }
  18994. },
  18995. comment: function (text) {
  18996. node.append(createNode('#comment', 8)).value = text;
  18997. },
  18998. pi: function (name, text) {
  18999. node.append(createNode(name, 7)).value = text;
  19000. removeWhitespaceBefore(node);
  19001. },
  19002. doctype: function (text) {
  19003. var newNode = node.append(createNode('#doctype', 10));
  19004. newNode.value = text;
  19005. removeWhitespaceBefore(node);
  19006. },
  19007. start: function (name, attrs, empty) {
  19008. var elementRule = validate ? schema.getElementRule(name) : {};
  19009. if (elementRule) {
  19010. var newNode = createNode(elementRule.outputName || name, 1);
  19011. newNode.attributes = attrs;
  19012. newNode.shortEnded = empty;
  19013. node.append(newNode);
  19014. var parent_2 = children[node.name];
  19015. if (parent_2 && children[newNode.name] && !parent_2[newNode.name]) {
  19016. invalidChildren.push(newNode);
  19017. }
  19018. var attrFiltersLen = attributeFilters.length;
  19019. while (attrFiltersLen--) {
  19020. var attrName = attributeFilters[attrFiltersLen].name;
  19021. if (attrName in attrs.map) {
  19022. list = matchedAttributes[attrName];
  19023. if (list) {
  19024. list.push(newNode);
  19025. } else {
  19026. matchedAttributes[attrName] = [newNode];
  19027. }
  19028. }
  19029. }
  19030. if (blockElements[name]) {
  19031. removeWhitespaceBefore(newNode);
  19032. }
  19033. if (!empty) {
  19034. node = newNode;
  19035. }
  19036. if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  19037. isInWhiteSpacePreservedElement = true;
  19038. }
  19039. }
  19040. },
  19041. end: function (name) {
  19042. var textNode, text, sibling;
  19043. var elementRule = validate ? schema.getElementRule(name) : {};
  19044. if (elementRule) {
  19045. if (blockElements[name]) {
  19046. if (!isInWhiteSpacePreservedElement) {
  19047. textNode = node.firstChild;
  19048. if (textNode && textNode.type === 3) {
  19049. text = textNode.value.replace(startWhiteSpaceRegExp, '');
  19050. if (text.length > 0) {
  19051. textNode.value = text;
  19052. textNode = textNode.next;
  19053. } else {
  19054. sibling = textNode.next;
  19055. textNode.remove();
  19056. textNode = sibling;
  19057. while (textNode && textNode.type === 3) {
  19058. text = textNode.value;
  19059. sibling = textNode.next;
  19060. if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  19061. textNode.remove();
  19062. textNode = sibling;
  19063. }
  19064. textNode = sibling;
  19065. }
  19066. }
  19067. }
  19068. textNode = node.lastChild;
  19069. if (textNode && textNode.type === 3) {
  19070. text = textNode.value.replace(endWhiteSpaceRegExp, '');
  19071. if (text.length > 0) {
  19072. textNode.value = text;
  19073. textNode = textNode.prev;
  19074. } else {
  19075. sibling = textNode.prev;
  19076. textNode.remove();
  19077. textNode = sibling;
  19078. while (textNode && textNode.type === 3) {
  19079. text = textNode.value;
  19080. sibling = textNode.prev;
  19081. if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  19082. textNode.remove();
  19083. textNode = sibling;
  19084. }
  19085. textNode = sibling;
  19086. }
  19087. }
  19088. }
  19089. }
  19090. }
  19091. if (isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  19092. isInWhiteSpacePreservedElement = false;
  19093. }
  19094. var isNodeEmpty = isEmpty(schema, nonEmptyElements, whiteSpaceElements, node);
  19095. var parentNode = node.parent;
  19096. if (elementRule.paddInEmptyBlock && isNodeEmpty && isTextRootBlockEmpty(node)) {
  19097. paddEmptyNode(settings, args, blockElements, node);
  19098. } else if (elementRule.removeEmpty && isNodeEmpty) {
  19099. if (blockElements[node.name]) {
  19100. node.empty().remove();
  19101. } else {
  19102. node.unwrap();
  19103. }
  19104. } else if (elementRule.paddEmpty && (isPaddedWithNbsp(node) || isNodeEmpty)) {
  19105. paddEmptyNode(settings, args, blockElements, node);
  19106. }
  19107. node = parentNode;
  19108. }
  19109. }
  19110. }, schema);
  19111. var rootNode = node = new AstNode(args.context || settings.root_name, 11);
  19112. parser.parse(html, args.format);
  19113. if (validate && invalidChildren.length) {
  19114. if (!args.context) {
  19115. fixInvalidChildren(invalidChildren);
  19116. } else {
  19117. args.invalid = true;
  19118. }
  19119. }
  19120. if (rootBlockName && (rootNode.name === 'body' || args.isRootContent)) {
  19121. addRootBlocks();
  19122. }
  19123. if (!args.invalid) {
  19124. for (name in matchedNodes) {
  19125. if (!has$2(matchedNodes, name)) {
  19126. continue;
  19127. }
  19128. list = nodeFilters[name];
  19129. nodes = matchedNodes[name];
  19130. fi = nodes.length;
  19131. while (fi--) {
  19132. if (!nodes[fi].parent) {
  19133. nodes.splice(fi, 1);
  19134. }
  19135. }
  19136. for (i = 0, l = list.length; i < l; i++) {
  19137. list[i](nodes, name, args);
  19138. }
  19139. }
  19140. for (i = 0, l = attributeFilters.length; i < l; i++) {
  19141. list = attributeFilters[i];
  19142. if (list.name in matchedAttributes) {
  19143. nodes = matchedAttributes[list.name];
  19144. fi = nodes.length;
  19145. while (fi--) {
  19146. if (!nodes[fi].parent) {
  19147. nodes.splice(fi, 1);
  19148. }
  19149. }
  19150. for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) {
  19151. list.callbacks[fi](nodes, list.name, args);
  19152. }
  19153. }
  19154. }
  19155. }
  19156. return rootNode;
  19157. };
  19158. var exports = {
  19159. schema: schema,
  19160. addAttributeFilter: addAttributeFilter,
  19161. getAttributeFilters: getAttributeFilters,
  19162. addNodeFilter: addNodeFilter,
  19163. getNodeFilters: getNodeFilters,
  19164. filterNode: filterNode,
  19165. parse: parse
  19166. };
  19167. register$1(exports, settings);
  19168. register$2(exports, settings);
  19169. return exports;
  19170. };
  19171. var register = function (htmlParser, settings, dom) {
  19172. htmlParser.addAttributeFilter('data-mce-tabindex', function (nodes, name) {
  19173. var i = nodes.length;
  19174. while (i--) {
  19175. var node = nodes[i];
  19176. node.attr('tabindex', node.attr('data-mce-tabindex'));
  19177. node.attr(name, null);
  19178. }
  19179. });
  19180. htmlParser.addAttributeFilter('src,href,style', function (nodes, name) {
  19181. var internalName = 'data-mce-' + name;
  19182. var urlConverter = settings.url_converter;
  19183. var urlConverterScope = settings.url_converter_scope;
  19184. var i = nodes.length;
  19185. while (i--) {
  19186. var node = nodes[i];
  19187. var value = node.attr(internalName);
  19188. if (value !== undefined) {
  19189. node.attr(name, value.length > 0 ? value : null);
  19190. node.attr(internalName, null);
  19191. } else {
  19192. value = node.attr(name);
  19193. if (name === 'style') {
  19194. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  19195. } else if (urlConverter) {
  19196. value = urlConverter.call(urlConverterScope, value, name, node.name);
  19197. }
  19198. node.attr(name, value.length > 0 ? value : null);
  19199. }
  19200. }
  19201. });
  19202. htmlParser.addAttributeFilter('class', function (nodes) {
  19203. var i = nodes.length;
  19204. while (i--) {
  19205. var node = nodes[i];
  19206. var value = node.attr('class');
  19207. if (value) {
  19208. value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
  19209. node.attr('class', value.length > 0 ? value : null);
  19210. }
  19211. }
  19212. });
  19213. htmlParser.addAttributeFilter('data-mce-type', function (nodes, name, args) {
  19214. var i = nodes.length;
  19215. while (i--) {
  19216. var node = nodes[i];
  19217. if (node.attr('data-mce-type') === 'bookmark' && !args.cleanup) {
  19218. var hasChildren = Optional.from(node.firstChild).exists(function (firstChild) {
  19219. return !isZwsp(firstChild.value);
  19220. });
  19221. if (hasChildren) {
  19222. node.unwrap();
  19223. } else {
  19224. node.remove();
  19225. }
  19226. }
  19227. }
  19228. });
  19229. htmlParser.addNodeFilter('noscript', function (nodes) {
  19230. var i = nodes.length;
  19231. while (i--) {
  19232. var node = nodes[i].firstChild;
  19233. if (node) {
  19234. node.value = Entities.decode(node.value);
  19235. }
  19236. }
  19237. });
  19238. htmlParser.addNodeFilter('script,style', function (nodes, name) {
  19239. var trim = function (value) {
  19240. 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, '');
  19241. };
  19242. var i = nodes.length;
  19243. while (i--) {
  19244. var node = nodes[i];
  19245. var value = node.firstChild ? node.firstChild.value : '';
  19246. if (name === 'script') {
  19247. var type = node.attr('type');
  19248. if (type) {
  19249. node.attr('type', type === 'mce-no/type' ? null : type.replace(/^mce\-/, ''));
  19250. }
  19251. if (settings.element_format === 'xhtml' && value.length > 0) {
  19252. node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
  19253. }
  19254. } else {
  19255. if (settings.element_format === 'xhtml' && value.length > 0) {
  19256. node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
  19257. }
  19258. }
  19259. }
  19260. });
  19261. htmlParser.addNodeFilter('#comment', function (nodes) {
  19262. var i = nodes.length;
  19263. while (i--) {
  19264. var node = nodes[i];
  19265. if (settings.preserve_cdata && node.value.indexOf('[CDATA[') === 0) {
  19266. node.name = '#cdata';
  19267. node.type = 4;
  19268. node.value = dom.decode(node.value.replace(/^\[CDATA\[|\]\]$/g, ''));
  19269. } else if (node.value.indexOf('mce:protected ') === 0) {
  19270. node.name = '#text';
  19271. node.type = 3;
  19272. node.raw = true;
  19273. node.value = unescape(node.value).substr(14);
  19274. }
  19275. }
  19276. });
  19277. htmlParser.addNodeFilter('xml:namespace,input', function (nodes, name) {
  19278. var i = nodes.length;
  19279. while (i--) {
  19280. var node = nodes[i];
  19281. if (node.type === 7) {
  19282. node.remove();
  19283. } else if (node.type === 1) {
  19284. if (name === 'input' && !node.attr('type')) {
  19285. node.attr('type', 'text');
  19286. }
  19287. }
  19288. }
  19289. });
  19290. htmlParser.addAttributeFilter('data-mce-type', function (nodes) {
  19291. each$k(nodes, function (node) {
  19292. if (node.attr('data-mce-type') === 'format-caret') {
  19293. if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
  19294. node.remove();
  19295. } else {
  19296. node.unwrap();
  19297. }
  19298. }
  19299. });
  19300. });
  19301. 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) {
  19302. var i = nodes.length;
  19303. while (i--) {
  19304. nodes[i].attr(name, null);
  19305. }
  19306. });
  19307. };
  19308. var trimTrailingBr = function (rootNode) {
  19309. var isBr = function (node) {
  19310. return node && node.name === 'br';
  19311. };
  19312. var brNode1 = rootNode.lastChild;
  19313. if (isBr(brNode1)) {
  19314. var brNode2 = brNode1.prev;
  19315. if (isBr(brNode2)) {
  19316. brNode1.remove();
  19317. brNode2.remove();
  19318. }
  19319. }
  19320. };
  19321. var preProcess = function (editor, node, args) {
  19322. var oldDoc;
  19323. var dom = editor.dom;
  19324. var clonedNode = node.cloneNode(true);
  19325. var impl = document.implementation;
  19326. if (impl.createHTMLDocument) {
  19327. var doc_1 = impl.createHTMLDocument('');
  19328. Tools.each(clonedNode.nodeName === 'BODY' ? clonedNode.childNodes : [clonedNode], function (node) {
  19329. doc_1.body.appendChild(doc_1.importNode(node, true));
  19330. });
  19331. if (clonedNode.nodeName !== 'BODY') {
  19332. clonedNode = doc_1.body.firstChild;
  19333. } else {
  19334. clonedNode = doc_1.body;
  19335. }
  19336. oldDoc = dom.doc;
  19337. dom.doc = doc_1;
  19338. }
  19339. firePreProcess(editor, __assign(__assign({}, args), { node: clonedNode }));
  19340. if (oldDoc) {
  19341. dom.doc = oldDoc;
  19342. }
  19343. return clonedNode;
  19344. };
  19345. var shouldFireEvent = function (editor, args) {
  19346. return editor && editor.hasEventListeners('PreProcess') && !args.no_events;
  19347. };
  19348. var process = function (editor, node, args) {
  19349. return shouldFireEvent(editor, args) ? preProcess(editor, node, args) : node;
  19350. };
  19351. var addTempAttr = function (htmlParser, tempAttrs, name) {
  19352. if (Tools.inArray(tempAttrs, name) === -1) {
  19353. htmlParser.addAttributeFilter(name, function (nodes, name) {
  19354. var i = nodes.length;
  19355. while (i--) {
  19356. nodes[i].attr(name, null);
  19357. }
  19358. });
  19359. tempAttrs.push(name);
  19360. }
  19361. };
  19362. var postProcess = function (editor, args, content) {
  19363. if (!args.no_events && editor) {
  19364. var outArgs = firePostProcess(editor, __assign(__assign({}, args), { content: content }));
  19365. return outArgs.content;
  19366. } else {
  19367. return content;
  19368. }
  19369. };
  19370. var getHtmlFromNode = function (dom, node, args) {
  19371. var html = trim$2(args.getInner ? node.innerHTML : dom.getOuterHTML(node));
  19372. return args.selection || isWsPreserveElement(SugarElement.fromDom(node)) ? html : Tools.trim(html);
  19373. };
  19374. var parseHtml = function (htmlParser, html, args) {
  19375. var parserArgs = args.selection ? __assign({ forced_root_block: false }, args) : args;
  19376. var rootNode = htmlParser.parse(html, parserArgs);
  19377. trimTrailingBr(rootNode);
  19378. return rootNode;
  19379. };
  19380. var serializeNode = function (settings, schema, node) {
  19381. var htmlSerializer = HtmlSerializer(settings, schema);
  19382. return htmlSerializer.serialize(node);
  19383. };
  19384. var toHtml = function (editor, settings, schema, rootNode, args) {
  19385. var content = serializeNode(settings, schema, rootNode);
  19386. return postProcess(editor, args, content);
  19387. };
  19388. var DomSerializerImpl = function (settings, editor) {
  19389. var tempAttrs = ['data-mce-selected'];
  19390. var dom = editor && editor.dom ? editor.dom : DOMUtils.DOM;
  19391. var schema = editor && editor.schema ? editor.schema : Schema(settings);
  19392. settings.entity_encoding = settings.entity_encoding || 'named';
  19393. settings.remove_trailing_brs = 'remove_trailing_brs' in settings ? settings.remove_trailing_brs : true;
  19394. var htmlParser = DomParser(settings, schema);
  19395. register(htmlParser, settings, dom);
  19396. var serialize = function (node, parserArgs) {
  19397. if (parserArgs === void 0) {
  19398. parserArgs = {};
  19399. }
  19400. var args = __assign({ format: 'html' }, parserArgs);
  19401. var targetNode = process(editor, node, args);
  19402. var html = getHtmlFromNode(dom, targetNode, args);
  19403. var rootNode = parseHtml(htmlParser, html, args);
  19404. return args.format === 'tree' ? rootNode : toHtml(editor, settings, schema, rootNode, args);
  19405. };
  19406. return {
  19407. schema: schema,
  19408. addNodeFilter: htmlParser.addNodeFilter,
  19409. addAttributeFilter: htmlParser.addAttributeFilter,
  19410. serialize: serialize,
  19411. addRules: schema.addValidElements,
  19412. setRules: schema.setValidElements,
  19413. addTempAttr: curry(addTempAttr, htmlParser, tempAttrs),
  19414. getTempAttrs: constant(tempAttrs),
  19415. getNodeFilters: htmlParser.getNodeFilters,
  19416. getAttributeFilters: htmlParser.getAttributeFilters
  19417. };
  19418. };
  19419. var DomSerializer = function (settings, editor) {
  19420. var domSerializer = DomSerializerImpl(settings, editor);
  19421. return {
  19422. schema: domSerializer.schema,
  19423. addNodeFilter: domSerializer.addNodeFilter,
  19424. addAttributeFilter: domSerializer.addAttributeFilter,
  19425. serialize: domSerializer.serialize,
  19426. addRules: domSerializer.addRules,
  19427. setRules: domSerializer.setRules,
  19428. addTempAttr: domSerializer.addTempAttr,
  19429. getTempAttrs: domSerializer.getTempAttrs,
  19430. getNodeFilters: domSerializer.getNodeFilters,
  19431. getAttributeFilters: domSerializer.getAttributeFilters
  19432. };
  19433. };
  19434. var defaultFormat = 'html';
  19435. var getContent = function (editor, args) {
  19436. if (args === void 0) {
  19437. args = {};
  19438. }
  19439. var format = args.format ? args.format : defaultFormat;
  19440. return getContent$2(editor, args, format);
  19441. };
  19442. var setContent = function (editor, content, args) {
  19443. if (args === void 0) {
  19444. args = {};
  19445. }
  19446. return setContent$2(editor, content, args);
  19447. };
  19448. var DOM$7 = DOMUtils.DOM;
  19449. var restoreOriginalStyles = function (editor) {
  19450. DOM$7.setStyle(editor.id, 'display', editor.orgDisplay);
  19451. };
  19452. var safeDestroy = function (x) {
  19453. return Optional.from(x).each(function (x) {
  19454. return x.destroy();
  19455. });
  19456. };
  19457. var clearDomReferences = function (editor) {
  19458. editor.contentAreaContainer = editor.formElement = editor.container = editor.editorContainer = null;
  19459. editor.bodyElement = editor.contentDocument = editor.contentWindow = null;
  19460. editor.iframeElement = editor.targetElm = null;
  19461. if (editor.selection) {
  19462. editor.selection = editor.selection.win = editor.selection.dom = editor.selection.dom.doc = null;
  19463. }
  19464. };
  19465. var restoreForm = function (editor) {
  19466. var form = editor.formElement;
  19467. if (form) {
  19468. if (form._mceOldSubmit) {
  19469. form.submit = form._mceOldSubmit;
  19470. form._mceOldSubmit = null;
  19471. }
  19472. DOM$7.unbind(form, 'submit reset', editor.formEventDelegate);
  19473. }
  19474. };
  19475. var remove = function (editor) {
  19476. if (!editor.removed) {
  19477. var _selectionOverrides = editor._selectionOverrides, editorUpload = editor.editorUpload;
  19478. var body = editor.getBody();
  19479. var element = editor.getElement();
  19480. if (body) {
  19481. editor.save({ is_removing: true });
  19482. }
  19483. editor.removed = true;
  19484. editor.unbindAllNativeEvents();
  19485. if (editor.hasHiddenInput && element) {
  19486. DOM$7.remove(element.nextSibling);
  19487. }
  19488. fireRemove(editor);
  19489. editor.editorManager.remove(editor);
  19490. if (!editor.inline && body) {
  19491. restoreOriginalStyles(editor);
  19492. }
  19493. fireDetach(editor);
  19494. DOM$7.remove(editor.getContainer());
  19495. safeDestroy(_selectionOverrides);
  19496. safeDestroy(editorUpload);
  19497. editor.destroy();
  19498. }
  19499. };
  19500. var destroy = function (editor, automatic) {
  19501. var selection = editor.selection, dom = editor.dom;
  19502. if (editor.destroyed) {
  19503. return;
  19504. }
  19505. if (!automatic && !editor.removed) {
  19506. editor.remove();
  19507. return;
  19508. }
  19509. if (!automatic) {
  19510. editor.editorManager.off('beforeunload', editor._beforeUnload);
  19511. if (editor.theme && editor.theme.destroy) {
  19512. editor.theme.destroy();
  19513. }
  19514. safeDestroy(selection);
  19515. safeDestroy(dom);
  19516. }
  19517. restoreForm(editor);
  19518. clearDomReferences(editor);
  19519. editor.destroyed = true;
  19520. };
  19521. var deep = function (old, nu) {
  19522. var bothObjects = isObject(old) && isObject(nu);
  19523. return bothObjects ? deepMerge(old, nu) : nu;
  19524. };
  19525. var baseMerge = function (merger) {
  19526. return function () {
  19527. var objects = [];
  19528. for (var _i = 0; _i < arguments.length; _i++) {
  19529. objects[_i] = arguments[_i];
  19530. }
  19531. if (objects.length === 0) {
  19532. throw new Error('Can\'t merge zero objects');
  19533. }
  19534. var ret = {};
  19535. for (var j = 0; j < objects.length; j++) {
  19536. var curObject = objects[j];
  19537. for (var key in curObject) {
  19538. if (has$2(curObject, key)) {
  19539. ret[key] = merger(ret[key], curObject[key]);
  19540. }
  19541. }
  19542. }
  19543. return ret;
  19544. };
  19545. };
  19546. var deepMerge = baseMerge(deep);
  19547. 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(',');
  19548. var deprecatedPlugins = 'bbcode,colorpicker,contextmenu,fullpage,legacyoutput,spellchecker,textcolor'.split(',');
  19549. var movedToPremiumPlugins = 'imagetools,toc'.split(',');
  19550. var getDeprecatedSettings = function (settings) {
  19551. var settingNames = filter$4(deprecatedSettings, function (setting) {
  19552. return has$2(settings, setting);
  19553. });
  19554. var forcedRootBlock = settings.forced_root_block;
  19555. if (forcedRootBlock === false || forcedRootBlock === '') {
  19556. settingNames.push('forced_root_block (false only)');
  19557. }
  19558. return sort(settingNames);
  19559. };
  19560. var getDeprecatedPlugins = function (settings) {
  19561. var plugins = Tools.makeMap(settings.plugins, ' ');
  19562. var hasPlugin = function (plugin) {
  19563. return has$2(plugins, plugin);
  19564. };
  19565. var pluginNames = __spreadArray(__spreadArray([], filter$4(deprecatedPlugins, hasPlugin), true), bind(movedToPremiumPlugins, function (plugin) {
  19566. return hasPlugin(plugin) ? [plugin + ' (moving to premium)'] : [];
  19567. }), true);
  19568. return sort(pluginNames);
  19569. };
  19570. var logDeprecationsWarning = function (rawSettings, finalSettings) {
  19571. var deprecatedSettings = getDeprecatedSettings(rawSettings);
  19572. var deprecatedPlugins = getDeprecatedPlugins(finalSettings);
  19573. var hasDeprecatedPlugins = deprecatedPlugins.length > 0;
  19574. var hasDeprecatedSettings = deprecatedSettings.length > 0;
  19575. var isLegacyMobileTheme = finalSettings.theme === 'mobile';
  19576. if (hasDeprecatedPlugins || hasDeprecatedSettings || isLegacyMobileTheme) {
  19577. var listJoiner = '\n- ';
  19578. var themesMessage = isLegacyMobileTheme ? '\n\nThemes:' + listJoiner + 'mobile' : '';
  19579. var pluginsMessage = hasDeprecatedPlugins ? '\n\nPlugins:' + listJoiner + deprecatedPlugins.join(listJoiner) : '';
  19580. var settingsMessage = hasDeprecatedSettings ? '\n\nSettings:' + listJoiner + deprecatedSettings.join(listJoiner) : '';
  19581. 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);
  19582. }
  19583. };
  19584. var sectionResult = function (sections, settings) {
  19585. return {
  19586. sections: constant(sections),
  19587. settings: constant(settings)
  19588. };
  19589. };
  19590. var deviceDetection = detect().deviceType;
  19591. var isTouch = deviceDetection.isTouch();
  19592. var isPhone = deviceDetection.isPhone();
  19593. var isTablet = deviceDetection.isTablet();
  19594. var legacyMobilePlugins = [
  19595. 'lists',
  19596. 'autolink',
  19597. 'autosave'
  19598. ];
  19599. var defaultTouchSettings = {
  19600. table_grid: false,
  19601. object_resizing: false,
  19602. resize: false
  19603. };
  19604. var normalizePlugins = function (plugins) {
  19605. var pluginNames = isArray$1(plugins) ? plugins.join(' ') : plugins;
  19606. var trimmedPlugins = map$3(isString$1(pluginNames) ? pluginNames.split(' ') : [], trim$4);
  19607. return filter$4(trimmedPlugins, function (item) {
  19608. return item.length > 0;
  19609. });
  19610. };
  19611. var filterLegacyMobilePlugins = function (plugins) {
  19612. return filter$4(plugins, curry(contains$3, legacyMobilePlugins));
  19613. };
  19614. var extractSections = function (keys, settings) {
  19615. var result = bifilter(settings, function (value, key) {
  19616. return contains$3(keys, key);
  19617. });
  19618. return sectionResult(result.t, result.f);
  19619. };
  19620. var getSection = function (sectionResult, name, defaults) {
  19621. if (defaults === void 0) {
  19622. defaults = {};
  19623. }
  19624. var sections = sectionResult.sections();
  19625. var sectionSettings = get$9(sections, name).getOr({});
  19626. return Tools.extend({}, defaults, sectionSettings);
  19627. };
  19628. var hasSection = function (sectionResult, name) {
  19629. return has$2(sectionResult.sections(), name);
  19630. };
  19631. var isSectionTheme = function (sectionResult, name, theme) {
  19632. var section = sectionResult.sections();
  19633. return hasSection(sectionResult, name) && section[name].theme === theme;
  19634. };
  19635. var getSectionConfig = function (sectionResult, name) {
  19636. return hasSection(sectionResult, name) ? sectionResult.sections()[name] : {};
  19637. };
  19638. var getToolbarMode = function (settings, defaultVal) {
  19639. return get$9(settings, 'toolbar_mode').orThunk(function () {
  19640. return get$9(settings, 'toolbar_drawer').map(function (val) {
  19641. return val === false ? 'wrap' : val;
  19642. });
  19643. }).getOr(defaultVal);
  19644. };
  19645. var getDefaultSettings = function (settings, id, documentBaseUrl, isTouch, editor) {
  19646. var baseDefaults = {
  19647. id: id,
  19648. theme: 'silver',
  19649. toolbar_mode: getToolbarMode(settings, 'floating'),
  19650. plugins: '',
  19651. document_base_url: documentBaseUrl,
  19652. add_form_submit_trigger: true,
  19653. submit_patch: true,
  19654. add_unload_trigger: true,
  19655. convert_urls: true,
  19656. relative_urls: true,
  19657. remove_script_host: true,
  19658. object_resizing: true,
  19659. doctype: '<!DOCTYPE html>',
  19660. visual: true,
  19661. font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%',
  19662. forced_root_block: 'p',
  19663. hidden_input: true,
  19664. inline_styles: true,
  19665. convert_fonts_to_spans: true,
  19666. indent: true,
  19667. 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',
  19668. 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',
  19669. entity_encoding: 'named',
  19670. url_converter: editor.convertURL,
  19671. url_converter_scope: editor
  19672. };
  19673. return __assign(__assign({}, baseDefaults), isTouch ? defaultTouchSettings : {});
  19674. };
  19675. var getDefaultMobileSettings = function (mobileSettings, isPhone) {
  19676. var defaultMobileSettings = {
  19677. resize: false,
  19678. toolbar_mode: getToolbarMode(mobileSettings, 'scrolling'),
  19679. toolbar_sticky: false
  19680. };
  19681. var defaultPhoneSettings = { menubar: false };
  19682. return __assign(__assign(__assign({}, defaultTouchSettings), defaultMobileSettings), isPhone ? defaultPhoneSettings : {});
  19683. };
  19684. var getExternalPlugins = function (overrideSettings, settings) {
  19685. var userDefinedExternalPlugins = settings.external_plugins ? settings.external_plugins : {};
  19686. if (overrideSettings && overrideSettings.external_plugins) {
  19687. return Tools.extend({}, overrideSettings.external_plugins, userDefinedExternalPlugins);
  19688. } else {
  19689. return userDefinedExternalPlugins;
  19690. }
  19691. };
  19692. var combinePlugins = function (forcedPlugins, plugins) {
  19693. return [].concat(normalizePlugins(forcedPlugins)).concat(normalizePlugins(plugins));
  19694. };
  19695. var getPlatformPlugins = function (isMobileDevice, sectionResult, desktopPlugins, mobilePlugins) {
  19696. if (isMobileDevice && isSectionTheme(sectionResult, 'mobile', 'mobile')) {
  19697. return filterLegacyMobilePlugins(mobilePlugins);
  19698. } else if (isMobileDevice && hasSection(sectionResult, 'mobile')) {
  19699. return mobilePlugins;
  19700. } else {
  19701. return desktopPlugins;
  19702. }
  19703. };
  19704. var processPlugins = function (isMobileDevice, sectionResult, defaultOverrideSettings, settings) {
  19705. var forcedPlugins = normalizePlugins(defaultOverrideSettings.forced_plugins);
  19706. var desktopPlugins = normalizePlugins(settings.plugins);
  19707. var mobileConfig = getSectionConfig(sectionResult, 'mobile');
  19708. var mobilePlugins = mobileConfig.plugins ? normalizePlugins(mobileConfig.plugins) : desktopPlugins;
  19709. var platformPlugins = getPlatformPlugins(isMobileDevice, sectionResult, desktopPlugins, mobilePlugins);
  19710. var combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
  19711. if (Env.browser.isIE() && contains$3(combinedPlugins, 'rtc')) {
  19712. throw new Error('RTC plugin is not supported on IE 11.');
  19713. }
  19714. return Tools.extend(settings, { plugins: combinedPlugins.join(' ') });
  19715. };
  19716. var isOnMobile = function (isMobileDevice, sectionResult) {
  19717. return isMobileDevice && hasSection(sectionResult, 'mobile');
  19718. };
  19719. var combineSettings = function (isMobileDevice, isPhone, defaultSettings, defaultOverrideSettings, settings) {
  19720. var defaultDeviceSettings = isMobileDevice ? { mobile: getDefaultMobileSettings(settings.mobile || {}, isPhone) } : {};
  19721. var sectionResult = extractSections(['mobile'], deepMerge(defaultDeviceSettings, settings));
  19722. var extendedSettings = Tools.extend(defaultSettings, defaultOverrideSettings, sectionResult.settings(), isOnMobile(isMobileDevice, sectionResult) ? getSection(sectionResult, 'mobile') : {}, {
  19723. validate: true,
  19724. external_plugins: getExternalPlugins(defaultOverrideSettings, sectionResult.settings())
  19725. });
  19726. return processPlugins(isMobileDevice, sectionResult, defaultOverrideSettings, extendedSettings);
  19727. };
  19728. var getEditorSettings = function (editor, id, documentBaseUrl, defaultOverrideSettings, settings) {
  19729. var defaultSettings = getDefaultSettings(settings, id, documentBaseUrl, isTouch, editor);
  19730. var finalSettings = combineSettings(isPhone || isTablet, isPhone, defaultSettings, defaultOverrideSettings, settings);
  19731. if (finalSettings.deprecation_warnings !== false) {
  19732. logDeprecationsWarning(settings, finalSettings);
  19733. }
  19734. return finalSettings;
  19735. };
  19736. var getFiltered = function (predicate, editor, name) {
  19737. return Optional.from(editor.settings[name]).filter(predicate);
  19738. };
  19739. var getParamObject = function (value) {
  19740. var output = {};
  19741. if (typeof value === 'string') {
  19742. each$k(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function (val) {
  19743. var arr = val.split('=');
  19744. if (arr.length > 1) {
  19745. output[Tools.trim(arr[0])] = Tools.trim(arr[1]);
  19746. } else {
  19747. output[Tools.trim(arr[0])] = Tools.trim(arr[0]);
  19748. }
  19749. });
  19750. } else {
  19751. output = value;
  19752. }
  19753. return output;
  19754. };
  19755. var isArrayOf = function (p) {
  19756. return function (a) {
  19757. return isArray$1(a) && forall(a, p);
  19758. };
  19759. };
  19760. var getParam = function (editor, name, defaultVal, type) {
  19761. var value = name in editor.settings ? editor.settings[name] : defaultVal;
  19762. if (type === 'hash') {
  19763. return getParamObject(value);
  19764. } else if (type === 'string') {
  19765. return getFiltered(isString$1, editor, name).getOr(defaultVal);
  19766. } else if (type === 'number') {
  19767. return getFiltered(isNumber, editor, name).getOr(defaultVal);
  19768. } else if (type === 'boolean') {
  19769. return getFiltered(isBoolean, editor, name).getOr(defaultVal);
  19770. } else if (type === 'object') {
  19771. return getFiltered(isObject, editor, name).getOr(defaultVal);
  19772. } else if (type === 'array') {
  19773. return getFiltered(isArray$1, editor, name).getOr(defaultVal);
  19774. } else if (type === 'string[]') {
  19775. return getFiltered(isArrayOf(isString$1), editor, name).getOr(defaultVal);
  19776. } else if (type === 'function') {
  19777. return getFiltered(isFunction, editor, name).getOr(defaultVal);
  19778. } else {
  19779. return value;
  19780. }
  19781. };
  19782. var CreateIconManager = function () {
  19783. var lookup = {};
  19784. var add = function (id, iconPack) {
  19785. lookup[id] = iconPack;
  19786. };
  19787. var get = function (id) {
  19788. if (lookup[id]) {
  19789. return lookup[id];
  19790. }
  19791. return { icons: {} };
  19792. };
  19793. var has = function (id) {
  19794. return has$2(lookup, id);
  19795. };
  19796. return {
  19797. add: add,
  19798. get: get,
  19799. has: has
  19800. };
  19801. };
  19802. var IconManager = CreateIconManager();
  19803. var getProp = function (propName, elm) {
  19804. var rawElm = elm.dom;
  19805. return rawElm[propName];
  19806. };
  19807. var getComputedSizeProp = function (propName, elm) {
  19808. return parseInt(get$5(elm, propName), 10);
  19809. };
  19810. var getClientWidth = curry(getProp, 'clientWidth');
  19811. var getClientHeight = curry(getProp, 'clientHeight');
  19812. var getMarginTop = curry(getComputedSizeProp, 'margin-top');
  19813. var getMarginLeft = curry(getComputedSizeProp, 'margin-left');
  19814. var getBoundingClientRect = function (elm) {
  19815. return elm.dom.getBoundingClientRect();
  19816. };
  19817. var isInsideElementContentArea = function (bodyElm, clientX, clientY) {
  19818. var clientWidth = getClientWidth(bodyElm);
  19819. var clientHeight = getClientHeight(bodyElm);
  19820. return clientX >= 0 && clientY >= 0 && clientX <= clientWidth && clientY <= clientHeight;
  19821. };
  19822. var transpose = function (inline, elm, clientX, clientY) {
  19823. var clientRect = getBoundingClientRect(elm);
  19824. var deltaX = inline ? clientRect.left + elm.dom.clientLeft + getMarginLeft(elm) : 0;
  19825. var deltaY = inline ? clientRect.top + elm.dom.clientTop + getMarginTop(elm) : 0;
  19826. var x = clientX - deltaX;
  19827. var y = clientY - deltaY;
  19828. return {
  19829. x: x,
  19830. y: y
  19831. };
  19832. };
  19833. var isXYInContentArea = function (editor, clientX, clientY) {
  19834. var bodyElm = SugarElement.fromDom(editor.getBody());
  19835. var targetElm = editor.inline ? bodyElm : documentElement(bodyElm);
  19836. var transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
  19837. return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
  19838. };
  19839. var fromDomSafe = function (node) {
  19840. return Optional.from(node).map(SugarElement.fromDom);
  19841. };
  19842. var isEditorAttachedToDom = function (editor) {
  19843. var rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
  19844. return fromDomSafe(rawContainer).map(inBody).getOr(false);
  19845. };
  19846. var NotificationManagerImpl = function () {
  19847. var unimplemented = function () {
  19848. throw new Error('Theme did not provide a NotificationManager implementation.');
  19849. };
  19850. return {
  19851. open: unimplemented,
  19852. close: unimplemented,
  19853. reposition: unimplemented,
  19854. getArgs: unimplemented
  19855. };
  19856. };
  19857. var NotificationManager = function (editor) {
  19858. var notifications = [];
  19859. var getImplementation = function () {
  19860. var theme = editor.theme;
  19861. return theme && theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
  19862. };
  19863. var getTopNotification = function () {
  19864. return Optional.from(notifications[0]);
  19865. };
  19866. var isEqual = function (a, b) {
  19867. return a.type === b.type && a.text === b.text && !a.progressBar && !a.timeout && !b.progressBar && !b.timeout;
  19868. };
  19869. var reposition = function () {
  19870. if (notifications.length > 0) {
  19871. getImplementation().reposition(notifications);
  19872. }
  19873. };
  19874. var addNotification = function (notification) {
  19875. notifications.push(notification);
  19876. };
  19877. var closeNotification = function (notification) {
  19878. findIndex$2(notifications, function (otherNotification) {
  19879. return otherNotification === notification;
  19880. }).each(function (index) {
  19881. notifications.splice(index, 1);
  19882. });
  19883. };
  19884. var open = function (spec, fireEvent) {
  19885. if (fireEvent === void 0) {
  19886. fireEvent = true;
  19887. }
  19888. if (editor.removed || !isEditorAttachedToDom(editor)) {
  19889. return;
  19890. }
  19891. if (fireEvent) {
  19892. editor.fire('BeforeOpenNotification', { notification: spec });
  19893. }
  19894. return find$3(notifications, function (notification) {
  19895. return isEqual(getImplementation().getArgs(notification), spec);
  19896. }).getOrThunk(function () {
  19897. editor.editorManager.setActive(editor);
  19898. var notification = getImplementation().open(spec, function () {
  19899. closeNotification(notification);
  19900. reposition();
  19901. getTopNotification().fold(function () {
  19902. return editor.focus();
  19903. }, function (top) {
  19904. return focus$1(SugarElement.fromDom(top.getEl()));
  19905. });
  19906. });
  19907. addNotification(notification);
  19908. reposition();
  19909. editor.fire('OpenNotification', { notification: __assign({}, notification) });
  19910. return notification;
  19911. });
  19912. };
  19913. var close = function () {
  19914. getTopNotification().each(function (notification) {
  19915. getImplementation().close(notification);
  19916. closeNotification(notification);
  19917. reposition();
  19918. });
  19919. };
  19920. var getNotifications = constant(notifications);
  19921. var registerEvents = function (editor) {
  19922. editor.on('SkinLoaded', function () {
  19923. var serviceMessage = getServiceMessage(editor);
  19924. if (serviceMessage) {
  19925. open({
  19926. text: serviceMessage,
  19927. type: 'warning',
  19928. timeout: 0
  19929. }, false);
  19930. }
  19931. reposition();
  19932. });
  19933. editor.on('show ResizeEditor ResizeWindow NodeChange', function () {
  19934. Delay.requestAnimationFrame(reposition);
  19935. });
  19936. editor.on('remove', function () {
  19937. each$k(notifications.slice(), function (notification) {
  19938. getImplementation().close(notification);
  19939. });
  19940. });
  19941. };
  19942. registerEvents(editor);
  19943. return {
  19944. open: open,
  19945. close: close,
  19946. getNotifications: getNotifications
  19947. };
  19948. };
  19949. var PluginManager = AddOnManager.PluginManager;
  19950. var ThemeManager = AddOnManager.ThemeManager;
  19951. function WindowManagerImpl () {
  19952. var unimplemented = function () {
  19953. throw new Error('Theme did not provide a WindowManager implementation.');
  19954. };
  19955. return {
  19956. open: unimplemented,
  19957. openUrl: unimplemented,
  19958. alert: unimplemented,
  19959. confirm: unimplemented,
  19960. close: unimplemented,
  19961. getParams: unimplemented,
  19962. setParams: unimplemented
  19963. };
  19964. }
  19965. var WindowManager = function (editor) {
  19966. var dialogs = [];
  19967. var getImplementation = function () {
  19968. var theme = editor.theme;
  19969. return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
  19970. };
  19971. var funcBind = function (scope, f) {
  19972. return function () {
  19973. var args = [];
  19974. for (var _i = 0; _i < arguments.length; _i++) {
  19975. args[_i] = arguments[_i];
  19976. }
  19977. return f ? f.apply(scope, args) : undefined;
  19978. };
  19979. };
  19980. var fireOpenEvent = function (dialog) {
  19981. editor.fire('OpenWindow', { dialog: dialog });
  19982. };
  19983. var fireCloseEvent = function (dialog) {
  19984. editor.fire('CloseWindow', { dialog: dialog });
  19985. };
  19986. var addDialog = function (dialog) {
  19987. dialogs.push(dialog);
  19988. fireOpenEvent(dialog);
  19989. };
  19990. var closeDialog = function (dialog) {
  19991. fireCloseEvent(dialog);
  19992. dialogs = filter$4(dialogs, function (otherDialog) {
  19993. return otherDialog !== dialog;
  19994. });
  19995. if (dialogs.length === 0) {
  19996. editor.focus();
  19997. }
  19998. };
  19999. var getTopDialog = function () {
  20000. return Optional.from(dialogs[dialogs.length - 1]);
  20001. };
  20002. var storeSelectionAndOpenDialog = function (openDialog) {
  20003. editor.editorManager.setActive(editor);
  20004. store(editor);
  20005. var dialog = openDialog();
  20006. addDialog(dialog);
  20007. return dialog;
  20008. };
  20009. var open = function (args, params) {
  20010. return storeSelectionAndOpenDialog(function () {
  20011. return getImplementation().open(args, params, closeDialog);
  20012. });
  20013. };
  20014. var openUrl = function (args) {
  20015. return storeSelectionAndOpenDialog(function () {
  20016. return getImplementation().openUrl(args, closeDialog);
  20017. });
  20018. };
  20019. var alert = function (message, callback, scope) {
  20020. var windowManagerImpl = getImplementation();
  20021. windowManagerImpl.alert(message, funcBind(scope ? scope : windowManagerImpl, callback));
  20022. };
  20023. var confirm = function (message, callback, scope) {
  20024. var windowManagerImpl = getImplementation();
  20025. windowManagerImpl.confirm(message, funcBind(scope ? scope : windowManagerImpl, callback));
  20026. };
  20027. var close = function () {
  20028. getTopDialog().each(function (dialog) {
  20029. getImplementation().close(dialog);
  20030. closeDialog(dialog);
  20031. });
  20032. };
  20033. editor.on('remove', function () {
  20034. each$k(dialogs, function (dialog) {
  20035. getImplementation().close(dialog);
  20036. });
  20037. });
  20038. return {
  20039. open: open,
  20040. openUrl: openUrl,
  20041. alert: alert,
  20042. confirm: confirm,
  20043. close: close
  20044. };
  20045. };
  20046. var displayNotification = function (editor, message) {
  20047. editor.notificationManager.open({
  20048. type: 'error',
  20049. text: message
  20050. });
  20051. };
  20052. var displayError = function (editor, message) {
  20053. if (editor._skinLoaded) {
  20054. displayNotification(editor, message);
  20055. } else {
  20056. editor.on('SkinLoaded', function () {
  20057. displayNotification(editor, message);
  20058. });
  20059. }
  20060. };
  20061. var uploadError = function (editor, message) {
  20062. displayError(editor, I18n.translate([
  20063. 'Failed to upload image: {0}',
  20064. message
  20065. ]));
  20066. };
  20067. var logError = function (editor, errorType, msg) {
  20068. fireError(editor, errorType, { message: msg });
  20069. console.error(msg);
  20070. };
  20071. var createLoadError = function (type, url, name) {
  20072. return name ? 'Failed to load ' + type + ': ' + name + ' from url ' + url : 'Failed to load ' + type + ' url: ' + url;
  20073. };
  20074. var pluginLoadError = function (editor, url, name) {
  20075. logError(editor, 'PluginLoadError', createLoadError('plugin', url, name));
  20076. };
  20077. var iconsLoadError = function (editor, url, name) {
  20078. logError(editor, 'IconsLoadError', createLoadError('icons', url, name));
  20079. };
  20080. var languageLoadError = function (editor, url, name) {
  20081. logError(editor, 'LanguageLoadError', createLoadError('language', url, name));
  20082. };
  20083. var pluginInitError = function (editor, name, err) {
  20084. var message = I18n.translate([
  20085. 'Failed to initialize plugin: {0}',
  20086. name
  20087. ]);
  20088. fireError(editor, 'PluginLoadError', { message: message });
  20089. initError(message, err);
  20090. displayError(editor, message);
  20091. };
  20092. var initError = function (message) {
  20093. var x = [];
  20094. for (var _i = 1; _i < arguments.length; _i++) {
  20095. x[_i - 1] = arguments[_i];
  20096. }
  20097. var console = window.console;
  20098. if (console) {
  20099. if (console.error) {
  20100. console.error.apply(console, __spreadArray([message], x, false));
  20101. } else {
  20102. console.log.apply(console, __spreadArray([message], x, false));
  20103. }
  20104. }
  20105. };
  20106. var isContentCssSkinName = function (url) {
  20107. return /^[a-z0-9\-]+$/i.test(url);
  20108. };
  20109. var getContentCssUrls = function (editor) {
  20110. return transformToUrls(editor, getContentCss(editor));
  20111. };
  20112. var getFontCssUrls = function (editor) {
  20113. return transformToUrls(editor, getFontCss(editor));
  20114. };
  20115. var transformToUrls = function (editor, cssLinks) {
  20116. var skinUrl = editor.editorManager.baseURL + '/skins/content';
  20117. var suffix = editor.editorManager.suffix;
  20118. var contentCssFile = 'content' + suffix + '.css';
  20119. var inline = editor.inline === true;
  20120. return map$3(cssLinks, function (url) {
  20121. if (isContentCssSkinName(url) && !inline) {
  20122. return skinUrl + '/' + url + '/' + contentCssFile;
  20123. } else {
  20124. return editor.documentBaseURI.toAbsolute(url);
  20125. }
  20126. });
  20127. };
  20128. var appendContentCssFromSettings = function (editor) {
  20129. editor.contentCSS = editor.contentCSS.concat(getContentCssUrls(editor), getFontCssUrls(editor));
  20130. };
  20131. var UploadStatus = function () {
  20132. var PENDING = 1, UPLOADED = 2;
  20133. var blobUriStatuses = {};
  20134. var createStatus = function (status, resultUri) {
  20135. return {
  20136. status: status,
  20137. resultUri: resultUri
  20138. };
  20139. };
  20140. var hasBlobUri = function (blobUri) {
  20141. return blobUri in blobUriStatuses;
  20142. };
  20143. var getResultUri = function (blobUri) {
  20144. var result = blobUriStatuses[blobUri];
  20145. return result ? result.resultUri : null;
  20146. };
  20147. var isPending = function (blobUri) {
  20148. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
  20149. };
  20150. var isUploaded = function (blobUri) {
  20151. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
  20152. };
  20153. var markPending = function (blobUri) {
  20154. blobUriStatuses[blobUri] = createStatus(PENDING, null);
  20155. };
  20156. var markUploaded = function (blobUri, resultUri) {
  20157. blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
  20158. };
  20159. var removeFailed = function (blobUri) {
  20160. delete blobUriStatuses[blobUri];
  20161. };
  20162. var destroy = function () {
  20163. blobUriStatuses = {};
  20164. };
  20165. return {
  20166. hasBlobUri: hasBlobUri,
  20167. getResultUri: getResultUri,
  20168. isPending: isPending,
  20169. isUploaded: isUploaded,
  20170. markPending: markPending,
  20171. markUploaded: markUploaded,
  20172. removeFailed: removeFailed,
  20173. destroy: destroy
  20174. };
  20175. };
  20176. var count = 0;
  20177. var seed = function () {
  20178. var rnd = function () {
  20179. return Math.round(Math.random() * 4294967295).toString(36);
  20180. };
  20181. var now = new Date().getTime();
  20182. return 's' + now.toString(36) + rnd() + rnd() + rnd();
  20183. };
  20184. var uuid = function (prefix) {
  20185. return prefix + count++ + seed();
  20186. };
  20187. var BlobCache = function () {
  20188. var cache = [];
  20189. var mimeToExt = function (mime) {
  20190. var mimes = {
  20191. 'image/jpeg': 'jpg',
  20192. 'image/jpg': 'jpg',
  20193. 'image/gif': 'gif',
  20194. 'image/png': 'png',
  20195. 'image/apng': 'apng',
  20196. 'image/avif': 'avif',
  20197. 'image/svg+xml': 'svg',
  20198. 'image/webp': 'webp',
  20199. 'image/bmp': 'bmp',
  20200. 'image/tiff': 'tiff'
  20201. };
  20202. return mimes[mime.toLowerCase()] || 'dat';
  20203. };
  20204. var create = function (o, blob, base64, name, filename) {
  20205. if (isString$1(o)) {
  20206. var id = o;
  20207. return toBlobInfo({
  20208. id: id,
  20209. name: name,
  20210. filename: filename,
  20211. blob: blob,
  20212. base64: base64
  20213. });
  20214. } else if (isObject(o)) {
  20215. return toBlobInfo(o);
  20216. } else {
  20217. throw new Error('Unknown input type');
  20218. }
  20219. };
  20220. var toBlobInfo = function (o) {
  20221. if (!o.blob || !o.base64) {
  20222. throw new Error('blob and base64 representations of the image are required for BlobInfo to be created');
  20223. }
  20224. var id = o.id || uuid('blobid');
  20225. var name = o.name || id;
  20226. var blob = o.blob;
  20227. return {
  20228. id: constant(id),
  20229. name: constant(name),
  20230. filename: constant(o.filename || name + '.' + mimeToExt(blob.type)),
  20231. blob: constant(blob),
  20232. base64: constant(o.base64),
  20233. blobUri: constant(o.blobUri || URL.createObjectURL(blob)),
  20234. uri: constant(o.uri)
  20235. };
  20236. };
  20237. var add = function (blobInfo) {
  20238. if (!get(blobInfo.id())) {
  20239. cache.push(blobInfo);
  20240. }
  20241. };
  20242. var findFirst = function (predicate) {
  20243. return find$3(cache, predicate).getOrUndefined();
  20244. };
  20245. var get = function (id) {
  20246. return findFirst(function (cachedBlobInfo) {
  20247. return cachedBlobInfo.id() === id;
  20248. });
  20249. };
  20250. var getByUri = function (blobUri) {
  20251. return findFirst(function (blobInfo) {
  20252. return blobInfo.blobUri() === blobUri;
  20253. });
  20254. };
  20255. var getByData = function (base64, type) {
  20256. return findFirst(function (blobInfo) {
  20257. return blobInfo.base64() === base64 && blobInfo.blob().type === type;
  20258. });
  20259. };
  20260. var removeByUri = function (blobUri) {
  20261. cache = filter$4(cache, function (blobInfo) {
  20262. if (blobInfo.blobUri() === blobUri) {
  20263. URL.revokeObjectURL(blobInfo.blobUri());
  20264. return false;
  20265. }
  20266. return true;
  20267. });
  20268. };
  20269. var destroy = function () {
  20270. each$k(cache, function (cachedBlobInfo) {
  20271. URL.revokeObjectURL(cachedBlobInfo.blobUri());
  20272. });
  20273. cache = [];
  20274. };
  20275. return {
  20276. create: create,
  20277. add: add,
  20278. get: get,
  20279. getByUri: getByUri,
  20280. getByData: getByData,
  20281. findFirst: findFirst,
  20282. removeByUri: removeByUri,
  20283. destroy: destroy
  20284. };
  20285. };
  20286. var Uploader = function (uploadStatus, settings) {
  20287. var pendingPromises = {};
  20288. var pathJoin = function (path1, path2) {
  20289. if (path1) {
  20290. return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
  20291. }
  20292. return path2;
  20293. };
  20294. var defaultHandler = function (blobInfo, success, failure, progress) {
  20295. var xhr = new XMLHttpRequest();
  20296. xhr.open('POST', settings.url);
  20297. xhr.withCredentials = settings.credentials;
  20298. xhr.upload.onprogress = function (e) {
  20299. progress(e.loaded / e.total * 100);
  20300. };
  20301. xhr.onerror = function () {
  20302. failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  20303. };
  20304. xhr.onload = function () {
  20305. if (xhr.status < 200 || xhr.status >= 300) {
  20306. failure('HTTP Error: ' + xhr.status);
  20307. return;
  20308. }
  20309. var json = JSON.parse(xhr.responseText);
  20310. if (!json || typeof json.location !== 'string') {
  20311. failure('Invalid JSON: ' + xhr.responseText);
  20312. return;
  20313. }
  20314. success(pathJoin(settings.basePath, json.location));
  20315. };
  20316. var formData = new FormData();
  20317. formData.append('file', blobInfo.blob(), blobInfo.filename());
  20318. xhr.send(formData);
  20319. };
  20320. var noUpload = function () {
  20321. return new promiseObj(function (resolve) {
  20322. resolve([]);
  20323. });
  20324. };
  20325. var handlerSuccess = function (blobInfo, url) {
  20326. return {
  20327. url: url,
  20328. blobInfo: blobInfo,
  20329. status: true
  20330. };
  20331. };
  20332. var handlerFailure = function (blobInfo, message, options) {
  20333. return {
  20334. url: '',
  20335. blobInfo: blobInfo,
  20336. status: false,
  20337. error: {
  20338. message: message,
  20339. options: options
  20340. }
  20341. };
  20342. };
  20343. var resolvePending = function (blobUri, result) {
  20344. Tools.each(pendingPromises[blobUri], function (resolve) {
  20345. resolve(result);
  20346. });
  20347. delete pendingPromises[blobUri];
  20348. };
  20349. var uploadBlobInfo = function (blobInfo, handler, openNotification) {
  20350. uploadStatus.markPending(blobInfo.blobUri());
  20351. return new promiseObj(function (resolve) {
  20352. var notification, progress;
  20353. try {
  20354. var closeNotification_1 = function () {
  20355. if (notification) {
  20356. notification.close();
  20357. progress = noop;
  20358. }
  20359. };
  20360. var success = function (url) {
  20361. closeNotification_1();
  20362. uploadStatus.markUploaded(blobInfo.blobUri(), url);
  20363. resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
  20364. resolve(handlerSuccess(blobInfo, url));
  20365. };
  20366. var failure = function (error, options) {
  20367. var failureOptions = options ? options : {};
  20368. closeNotification_1();
  20369. uploadStatus.removeFailed(blobInfo.blobUri());
  20370. resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error, failureOptions));
  20371. resolve(handlerFailure(blobInfo, error, failureOptions));
  20372. };
  20373. progress = function (percent) {
  20374. if (percent < 0 || percent > 100) {
  20375. return;
  20376. }
  20377. Optional.from(notification).orThunk(function () {
  20378. return Optional.from(openNotification).map(apply);
  20379. }).each(function (n) {
  20380. notification = n;
  20381. n.progressBar.value(percent);
  20382. });
  20383. };
  20384. handler(blobInfo, success, failure, progress);
  20385. } catch (ex) {
  20386. resolve(handlerFailure(blobInfo, ex.message, {}));
  20387. }
  20388. });
  20389. };
  20390. var isDefaultHandler = function (handler) {
  20391. return handler === defaultHandler;
  20392. };
  20393. var pendingUploadBlobInfo = function (blobInfo) {
  20394. var blobUri = blobInfo.blobUri();
  20395. return new promiseObj(function (resolve) {
  20396. pendingPromises[blobUri] = pendingPromises[blobUri] || [];
  20397. pendingPromises[blobUri].push(resolve);
  20398. });
  20399. };
  20400. var uploadBlobs = function (blobInfos, openNotification) {
  20401. blobInfos = Tools.grep(blobInfos, function (blobInfo) {
  20402. return !uploadStatus.isUploaded(blobInfo.blobUri());
  20403. });
  20404. return promiseObj.all(Tools.map(blobInfos, function (blobInfo) {
  20405. return uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification);
  20406. }));
  20407. };
  20408. var upload = function (blobInfos, openNotification) {
  20409. return !settings.url && isDefaultHandler(settings.handler) ? noUpload() : uploadBlobs(blobInfos, openNotification);
  20410. };
  20411. if (isFunction(settings.handler) === false) {
  20412. settings.handler = defaultHandler;
  20413. }
  20414. return { upload: upload };
  20415. };
  20416. var openNotification = function (editor) {
  20417. return function () {
  20418. return editor.notificationManager.open({
  20419. text: editor.translate('Image uploading...'),
  20420. type: 'info',
  20421. timeout: -1,
  20422. progressBar: true
  20423. });
  20424. };
  20425. };
  20426. var createUploader = function (editor, uploadStatus) {
  20427. return Uploader(uploadStatus, {
  20428. url: getImageUploadUrl(editor),
  20429. basePath: getImageUploadBasePath(editor),
  20430. credentials: getImagesUploadCredentials(editor),
  20431. handler: getImagesUploadHandler(editor)
  20432. });
  20433. };
  20434. var ImageUploader = function (editor) {
  20435. var uploadStatus = UploadStatus();
  20436. var uploader = createUploader(editor, uploadStatus);
  20437. return {
  20438. upload: function (blobInfos, showNotification) {
  20439. if (showNotification === void 0) {
  20440. showNotification = true;
  20441. }
  20442. return uploader.upload(blobInfos, showNotification ? openNotification(editor) : undefined);
  20443. }
  20444. };
  20445. };
  20446. var UploadChangeHandler = function (editor) {
  20447. var lastChangedLevel = Cell(null);
  20448. editor.on('change AddUndo', function (e) {
  20449. lastChangedLevel.set(__assign({}, e.level));
  20450. });
  20451. var fireIfChanged = function () {
  20452. var data = editor.undoManager.data;
  20453. last$2(data).filter(function (level) {
  20454. return !isEq$1(lastChangedLevel.get(), level);
  20455. }).each(function (level) {
  20456. editor.setDirty(true);
  20457. editor.fire('change', {
  20458. level: level,
  20459. lastLevel: get$a(data, data.length - 2).getOrNull()
  20460. });
  20461. });
  20462. };
  20463. return { fireIfChanged: fireIfChanged };
  20464. };
  20465. var EditorUpload = function (editor) {
  20466. var blobCache = BlobCache();
  20467. var uploader, imageScanner;
  20468. var uploadStatus = UploadStatus();
  20469. var urlFilters = [];
  20470. var changeHandler = UploadChangeHandler(editor);
  20471. var aliveGuard = function (callback) {
  20472. return function (result) {
  20473. if (editor.selection) {
  20474. return callback(result);
  20475. }
  20476. return [];
  20477. };
  20478. };
  20479. var cacheInvalidator = function (url) {
  20480. return url + (url.indexOf('?') === -1 ? '?' : '&') + new Date().getTime();
  20481. };
  20482. var replaceString = function (content, search, replace) {
  20483. var index = 0;
  20484. do {
  20485. index = content.indexOf(search, index);
  20486. if (index !== -1) {
  20487. content = content.substring(0, index) + replace + content.substr(index + search.length);
  20488. index += replace.length - search.length + 1;
  20489. }
  20490. } while (index !== -1);
  20491. return content;
  20492. };
  20493. var replaceImageUrl = function (content, targetUrl, replacementUrl) {
  20494. var replacementString = 'src="' + replacementUrl + '"' + (replacementUrl === Env.transparentSrc ? ' data-mce-placeholder="1"' : '');
  20495. content = replaceString(content, 'src="' + targetUrl + '"', replacementString);
  20496. content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
  20497. return content;
  20498. };
  20499. var replaceUrlInUndoStack = function (targetUrl, replacementUrl) {
  20500. each$k(editor.undoManager.data, function (level) {
  20501. if (level.type === 'fragmented') {
  20502. level.fragments = map$3(level.fragments, function (fragment) {
  20503. return replaceImageUrl(fragment, targetUrl, replacementUrl);
  20504. });
  20505. } else {
  20506. level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
  20507. }
  20508. });
  20509. };
  20510. var replaceImageUriInView = function (image, resultUri) {
  20511. var src = editor.convertURL(resultUri, 'src');
  20512. replaceUrlInUndoStack(image.src, resultUri);
  20513. editor.$(image).attr({
  20514. 'src': shouldReuseFileName(editor) ? cacheInvalidator(resultUri) : resultUri,
  20515. 'data-mce-src': src
  20516. });
  20517. };
  20518. var uploadImages = function (callback) {
  20519. if (!uploader) {
  20520. uploader = createUploader(editor, uploadStatus);
  20521. }
  20522. return scanForImages().then(aliveGuard(function (imageInfos) {
  20523. var blobInfos = map$3(imageInfos, function (imageInfo) {
  20524. return imageInfo.blobInfo;
  20525. });
  20526. return uploader.upload(blobInfos, openNotification(editor)).then(aliveGuard(function (result) {
  20527. var imagesToRemove = [];
  20528. var filteredResult = map$3(result, function (uploadInfo, index) {
  20529. var blobInfo = imageInfos[index].blobInfo;
  20530. var image = imageInfos[index].image;
  20531. if (uploadInfo.status && shouldReplaceBlobUris(editor)) {
  20532. blobCache.removeByUri(image.src);
  20533. if (isRtc(editor)) ; else {
  20534. replaceImageUriInView(image, uploadInfo.url);
  20535. }
  20536. } else if (uploadInfo.error) {
  20537. if (uploadInfo.error.options.remove) {
  20538. replaceUrlInUndoStack(image.getAttribute('src'), Env.transparentSrc);
  20539. imagesToRemove.push(image);
  20540. }
  20541. uploadError(editor, uploadInfo.error.message);
  20542. }
  20543. return {
  20544. element: image,
  20545. status: uploadInfo.status,
  20546. uploadUri: uploadInfo.url,
  20547. blobInfo: blobInfo
  20548. };
  20549. });
  20550. if (filteredResult.length > 0) {
  20551. changeHandler.fireIfChanged();
  20552. }
  20553. if (imagesToRemove.length > 0) {
  20554. if (isRtc(editor)) {
  20555. console.error('Removing images on failed uploads is currently unsupported for RTC');
  20556. } else {
  20557. editor.undoManager.transact(function () {
  20558. each$k(imagesToRemove, function (element) {
  20559. editor.dom.remove(element);
  20560. blobCache.removeByUri(element.src);
  20561. });
  20562. });
  20563. }
  20564. }
  20565. if (callback) {
  20566. callback(filteredResult);
  20567. }
  20568. return filteredResult;
  20569. }));
  20570. }));
  20571. };
  20572. var uploadImagesAuto = function (callback) {
  20573. if (isAutomaticUploadsEnabled(editor)) {
  20574. return uploadImages(callback);
  20575. }
  20576. };
  20577. var isValidDataUriImage = function (imgElm) {
  20578. if (forall(urlFilters, function (filter) {
  20579. return filter(imgElm);
  20580. }) === false) {
  20581. return false;
  20582. }
  20583. if (imgElm.getAttribute('src').indexOf('data:') === 0) {
  20584. var dataImgFilter = getImagesDataImgFilter(editor);
  20585. return dataImgFilter(imgElm);
  20586. }
  20587. return true;
  20588. };
  20589. var addFilter = function (filter) {
  20590. urlFilters.push(filter);
  20591. };
  20592. var scanForImages = function () {
  20593. if (!imageScanner) {
  20594. imageScanner = ImageScanner(uploadStatus, blobCache);
  20595. }
  20596. return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(function (result) {
  20597. result = filter$4(result, function (resultItem) {
  20598. if (typeof resultItem === 'string') {
  20599. displayError(editor, resultItem);
  20600. return false;
  20601. }
  20602. return true;
  20603. });
  20604. if (isRtc(editor)) ; else {
  20605. each$k(result, function (resultItem) {
  20606. replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
  20607. resultItem.image.src = resultItem.blobInfo.blobUri();
  20608. resultItem.image.removeAttribute('data-mce-src');
  20609. });
  20610. }
  20611. return result;
  20612. }));
  20613. };
  20614. var destroy = function () {
  20615. blobCache.destroy();
  20616. uploadStatus.destroy();
  20617. imageScanner = uploader = null;
  20618. };
  20619. var replaceBlobUris = function (content) {
  20620. return content.replace(/src="(blob:[^"]+)"/g, function (match, blobUri) {
  20621. var resultUri = uploadStatus.getResultUri(blobUri);
  20622. if (resultUri) {
  20623. return 'src="' + resultUri + '"';
  20624. }
  20625. var blobInfo = blobCache.getByUri(blobUri);
  20626. if (!blobInfo) {
  20627. blobInfo = foldl(editor.editorManager.get(), function (result, editor) {
  20628. return result || editor.editorUpload && editor.editorUpload.blobCache.getByUri(blobUri);
  20629. }, null);
  20630. }
  20631. if (blobInfo) {
  20632. var blob = blobInfo.blob();
  20633. return 'src="data:' + blob.type + ';base64,' + blobInfo.base64() + '"';
  20634. }
  20635. return match;
  20636. });
  20637. };
  20638. editor.on('SetContent', function () {
  20639. if (isAutomaticUploadsEnabled(editor)) {
  20640. uploadImagesAuto();
  20641. } else {
  20642. scanForImages();
  20643. }
  20644. });
  20645. editor.on('RawSaveContent', function (e) {
  20646. e.content = replaceBlobUris(e.content);
  20647. });
  20648. editor.on('GetContent', function (e) {
  20649. if (e.source_view || e.format === 'raw' || e.format === 'tree') {
  20650. return;
  20651. }
  20652. e.content = replaceBlobUris(e.content);
  20653. });
  20654. editor.on('PostRender', function () {
  20655. editor.parser.addNodeFilter('img', function (images) {
  20656. each$k(images, function (img) {
  20657. var src = img.attr('src');
  20658. if (blobCache.getByUri(src)) {
  20659. return;
  20660. }
  20661. var resultUri = uploadStatus.getResultUri(src);
  20662. if (resultUri) {
  20663. img.attr('src', resultUri);
  20664. }
  20665. });
  20666. });
  20667. });
  20668. return {
  20669. blobCache: blobCache,
  20670. addFilter: addFilter,
  20671. uploadImages: uploadImages,
  20672. uploadImagesAuto: uploadImagesAuto,
  20673. scanForImages: scanForImages,
  20674. destroy: destroy
  20675. };
  20676. };
  20677. var get = function (dom) {
  20678. var formats = {
  20679. valigntop: [{
  20680. selector: 'td,th',
  20681. styles: { verticalAlign: 'top' }
  20682. }],
  20683. valignmiddle: [{
  20684. selector: 'td,th',
  20685. styles: { verticalAlign: 'middle' }
  20686. }],
  20687. valignbottom: [{
  20688. selector: 'td,th',
  20689. styles: { verticalAlign: 'bottom' }
  20690. }],
  20691. alignleft: [
  20692. {
  20693. selector: 'figure.image',
  20694. collapsed: false,
  20695. classes: 'align-left',
  20696. ceFalseOverride: true,
  20697. preview: 'font-family font-size'
  20698. },
  20699. {
  20700. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20701. styles: { textAlign: 'left' },
  20702. inherit: false,
  20703. preview: false,
  20704. defaultBlock: 'div'
  20705. },
  20706. {
  20707. selector: 'img,table,audio,video',
  20708. collapsed: false,
  20709. styles: { float: 'left' },
  20710. preview: 'font-family font-size'
  20711. }
  20712. ],
  20713. aligncenter: [
  20714. {
  20715. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20716. styles: { textAlign: 'center' },
  20717. inherit: false,
  20718. preview: 'font-family font-size',
  20719. defaultBlock: 'div'
  20720. },
  20721. {
  20722. selector: 'figure.image',
  20723. collapsed: false,
  20724. classes: 'align-center',
  20725. ceFalseOverride: true,
  20726. preview: 'font-family font-size'
  20727. },
  20728. {
  20729. selector: 'img,audio,video',
  20730. collapsed: false,
  20731. styles: {
  20732. display: 'block',
  20733. marginLeft: 'auto',
  20734. marginRight: 'auto'
  20735. },
  20736. preview: false
  20737. },
  20738. {
  20739. selector: 'table',
  20740. collapsed: false,
  20741. styles: {
  20742. marginLeft: 'auto',
  20743. marginRight: 'auto'
  20744. },
  20745. preview: 'font-family font-size'
  20746. }
  20747. ],
  20748. alignright: [
  20749. {
  20750. selector: 'figure.image',
  20751. collapsed: false,
  20752. classes: 'align-right',
  20753. ceFalseOverride: true,
  20754. preview: 'font-family font-size'
  20755. },
  20756. {
  20757. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20758. styles: { textAlign: 'right' },
  20759. inherit: false,
  20760. preview: 'font-family font-size',
  20761. defaultBlock: 'div'
  20762. },
  20763. {
  20764. selector: 'img,table,audio,video',
  20765. collapsed: false,
  20766. styles: { float: 'right' },
  20767. preview: 'font-family font-size'
  20768. }
  20769. ],
  20770. alignjustify: [{
  20771. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20772. styles: { textAlign: 'justify' },
  20773. inherit: false,
  20774. defaultBlock: 'div',
  20775. preview: 'font-family font-size'
  20776. }],
  20777. bold: [
  20778. {
  20779. inline: 'strong',
  20780. remove: 'all',
  20781. preserve_attributes: [
  20782. 'class',
  20783. 'style'
  20784. ]
  20785. },
  20786. {
  20787. inline: 'span',
  20788. styles: { fontWeight: 'bold' }
  20789. },
  20790. {
  20791. inline: 'b',
  20792. remove: 'all',
  20793. preserve_attributes: [
  20794. 'class',
  20795. 'style'
  20796. ]
  20797. }
  20798. ],
  20799. italic: [
  20800. {
  20801. inline: 'em',
  20802. remove: 'all',
  20803. preserve_attributes: [
  20804. 'class',
  20805. 'style'
  20806. ]
  20807. },
  20808. {
  20809. inline: 'span',
  20810. styles: { fontStyle: 'italic' }
  20811. },
  20812. {
  20813. inline: 'i',
  20814. remove: 'all',
  20815. preserve_attributes: [
  20816. 'class',
  20817. 'style'
  20818. ]
  20819. }
  20820. ],
  20821. underline: [
  20822. {
  20823. inline: 'span',
  20824. styles: { textDecoration: 'underline' },
  20825. exact: true
  20826. },
  20827. {
  20828. inline: 'u',
  20829. remove: 'all',
  20830. preserve_attributes: [
  20831. 'class',
  20832. 'style'
  20833. ]
  20834. }
  20835. ],
  20836. strikethrough: [
  20837. {
  20838. inline: 'span',
  20839. styles: { textDecoration: 'line-through' },
  20840. exact: true
  20841. },
  20842. {
  20843. inline: 'strike',
  20844. remove: 'all',
  20845. preserve_attributes: [
  20846. 'class',
  20847. 'style'
  20848. ]
  20849. },
  20850. {
  20851. inline: 's',
  20852. remove: 'all',
  20853. preserve_attributes: [
  20854. 'class',
  20855. 'style'
  20856. ]
  20857. }
  20858. ],
  20859. forecolor: {
  20860. inline: 'span',
  20861. styles: { color: '%value' },
  20862. links: true,
  20863. remove_similar: true,
  20864. clear_child_styles: true
  20865. },
  20866. hilitecolor: {
  20867. inline: 'span',
  20868. styles: { backgroundColor: '%value' },
  20869. links: true,
  20870. remove_similar: true,
  20871. clear_child_styles: true
  20872. },
  20873. fontname: {
  20874. inline: 'span',
  20875. toggle: false,
  20876. styles: { fontFamily: '%value' },
  20877. clear_child_styles: true
  20878. },
  20879. fontsize: {
  20880. inline: 'span',
  20881. toggle: false,
  20882. styles: { fontSize: '%value' },
  20883. clear_child_styles: true
  20884. },
  20885. lineheight: {
  20886. selector: 'h1,h2,h3,h4,h5,h6,p,li,td,th,div',
  20887. defaultBlock: 'p',
  20888. styles: { lineHeight: '%value' }
  20889. },
  20890. fontsize_class: {
  20891. inline: 'span',
  20892. attributes: { class: '%value' }
  20893. },
  20894. blockquote: {
  20895. block: 'blockquote',
  20896. wrapper: true,
  20897. remove: 'all'
  20898. },
  20899. subscript: { inline: 'sub' },
  20900. superscript: { inline: 'sup' },
  20901. code: { inline: 'code' },
  20902. link: {
  20903. inline: 'a',
  20904. selector: 'a',
  20905. remove: 'all',
  20906. split: true,
  20907. deep: true,
  20908. onmatch: function (node, _fmt, _itemName) {
  20909. return isElement$5(node) && node.hasAttribute('href');
  20910. },
  20911. onformat: function (elm, _fmt, vars) {
  20912. Tools.each(vars, function (value, key) {
  20913. dom.setAttrib(elm, key, value);
  20914. });
  20915. }
  20916. },
  20917. lang: {
  20918. inline: 'span',
  20919. clear_child_styles: true,
  20920. remove_similar: true,
  20921. attributes: {
  20922. 'lang': '%value',
  20923. 'data-mce-lang': function (vars) {
  20924. var _a;
  20925. return (_a = vars === null || vars === void 0 ? void 0 : vars.customValue) !== null && _a !== void 0 ? _a : null;
  20926. }
  20927. }
  20928. },
  20929. removeformat: [
  20930. {
  20931. selector: 'b,strong,em,i,font,u,strike,s,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins,small',
  20932. remove: 'all',
  20933. split: true,
  20934. expand: false,
  20935. block_expand: true,
  20936. deep: true
  20937. },
  20938. {
  20939. selector: 'span',
  20940. attributes: [
  20941. 'style',
  20942. 'class'
  20943. ],
  20944. remove: 'empty',
  20945. split: true,
  20946. expand: false,
  20947. deep: true
  20948. },
  20949. {
  20950. selector: '*',
  20951. attributes: [
  20952. 'style',
  20953. 'class'
  20954. ],
  20955. split: false,
  20956. expand: false,
  20957. deep: true
  20958. }
  20959. ]
  20960. };
  20961. Tools.each('p h1 h2 h3 h4 h5 h6 div address pre dt dd samp'.split(/\s/), function (name) {
  20962. formats[name] = {
  20963. block: name,
  20964. remove: 'all'
  20965. };
  20966. });
  20967. return formats;
  20968. };
  20969. var FormatRegistry = function (editor) {
  20970. var formats = {};
  20971. var get$1 = function (name) {
  20972. return isNonNullable(name) ? formats[name] : formats;
  20973. };
  20974. var has = function (name) {
  20975. return has$2(formats, name);
  20976. };
  20977. var register = function (name, format) {
  20978. if (name) {
  20979. if (!isString$1(name)) {
  20980. each$j(name, function (format, name) {
  20981. register(name, format);
  20982. });
  20983. } else {
  20984. if (!isArray$1(format)) {
  20985. format = [format];
  20986. }
  20987. each$k(format, function (format) {
  20988. if (isUndefined(format.deep)) {
  20989. format.deep = !isSelectorFormat(format);
  20990. }
  20991. if (isUndefined(format.split)) {
  20992. format.split = !isSelectorFormat(format) || isInlineFormat(format);
  20993. }
  20994. if (isUndefined(format.remove) && isSelectorFormat(format) && !isInlineFormat(format)) {
  20995. format.remove = 'none';
  20996. }
  20997. if (isSelectorFormat(format) && isInlineFormat(format)) {
  20998. format.mixed = true;
  20999. format.block_expand = true;
  21000. }
  21001. if (isString$1(format.classes)) {
  21002. format.classes = format.classes.split(/\s+/);
  21003. }
  21004. });
  21005. formats[name] = format;
  21006. }
  21007. }
  21008. };
  21009. var unregister = function (name) {
  21010. if (name && formats[name]) {
  21011. delete formats[name];
  21012. }
  21013. return formats;
  21014. };
  21015. register(get(editor.dom));
  21016. register(getFormats(editor));
  21017. return {
  21018. get: get$1,
  21019. has: has,
  21020. register: register,
  21021. unregister: unregister
  21022. };
  21023. };
  21024. var each$5 = Tools.each;
  21025. var dom = DOMUtils.DOM;
  21026. var parsedSelectorToHtml = function (ancestry, editor) {
  21027. var elm, item, fragment;
  21028. var schema = editor && editor.schema || Schema({});
  21029. var decorate = function (elm, item) {
  21030. if (item.classes.length) {
  21031. dom.addClass(elm, item.classes.join(' '));
  21032. }
  21033. dom.setAttribs(elm, item.attrs);
  21034. };
  21035. var createElement = function (sItem) {
  21036. item = typeof sItem === 'string' ? {
  21037. name: sItem,
  21038. classes: [],
  21039. attrs: {}
  21040. } : sItem;
  21041. var elm = dom.create(item.name);
  21042. decorate(elm, item);
  21043. return elm;
  21044. };
  21045. var getRequiredParent = function (elm, candidate) {
  21046. var name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm;
  21047. var elmRule = schema.getElementRule(name);
  21048. var parentsRequired = elmRule && elmRule.parentsRequired;
  21049. if (parentsRequired && parentsRequired.length) {
  21050. return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
  21051. } else {
  21052. return false;
  21053. }
  21054. };
  21055. var wrapInHtml = function (elm, ancestry, siblings) {
  21056. var parent, parentCandidate;
  21057. var ancestor = ancestry.length > 0 && ancestry[0];
  21058. var ancestorName = ancestor && ancestor.name;
  21059. var parentRequired = getRequiredParent(elm, ancestorName);
  21060. if (parentRequired) {
  21061. if (ancestorName === parentRequired) {
  21062. parentCandidate = ancestry[0];
  21063. ancestry = ancestry.slice(1);
  21064. } else {
  21065. parentCandidate = parentRequired;
  21066. }
  21067. } else if (ancestor) {
  21068. parentCandidate = ancestry[0];
  21069. ancestry = ancestry.slice(1);
  21070. } else if (!siblings) {
  21071. return elm;
  21072. }
  21073. if (parentCandidate) {
  21074. parent = createElement(parentCandidate);
  21075. parent.appendChild(elm);
  21076. }
  21077. if (siblings) {
  21078. if (!parent) {
  21079. parent = dom.create('div');
  21080. parent.appendChild(elm);
  21081. }
  21082. Tools.each(siblings, function (sibling) {
  21083. var siblingElm = createElement(sibling);
  21084. parent.insertBefore(siblingElm, elm);
  21085. });
  21086. }
  21087. return wrapInHtml(parent, ancestry, parentCandidate && parentCandidate.siblings);
  21088. };
  21089. if (ancestry && ancestry.length) {
  21090. item = ancestry[0];
  21091. elm = createElement(item);
  21092. fragment = dom.create('div');
  21093. fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
  21094. return fragment;
  21095. } else {
  21096. return '';
  21097. }
  21098. };
  21099. var parseSelectorItem = function (item) {
  21100. var tagName;
  21101. var obj = {
  21102. classes: [],
  21103. attrs: {}
  21104. };
  21105. item = obj.selector = Tools.trim(item);
  21106. if (item !== '*') {
  21107. tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function ($0, $1, $2, $3, $4) {
  21108. switch ($1) {
  21109. case '#':
  21110. obj.attrs.id = $2;
  21111. break;
  21112. case '.':
  21113. obj.classes.push($2);
  21114. break;
  21115. case ':':
  21116. if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
  21117. obj.attrs[$2] = $2;
  21118. }
  21119. break;
  21120. }
  21121. if ($3 === '[') {
  21122. var m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
  21123. if (m) {
  21124. obj.attrs[m[1]] = m[2];
  21125. }
  21126. }
  21127. return '';
  21128. });
  21129. }
  21130. obj.name = tagName || 'div';
  21131. return obj;
  21132. };
  21133. var parseSelector = function (selector) {
  21134. if (!selector || typeof selector !== 'string') {
  21135. return [];
  21136. }
  21137. selector = selector.split(/\s*,\s*/)[0];
  21138. selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1');
  21139. return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), function (item) {
  21140. var siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
  21141. var obj = siblings.pop();
  21142. if (siblings.length) {
  21143. obj.siblings = siblings;
  21144. }
  21145. return obj;
  21146. }).reverse();
  21147. };
  21148. var getCssText = function (editor, format) {
  21149. var name, previewFrag;
  21150. var previewCss = '', parentFontSize;
  21151. var previewStyles = getPreviewStyles(editor);
  21152. if (previewStyles === '') {
  21153. return '';
  21154. }
  21155. var removeVars = function (val) {
  21156. return val.replace(/%(\w+)/g, '');
  21157. };
  21158. if (typeof format === 'string') {
  21159. format = editor.formatter.get(format);
  21160. if (!format) {
  21161. return;
  21162. }
  21163. format = format[0];
  21164. }
  21165. if ('preview' in format) {
  21166. var previewOpt = get$9(format, 'preview');
  21167. if (is$1(previewOpt, false)) {
  21168. return '';
  21169. } else {
  21170. previewStyles = previewOpt.getOr(previewStyles);
  21171. }
  21172. }
  21173. name = format.block || format.inline || 'span';
  21174. var items = parseSelector(format.selector);
  21175. if (items.length) {
  21176. if (!items[0].name) {
  21177. items[0].name = name;
  21178. }
  21179. name = format.selector;
  21180. previewFrag = parsedSelectorToHtml(items, editor);
  21181. } else {
  21182. previewFrag = parsedSelectorToHtml([name], editor);
  21183. }
  21184. var previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;
  21185. each$5(format.styles, function (value, name) {
  21186. var newValue = removeVars(value);
  21187. if (newValue) {
  21188. dom.setStyle(previewElm, name, newValue);
  21189. }
  21190. });
  21191. each$5(format.attributes, function (value, name) {
  21192. var newValue = removeVars(value);
  21193. if (newValue) {
  21194. dom.setAttrib(previewElm, name, newValue);
  21195. }
  21196. });
  21197. each$5(format.classes, function (value) {
  21198. var newValue = removeVars(value);
  21199. if (!dom.hasClass(previewElm, newValue)) {
  21200. dom.addClass(previewElm, newValue);
  21201. }
  21202. });
  21203. editor.fire('PreviewFormats');
  21204. dom.setStyles(previewFrag, {
  21205. position: 'absolute',
  21206. left: -65535
  21207. });
  21208. editor.getBody().appendChild(previewFrag);
  21209. parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
  21210. parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
  21211. each$5(previewStyles.split(' '), function (name) {
  21212. var value = dom.getStyle(previewElm, name, true);
  21213. if (name === 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
  21214. value = dom.getStyle(editor.getBody(), name, true);
  21215. if (dom.toHex(value).toLowerCase() === '#ffffff') {
  21216. return;
  21217. }
  21218. }
  21219. if (name === 'color') {
  21220. if (dom.toHex(value).toLowerCase() === '#000000') {
  21221. return;
  21222. }
  21223. }
  21224. if (name === 'font-size') {
  21225. if (/em|%$/.test(value)) {
  21226. if (parentFontSize === 0) {
  21227. return;
  21228. }
  21229. var numValue = parseFloat(value) / (/%$/.test(value) ? 100 : 1);
  21230. value = numValue * parentFontSize + 'px';
  21231. }
  21232. }
  21233. if (name === 'border' && value) {
  21234. previewCss += 'padding:0 2px;';
  21235. }
  21236. previewCss += name + ':' + value + ';';
  21237. });
  21238. editor.fire('AfterPreviewFormats');
  21239. dom.remove(previewFrag);
  21240. return previewCss;
  21241. };
  21242. var setup$h = function (editor) {
  21243. editor.addShortcut('meta+b', '', 'Bold');
  21244. editor.addShortcut('meta+i', '', 'Italic');
  21245. editor.addShortcut('meta+u', '', 'Underline');
  21246. for (var i = 1; i <= 6; i++) {
  21247. editor.addShortcut('access+' + i, '', [
  21248. 'FormatBlock',
  21249. false,
  21250. 'h' + i
  21251. ]);
  21252. }
  21253. editor.addShortcut('access+7', '', [
  21254. 'FormatBlock',
  21255. false,
  21256. 'p'
  21257. ]);
  21258. editor.addShortcut('access+8', '', [
  21259. 'FormatBlock',
  21260. false,
  21261. 'div'
  21262. ]);
  21263. editor.addShortcut('access+9', '', [
  21264. 'FormatBlock',
  21265. false,
  21266. 'address'
  21267. ]);
  21268. };
  21269. var Formatter = function (editor) {
  21270. var formats = FormatRegistry(editor);
  21271. var formatChangeState = Cell(null);
  21272. setup$h(editor);
  21273. setup$k(editor);
  21274. return {
  21275. get: formats.get,
  21276. has: formats.has,
  21277. register: formats.register,
  21278. unregister: formats.unregister,
  21279. apply: function (name, vars, node) {
  21280. applyFormat(editor, name, vars, node);
  21281. },
  21282. remove: function (name, vars, node, similar) {
  21283. removeFormat(editor, name, vars, node, similar);
  21284. },
  21285. toggle: function (name, vars, node) {
  21286. toggleFormat(editor, name, vars, node);
  21287. },
  21288. match: function (name, vars, node, similar) {
  21289. return matchFormat(editor, name, vars, node, similar);
  21290. },
  21291. closest: function (names) {
  21292. return closestFormat(editor, names);
  21293. },
  21294. matchAll: function (names, vars) {
  21295. return matchAllFormats(editor, names, vars);
  21296. },
  21297. matchNode: function (node, name, vars, similar) {
  21298. return matchNodeFormat(editor, node, name, vars, similar);
  21299. },
  21300. canApply: function (name) {
  21301. return canApplyFormat(editor, name);
  21302. },
  21303. formatChanged: function (formats, callback, similar, vars) {
  21304. return formatChanged(editor, formatChangeState, formats, callback, similar, vars);
  21305. },
  21306. getCssText: curry(getCssText, editor)
  21307. };
  21308. };
  21309. var shouldIgnoreCommand = function (cmd) {
  21310. switch (cmd.toLowerCase()) {
  21311. case 'undo':
  21312. case 'redo':
  21313. case 'mcerepaint':
  21314. case 'mcefocus':
  21315. return true;
  21316. default:
  21317. return false;
  21318. }
  21319. };
  21320. var registerEvents = function (editor, undoManager, locks) {
  21321. var isFirstTypedCharacter = Cell(false);
  21322. var addNonTypingUndoLevel = function (e) {
  21323. setTyping(undoManager, false, locks);
  21324. undoManager.add({}, e);
  21325. };
  21326. editor.on('init', function () {
  21327. undoManager.add();
  21328. });
  21329. editor.on('BeforeExecCommand', function (e) {
  21330. var cmd = e.command;
  21331. if (!shouldIgnoreCommand(cmd)) {
  21332. endTyping(undoManager, locks);
  21333. undoManager.beforeChange();
  21334. }
  21335. });
  21336. editor.on('ExecCommand', function (e) {
  21337. var cmd = e.command;
  21338. if (!shouldIgnoreCommand(cmd)) {
  21339. addNonTypingUndoLevel(e);
  21340. }
  21341. });
  21342. editor.on('ObjectResizeStart cut', function () {
  21343. undoManager.beforeChange();
  21344. });
  21345. editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
  21346. editor.on('dragend', addNonTypingUndoLevel);
  21347. editor.on('keyup', function (e) {
  21348. var keyCode = e.keyCode;
  21349. if (e.isDefaultPrevented()) {
  21350. return;
  21351. }
  21352. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45 || e.ctrlKey) {
  21353. addNonTypingUndoLevel();
  21354. editor.nodeChanged();
  21355. }
  21356. if (keyCode === 46 || keyCode === 8) {
  21357. editor.nodeChanged();
  21358. }
  21359. if (isFirstTypedCharacter.get() && undoManager.typing && isEq$1(createFromEditor(editor), undoManager.data[0]) === false) {
  21360. if (editor.isDirty() === false) {
  21361. editor.setDirty(true);
  21362. editor.fire('change', {
  21363. level: undoManager.data[0],
  21364. lastLevel: null
  21365. });
  21366. }
  21367. editor.fire('TypingUndo');
  21368. isFirstTypedCharacter.set(false);
  21369. editor.nodeChanged();
  21370. }
  21371. });
  21372. editor.on('keydown', function (e) {
  21373. var keyCode = e.keyCode;
  21374. if (e.isDefaultPrevented()) {
  21375. return;
  21376. }
  21377. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45) {
  21378. if (undoManager.typing) {
  21379. addNonTypingUndoLevel(e);
  21380. }
  21381. return;
  21382. }
  21383. var modKey = e.ctrlKey && !e.altKey || e.metaKey;
  21384. if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !undoManager.typing && !modKey) {
  21385. undoManager.beforeChange();
  21386. setTyping(undoManager, true, locks);
  21387. undoManager.add({}, e);
  21388. isFirstTypedCharacter.set(true);
  21389. }
  21390. });
  21391. editor.on('mousedown', function (e) {
  21392. if (undoManager.typing) {
  21393. addNonTypingUndoLevel(e);
  21394. }
  21395. });
  21396. var isInsertReplacementText = function (event) {
  21397. return event.inputType === 'insertReplacementText';
  21398. };
  21399. var isInsertTextDataNull = function (event) {
  21400. return event.inputType === 'insertText' && event.data === null;
  21401. };
  21402. var isInsertFromPasteOrDrop = function (event) {
  21403. return event.inputType === 'insertFromPaste' || event.inputType === 'insertFromDrop';
  21404. };
  21405. editor.on('input', function (e) {
  21406. if (e.inputType && (isInsertReplacementText(e) || isInsertTextDataNull(e) || isInsertFromPasteOrDrop(e))) {
  21407. addNonTypingUndoLevel(e);
  21408. }
  21409. });
  21410. editor.on('AddUndo Undo Redo ClearUndos', function (e) {
  21411. if (!e.isDefaultPrevented()) {
  21412. editor.nodeChanged();
  21413. }
  21414. });
  21415. };
  21416. var addKeyboardShortcuts = function (editor) {
  21417. editor.addShortcut('meta+z', '', 'Undo');
  21418. editor.addShortcut('meta+y,meta+shift+z', '', 'Redo');
  21419. };
  21420. var UndoManager = function (editor) {
  21421. var beforeBookmark = value();
  21422. var locks = Cell(0);
  21423. var index = Cell(0);
  21424. var undoManager = {
  21425. data: [],
  21426. typing: false,
  21427. beforeChange: function () {
  21428. beforeChange(editor, locks, beforeBookmark);
  21429. },
  21430. add: function (level, event) {
  21431. return addUndoLevel(editor, undoManager, index, locks, beforeBookmark, level, event);
  21432. },
  21433. undo: function () {
  21434. return undo(editor, undoManager, locks, index);
  21435. },
  21436. redo: function () {
  21437. return redo(editor, index, undoManager.data);
  21438. },
  21439. clear: function () {
  21440. clear(editor, undoManager, index);
  21441. },
  21442. reset: function () {
  21443. reset(editor, undoManager);
  21444. },
  21445. hasUndo: function () {
  21446. return hasUndo(editor, undoManager, index);
  21447. },
  21448. hasRedo: function () {
  21449. return hasRedo(editor, undoManager, index);
  21450. },
  21451. transact: function (callback) {
  21452. return transact(editor, undoManager, locks, callback);
  21453. },
  21454. ignore: function (callback) {
  21455. ignore(editor, locks, callback);
  21456. },
  21457. extra: function (callback1, callback2) {
  21458. extra(editor, undoManager, index, callback1, callback2);
  21459. }
  21460. };
  21461. if (!isRtc(editor)) {
  21462. registerEvents(editor, undoManager, locks);
  21463. }
  21464. addKeyboardShortcuts(editor);
  21465. return undoManager;
  21466. };
  21467. var nonTypingKeycodes = [
  21468. 9,
  21469. 27,
  21470. VK.HOME,
  21471. VK.END,
  21472. 19,
  21473. 20,
  21474. 44,
  21475. 144,
  21476. 145,
  21477. 33,
  21478. 34,
  21479. 45,
  21480. 16,
  21481. 17,
  21482. 18,
  21483. 91,
  21484. 92,
  21485. 93,
  21486. VK.DOWN,
  21487. VK.UP,
  21488. VK.LEFT,
  21489. VK.RIGHT
  21490. ].concat(Env.browser.isFirefox() ? [224] : []);
  21491. var placeholderAttr = 'data-mce-placeholder';
  21492. var isKeyboardEvent = function (e) {
  21493. return e.type === 'keydown' || e.type === 'keyup';
  21494. };
  21495. var isDeleteEvent = function (e) {
  21496. var keyCode = e.keyCode;
  21497. return keyCode === VK.BACKSPACE || keyCode === VK.DELETE;
  21498. };
  21499. var isNonTypingKeyboardEvent = function (e) {
  21500. if (isKeyboardEvent(e)) {
  21501. var keyCode = e.keyCode;
  21502. return !isDeleteEvent(e) && (VK.metaKeyPressed(e) || e.altKey || keyCode >= 112 && keyCode <= 123 || contains$3(nonTypingKeycodes, keyCode));
  21503. } else {
  21504. return false;
  21505. }
  21506. };
  21507. var isTypingKeyboardEvent = function (e) {
  21508. return isKeyboardEvent(e) && !(isDeleteEvent(e) || e.type === 'keyup' && e.keyCode === 229);
  21509. };
  21510. var isVisuallyEmpty = function (dom, rootElm, forcedRootBlock) {
  21511. if (isEmpty$2(SugarElement.fromDom(rootElm), false)) {
  21512. var isForcedRootBlockFalse = forcedRootBlock === '';
  21513. var firstElement = rootElm.firstElementChild;
  21514. if (!firstElement) {
  21515. return true;
  21516. } else if (dom.getStyle(rootElm.firstElementChild, 'padding-left') || dom.getStyle(rootElm.firstElementChild, 'padding-right')) {
  21517. return false;
  21518. } else {
  21519. return isForcedRootBlockFalse ? !dom.isBlock(firstElement) : forcedRootBlock === firstElement.nodeName.toLowerCase();
  21520. }
  21521. } else {
  21522. return false;
  21523. }
  21524. };
  21525. var setup$g = function (editor) {
  21526. var dom = editor.dom;
  21527. var rootBlock = getForcedRootBlock(editor);
  21528. var placeholder = getPlaceholder(editor);
  21529. var updatePlaceholder = function (e, initial) {
  21530. if (isNonTypingKeyboardEvent(e)) {
  21531. return;
  21532. }
  21533. var body = editor.getBody();
  21534. var showPlaceholder = isTypingKeyboardEvent(e) ? false : isVisuallyEmpty(dom, body, rootBlock);
  21535. var isPlaceholderShown = dom.getAttrib(body, placeholderAttr) !== '';
  21536. if (isPlaceholderShown !== showPlaceholder || initial) {
  21537. dom.setAttrib(body, placeholderAttr, showPlaceholder ? placeholder : null);
  21538. dom.setAttrib(body, 'aria-placeholder', showPlaceholder ? placeholder : null);
  21539. firePlaceholderToggle(editor, showPlaceholder);
  21540. editor.on(showPlaceholder ? 'keydown' : 'keyup', updatePlaceholder);
  21541. editor.off(showPlaceholder ? 'keyup' : 'keydown', updatePlaceholder);
  21542. }
  21543. };
  21544. if (placeholder) {
  21545. editor.on('init', function (e) {
  21546. updatePlaceholder(e, true);
  21547. editor.on('change SetContent ExecCommand', updatePlaceholder);
  21548. editor.on('paste', function (e) {
  21549. return Delay.setEditorTimeout(editor, function () {
  21550. return updatePlaceholder(e);
  21551. });
  21552. });
  21553. });
  21554. }
  21555. };
  21556. var strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
  21557. var hasStrongRtl = function (text) {
  21558. return strongRtl.test(text);
  21559. };
  21560. var isInlineTarget = function (editor, elm) {
  21561. return is$2(SugarElement.fromDom(elm), getInlineBoundarySelector(editor));
  21562. };
  21563. var isRtl = function (element) {
  21564. return DOMUtils.DOM.getStyle(element, 'direction', true) === 'rtl' || hasStrongRtl(element.textContent);
  21565. };
  21566. var findInlineParents = function (isInlineTarget, rootNode, pos) {
  21567. return filter$4(DOMUtils.DOM.getParents(pos.container(), '*', rootNode), isInlineTarget);
  21568. };
  21569. var findRootInline = function (isInlineTarget, rootNode, pos) {
  21570. var parents = findInlineParents(isInlineTarget, rootNode, pos);
  21571. return Optional.from(parents[parents.length - 1]);
  21572. };
  21573. var hasSameParentBlock = function (rootNode, node1, node2) {
  21574. var block1 = getParentBlock$2(node1, rootNode);
  21575. var block2 = getParentBlock$2(node2, rootNode);
  21576. return block1 && block1 === block2;
  21577. };
  21578. var isAtZwsp = function (pos) {
  21579. return isBeforeInline(pos) || isAfterInline(pos);
  21580. };
  21581. var normalizePosition = function (forward, pos) {
  21582. if (!pos) {
  21583. return pos;
  21584. }
  21585. var container = pos.container(), offset = pos.offset();
  21586. if (forward) {
  21587. if (isCaretContainerInline(container)) {
  21588. if (isText$7(container.nextSibling)) {
  21589. return CaretPosition(container.nextSibling, 0);
  21590. } else {
  21591. return CaretPosition.after(container);
  21592. }
  21593. } else {
  21594. return isBeforeInline(pos) ? CaretPosition(container, offset + 1) : pos;
  21595. }
  21596. } else {
  21597. if (isCaretContainerInline(container)) {
  21598. if (isText$7(container.previousSibling)) {
  21599. return CaretPosition(container.previousSibling, container.previousSibling.data.length);
  21600. } else {
  21601. return CaretPosition.before(container);
  21602. }
  21603. } else {
  21604. return isAfterInline(pos) ? CaretPosition(container, offset - 1) : pos;
  21605. }
  21606. }
  21607. };
  21608. var normalizeForwards = curry(normalizePosition, true);
  21609. var normalizeBackwards = curry(normalizePosition, false);
  21610. var isBeforeRoot = function (rootNode) {
  21611. return function (elm) {
  21612. return eq(rootNode, SugarElement.fromDom(elm.dom.parentNode));
  21613. };
  21614. };
  21615. var isTextBlockOrListItem = function (element) {
  21616. return isTextBlock$2(element) || isListItem(element);
  21617. };
  21618. var getParentBlock$1 = function (rootNode, elm) {
  21619. if (contains$1(rootNode, elm)) {
  21620. return closest$3(elm, isTextBlockOrListItem, isBeforeRoot(rootNode));
  21621. } else {
  21622. return Optional.none();
  21623. }
  21624. };
  21625. var placeCaretInEmptyBody = function (editor) {
  21626. var body = editor.getBody();
  21627. var node = body.firstChild && editor.dom.isBlock(body.firstChild) ? body.firstChild : body;
  21628. editor.selection.setCursorLocation(node, 0);
  21629. };
  21630. var paddEmptyBody = function (editor) {
  21631. if (editor.dom.isEmpty(editor.getBody())) {
  21632. editor.setContent('');
  21633. placeCaretInEmptyBody(editor);
  21634. }
  21635. };
  21636. var willDeleteLastPositionInElement = function (forward, fromPos, elm) {
  21637. return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  21638. var normalizedFirstPos = normalizePosition(true, firstPos);
  21639. var normalizedLastPos = normalizePosition(false, lastPos);
  21640. var normalizedFromPos = normalizePosition(false, fromPos);
  21641. if (forward) {
  21642. return nextPosition(elm, normalizedFromPos).exists(function (nextPos) {
  21643. return nextPos.isEqual(normalizedLastPos) && fromPos.isEqual(normalizedFirstPos);
  21644. });
  21645. } else {
  21646. return prevPosition(elm, normalizedFromPos).exists(function (prevPos) {
  21647. return prevPos.isEqual(normalizedFirstPos) && fromPos.isEqual(normalizedLastPos);
  21648. });
  21649. }
  21650. }).getOr(true);
  21651. };
  21652. var blockPosition = function (block, position) {
  21653. return {
  21654. block: block,
  21655. position: position
  21656. };
  21657. };
  21658. var blockBoundary = function (from, to) {
  21659. return {
  21660. from: from,
  21661. to: to
  21662. };
  21663. };
  21664. var getBlockPosition = function (rootNode, pos) {
  21665. var rootElm = SugarElement.fromDom(rootNode);
  21666. var containerElm = SugarElement.fromDom(pos.container());
  21667. return getParentBlock$1(rootElm, containerElm).map(function (block) {
  21668. return blockPosition(block, pos);
  21669. });
  21670. };
  21671. var isDifferentBlocks = function (blockBoundary) {
  21672. return eq(blockBoundary.from.block, blockBoundary.to.block) === false;
  21673. };
  21674. var hasSameParent = function (blockBoundary) {
  21675. return parent(blockBoundary.from.block).bind(function (parent1) {
  21676. return parent(blockBoundary.to.block).filter(function (parent2) {
  21677. return eq(parent1, parent2);
  21678. });
  21679. }).isSome();
  21680. };
  21681. var isEditable$1 = function (blockBoundary) {
  21682. return isContentEditableFalse$b(blockBoundary.from.block.dom) === false && isContentEditableFalse$b(blockBoundary.to.block.dom) === false;
  21683. };
  21684. var skipLastBr = function (rootNode, forward, blockPosition) {
  21685. if (isBr$5(blockPosition.position.getNode()) && isEmpty$2(blockPosition.block) === false) {
  21686. return positionIn(false, blockPosition.block.dom).bind(function (lastPositionInBlock) {
  21687. if (lastPositionInBlock.isEqual(blockPosition.position)) {
  21688. return fromPosition(forward, rootNode, lastPositionInBlock).bind(function (to) {
  21689. return getBlockPosition(rootNode, to);
  21690. });
  21691. } else {
  21692. return Optional.some(blockPosition);
  21693. }
  21694. }).getOr(blockPosition);
  21695. } else {
  21696. return blockPosition;
  21697. }
  21698. };
  21699. var readFromRange = function (rootNode, forward, rng) {
  21700. var fromBlockPos = getBlockPosition(rootNode, CaretPosition.fromRangeStart(rng));
  21701. var toBlockPos = fromBlockPos.bind(function (blockPos) {
  21702. return fromPosition(forward, rootNode, blockPos.position).bind(function (to) {
  21703. return getBlockPosition(rootNode, to).map(function (blockPos) {
  21704. return skipLastBr(rootNode, forward, blockPos);
  21705. });
  21706. });
  21707. });
  21708. return lift2(fromBlockPos, toBlockPos, blockBoundary).filter(function (blockBoundary) {
  21709. return isDifferentBlocks(blockBoundary) && hasSameParent(blockBoundary) && isEditable$1(blockBoundary);
  21710. });
  21711. };
  21712. var read$1 = function (rootNode, forward, rng) {
  21713. return rng.collapsed ? readFromRange(rootNode, forward, rng) : Optional.none();
  21714. };
  21715. var getChildrenUntilBlockBoundary = function (block) {
  21716. var children$1 = children(block);
  21717. return findIndex$2(children$1, isBlock$2).fold(constant(children$1), function (index) {
  21718. return children$1.slice(0, index);
  21719. });
  21720. };
  21721. var extractChildren = function (block) {
  21722. var children = getChildrenUntilBlockBoundary(block);
  21723. each$k(children, remove$7);
  21724. return children;
  21725. };
  21726. var removeEmptyRoot = function (rootNode, block) {
  21727. var parents = parentsAndSelf(block, rootNode);
  21728. return find$3(parents.reverse(), function (element) {
  21729. return isEmpty$2(element);
  21730. }).each(remove$7);
  21731. };
  21732. var isEmptyBefore = function (el) {
  21733. return filter$4(prevSiblings(el), function (el) {
  21734. return !isEmpty$2(el);
  21735. }).length === 0;
  21736. };
  21737. var nestedBlockMerge = function (rootNode, fromBlock, toBlock, insertionPoint) {
  21738. if (isEmpty$2(toBlock)) {
  21739. fillWithPaddingBr(toBlock);
  21740. return firstPositionIn(toBlock.dom);
  21741. }
  21742. if (isEmptyBefore(insertionPoint) && isEmpty$2(fromBlock)) {
  21743. before$4(insertionPoint, SugarElement.fromTag('br'));
  21744. }
  21745. var position = prevPosition(toBlock.dom, CaretPosition.before(insertionPoint.dom));
  21746. each$k(extractChildren(fromBlock), function (child) {
  21747. before$4(insertionPoint, child);
  21748. });
  21749. removeEmptyRoot(rootNode, fromBlock);
  21750. return position;
  21751. };
  21752. var sidelongBlockMerge = function (rootNode, fromBlock, toBlock) {
  21753. if (isEmpty$2(toBlock)) {
  21754. remove$7(toBlock);
  21755. if (isEmpty$2(fromBlock)) {
  21756. fillWithPaddingBr(fromBlock);
  21757. }
  21758. return firstPositionIn(fromBlock.dom);
  21759. }
  21760. var position = lastPositionIn(toBlock.dom);
  21761. each$k(extractChildren(fromBlock), function (child) {
  21762. append$1(toBlock, child);
  21763. });
  21764. removeEmptyRoot(rootNode, fromBlock);
  21765. return position;
  21766. };
  21767. var findInsertionPoint = function (toBlock, block) {
  21768. var parentsAndSelf$1 = parentsAndSelf(block, toBlock);
  21769. return Optional.from(parentsAndSelf$1[parentsAndSelf$1.length - 1]);
  21770. };
  21771. var getInsertionPoint = function (fromBlock, toBlock) {
  21772. return contains$1(toBlock, fromBlock) ? findInsertionPoint(toBlock, fromBlock) : Optional.none();
  21773. };
  21774. var trimBr = function (first, block) {
  21775. positionIn(first, block.dom).map(function (position) {
  21776. return position.getNode();
  21777. }).map(SugarElement.fromDom).filter(isBr$4).each(remove$7);
  21778. };
  21779. var mergeBlockInto = function (rootNode, fromBlock, toBlock) {
  21780. trimBr(true, fromBlock);
  21781. trimBr(false, toBlock);
  21782. return getInsertionPoint(fromBlock, toBlock).fold(curry(sidelongBlockMerge, rootNode, fromBlock, toBlock), curry(nestedBlockMerge, rootNode, fromBlock, toBlock));
  21783. };
  21784. var mergeBlocks = function (rootNode, forward, block1, block2) {
  21785. return forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
  21786. };
  21787. var backspaceDelete$8 = function (editor, forward) {
  21788. var rootNode = SugarElement.fromDom(editor.getBody());
  21789. var position = read$1(rootNode.dom, forward, editor.selection.getRng()).bind(function (blockBoundary) {
  21790. return mergeBlocks(rootNode, forward, blockBoundary.from.block, blockBoundary.to.block);
  21791. });
  21792. position.each(function (pos) {
  21793. editor.selection.setRng(pos.toRange());
  21794. });
  21795. return position.isSome();
  21796. };
  21797. var deleteRangeMergeBlocks = function (rootNode, selection) {
  21798. var rng = selection.getRng();
  21799. return lift2(getParentBlock$1(rootNode, SugarElement.fromDom(rng.startContainer)), getParentBlock$1(rootNode, SugarElement.fromDom(rng.endContainer)), function (block1, block2) {
  21800. if (eq(block1, block2) === false) {
  21801. rng.deleteContents();
  21802. mergeBlocks(rootNode, true, block1, block2).each(function (pos) {
  21803. selection.setRng(pos.toRange());
  21804. });
  21805. return true;
  21806. } else {
  21807. return false;
  21808. }
  21809. }).getOr(false);
  21810. };
  21811. var isRawNodeInTable = function (root, rawNode) {
  21812. var node = SugarElement.fromDom(rawNode);
  21813. var isRoot = curry(eq, root);
  21814. return ancestor$3(node, isTableCell$4, isRoot).isSome();
  21815. };
  21816. var isSelectionInTable = function (root, rng) {
  21817. return isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
  21818. };
  21819. var isEverythingSelected = function (root, rng) {
  21820. var noPrevious = prevPosition(root.dom, CaretPosition.fromRangeStart(rng)).isNone();
  21821. var noNext = nextPosition(root.dom, CaretPosition.fromRangeEnd(rng)).isNone();
  21822. return !isSelectionInTable(root, rng) && noPrevious && noNext;
  21823. };
  21824. var emptyEditor = function (editor) {
  21825. editor.setContent('');
  21826. editor.selection.setCursorLocation();
  21827. return true;
  21828. };
  21829. var deleteRange$1 = function (editor) {
  21830. var rootNode = SugarElement.fromDom(editor.getBody());
  21831. var rng = editor.selection.getRng();
  21832. return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
  21833. };
  21834. var backspaceDelete$7 = function (editor, _forward) {
  21835. return editor.selection.isCollapsed() ? false : deleteRange$1(editor);
  21836. };
  21837. var isContentEditableTrue$2 = isContentEditableTrue$4;
  21838. var isContentEditableFalse$4 = isContentEditableFalse$b;
  21839. var showCaret = function (direction, editor, node, before, scrollIntoView) {
  21840. return Optional.from(editor._selectionOverrides.showCaret(direction, node, before, scrollIntoView));
  21841. };
  21842. var getNodeRange = function (node) {
  21843. var rng = node.ownerDocument.createRange();
  21844. rng.selectNode(node);
  21845. return rng;
  21846. };
  21847. var selectNode = function (editor, node) {
  21848. var e = editor.fire('BeforeObjectSelected', { target: node });
  21849. if (e.isDefaultPrevented()) {
  21850. return Optional.none();
  21851. }
  21852. return Optional.some(getNodeRange(node));
  21853. };
  21854. var renderCaretAtRange = function (editor, range, scrollIntoView) {
  21855. var normalizedRange = normalizeRange(1, editor.getBody(), range);
  21856. var caretPosition = CaretPosition.fromRangeStart(normalizedRange);
  21857. var caretPositionNode = caretPosition.getNode();
  21858. if (isInlineFakeCaretTarget(caretPositionNode)) {
  21859. return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
  21860. }
  21861. var caretPositionBeforeNode = caretPosition.getNode(true);
  21862. if (isInlineFakeCaretTarget(caretPositionBeforeNode)) {
  21863. return showCaret(1, editor, caretPositionBeforeNode, false, false);
  21864. }
  21865. var ceRoot = editor.dom.getParent(caretPosition.getNode(), function (node) {
  21866. return isContentEditableFalse$4(node) || isContentEditableTrue$2(node);
  21867. });
  21868. if (isInlineFakeCaretTarget(ceRoot)) {
  21869. return showCaret(1, editor, ceRoot, false, scrollIntoView);
  21870. }
  21871. return Optional.none();
  21872. };
  21873. var renderRangeCaret = function (editor, range, scrollIntoView) {
  21874. return range.collapsed ? renderCaretAtRange(editor, range, scrollIntoView).getOr(range) : range;
  21875. };
  21876. var isBeforeBoundary = function (pos) {
  21877. return isBeforeContentEditableFalse(pos) || isBeforeMedia(pos);
  21878. };
  21879. var isAfterBoundary = function (pos) {
  21880. return isAfterContentEditableFalse(pos) || isAfterMedia(pos);
  21881. };
  21882. var trimEmptyTextNode = function (dom, node) {
  21883. if (isText$7(node) && node.data.length === 0) {
  21884. dom.remove(node);
  21885. }
  21886. };
  21887. var deleteContentAndShowCaret = function (editor, range, node, direction, forward, peekCaretPosition) {
  21888. showCaret(direction, editor, peekCaretPosition.getNode(!forward), forward, true).each(function (caretRange) {
  21889. if (range.collapsed) {
  21890. var deleteRange = range.cloneRange();
  21891. if (forward) {
  21892. deleteRange.setEnd(caretRange.startContainer, caretRange.startOffset);
  21893. } else {
  21894. deleteRange.setStart(caretRange.endContainer, caretRange.endOffset);
  21895. }
  21896. deleteRange.deleteContents();
  21897. } else {
  21898. range.deleteContents();
  21899. }
  21900. editor.selection.setRng(caretRange);
  21901. });
  21902. trimEmptyTextNode(editor.dom, node);
  21903. return true;
  21904. };
  21905. var deleteBoundaryText = function (editor, forward) {
  21906. var range = editor.selection.getRng();
  21907. if (!isText$7(range.commonAncestorContainer)) {
  21908. return false;
  21909. }
  21910. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  21911. var caretWalker = CaretWalker(editor.getBody());
  21912. var getNextPosFn = curry(getVisualCaretPosition, forward ? caretWalker.next : caretWalker.prev);
  21913. var isBeforeFn = forward ? isBeforeBoundary : isAfterBoundary;
  21914. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  21915. var nextCaretPosition = normalizePosition(forward, getNextPosFn(caretPosition));
  21916. if (!nextCaretPosition || !isMoveInsideSameBlock(caretPosition, nextCaretPosition)) {
  21917. return false;
  21918. } else if (isBeforeFn(nextCaretPosition)) {
  21919. return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, nextCaretPosition);
  21920. }
  21921. var peekCaretPosition = getNextPosFn(nextCaretPosition);
  21922. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  21923. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  21924. return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, peekCaretPosition);
  21925. }
  21926. }
  21927. return false;
  21928. };
  21929. var backspaceDelete$6 = function (editor, forward) {
  21930. return deleteBoundaryText(editor, forward);
  21931. };
  21932. var isCompoundElement = function (node) {
  21933. return isTableCell$4(SugarElement.fromDom(node)) || isListItem(SugarElement.fromDom(node));
  21934. };
  21935. var DeleteAction = Adt.generate([
  21936. { remove: ['element'] },
  21937. { moveToElement: ['element'] },
  21938. { moveToPosition: ['position'] }
  21939. ]);
  21940. var isAtContentEditableBlockCaret = function (forward, from) {
  21941. var elm = from.getNode(forward === false);
  21942. var caretLocation = forward ? 'after' : 'before';
  21943. return isElement$5(elm) && elm.getAttribute('data-mce-caret') === caretLocation;
  21944. };
  21945. var isDeleteFromCefDifferentBlocks = function (root, forward, from, to) {
  21946. var inSameBlock = function (elm) {
  21947. return isInline$1(SugarElement.fromDom(elm)) && !isInSameBlock(from, to, root);
  21948. };
  21949. return getRelativeCefElm(!forward, from).fold(function () {
  21950. return getRelativeCefElm(forward, to).fold(never, inSameBlock);
  21951. }, inSameBlock);
  21952. };
  21953. var deleteEmptyBlockOrMoveToCef = function (root, forward, from, to) {
  21954. var toCefElm = to.getNode(forward === false);
  21955. return getParentBlock$1(SugarElement.fromDom(root), SugarElement.fromDom(from.getNode())).map(function (blockElm) {
  21956. return isEmpty$2(blockElm) ? DeleteAction.remove(blockElm.dom) : DeleteAction.moveToElement(toCefElm);
  21957. }).orThunk(function () {
  21958. return Optional.some(DeleteAction.moveToElement(toCefElm));
  21959. });
  21960. };
  21961. var findCefPosition = function (root, forward, from) {
  21962. return fromPosition(forward, root, from).bind(function (to) {
  21963. if (isCompoundElement(to.getNode())) {
  21964. return Optional.none();
  21965. } else if (isDeleteFromCefDifferentBlocks(root, forward, from, to)) {
  21966. return Optional.none();
  21967. } else if (forward && isContentEditableFalse$b(to.getNode())) {
  21968. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  21969. } else if (forward === false && isContentEditableFalse$b(to.getNode(true))) {
  21970. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  21971. } else if (forward && isAfterContentEditableFalse(from)) {
  21972. return Optional.some(DeleteAction.moveToPosition(to));
  21973. } else if (forward === false && isBeforeContentEditableFalse(from)) {
  21974. return Optional.some(DeleteAction.moveToPosition(to));
  21975. } else {
  21976. return Optional.none();
  21977. }
  21978. });
  21979. };
  21980. var getContentEditableBlockAction = function (forward, elm) {
  21981. if (forward && isContentEditableFalse$b(elm.nextSibling)) {
  21982. return Optional.some(DeleteAction.moveToElement(elm.nextSibling));
  21983. } else if (forward === false && isContentEditableFalse$b(elm.previousSibling)) {
  21984. return Optional.some(DeleteAction.moveToElement(elm.previousSibling));
  21985. } else {
  21986. return Optional.none();
  21987. }
  21988. };
  21989. var skipMoveToActionFromInlineCefToContent = function (root, from, deleteAction) {
  21990. return deleteAction.fold(function (elm) {
  21991. return Optional.some(DeleteAction.remove(elm));
  21992. }, function (elm) {
  21993. return Optional.some(DeleteAction.moveToElement(elm));
  21994. }, function (to) {
  21995. if (isInSameBlock(from, to, root)) {
  21996. return Optional.none();
  21997. } else {
  21998. return Optional.some(DeleteAction.moveToPosition(to));
  21999. }
  22000. });
  22001. };
  22002. var getContentEditableAction = function (root, forward, from) {
  22003. if (isAtContentEditableBlockCaret(forward, from)) {
  22004. return getContentEditableBlockAction(forward, from.getNode(forward === false)).fold(function () {
  22005. return findCefPosition(root, forward, from);
  22006. }, Optional.some);
  22007. } else {
  22008. return findCefPosition(root, forward, from).bind(function (deleteAction) {
  22009. return skipMoveToActionFromInlineCefToContent(root, from, deleteAction);
  22010. });
  22011. }
  22012. };
  22013. var read = function (root, forward, rng) {
  22014. var normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
  22015. var from = CaretPosition.fromRangeStart(normalizedRange);
  22016. var rootElement = SugarElement.fromDom(root);
  22017. if (forward === false && isAfterContentEditableFalse(from)) {
  22018. return Optional.some(DeleteAction.remove(from.getNode(true)));
  22019. } else if (forward && isBeforeContentEditableFalse(from)) {
  22020. return Optional.some(DeleteAction.remove(from.getNode()));
  22021. } else if (forward === false && isBeforeContentEditableFalse(from) && isAfterBr(rootElement, from)) {
  22022. return findPreviousBr(rootElement, from).map(function (br) {
  22023. return DeleteAction.remove(br.getNode());
  22024. });
  22025. } else if (forward && isAfterContentEditableFalse(from) && isBeforeBr$1(rootElement, from)) {
  22026. return findNextBr(rootElement, from).map(function (br) {
  22027. return DeleteAction.remove(br.getNode());
  22028. });
  22029. } else {
  22030. return getContentEditableAction(root, forward, from);
  22031. }
  22032. };
  22033. var deleteElement$1 = function (editor, forward) {
  22034. return function (element) {
  22035. editor._selectionOverrides.hideFakeCaret();
  22036. deleteElement$2(editor, forward, SugarElement.fromDom(element));
  22037. return true;
  22038. };
  22039. };
  22040. var moveToElement = function (editor, forward) {
  22041. return function (element) {
  22042. var pos = forward ? CaretPosition.before(element) : CaretPosition.after(element);
  22043. editor.selection.setRng(pos.toRange());
  22044. return true;
  22045. };
  22046. };
  22047. var moveToPosition = function (editor) {
  22048. return function (pos) {
  22049. editor.selection.setRng(pos.toRange());
  22050. return true;
  22051. };
  22052. };
  22053. var getAncestorCe = function (editor, node) {
  22054. return Optional.from(getContentEditableRoot$1(editor.getBody(), node));
  22055. };
  22056. var backspaceDeleteCaret = function (editor, forward) {
  22057. var selectedNode = editor.selection.getNode();
  22058. return getAncestorCe(editor, selectedNode).filter(isContentEditableFalse$b).fold(function () {
  22059. return read(editor.getBody(), forward, editor.selection.getRng()).exists(function (deleteAction) {
  22060. return deleteAction.fold(deleteElement$1(editor, forward), moveToElement(editor, forward), moveToPosition(editor));
  22061. });
  22062. }, always);
  22063. };
  22064. var deleteOffscreenSelection = function (rootElement) {
  22065. each$k(descendants(rootElement, '.mce-offscreen-selection'), remove$7);
  22066. };
  22067. var backspaceDeleteRange = function (editor, forward) {
  22068. var selectedNode = editor.selection.getNode();
  22069. if (isContentEditableFalse$b(selectedNode) && !isTableCell$5(selectedNode)) {
  22070. var hasCefAncestor = getAncestorCe(editor, selectedNode.parentNode).filter(isContentEditableFalse$b);
  22071. return hasCefAncestor.fold(function () {
  22072. deleteOffscreenSelection(SugarElement.fromDom(editor.getBody()));
  22073. deleteElement$2(editor, forward, SugarElement.fromDom(editor.selection.getNode()));
  22074. paddEmptyBody(editor);
  22075. return true;
  22076. }, always);
  22077. }
  22078. return false;
  22079. };
  22080. var paddEmptyElement = function (editor) {
  22081. var dom = editor.dom, selection = editor.selection;
  22082. var ceRoot = getContentEditableRoot$1(editor.getBody(), selection.getNode());
  22083. if (isContentEditableTrue$4(ceRoot) && dom.isBlock(ceRoot) && dom.isEmpty(ceRoot)) {
  22084. var br = dom.create('br', { 'data-mce-bogus': '1' });
  22085. dom.setHTML(ceRoot, '');
  22086. ceRoot.appendChild(br);
  22087. selection.setRng(CaretPosition.before(br).toRange());
  22088. }
  22089. return true;
  22090. };
  22091. var backspaceDelete$5 = function (editor, forward) {
  22092. if (editor.selection.isCollapsed()) {
  22093. return backspaceDeleteCaret(editor, forward);
  22094. } else {
  22095. return backspaceDeleteRange(editor, forward);
  22096. }
  22097. };
  22098. var deleteCaret$2 = function (editor, forward) {
  22099. var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22100. return fromPosition(forward, editor.getBody(), fromPos).filter(function (pos) {
  22101. return forward ? isBeforeImageBlock(pos) : isAfterImageBlock(pos);
  22102. }).bind(function (pos) {
  22103. return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, pos));
  22104. }).exists(function (elm) {
  22105. editor.selection.select(elm);
  22106. return true;
  22107. });
  22108. };
  22109. var backspaceDelete$4 = function (editor, forward) {
  22110. return editor.selection.isCollapsed() ? deleteCaret$2(editor, forward) : false;
  22111. };
  22112. var isText = isText$7;
  22113. var startsWithCaretContainer = function (node) {
  22114. return isText(node) && node.data[0] === ZWSP$1;
  22115. };
  22116. var endsWithCaretContainer = function (node) {
  22117. return isText(node) && node.data[node.data.length - 1] === ZWSP$1;
  22118. };
  22119. var createZwsp = function (node) {
  22120. return node.ownerDocument.createTextNode(ZWSP$1);
  22121. };
  22122. var insertBefore = function (node) {
  22123. if (isText(node.previousSibling)) {
  22124. if (endsWithCaretContainer(node.previousSibling)) {
  22125. return node.previousSibling;
  22126. } else {
  22127. node.previousSibling.appendData(ZWSP$1);
  22128. return node.previousSibling;
  22129. }
  22130. } else if (isText(node)) {
  22131. if (startsWithCaretContainer(node)) {
  22132. return node;
  22133. } else {
  22134. node.insertData(0, ZWSP$1);
  22135. return node;
  22136. }
  22137. } else {
  22138. var newNode = createZwsp(node);
  22139. node.parentNode.insertBefore(newNode, node);
  22140. return newNode;
  22141. }
  22142. };
  22143. var insertAfter = function (node) {
  22144. if (isText(node.nextSibling)) {
  22145. if (startsWithCaretContainer(node.nextSibling)) {
  22146. return node.nextSibling;
  22147. } else {
  22148. node.nextSibling.insertData(0, ZWSP$1);
  22149. return node.nextSibling;
  22150. }
  22151. } else if (isText(node)) {
  22152. if (endsWithCaretContainer(node)) {
  22153. return node;
  22154. } else {
  22155. node.appendData(ZWSP$1);
  22156. return node;
  22157. }
  22158. } else {
  22159. var newNode = createZwsp(node);
  22160. if (node.nextSibling) {
  22161. node.parentNode.insertBefore(newNode, node.nextSibling);
  22162. } else {
  22163. node.parentNode.appendChild(newNode);
  22164. }
  22165. return newNode;
  22166. }
  22167. };
  22168. var insertInline = function (before, node) {
  22169. return before ? insertBefore(node) : insertAfter(node);
  22170. };
  22171. var insertInlineBefore = curry(insertInline, true);
  22172. var insertInlineAfter = curry(insertInline, false);
  22173. var insertInlinePos = function (pos, before) {
  22174. if (isText$7(pos.container())) {
  22175. return insertInline(before, pos.container());
  22176. } else {
  22177. return insertInline(before, pos.getNode());
  22178. }
  22179. };
  22180. var isPosCaretContainer = function (pos, caret) {
  22181. var caretNode = caret.get();
  22182. return caretNode && pos.container() === caretNode && isCaretContainerInline(caretNode);
  22183. };
  22184. var renderCaret = function (caret, location) {
  22185. return location.fold(function (element) {
  22186. remove$2(caret.get());
  22187. var text = insertInlineBefore(element);
  22188. caret.set(text);
  22189. return Optional.some(CaretPosition(text, text.length - 1));
  22190. }, function (element) {
  22191. return firstPositionIn(element).map(function (pos) {
  22192. if (!isPosCaretContainer(pos, caret)) {
  22193. remove$2(caret.get());
  22194. var text = insertInlinePos(pos, true);
  22195. caret.set(text);
  22196. return CaretPosition(text, 1);
  22197. } else {
  22198. return CaretPosition(caret.get(), 1);
  22199. }
  22200. });
  22201. }, function (element) {
  22202. return lastPositionIn(element).map(function (pos) {
  22203. if (!isPosCaretContainer(pos, caret)) {
  22204. remove$2(caret.get());
  22205. var text = insertInlinePos(pos, false);
  22206. caret.set(text);
  22207. return CaretPosition(text, text.length - 1);
  22208. } else {
  22209. return CaretPosition(caret.get(), caret.get().length - 1);
  22210. }
  22211. });
  22212. }, function (element) {
  22213. remove$2(caret.get());
  22214. var text = insertInlineAfter(element);
  22215. caret.set(text);
  22216. return Optional.some(CaretPosition(text, 1));
  22217. });
  22218. };
  22219. var evaluateUntil = function (fns, args) {
  22220. for (var i = 0; i < fns.length; i++) {
  22221. var result = fns[i].apply(null, args);
  22222. if (result.isSome()) {
  22223. return result;
  22224. }
  22225. }
  22226. return Optional.none();
  22227. };
  22228. var Location = Adt.generate([
  22229. { before: ['element'] },
  22230. { start: ['element'] },
  22231. { end: ['element'] },
  22232. { after: ['element'] }
  22233. ]);
  22234. var rescope$1 = function (rootNode, node) {
  22235. var parentBlock = getParentBlock$2(node, rootNode);
  22236. return parentBlock ? parentBlock : rootNode;
  22237. };
  22238. var before = function (isInlineTarget, rootNode, pos) {
  22239. var nPos = normalizeForwards(pos);
  22240. var scope = rescope$1(rootNode, nPos.container());
  22241. return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  22242. return nextPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  22243. return Location.before(inline);
  22244. });
  22245. }, Optional.none);
  22246. };
  22247. var isNotInsideFormatCaretContainer = function (rootNode, elm) {
  22248. return getParentCaretContainer(rootNode, elm) === null;
  22249. };
  22250. var findInsideRootInline = function (isInlineTarget, rootNode, pos) {
  22251. return findRootInline(isInlineTarget, rootNode, pos).filter(curry(isNotInsideFormatCaretContainer, rootNode));
  22252. };
  22253. var start$1 = function (isInlineTarget, rootNode, pos) {
  22254. var nPos = normalizeBackwards(pos);
  22255. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  22256. var prevPos = prevPosition(inline, nPos);
  22257. return prevPos.isNone() ? Optional.some(Location.start(inline)) : Optional.none();
  22258. });
  22259. };
  22260. var end = function (isInlineTarget, rootNode, pos) {
  22261. var nPos = normalizeForwards(pos);
  22262. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  22263. var nextPos = nextPosition(inline, nPos);
  22264. return nextPos.isNone() ? Optional.some(Location.end(inline)) : Optional.none();
  22265. });
  22266. };
  22267. var after = function (isInlineTarget, rootNode, pos) {
  22268. var nPos = normalizeBackwards(pos);
  22269. var scope = rescope$1(rootNode, nPos.container());
  22270. return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  22271. return prevPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  22272. return Location.after(inline);
  22273. });
  22274. }, Optional.none);
  22275. };
  22276. var isValidLocation = function (location) {
  22277. return isRtl(getElement(location)) === false;
  22278. };
  22279. var readLocation = function (isInlineTarget, rootNode, pos) {
  22280. var location = evaluateUntil([
  22281. before,
  22282. start$1,
  22283. end,
  22284. after
  22285. ], [
  22286. isInlineTarget,
  22287. rootNode,
  22288. pos
  22289. ]);
  22290. return location.filter(isValidLocation);
  22291. };
  22292. var getElement = function (location) {
  22293. return location.fold(identity, identity, identity, identity);
  22294. };
  22295. var getName = function (location) {
  22296. return location.fold(constant('before'), constant('start'), constant('end'), constant('after'));
  22297. };
  22298. var outside = function (location) {
  22299. return location.fold(Location.before, Location.before, Location.after, Location.after);
  22300. };
  22301. var inside = function (location) {
  22302. return location.fold(Location.start, Location.start, Location.end, Location.end);
  22303. };
  22304. var isEq = function (location1, location2) {
  22305. return getName(location1) === getName(location2) && getElement(location1) === getElement(location2);
  22306. };
  22307. var betweenInlines = function (forward, isInlineTarget, rootNode, from, to, location) {
  22308. return lift2(findRootInline(isInlineTarget, rootNode, from), findRootInline(isInlineTarget, rootNode, to), function (fromInline, toInline) {
  22309. if (fromInline !== toInline && hasSameParentBlock(rootNode, fromInline, toInline)) {
  22310. return Location.after(forward ? fromInline : toInline);
  22311. } else {
  22312. return location;
  22313. }
  22314. }).getOr(location);
  22315. };
  22316. var skipNoMovement = function (fromLocation, toLocation) {
  22317. return fromLocation.fold(always, function (fromLocation) {
  22318. return !isEq(fromLocation, toLocation);
  22319. });
  22320. };
  22321. var findLocationTraverse = function (forward, isInlineTarget, rootNode, fromLocation, pos) {
  22322. var from = normalizePosition(forward, pos);
  22323. var to = fromPosition(forward, rootNode, from).map(curry(normalizePosition, forward));
  22324. var location = to.fold(function () {
  22325. return fromLocation.map(outside);
  22326. }, function (to) {
  22327. return readLocation(isInlineTarget, rootNode, to).map(curry(betweenInlines, forward, isInlineTarget, rootNode, from, to)).filter(curry(skipNoMovement, fromLocation));
  22328. });
  22329. return location.filter(isValidLocation);
  22330. };
  22331. var findLocationSimple = function (forward, location) {
  22332. if (forward) {
  22333. return location.fold(compose(Optional.some, Location.start), Optional.none, compose(Optional.some, Location.after), Optional.none);
  22334. } else {
  22335. return location.fold(Optional.none, compose(Optional.some, Location.before), Optional.none, compose(Optional.some, Location.end));
  22336. }
  22337. };
  22338. var findLocation$1 = function (forward, isInlineTarget, rootNode, pos) {
  22339. var from = normalizePosition(forward, pos);
  22340. var fromLocation = readLocation(isInlineTarget, rootNode, from);
  22341. return readLocation(isInlineTarget, rootNode, from).bind(curry(findLocationSimple, forward)).orThunk(function () {
  22342. return findLocationTraverse(forward, isInlineTarget, rootNode, fromLocation, pos);
  22343. });
  22344. };
  22345. curry(findLocation$1, false);
  22346. curry(findLocation$1, true);
  22347. var hasSelectionModifyApi = function (editor) {
  22348. return isFunction(editor.selection.getSel().modify);
  22349. };
  22350. var moveRel = function (forward, selection, pos) {
  22351. var delta = forward ? 1 : -1;
  22352. selection.setRng(CaretPosition(pos.container(), pos.offset() + delta).toRange());
  22353. selection.getSel().modify('move', forward ? 'forward' : 'backward', 'word');
  22354. return true;
  22355. };
  22356. var moveByWord = function (forward, editor) {
  22357. var rng = editor.selection.getRng();
  22358. var pos = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  22359. if (!hasSelectionModifyApi(editor)) {
  22360. return false;
  22361. } else if (forward && isBeforeInline(pos)) {
  22362. return moveRel(true, editor.selection, pos);
  22363. } else if (!forward && isAfterInline(pos)) {
  22364. return moveRel(false, editor.selection, pos);
  22365. } else {
  22366. return false;
  22367. }
  22368. };
  22369. var BreakType;
  22370. (function (BreakType) {
  22371. BreakType[BreakType['Br'] = 0] = 'Br';
  22372. BreakType[BreakType['Block'] = 1] = 'Block';
  22373. BreakType[BreakType['Wrap'] = 2] = 'Wrap';
  22374. BreakType[BreakType['Eol'] = 3] = 'Eol';
  22375. }(BreakType || (BreakType = {})));
  22376. var flip = function (direction, positions) {
  22377. return direction === HDirection.Backwards ? reverse(positions) : positions;
  22378. };
  22379. var walk = function (direction, caretWalker, pos) {
  22380. return direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
  22381. };
  22382. var getBreakType = function (scope, direction, currentPos, nextPos) {
  22383. if (isBr$5(nextPos.getNode(direction === HDirection.Forwards))) {
  22384. return BreakType.Br;
  22385. } else if (isInSameBlock(currentPos, nextPos) === false) {
  22386. return BreakType.Block;
  22387. } else {
  22388. return BreakType.Wrap;
  22389. }
  22390. };
  22391. var getPositionsUntil = function (predicate, direction, scope, start) {
  22392. var caretWalker = CaretWalker(scope);
  22393. var currentPos = start;
  22394. var positions = [];
  22395. while (currentPos) {
  22396. var nextPos = walk(direction, caretWalker, currentPos);
  22397. if (!nextPos) {
  22398. break;
  22399. }
  22400. if (isBr$5(nextPos.getNode(false))) {
  22401. if (direction === HDirection.Forwards) {
  22402. return {
  22403. positions: flip(direction, positions).concat([nextPos]),
  22404. breakType: BreakType.Br,
  22405. breakAt: Optional.some(nextPos)
  22406. };
  22407. } else {
  22408. return {
  22409. positions: flip(direction, positions),
  22410. breakType: BreakType.Br,
  22411. breakAt: Optional.some(nextPos)
  22412. };
  22413. }
  22414. }
  22415. if (!nextPos.isVisible()) {
  22416. currentPos = nextPos;
  22417. continue;
  22418. }
  22419. if (predicate(currentPos, nextPos)) {
  22420. var breakType = getBreakType(scope, direction, currentPos, nextPos);
  22421. return {
  22422. positions: flip(direction, positions),
  22423. breakType: breakType,
  22424. breakAt: Optional.some(nextPos)
  22425. };
  22426. }
  22427. positions.push(nextPos);
  22428. currentPos = nextPos;
  22429. }
  22430. return {
  22431. positions: flip(direction, positions),
  22432. breakType: BreakType.Eol,
  22433. breakAt: Optional.none()
  22434. };
  22435. };
  22436. var getAdjacentLinePositions = function (direction, getPositionsUntilBreak, scope, start) {
  22437. return getPositionsUntilBreak(scope, start).breakAt.map(function (pos) {
  22438. var positions = getPositionsUntilBreak(scope, pos).positions;
  22439. return direction === HDirection.Backwards ? positions.concat(pos) : [pos].concat(positions);
  22440. }).getOr([]);
  22441. };
  22442. var findClosestHorizontalPositionFromPoint = function (positions, x) {
  22443. return foldl(positions, function (acc, newPos) {
  22444. return acc.fold(function () {
  22445. return Optional.some(newPos);
  22446. }, function (lastPos) {
  22447. return lift2(head(lastPos.getClientRects()), head(newPos.getClientRects()), function (lastRect, newRect) {
  22448. var lastDist = Math.abs(x - lastRect.left);
  22449. var newDist = Math.abs(x - newRect.left);
  22450. return newDist <= lastDist ? newPos : lastPos;
  22451. }).or(acc);
  22452. });
  22453. }, Optional.none());
  22454. };
  22455. var findClosestHorizontalPosition = function (positions, pos) {
  22456. return head(pos.getClientRects()).bind(function (targetRect) {
  22457. return findClosestHorizontalPositionFromPoint(positions, targetRect.left);
  22458. });
  22459. };
  22460. var getPositionsUntilPreviousLine = curry(getPositionsUntil, CaretPosition.isAbove, -1);
  22461. var getPositionsUntilNextLine = curry(getPositionsUntil, CaretPosition.isBelow, 1);
  22462. var getPositionsAbove = curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
  22463. var getPositionsBelow = curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
  22464. var isAtFirstLine = function (scope, pos) {
  22465. return getPositionsUntilPreviousLine(scope, pos).breakAt.isNone();
  22466. };
  22467. var isAtLastLine = function (scope, pos) {
  22468. return getPositionsUntilNextLine(scope, pos).breakAt.isNone();
  22469. };
  22470. var getFirstLinePositions = function (scope) {
  22471. return firstPositionIn(scope).map(function (pos) {
  22472. return [pos].concat(getPositionsUntilNextLine(scope, pos).positions);
  22473. }).getOr([]);
  22474. };
  22475. var getLastLinePositions = function (scope) {
  22476. return lastPositionIn(scope).map(function (pos) {
  22477. return getPositionsUntilPreviousLine(scope, pos).positions.concat(pos);
  22478. }).getOr([]);
  22479. };
  22480. var getNodeClientRects = function (node) {
  22481. var toArrayWithNode = function (clientRects) {
  22482. return map$3(clientRects, function (rect) {
  22483. var clientRect = clone(rect);
  22484. clientRect.node = node;
  22485. return clientRect;
  22486. });
  22487. };
  22488. if (isElement$5(node)) {
  22489. return toArrayWithNode(node.getClientRects());
  22490. }
  22491. if (isText$7(node)) {
  22492. var rng = node.ownerDocument.createRange();
  22493. rng.setStart(node, 0);
  22494. rng.setEnd(node, node.data.length);
  22495. return toArrayWithNode(rng.getClientRects());
  22496. }
  22497. };
  22498. var getClientRects = function (nodes) {
  22499. return bind(nodes, getNodeClientRects);
  22500. };
  22501. var VDirection;
  22502. (function (VDirection) {
  22503. VDirection[VDirection['Up'] = -1] = 'Up';
  22504. VDirection[VDirection['Down'] = 1] = 'Down';
  22505. }(VDirection || (VDirection = {})));
  22506. var findUntil = function (direction, root, predicateFn, node) {
  22507. while (node = findNode$1(node, direction, isEditableCaretCandidate$1, root)) {
  22508. if (predicateFn(node)) {
  22509. return;
  22510. }
  22511. }
  22512. };
  22513. var walkUntil$1 = function (direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) {
  22514. var line = 0;
  22515. var result = [];
  22516. var add = function (node) {
  22517. var clientRects = getClientRects([node]);
  22518. if (direction === -1) {
  22519. clientRects = clientRects.reverse();
  22520. }
  22521. for (var i = 0; i < clientRects.length; i++) {
  22522. var clientRect = clientRects[i];
  22523. if (isBeflowFn(clientRect, targetClientRect)) {
  22524. continue;
  22525. }
  22526. if (result.length > 0 && isAboveFn(clientRect, last$1(result))) {
  22527. line++;
  22528. }
  22529. clientRect.line = line;
  22530. if (predicateFn(clientRect)) {
  22531. return true;
  22532. }
  22533. result.push(clientRect);
  22534. }
  22535. };
  22536. var targetClientRect = last$1(caretPosition.getClientRects());
  22537. if (!targetClientRect) {
  22538. return result;
  22539. }
  22540. var node = caretPosition.getNode();
  22541. add(node);
  22542. findUntil(direction, root, add, node);
  22543. return result;
  22544. };
  22545. var aboveLineNumber = function (lineNumber, clientRect) {
  22546. return clientRect.line > lineNumber;
  22547. };
  22548. var isLineNumber = function (lineNumber, clientRect) {
  22549. return clientRect.line === lineNumber;
  22550. };
  22551. var upUntil = curry(walkUntil$1, VDirection.Up, isAbove$1, isBelow$1);
  22552. var downUntil = curry(walkUntil$1, VDirection.Down, isBelow$1, isAbove$1);
  22553. var positionsUntil = function (direction, root, predicateFn, node) {
  22554. var caretWalker = CaretWalker(root);
  22555. var walkFn;
  22556. var isBelowFn;
  22557. var isAboveFn;
  22558. var caretPosition;
  22559. var result = [];
  22560. var line = 0;
  22561. var getClientRect = function (caretPosition) {
  22562. if (direction === 1) {
  22563. return last$1(caretPosition.getClientRects());
  22564. }
  22565. return last$1(caretPosition.getClientRects());
  22566. };
  22567. if (direction === 1) {
  22568. walkFn = caretWalker.next;
  22569. isBelowFn = isBelow$1;
  22570. isAboveFn = isAbove$1;
  22571. caretPosition = CaretPosition.after(node);
  22572. } else {
  22573. walkFn = caretWalker.prev;
  22574. isBelowFn = isAbove$1;
  22575. isAboveFn = isBelow$1;
  22576. caretPosition = CaretPosition.before(node);
  22577. }
  22578. var targetClientRect = getClientRect(caretPosition);
  22579. do {
  22580. if (!caretPosition.isVisible()) {
  22581. continue;
  22582. }
  22583. var rect = getClientRect(caretPosition);
  22584. if (isAboveFn(rect, targetClientRect)) {
  22585. continue;
  22586. }
  22587. if (result.length > 0 && isBelowFn(rect, last$1(result))) {
  22588. line++;
  22589. }
  22590. var clientRect = clone(rect);
  22591. clientRect.position = caretPosition;
  22592. clientRect.line = line;
  22593. if (predicateFn(clientRect)) {
  22594. return result;
  22595. }
  22596. result.push(clientRect);
  22597. } while (caretPosition = walkFn(caretPosition));
  22598. return result;
  22599. };
  22600. var isAboveLine = function (lineNumber) {
  22601. return function (clientRect) {
  22602. return aboveLineNumber(lineNumber, clientRect);
  22603. };
  22604. };
  22605. var isLine = function (lineNumber) {
  22606. return function (clientRect) {
  22607. return isLineNumber(lineNumber, clientRect);
  22608. };
  22609. };
  22610. var isContentEditableFalse$3 = isContentEditableFalse$b;
  22611. var findNode = findNode$1;
  22612. var distanceToRectLeft = function (clientRect, clientX) {
  22613. return Math.abs(clientRect.left - clientX);
  22614. };
  22615. var distanceToRectRight = function (clientRect, clientX) {
  22616. return Math.abs(clientRect.right - clientX);
  22617. };
  22618. var isInsideX = function (clientX, clientRect) {
  22619. return clientX >= clientRect.left && clientX <= clientRect.right;
  22620. };
  22621. var isInsideY = function (clientY, clientRect) {
  22622. return clientY >= clientRect.top && clientY <= clientRect.bottom;
  22623. };
  22624. var isNodeClientRect = function (rect) {
  22625. return hasNonNullableKey(rect, 'node');
  22626. };
  22627. var findClosestClientRect = function (clientRects, clientX, allowInside) {
  22628. if (allowInside === void 0) {
  22629. allowInside = always;
  22630. }
  22631. return reduce(clientRects, function (oldClientRect, clientRect) {
  22632. if (isInsideX(clientX, clientRect)) {
  22633. return allowInside(clientRect) ? clientRect : oldClientRect;
  22634. }
  22635. if (isInsideX(clientX, oldClientRect)) {
  22636. return allowInside(oldClientRect) ? oldClientRect : clientRect;
  22637. }
  22638. var oldDistance = Math.min(distanceToRectLeft(oldClientRect, clientX), distanceToRectRight(oldClientRect, clientX));
  22639. var newDistance = Math.min(distanceToRectLeft(clientRect, clientX), distanceToRectRight(clientRect, clientX));
  22640. if (newDistance === oldDistance && isNodeClientRect(clientRect) && isContentEditableFalse$3(clientRect.node)) {
  22641. return clientRect;
  22642. }
  22643. if (newDistance < oldDistance) {
  22644. return clientRect;
  22645. }
  22646. return oldClientRect;
  22647. });
  22648. };
  22649. var walkUntil = function (direction, root, predicateFn, startNode, includeChildren) {
  22650. var node = findNode(startNode, direction, isEditableCaretCandidate$1, root, !includeChildren);
  22651. do {
  22652. if (!node || predicateFn(node)) {
  22653. return;
  22654. }
  22655. } while (node = findNode(node, direction, isEditableCaretCandidate$1, root));
  22656. };
  22657. var findLineNodeRects = function (root, targetNodeRect, includeChildren) {
  22658. if (includeChildren === void 0) {
  22659. includeChildren = true;
  22660. }
  22661. var clientRects = [];
  22662. var collect = function (checkPosFn, node) {
  22663. var lineRects = filter$4(getClientRects([node]), function (clientRect) {
  22664. return !checkPosFn(clientRect, targetNodeRect);
  22665. });
  22666. clientRects = clientRects.concat(lineRects);
  22667. return lineRects.length === 0;
  22668. };
  22669. clientRects.push(targetNodeRect);
  22670. walkUntil(VDirection.Up, root, curry(collect, isAbove$1), targetNodeRect.node, includeChildren);
  22671. walkUntil(VDirection.Down, root, curry(collect, isBelow$1), targetNodeRect.node, includeChildren);
  22672. return clientRects;
  22673. };
  22674. var getFakeCaretTargets = function (root) {
  22675. return filter$4(from(root.getElementsByTagName('*')), isFakeCaretTarget);
  22676. };
  22677. var caretInfo = function (clientRect, clientX) {
  22678. return {
  22679. node: clientRect.node,
  22680. before: distanceToRectLeft(clientRect, clientX) < distanceToRectRight(clientRect, clientX)
  22681. };
  22682. };
  22683. var closestFakeCaret = function (root, clientX, clientY) {
  22684. var fakeTargetNodeRects = getClientRects(getFakeCaretTargets(root));
  22685. var targetNodeRects = filter$4(fakeTargetNodeRects, curry(isInsideY, clientY));
  22686. var checkInside = function (clientRect) {
  22687. return !isTable$3(clientRect.node) && !isMedia$2(clientRect.node);
  22688. };
  22689. var closestNodeRect = findClosestClientRect(targetNodeRects, clientX, checkInside);
  22690. if (closestNodeRect) {
  22691. var includeChildren = checkInside(closestNodeRect);
  22692. closestNodeRect = findClosestClientRect(findLineNodeRects(root, closestNodeRect, includeChildren), clientX, checkInside);
  22693. if (closestNodeRect && isFakeCaretTarget(closestNodeRect.node)) {
  22694. return caretInfo(closestNodeRect, clientX);
  22695. }
  22696. }
  22697. return null;
  22698. };
  22699. var moveToRange = function (editor, rng) {
  22700. editor.selection.setRng(rng);
  22701. scrollRangeIntoView(editor, editor.selection.getRng());
  22702. };
  22703. var renderRangeCaretOpt = function (editor, range, scrollIntoView) {
  22704. return Optional.some(renderRangeCaret(editor, range, scrollIntoView));
  22705. };
  22706. var moveHorizontally = function (editor, direction, range, isBefore, isAfter, isElement) {
  22707. var forwards = direction === HDirection.Forwards;
  22708. var caretWalker = CaretWalker(editor.getBody());
  22709. var getNextPosFn = curry(getVisualCaretPosition, forwards ? caretWalker.next : caretWalker.prev);
  22710. var isBeforeFn = forwards ? isBefore : isAfter;
  22711. if (!range.collapsed) {
  22712. var node = getSelectedNode(range);
  22713. if (isElement(node)) {
  22714. return showCaret(direction, editor, node, direction === HDirection.Backwards, false);
  22715. }
  22716. }
  22717. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22718. if (isBeforeFn(caretPosition)) {
  22719. return selectNode(editor, caretPosition.getNode(!forwards));
  22720. }
  22721. var nextCaretPosition = normalizePosition(forwards, getNextPosFn(caretPosition));
  22722. var rangeIsInContainerBlock = isRangeInCaretContainerBlock(range);
  22723. if (!nextCaretPosition) {
  22724. return rangeIsInContainerBlock ? Optional.some(range) : Optional.none();
  22725. }
  22726. if (isBeforeFn(nextCaretPosition)) {
  22727. return showCaret(direction, editor, nextCaretPosition.getNode(!forwards), forwards, false);
  22728. }
  22729. var peekCaretPosition = getNextPosFn(nextCaretPosition);
  22730. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  22731. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  22732. return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, false);
  22733. }
  22734. }
  22735. if (rangeIsInContainerBlock) {
  22736. return renderRangeCaretOpt(editor, nextCaretPosition.toRange(), false);
  22737. }
  22738. return Optional.none();
  22739. };
  22740. var moveVertically = function (editor, direction, range, isBefore, isAfter, isElement) {
  22741. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22742. var caretClientRect = last$1(caretPosition.getClientRects());
  22743. var forwards = direction === VDirection.Down;
  22744. if (!caretClientRect) {
  22745. return Optional.none();
  22746. }
  22747. var walkerFn = forwards ? downUntil : upUntil;
  22748. var linePositions = walkerFn(editor.getBody(), isAboveLine(1), caretPosition);
  22749. var nextLinePositions = filter$4(linePositions, isLine(1));
  22750. var clientX = caretClientRect.left;
  22751. var nextLineRect = findClosestClientRect(nextLinePositions, clientX);
  22752. if (nextLineRect && isElement(nextLineRect.node)) {
  22753. var dist1 = Math.abs(clientX - nextLineRect.left);
  22754. var dist2 = Math.abs(clientX - nextLineRect.right);
  22755. return showCaret(direction, editor, nextLineRect.node, dist1 < dist2, false);
  22756. }
  22757. var currentNode;
  22758. if (isBefore(caretPosition)) {
  22759. currentNode = caretPosition.getNode();
  22760. } else if (isAfter(caretPosition)) {
  22761. currentNode = caretPosition.getNode(true);
  22762. } else {
  22763. currentNode = getSelectedNode(range);
  22764. }
  22765. if (currentNode) {
  22766. var caretPositions = positionsUntil(direction, editor.getBody(), isAboveLine(1), currentNode);
  22767. var closestNextLineRect = findClosestClientRect(filter$4(caretPositions, isLine(1)), clientX);
  22768. if (closestNextLineRect) {
  22769. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  22770. }
  22771. closestNextLineRect = last$1(filter$4(caretPositions, isLine(0)));
  22772. if (closestNextLineRect) {
  22773. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  22774. }
  22775. }
  22776. if (nextLinePositions.length === 0) {
  22777. return getLineEndPoint(editor, forwards).filter(forwards ? isAfter : isBefore).map(function (pos) {
  22778. return renderRangeCaret(editor, pos.toRange(), false);
  22779. });
  22780. }
  22781. return Optional.none();
  22782. };
  22783. var getLineEndPoint = function (editor, forward) {
  22784. var rng = editor.selection.getRng();
  22785. var body = editor.getBody();
  22786. if (forward) {
  22787. var from = CaretPosition.fromRangeEnd(rng);
  22788. var result = getPositionsUntilNextLine(body, from);
  22789. return last$2(result.positions);
  22790. } else {
  22791. var from = CaretPosition.fromRangeStart(rng);
  22792. var result = getPositionsUntilPreviousLine(body, from);
  22793. return head(result.positions);
  22794. }
  22795. };
  22796. var moveToLineEndPoint$3 = function (editor, forward, isElementPosition) {
  22797. return getLineEndPoint(editor, forward).filter(isElementPosition).exists(function (pos) {
  22798. editor.selection.setRng(pos.toRange());
  22799. return true;
  22800. });
  22801. };
  22802. var setCaretPosition = function (editor, pos) {
  22803. var rng = editor.dom.createRng();
  22804. rng.setStart(pos.container(), pos.offset());
  22805. rng.setEnd(pos.container(), pos.offset());
  22806. editor.selection.setRng(rng);
  22807. };
  22808. var setSelected = function (state, elm) {
  22809. if (state) {
  22810. elm.setAttribute('data-mce-selected', 'inline-boundary');
  22811. } else {
  22812. elm.removeAttribute('data-mce-selected');
  22813. }
  22814. };
  22815. var renderCaretLocation = function (editor, caret, location) {
  22816. return renderCaret(caret, location).map(function (pos) {
  22817. setCaretPosition(editor, pos);
  22818. return location;
  22819. });
  22820. };
  22821. var findLocation = function (editor, caret, forward) {
  22822. var rootNode = editor.getBody();
  22823. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  22824. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22825. var location = findLocation$1(forward, isInlineTarget$1, rootNode, from);
  22826. return location.bind(function (location) {
  22827. return renderCaretLocation(editor, caret, location);
  22828. });
  22829. };
  22830. var toggleInlines = function (isInlineTarget, dom, elms) {
  22831. var inlineBoundaries = map$3(descendants(SugarElement.fromDom(dom.getRoot()), '*[data-mce-selected="inline-boundary"]'), function (e) {
  22832. return e.dom;
  22833. });
  22834. var selectedInlines = filter$4(inlineBoundaries, isInlineTarget);
  22835. var targetInlines = filter$4(elms, isInlineTarget);
  22836. each$k(difference(selectedInlines, targetInlines), curry(setSelected, false));
  22837. each$k(difference(targetInlines, selectedInlines), curry(setSelected, true));
  22838. };
  22839. var safeRemoveCaretContainer = function (editor, caret) {
  22840. if (editor.selection.isCollapsed() && editor.composing !== true && caret.get()) {
  22841. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22842. if (CaretPosition.isTextPosition(pos) && isAtZwsp(pos) === false) {
  22843. setCaretPosition(editor, removeAndReposition(caret.get(), pos));
  22844. caret.set(null);
  22845. }
  22846. }
  22847. };
  22848. var renderInsideInlineCaret = function (isInlineTarget, editor, caret, elms) {
  22849. if (editor.selection.isCollapsed()) {
  22850. var inlines = filter$4(elms, isInlineTarget);
  22851. each$k(inlines, function (_inline) {
  22852. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22853. readLocation(isInlineTarget, editor.getBody(), pos).bind(function (location) {
  22854. return renderCaretLocation(editor, caret, location);
  22855. });
  22856. });
  22857. }
  22858. };
  22859. var move$2 = function (editor, caret, forward) {
  22860. return isInlineBoundariesEnabled(editor) ? findLocation(editor, caret, forward).isSome() : false;
  22861. };
  22862. var moveWord = function (forward, editor, _caret) {
  22863. return isInlineBoundariesEnabled(editor) ? moveByWord(forward, editor) : false;
  22864. };
  22865. var setupSelectedState = function (editor) {
  22866. var caret = Cell(null);
  22867. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22868. editor.on('NodeChange', function (e) {
  22869. if (isInlineBoundariesEnabled(editor) && !(Env.browser.isIE() && e.initial)) {
  22870. toggleInlines(isInlineTarget$1, editor.dom, e.parents);
  22871. safeRemoveCaretContainer(editor, caret);
  22872. renderInsideInlineCaret(isInlineTarget$1, editor, caret, e.parents);
  22873. }
  22874. });
  22875. return caret;
  22876. };
  22877. var moveNextWord = curry(moveWord, true);
  22878. var movePrevWord = curry(moveWord, false);
  22879. var moveToLineEndPoint$2 = function (editor, forward, caret) {
  22880. if (isInlineBoundariesEnabled(editor)) {
  22881. var linePoint = getLineEndPoint(editor, forward).getOrThunk(function () {
  22882. var rng = editor.selection.getRng();
  22883. return forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  22884. });
  22885. return readLocation(curry(isInlineTarget, editor), editor.getBody(), linePoint).exists(function (loc) {
  22886. var outsideLoc = outside(loc);
  22887. return renderCaret(caret, outsideLoc).exists(function (pos) {
  22888. setCaretPosition(editor, pos);
  22889. return true;
  22890. });
  22891. });
  22892. } else {
  22893. return false;
  22894. }
  22895. };
  22896. var rangeFromPositions = function (from, to) {
  22897. var range = document.createRange();
  22898. range.setStart(from.container(), from.offset());
  22899. range.setEnd(to.container(), to.offset());
  22900. return range;
  22901. };
  22902. var hasOnlyTwoOrLessPositionsLeft = function (elm) {
  22903. return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  22904. var normalizedFirstPos = normalizePosition(true, firstPos);
  22905. var normalizedLastPos = normalizePosition(false, lastPos);
  22906. return nextPosition(elm, normalizedFirstPos).forall(function (pos) {
  22907. return pos.isEqual(normalizedLastPos);
  22908. });
  22909. }).getOr(true);
  22910. };
  22911. var setCaretLocation = function (editor, caret) {
  22912. return function (location) {
  22913. return renderCaret(caret, location).exists(function (pos) {
  22914. setCaretPosition(editor, pos);
  22915. return true;
  22916. });
  22917. };
  22918. };
  22919. var deleteFromTo = function (editor, caret, from, to) {
  22920. var rootNode = editor.getBody();
  22921. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22922. editor.undoManager.ignore(function () {
  22923. editor.selection.setRng(rangeFromPositions(from, to));
  22924. editor.execCommand('Delete');
  22925. readLocation(isInlineTarget$1, rootNode, CaretPosition.fromRangeStart(editor.selection.getRng())).map(inside).map(setCaretLocation(editor, caret));
  22926. });
  22927. editor.nodeChanged();
  22928. };
  22929. var rescope = function (rootNode, node) {
  22930. var parentBlock = getParentBlock$2(node, rootNode);
  22931. return parentBlock ? parentBlock : rootNode;
  22932. };
  22933. var backspaceDeleteCollapsed = function (editor, caret, forward, from) {
  22934. var rootNode = rescope(editor.getBody(), from.container());
  22935. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22936. var fromLocation = readLocation(isInlineTarget$1, rootNode, from);
  22937. return fromLocation.bind(function (location) {
  22938. if (forward) {
  22939. return location.fold(constant(Optional.some(inside(location))), Optional.none, constant(Optional.some(outside(location))), Optional.none);
  22940. } else {
  22941. return location.fold(Optional.none, constant(Optional.some(outside(location))), Optional.none, constant(Optional.some(inside(location))));
  22942. }
  22943. }).map(setCaretLocation(editor, caret)).getOrThunk(function () {
  22944. var toPosition = navigate(forward, rootNode, from);
  22945. var toLocation = toPosition.bind(function (pos) {
  22946. return readLocation(isInlineTarget$1, rootNode, pos);
  22947. });
  22948. return lift2(fromLocation, toLocation, function () {
  22949. return findRootInline(isInlineTarget$1, rootNode, from).exists(function (elm) {
  22950. if (hasOnlyTwoOrLessPositionsLeft(elm)) {
  22951. deleteElement$2(editor, forward, SugarElement.fromDom(elm));
  22952. return true;
  22953. } else {
  22954. return false;
  22955. }
  22956. });
  22957. }).orThunk(function () {
  22958. return toLocation.bind(function (_) {
  22959. return toPosition.map(function (to) {
  22960. if (forward) {
  22961. deleteFromTo(editor, caret, from, to);
  22962. } else {
  22963. deleteFromTo(editor, caret, to, from);
  22964. }
  22965. return true;
  22966. });
  22967. });
  22968. }).getOr(false);
  22969. });
  22970. };
  22971. var backspaceDelete$3 = function (editor, caret, forward) {
  22972. if (editor.selection.isCollapsed() && isInlineBoundariesEnabled(editor)) {
  22973. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  22974. return backspaceDeleteCollapsed(editor, caret, forward, from);
  22975. }
  22976. return false;
  22977. };
  22978. var getParentInlines = function (rootElm, startElm) {
  22979. var parents = parentsAndSelf(startElm, rootElm);
  22980. return findIndex$2(parents, isBlock$2).fold(constant(parents), function (index) {
  22981. return parents.slice(0, index);
  22982. });
  22983. };
  22984. var hasOnlyOneChild = function (elm) {
  22985. return childNodesCount(elm) === 1;
  22986. };
  22987. var deleteLastPosition = function (forward, editor, target, parentInlines) {
  22988. var isFormatElement$1 = curry(isFormatElement, editor);
  22989. var formatNodes = map$3(filter$4(parentInlines, isFormatElement$1), function (elm) {
  22990. return elm.dom;
  22991. });
  22992. if (formatNodes.length === 0) {
  22993. deleteElement$2(editor, forward, target);
  22994. } else {
  22995. var pos = replaceWithCaretFormat(target.dom, formatNodes);
  22996. editor.selection.setRng(pos.toRange());
  22997. }
  22998. };
  22999. var deleteCaret$1 = function (editor, forward) {
  23000. var rootElm = SugarElement.fromDom(editor.getBody());
  23001. var startElm = SugarElement.fromDom(editor.selection.getStart());
  23002. var parentInlines = filter$4(getParentInlines(rootElm, startElm), hasOnlyOneChild);
  23003. return last$2(parentInlines).exists(function (target) {
  23004. var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23005. if (willDeleteLastPositionInElement(forward, fromPos, target.dom) && !isEmptyCaretFormatElement(target)) {
  23006. deleteLastPosition(forward, editor, target, parentInlines);
  23007. return true;
  23008. } else {
  23009. return false;
  23010. }
  23011. });
  23012. };
  23013. var backspaceDelete$2 = function (editor, forward) {
  23014. return editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : false;
  23015. };
  23016. var deleteElement = function (editor, forward, element) {
  23017. editor._selectionOverrides.hideFakeCaret();
  23018. deleteElement$2(editor, forward, SugarElement.fromDom(element));
  23019. return true;
  23020. };
  23021. var deleteCaret = function (editor, forward) {
  23022. var isNearMedia = forward ? isBeforeMedia : isAfterMedia;
  23023. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23024. var fromPos = getNormalizedRangeEndPoint(direction, editor.getBody(), editor.selection.getRng());
  23025. if (isNearMedia(fromPos)) {
  23026. return deleteElement(editor, forward, fromPos.getNode(!forward));
  23027. } else {
  23028. return Optional.from(normalizePosition(forward, fromPos)).filter(function (pos) {
  23029. return isNearMedia(pos) && isMoveInsideSameBlock(fromPos, pos);
  23030. }).exists(function (pos) {
  23031. return deleteElement(editor, forward, pos.getNode(!forward));
  23032. });
  23033. }
  23034. };
  23035. var deleteRange = function (editor, forward) {
  23036. var selectedNode = editor.selection.getNode();
  23037. return isMedia$2(selectedNode) ? deleteElement(editor, forward, selectedNode) : false;
  23038. };
  23039. var backspaceDelete$1 = function (editor, forward) {
  23040. return editor.selection.isCollapsed() ? deleteCaret(editor, forward) : deleteRange(editor, forward);
  23041. };
  23042. var isEditable = function (target) {
  23043. return closest$3(target, function (elm) {
  23044. return isContentEditableTrue$4(elm.dom) || isContentEditableFalse$b(elm.dom);
  23045. }).exists(function (elm) {
  23046. return isContentEditableTrue$4(elm.dom);
  23047. });
  23048. };
  23049. var parseIndentValue = function (value) {
  23050. var number = parseInt(value, 10);
  23051. return isNaN(number) ? 0 : number;
  23052. };
  23053. var getIndentStyleName = function (useMargin, element) {
  23054. var indentStyleName = useMargin || isTable$2(element) ? 'margin' : 'padding';
  23055. var suffix = get$5(element, 'direction') === 'rtl' ? '-right' : '-left';
  23056. return indentStyleName + suffix;
  23057. };
  23058. var indentElement = function (dom, command, useMargin, value, unit, element) {
  23059. var indentStyleName = getIndentStyleName(useMargin, SugarElement.fromDom(element));
  23060. if (command === 'outdent') {
  23061. var styleValue = Math.max(0, parseIndentValue(element.style[indentStyleName]) - value);
  23062. dom.setStyle(element, indentStyleName, styleValue ? styleValue + unit : '');
  23063. } else {
  23064. var styleValue = parseIndentValue(element.style[indentStyleName]) + value + unit;
  23065. dom.setStyle(element, indentStyleName, styleValue);
  23066. }
  23067. };
  23068. var validateBlocks = function (editor, blocks) {
  23069. return forall(blocks, function (block) {
  23070. var indentStyleName = getIndentStyleName(shouldIndentUseMargin(editor), block);
  23071. var intentValue = getRaw(block, indentStyleName).map(parseIndentValue).getOr(0);
  23072. var contentEditable = editor.dom.getContentEditable(block.dom);
  23073. return contentEditable !== 'false' && intentValue > 0;
  23074. });
  23075. };
  23076. var canOutdent = function (editor) {
  23077. var blocks = getBlocksToIndent(editor);
  23078. return !editor.mode.isReadOnly() && (blocks.length > 1 || validateBlocks(editor, blocks));
  23079. };
  23080. var isListComponent = function (el) {
  23081. return isList(el) || isListItem(el);
  23082. };
  23083. var parentIsListComponent = function (el) {
  23084. return parent(el).exists(isListComponent);
  23085. };
  23086. var getBlocksToIndent = function (editor) {
  23087. return filter$4(fromDom$1(editor.selection.getSelectedBlocks()), function (el) {
  23088. return !isListComponent(el) && !parentIsListComponent(el) && isEditable(el);
  23089. });
  23090. };
  23091. var handle = function (editor, command) {
  23092. var dom = editor.dom, selection = editor.selection, formatter = editor.formatter;
  23093. var indentation = getIndentation(editor);
  23094. var indentUnit = /[a-z%]+$/i.exec(indentation)[0];
  23095. var indentValue = parseInt(indentation, 10);
  23096. var useMargin = shouldIndentUseMargin(editor);
  23097. var forcedRootBlock = getForcedRootBlock(editor);
  23098. if (!editor.queryCommandState('InsertUnorderedList') && !editor.queryCommandState('InsertOrderedList')) {
  23099. if (forcedRootBlock === '' && !dom.getParent(selection.getNode(), dom.isBlock)) {
  23100. formatter.apply('div');
  23101. }
  23102. }
  23103. each$k(getBlocksToIndent(editor), function (block) {
  23104. indentElement(dom, command, useMargin, indentValue, indentUnit, block.dom);
  23105. });
  23106. };
  23107. var backspaceDelete = function (editor, _forward) {
  23108. if (editor.selection.isCollapsed() && canOutdent(editor)) {
  23109. var dom = editor.dom;
  23110. var rng = editor.selection.getRng();
  23111. var pos = CaretPosition.fromRangeStart(rng);
  23112. var block = dom.getParent(rng.startContainer, dom.isBlock);
  23113. if (block !== null && isAtStartOfBlock(SugarElement.fromDom(block), pos)) {
  23114. handle(editor, 'outdent');
  23115. return true;
  23116. }
  23117. }
  23118. return false;
  23119. };
  23120. var nativeCommand = function (editor, command) {
  23121. editor.getDoc().execCommand(command, false, null);
  23122. };
  23123. var deleteCommand = function (editor, caret) {
  23124. if (backspaceDelete(editor)) {
  23125. return;
  23126. } else if (backspaceDelete$5(editor, false)) {
  23127. return;
  23128. } else if (backspaceDelete$6(editor, false)) {
  23129. return;
  23130. } else if (backspaceDelete$3(editor, caret, false)) {
  23131. return;
  23132. } else if (backspaceDelete$8(editor, false)) {
  23133. return;
  23134. } else if (backspaceDelete$9(editor)) {
  23135. return;
  23136. } else if (backspaceDelete$4(editor, false)) {
  23137. return;
  23138. } else if (backspaceDelete$1(editor, false)) {
  23139. return;
  23140. } else if (backspaceDelete$7(editor)) {
  23141. return;
  23142. } else if (backspaceDelete$2(editor, false)) {
  23143. return;
  23144. } else {
  23145. nativeCommand(editor, 'Delete');
  23146. paddEmptyBody(editor);
  23147. }
  23148. };
  23149. var forwardDeleteCommand = function (editor, caret) {
  23150. if (backspaceDelete$5(editor, true)) {
  23151. return;
  23152. } else if (backspaceDelete$6(editor, true)) {
  23153. return;
  23154. } else if (backspaceDelete$3(editor, caret, true)) {
  23155. return;
  23156. } else if (backspaceDelete$8(editor, true)) {
  23157. return;
  23158. } else if (backspaceDelete$9(editor)) {
  23159. return;
  23160. } else if (backspaceDelete$4(editor, true)) {
  23161. return;
  23162. } else if (backspaceDelete$1(editor, true)) {
  23163. return;
  23164. } else if (backspaceDelete$7(editor)) {
  23165. return;
  23166. } else if (backspaceDelete$2(editor, true)) {
  23167. return;
  23168. } else {
  23169. nativeCommand(editor, 'ForwardDelete');
  23170. }
  23171. };
  23172. var setup$f = function (editor, caret) {
  23173. editor.addCommand('delete', function () {
  23174. deleteCommand(editor, caret);
  23175. });
  23176. editor.addCommand('forwardDelete', function () {
  23177. forwardDeleteCommand(editor, caret);
  23178. });
  23179. };
  23180. var SIGNIFICANT_MOVE = 5;
  23181. var LONGPRESS_DELAY = 400;
  23182. var getTouch = function (event) {
  23183. if (event.touches === undefined || event.touches.length !== 1) {
  23184. return Optional.none();
  23185. }
  23186. return Optional.some(event.touches[0]);
  23187. };
  23188. var isFarEnough = function (touch, data) {
  23189. var distX = Math.abs(touch.clientX - data.x);
  23190. var distY = Math.abs(touch.clientY - data.y);
  23191. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  23192. };
  23193. var setup$e = function (editor) {
  23194. var startData = value();
  23195. var longpressFired = Cell(false);
  23196. var debounceLongpress = last(function (e) {
  23197. editor.fire('longpress', __assign(__assign({}, e), { type: 'longpress' }));
  23198. longpressFired.set(true);
  23199. }, LONGPRESS_DELAY);
  23200. editor.on('touchstart', function (e) {
  23201. getTouch(e).each(function (touch) {
  23202. debounceLongpress.cancel();
  23203. var data = {
  23204. x: touch.clientX,
  23205. y: touch.clientY,
  23206. target: e.target
  23207. };
  23208. debounceLongpress.throttle(e);
  23209. longpressFired.set(false);
  23210. startData.set(data);
  23211. });
  23212. }, true);
  23213. editor.on('touchmove', function (e) {
  23214. debounceLongpress.cancel();
  23215. getTouch(e).each(function (touch) {
  23216. startData.on(function (data) {
  23217. if (isFarEnough(touch, data)) {
  23218. startData.clear();
  23219. longpressFired.set(false);
  23220. editor.fire('longpresscancel');
  23221. }
  23222. });
  23223. });
  23224. }, true);
  23225. editor.on('touchend touchcancel', function (e) {
  23226. debounceLongpress.cancel();
  23227. if (e.type === 'touchcancel') {
  23228. return;
  23229. }
  23230. startData.get().filter(function (data) {
  23231. return data.target.isEqualNode(e.target);
  23232. }).each(function () {
  23233. if (longpressFired.get()) {
  23234. e.preventDefault();
  23235. } else {
  23236. editor.fire('tap', __assign(__assign({}, e), { type: 'tap' }));
  23237. }
  23238. });
  23239. }, true);
  23240. };
  23241. var isBlockElement = function (blockElements, node) {
  23242. return has$2(blockElements, node.nodeName);
  23243. };
  23244. var isValidTarget = function (blockElements, node) {
  23245. if (isText$7(node)) {
  23246. return true;
  23247. } else if (isElement$5(node)) {
  23248. return !isBlockElement(blockElements, node) && !isBookmarkNode$1(node);
  23249. } else {
  23250. return false;
  23251. }
  23252. };
  23253. var hasBlockParent = function (blockElements, root, node) {
  23254. return exists(parents(SugarElement.fromDom(node), SugarElement.fromDom(root)), function (elm) {
  23255. return isBlockElement(blockElements, elm.dom);
  23256. });
  23257. };
  23258. var shouldRemoveTextNode = function (blockElements, node) {
  23259. if (isText$7(node)) {
  23260. if (node.nodeValue.length === 0) {
  23261. return true;
  23262. } else if (/^\s+$/.test(node.nodeValue) && (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
  23263. return true;
  23264. }
  23265. }
  23266. return false;
  23267. };
  23268. var addRootBlocks = function (editor) {
  23269. var dom = editor.dom, selection = editor.selection;
  23270. var schema = editor.schema, blockElements = schema.getBlockElements();
  23271. var node = selection.getStart();
  23272. var rootNode = editor.getBody();
  23273. var rootBlockNode, tempNode, wrapped;
  23274. var forcedRootBlock = getForcedRootBlock(editor);
  23275. if (!node || !isElement$5(node) || !forcedRootBlock) {
  23276. return;
  23277. }
  23278. var rootNodeName = rootNode.nodeName.toLowerCase();
  23279. if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, node)) {
  23280. return;
  23281. }
  23282. var rng = selection.getRng();
  23283. var startContainer = rng.startContainer;
  23284. var startOffset = rng.startOffset;
  23285. var endContainer = rng.endContainer;
  23286. var endOffset = rng.endOffset;
  23287. var restoreSelection = hasFocus(editor);
  23288. node = rootNode.firstChild;
  23289. while (node) {
  23290. if (isValidTarget(blockElements, node)) {
  23291. if (shouldRemoveTextNode(blockElements, node)) {
  23292. tempNode = node;
  23293. node = node.nextSibling;
  23294. dom.remove(tempNode);
  23295. continue;
  23296. }
  23297. if (!rootBlockNode) {
  23298. rootBlockNode = dom.create(forcedRootBlock, getForcedRootBlockAttrs(editor));
  23299. node.parentNode.insertBefore(rootBlockNode, node);
  23300. wrapped = true;
  23301. }
  23302. tempNode = node;
  23303. node = node.nextSibling;
  23304. rootBlockNode.appendChild(tempNode);
  23305. } else {
  23306. rootBlockNode = null;
  23307. node = node.nextSibling;
  23308. }
  23309. }
  23310. if (wrapped && restoreSelection) {
  23311. rng.setStart(startContainer, startOffset);
  23312. rng.setEnd(endContainer, endOffset);
  23313. selection.setRng(rng);
  23314. editor.nodeChanged();
  23315. }
  23316. };
  23317. var setup$d = function (editor) {
  23318. if (getForcedRootBlock(editor)) {
  23319. editor.on('NodeChange', curry(addRootBlocks, editor));
  23320. }
  23321. };
  23322. var findBlockCaretContainer = function (editor) {
  23323. return descendant(SugarElement.fromDom(editor.getBody()), '*[data-mce-caret]').map(function (elm) {
  23324. return elm.dom;
  23325. }).getOrNull();
  23326. };
  23327. var removeIeControlRect = function (editor) {
  23328. editor.selection.setRng(editor.selection.getRng());
  23329. };
  23330. var showBlockCaretContainer = function (editor, blockCaretContainer) {
  23331. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  23332. showCaretContainerBlock(blockCaretContainer);
  23333. removeIeControlRect(editor);
  23334. editor.selection.scrollIntoView(blockCaretContainer);
  23335. }
  23336. };
  23337. var handleBlockContainer = function (editor, e) {
  23338. var blockCaretContainer = findBlockCaretContainer(editor);
  23339. if (!blockCaretContainer) {
  23340. return;
  23341. }
  23342. if (e.type === 'compositionstart') {
  23343. e.preventDefault();
  23344. e.stopPropagation();
  23345. showBlockCaretContainer(editor, blockCaretContainer);
  23346. return;
  23347. }
  23348. if (hasContent(blockCaretContainer)) {
  23349. showBlockCaretContainer(editor, blockCaretContainer);
  23350. editor.undoManager.add();
  23351. }
  23352. };
  23353. var setup$c = function (editor) {
  23354. editor.on('keyup compositionstart', curry(handleBlockContainer, editor));
  23355. };
  23356. var isContentEditableFalse$2 = isContentEditableFalse$b;
  23357. var moveToCeFalseHorizontally = function (direction, editor, range) {
  23358. return moveHorizontally(editor, direction, range, isBeforeContentEditableFalse, isAfterContentEditableFalse, isContentEditableFalse$2);
  23359. };
  23360. var moveToCeFalseVertically = function (direction, editor, range) {
  23361. var isBefore = function (caretPosition) {
  23362. return isBeforeContentEditableFalse(caretPosition) || isBeforeTable(caretPosition);
  23363. };
  23364. var isAfter = function (caretPosition) {
  23365. return isAfterContentEditableFalse(caretPosition) || isAfterTable(caretPosition);
  23366. };
  23367. return moveVertically(editor, direction, range, isBefore, isAfter, isContentEditableFalse$2);
  23368. };
  23369. var createTextBlock = function (editor) {
  23370. var textBlock = editor.dom.create(getForcedRootBlock(editor));
  23371. if (!Env.ie || Env.ie >= 11) {
  23372. textBlock.innerHTML = '<br data-mce-bogus="1">';
  23373. }
  23374. return textBlock;
  23375. };
  23376. var exitPreBlock = function (editor, direction, range) {
  23377. var caretWalker = CaretWalker(editor.getBody());
  23378. var getVisualCaretPosition$1 = curry(getVisualCaretPosition, direction === 1 ? caretWalker.next : caretWalker.prev);
  23379. if (range.collapsed && hasForcedRootBlock(editor)) {
  23380. var pre = editor.dom.getParent(range.startContainer, 'PRE');
  23381. if (!pre) {
  23382. return;
  23383. }
  23384. var caretPos = getVisualCaretPosition$1(CaretPosition.fromRangeStart(range));
  23385. if (!caretPos) {
  23386. var newBlock = createTextBlock(editor);
  23387. if (direction === 1) {
  23388. editor.$(pre).after(newBlock);
  23389. } else {
  23390. editor.$(pre).before(newBlock);
  23391. }
  23392. editor.selection.select(newBlock, true);
  23393. editor.selection.collapse();
  23394. }
  23395. }
  23396. };
  23397. var getHorizontalRange = function (editor, forward) {
  23398. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23399. var range = editor.selection.getRng();
  23400. return moveToCeFalseHorizontally(direction, editor, range).orThunk(function () {
  23401. exitPreBlock(editor, direction, range);
  23402. return Optional.none();
  23403. });
  23404. };
  23405. var getVerticalRange = function (editor, down) {
  23406. var direction = down ? 1 : -1;
  23407. var range = editor.selection.getRng();
  23408. return moveToCeFalseVertically(direction, editor, range).orThunk(function () {
  23409. exitPreBlock(editor, direction, range);
  23410. return Optional.none();
  23411. });
  23412. };
  23413. var moveH$2 = function (editor, forward) {
  23414. return getHorizontalRange(editor, forward).exists(function (newRange) {
  23415. moveToRange(editor, newRange);
  23416. return true;
  23417. });
  23418. };
  23419. var moveV$3 = function (editor, down) {
  23420. return getVerticalRange(editor, down).exists(function (newRange) {
  23421. moveToRange(editor, newRange);
  23422. return true;
  23423. });
  23424. };
  23425. var moveToLineEndPoint$1 = function (editor, forward) {
  23426. var isCefPosition = forward ? isAfterContentEditableFalse : isBeforeContentEditableFalse;
  23427. return moveToLineEndPoint$3(editor, forward, isCefPosition);
  23428. };
  23429. var isTarget = function (node) {
  23430. return contains$3(['figcaption'], name(node));
  23431. };
  23432. var rangeBefore = function (target) {
  23433. var rng = document.createRange();
  23434. rng.setStartBefore(target.dom);
  23435. rng.setEndBefore(target.dom);
  23436. return rng;
  23437. };
  23438. var insertElement = function (root, elm, forward) {
  23439. if (forward) {
  23440. append$1(root, elm);
  23441. } else {
  23442. prepend(root, elm);
  23443. }
  23444. };
  23445. var insertBr = function (root, forward) {
  23446. var br = SugarElement.fromTag('br');
  23447. insertElement(root, br, forward);
  23448. return rangeBefore(br);
  23449. };
  23450. var insertBlock = function (root, forward, blockName, attrs) {
  23451. var block = SugarElement.fromTag(blockName);
  23452. var br = SugarElement.fromTag('br');
  23453. setAll$1(block, attrs);
  23454. append$1(block, br);
  23455. insertElement(root, block, forward);
  23456. return rangeBefore(br);
  23457. };
  23458. var insertEmptyLine = function (root, rootBlockName, attrs, forward) {
  23459. if (rootBlockName === '') {
  23460. return insertBr(root, forward);
  23461. } else {
  23462. return insertBlock(root, forward, rootBlockName, attrs);
  23463. }
  23464. };
  23465. var getClosestTargetBlock = function (pos, root) {
  23466. var isRoot = curry(eq, root);
  23467. return closest$3(SugarElement.fromDom(pos.container()), isBlock$2, isRoot).filter(isTarget);
  23468. };
  23469. var isAtFirstOrLastLine = function (root, forward, pos) {
  23470. return forward ? isAtLastLine(root.dom, pos) : isAtFirstLine(root.dom, pos);
  23471. };
  23472. var moveCaretToNewEmptyLine = function (editor, forward) {
  23473. var root = SugarElement.fromDom(editor.getBody());
  23474. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23475. var rootBlock = getForcedRootBlock(editor);
  23476. var rootBlockAttrs = getForcedRootBlockAttrs(editor);
  23477. return getClosestTargetBlock(pos, root).exists(function () {
  23478. if (isAtFirstOrLastLine(root, forward, pos)) {
  23479. var rng = insertEmptyLine(root, rootBlock, rootBlockAttrs, forward);
  23480. editor.selection.setRng(rng);
  23481. return true;
  23482. } else {
  23483. return false;
  23484. }
  23485. });
  23486. };
  23487. var moveV$2 = function (editor, forward) {
  23488. if (editor.selection.isCollapsed()) {
  23489. return moveCaretToNewEmptyLine(editor, forward);
  23490. } else {
  23491. return false;
  23492. }
  23493. };
  23494. var defaultPatterns = function (patterns) {
  23495. return map$3(patterns, function (pattern) {
  23496. return __assign({
  23497. shiftKey: false,
  23498. altKey: false,
  23499. ctrlKey: false,
  23500. metaKey: false,
  23501. keyCode: 0,
  23502. action: noop
  23503. }, pattern);
  23504. });
  23505. };
  23506. var matchesEvent = function (pattern, evt) {
  23507. return evt.keyCode === pattern.keyCode && evt.shiftKey === pattern.shiftKey && evt.altKey === pattern.altKey && evt.ctrlKey === pattern.ctrlKey && evt.metaKey === pattern.metaKey;
  23508. };
  23509. var match$1 = function (patterns, evt) {
  23510. return bind(defaultPatterns(patterns), function (pattern) {
  23511. return matchesEvent(pattern, evt) ? [pattern] : [];
  23512. });
  23513. };
  23514. var action = function (f) {
  23515. var x = [];
  23516. for (var _i = 1; _i < arguments.length; _i++) {
  23517. x[_i - 1] = arguments[_i];
  23518. }
  23519. return function () {
  23520. return f.apply(null, x);
  23521. };
  23522. };
  23523. var execute = function (patterns, evt) {
  23524. return find$3(match$1(patterns, evt), function (pattern) {
  23525. return pattern.action();
  23526. });
  23527. };
  23528. var moveH$1 = function (editor, forward) {
  23529. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23530. var range = editor.selection.getRng();
  23531. return moveHorizontally(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(function (newRange) {
  23532. moveToRange(editor, newRange);
  23533. return true;
  23534. });
  23535. };
  23536. var moveV$1 = function (editor, down) {
  23537. var direction = down ? 1 : -1;
  23538. var range = editor.selection.getRng();
  23539. return moveVertically(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(function (newRange) {
  23540. moveToRange(editor, newRange);
  23541. return true;
  23542. });
  23543. };
  23544. var moveToLineEndPoint = function (editor, forward) {
  23545. var isNearMedia = forward ? isAfterMedia : isBeforeMedia;
  23546. return moveToLineEndPoint$3(editor, forward, isNearMedia);
  23547. };
  23548. var deflate = function (rect, delta) {
  23549. return {
  23550. left: rect.left - delta,
  23551. top: rect.top - delta,
  23552. right: rect.right + delta * 2,
  23553. bottom: rect.bottom + delta * 2,
  23554. width: rect.width + delta,
  23555. height: rect.height + delta
  23556. };
  23557. };
  23558. var getCorners = function (getYAxisValue, tds) {
  23559. return bind(tds, function (td) {
  23560. var rect = deflate(clone(td.getBoundingClientRect()), -1);
  23561. return [
  23562. {
  23563. x: rect.left,
  23564. y: getYAxisValue(rect),
  23565. cell: td
  23566. },
  23567. {
  23568. x: rect.right,
  23569. y: getYAxisValue(rect),
  23570. cell: td
  23571. }
  23572. ];
  23573. });
  23574. };
  23575. var findClosestCorner = function (corners, x, y) {
  23576. return foldl(corners, function (acc, newCorner) {
  23577. return acc.fold(function () {
  23578. return Optional.some(newCorner);
  23579. }, function (oldCorner) {
  23580. var oldDist = Math.sqrt(Math.abs(oldCorner.x - x) + Math.abs(oldCorner.y - y));
  23581. var newDist = Math.sqrt(Math.abs(newCorner.x - x) + Math.abs(newCorner.y - y));
  23582. return Optional.some(newDist < oldDist ? newCorner : oldCorner);
  23583. });
  23584. }, Optional.none());
  23585. };
  23586. var getClosestCell = function (getYAxisValue, isTargetCorner, table, x, y) {
  23587. var cells = descendants(SugarElement.fromDom(table), 'td,th,caption').map(function (e) {
  23588. return e.dom;
  23589. });
  23590. var corners = filter$4(getCorners(getYAxisValue, cells), function (corner) {
  23591. return isTargetCorner(corner, y);
  23592. });
  23593. return findClosestCorner(corners, x, y).map(function (corner) {
  23594. return corner.cell;
  23595. });
  23596. };
  23597. var getBottomValue = function (rect) {
  23598. return rect.bottom;
  23599. };
  23600. var getTopValue = function (rect) {
  23601. return rect.top;
  23602. };
  23603. var isAbove = function (corner, y) {
  23604. return corner.y < y;
  23605. };
  23606. var isBelow = function (corner, y) {
  23607. return corner.y > y;
  23608. };
  23609. var getClosestCellAbove = curry(getClosestCell, getBottomValue, isAbove);
  23610. var getClosestCellBelow = curry(getClosestCell, getTopValue, isBelow);
  23611. var findClosestPositionInAboveCell = function (table, pos) {
  23612. return head(pos.getClientRects()).bind(function (rect) {
  23613. return getClosestCellAbove(table, rect.left, rect.top);
  23614. }).bind(function (cell) {
  23615. return findClosestHorizontalPosition(getLastLinePositions(cell), pos);
  23616. });
  23617. };
  23618. var findClosestPositionInBelowCell = function (table, pos) {
  23619. return last$2(pos.getClientRects()).bind(function (rect) {
  23620. return getClosestCellBelow(table, rect.left, rect.top);
  23621. }).bind(function (cell) {
  23622. return findClosestHorizontalPosition(getFirstLinePositions(cell), pos);
  23623. });
  23624. };
  23625. var hasNextBreak = function (getPositionsUntil, scope, lineInfo) {
  23626. return lineInfo.breakAt.exists(function (breakPos) {
  23627. return getPositionsUntil(scope, breakPos).breakAt.isSome();
  23628. });
  23629. };
  23630. var startsWithWrapBreak = function (lineInfo) {
  23631. return lineInfo.breakType === BreakType.Wrap && lineInfo.positions.length === 0;
  23632. };
  23633. var startsWithBrBreak = function (lineInfo) {
  23634. return lineInfo.breakType === BreakType.Br && lineInfo.positions.length === 1;
  23635. };
  23636. var isAtTableCellLine = function (getPositionsUntil, scope, pos) {
  23637. var lineInfo = getPositionsUntil(scope, pos);
  23638. if (startsWithWrapBreak(lineInfo) || !isBr$5(pos.getNode()) && startsWithBrBreak(lineInfo)) {
  23639. return !hasNextBreak(getPositionsUntil, scope, lineInfo);
  23640. } else {
  23641. return lineInfo.breakAt.isNone();
  23642. }
  23643. };
  23644. var isAtFirstTableCellLine = curry(isAtTableCellLine, getPositionsUntilPreviousLine);
  23645. var isAtLastTableCellLine = curry(isAtTableCellLine, getPositionsUntilNextLine);
  23646. var isCaretAtStartOrEndOfTable = function (forward, rng, table) {
  23647. var caretPos = CaretPosition.fromRangeStart(rng);
  23648. return positionIn(!forward, table).exists(function (pos) {
  23649. return pos.isEqual(caretPos);
  23650. });
  23651. };
  23652. var navigateHorizontally = function (editor, forward, table, _td) {
  23653. var rng = editor.selection.getRng();
  23654. var direction = forward ? 1 : -1;
  23655. if (isFakeCaretTableBrowser() && isCaretAtStartOrEndOfTable(forward, rng, table)) {
  23656. showCaret(direction, editor, table, !forward, false).each(function (newRng) {
  23657. moveToRange(editor, newRng);
  23658. });
  23659. return true;
  23660. }
  23661. return false;
  23662. };
  23663. var getClosestAbovePosition = function (root, table, start) {
  23664. return findClosestPositionInAboveCell(table, start).orThunk(function () {
  23665. return head(start.getClientRects()).bind(function (rect) {
  23666. return findClosestHorizontalPositionFromPoint(getPositionsAbove(root, CaretPosition.before(table)), rect.left);
  23667. });
  23668. }).getOr(CaretPosition.before(table));
  23669. };
  23670. var getClosestBelowPosition = function (root, table, start) {
  23671. return findClosestPositionInBelowCell(table, start).orThunk(function () {
  23672. return head(start.getClientRects()).bind(function (rect) {
  23673. return findClosestHorizontalPositionFromPoint(getPositionsBelow(root, CaretPosition.after(table)), rect.left);
  23674. });
  23675. }).getOr(CaretPosition.after(table));
  23676. };
  23677. var getTable = function (previous, pos) {
  23678. var node = pos.getNode(previous);
  23679. return isElement$5(node) && node.nodeName === 'TABLE' ? Optional.some(node) : Optional.none();
  23680. };
  23681. var renderBlock = function (down, editor, table, pos) {
  23682. var forcedRootBlock = getForcedRootBlock(editor);
  23683. if (forcedRootBlock) {
  23684. editor.undoManager.transact(function () {
  23685. var element = SugarElement.fromTag(forcedRootBlock);
  23686. setAll$1(element, getForcedRootBlockAttrs(editor));
  23687. append$1(element, SugarElement.fromTag('br'));
  23688. if (down) {
  23689. after$3(SugarElement.fromDom(table), element);
  23690. } else {
  23691. before$4(SugarElement.fromDom(table), element);
  23692. }
  23693. var rng = editor.dom.createRng();
  23694. rng.setStart(element.dom, 0);
  23695. rng.setEnd(element.dom, 0);
  23696. moveToRange(editor, rng);
  23697. });
  23698. } else {
  23699. moveToRange(editor, pos.toRange());
  23700. }
  23701. };
  23702. var moveCaret = function (editor, down, pos) {
  23703. var table = down ? getTable(true, pos) : getTable(false, pos);
  23704. var last = down === false;
  23705. table.fold(function () {
  23706. return moveToRange(editor, pos.toRange());
  23707. }, function (table) {
  23708. return positionIn(last, editor.getBody()).filter(function (lastPos) {
  23709. return lastPos.isEqual(pos);
  23710. }).fold(function () {
  23711. return moveToRange(editor, pos.toRange());
  23712. }, function (_) {
  23713. return renderBlock(down, editor, table, pos);
  23714. });
  23715. });
  23716. };
  23717. var navigateVertically = function (editor, down, table, td) {
  23718. var rng = editor.selection.getRng();
  23719. var pos = CaretPosition.fromRangeStart(rng);
  23720. var root = editor.getBody();
  23721. if (!down && isAtFirstTableCellLine(td, pos)) {
  23722. var newPos = getClosestAbovePosition(root, table, pos);
  23723. moveCaret(editor, down, newPos);
  23724. return true;
  23725. } else if (down && isAtLastTableCellLine(td, pos)) {
  23726. var newPos = getClosestBelowPosition(root, table, pos);
  23727. moveCaret(editor, down, newPos);
  23728. return true;
  23729. } else {
  23730. return false;
  23731. }
  23732. };
  23733. var move$1 = function (editor, forward, mover) {
  23734. return Optional.from(editor.dom.getParent(editor.selection.getNode(), 'td,th')).bind(function (td) {
  23735. return Optional.from(editor.dom.getParent(td, 'table')).map(function (table) {
  23736. return mover(editor, forward, table, td);
  23737. });
  23738. }).getOr(false);
  23739. };
  23740. var moveH = function (editor, forward) {
  23741. return move$1(editor, forward, navigateHorizontally);
  23742. };
  23743. var moveV = function (editor, forward) {
  23744. return move$1(editor, forward, navigateVertically);
  23745. };
  23746. var executeKeydownOverride$3 = function (editor, caret, evt) {
  23747. var os = detect().os;
  23748. execute([
  23749. {
  23750. keyCode: VK.RIGHT,
  23751. action: action(moveH$2, editor, true)
  23752. },
  23753. {
  23754. keyCode: VK.LEFT,
  23755. action: action(moveH$2, editor, false)
  23756. },
  23757. {
  23758. keyCode: VK.UP,
  23759. action: action(moveV$3, editor, false)
  23760. },
  23761. {
  23762. keyCode: VK.DOWN,
  23763. action: action(moveV$3, editor, true)
  23764. },
  23765. {
  23766. keyCode: VK.RIGHT,
  23767. action: action(moveH, editor, true)
  23768. },
  23769. {
  23770. keyCode: VK.LEFT,
  23771. action: action(moveH, editor, false)
  23772. },
  23773. {
  23774. keyCode: VK.UP,
  23775. action: action(moveV, editor, false)
  23776. },
  23777. {
  23778. keyCode: VK.DOWN,
  23779. action: action(moveV, editor, true)
  23780. },
  23781. {
  23782. keyCode: VK.RIGHT,
  23783. action: action(moveH$1, editor, true)
  23784. },
  23785. {
  23786. keyCode: VK.LEFT,
  23787. action: action(moveH$1, editor, false)
  23788. },
  23789. {
  23790. keyCode: VK.UP,
  23791. action: action(moveV$1, editor, false)
  23792. },
  23793. {
  23794. keyCode: VK.DOWN,
  23795. action: action(moveV$1, editor, true)
  23796. },
  23797. {
  23798. keyCode: VK.RIGHT,
  23799. action: action(move$2, editor, caret, true)
  23800. },
  23801. {
  23802. keyCode: VK.LEFT,
  23803. action: action(move$2, editor, caret, false)
  23804. },
  23805. {
  23806. keyCode: VK.RIGHT,
  23807. ctrlKey: !os.isOSX(),
  23808. altKey: os.isOSX(),
  23809. action: action(moveNextWord, editor, caret)
  23810. },
  23811. {
  23812. keyCode: VK.LEFT,
  23813. ctrlKey: !os.isOSX(),
  23814. altKey: os.isOSX(),
  23815. action: action(movePrevWord, editor, caret)
  23816. },
  23817. {
  23818. keyCode: VK.UP,
  23819. action: action(moveV$2, editor, false)
  23820. },
  23821. {
  23822. keyCode: VK.DOWN,
  23823. action: action(moveV$2, editor, true)
  23824. }
  23825. ], evt).each(function (_) {
  23826. evt.preventDefault();
  23827. });
  23828. };
  23829. var setup$b = function (editor, caret) {
  23830. editor.on('keydown', function (evt) {
  23831. if (evt.isDefaultPrevented() === false) {
  23832. executeKeydownOverride$3(editor, caret, evt);
  23833. }
  23834. });
  23835. };
  23836. var executeKeydownOverride$2 = function (editor, caret, evt) {
  23837. execute([
  23838. {
  23839. keyCode: VK.BACKSPACE,
  23840. action: action(backspaceDelete, editor, false)
  23841. },
  23842. {
  23843. keyCode: VK.BACKSPACE,
  23844. action: action(backspaceDelete$5, editor, false)
  23845. },
  23846. {
  23847. keyCode: VK.DELETE,
  23848. action: action(backspaceDelete$5, editor, true)
  23849. },
  23850. {
  23851. keyCode: VK.BACKSPACE,
  23852. action: action(backspaceDelete$6, editor, false)
  23853. },
  23854. {
  23855. keyCode: VK.DELETE,
  23856. action: action(backspaceDelete$6, editor, true)
  23857. },
  23858. {
  23859. keyCode: VK.BACKSPACE,
  23860. action: action(backspaceDelete$3, editor, caret, false)
  23861. },
  23862. {
  23863. keyCode: VK.DELETE,
  23864. action: action(backspaceDelete$3, editor, caret, true)
  23865. },
  23866. {
  23867. keyCode: VK.BACKSPACE,
  23868. action: action(backspaceDelete$9, editor, false)
  23869. },
  23870. {
  23871. keyCode: VK.DELETE,
  23872. action: action(backspaceDelete$9, editor, true)
  23873. },
  23874. {
  23875. keyCode: VK.BACKSPACE,
  23876. action: action(backspaceDelete$4, editor, false)
  23877. },
  23878. {
  23879. keyCode: VK.DELETE,
  23880. action: action(backspaceDelete$4, editor, true)
  23881. },
  23882. {
  23883. keyCode: VK.BACKSPACE,
  23884. action: action(backspaceDelete$1, editor, false)
  23885. },
  23886. {
  23887. keyCode: VK.DELETE,
  23888. action: action(backspaceDelete$1, editor, true)
  23889. },
  23890. {
  23891. keyCode: VK.BACKSPACE,
  23892. action: action(backspaceDelete$7, editor, false)
  23893. },
  23894. {
  23895. keyCode: VK.DELETE,
  23896. action: action(backspaceDelete$7, editor, true)
  23897. },
  23898. {
  23899. keyCode: VK.BACKSPACE,
  23900. action: action(backspaceDelete$8, editor, false)
  23901. },
  23902. {
  23903. keyCode: VK.DELETE,
  23904. action: action(backspaceDelete$8, editor, true)
  23905. },
  23906. {
  23907. keyCode: VK.BACKSPACE,
  23908. action: action(backspaceDelete$2, editor, false)
  23909. },
  23910. {
  23911. keyCode: VK.DELETE,
  23912. action: action(backspaceDelete$2, editor, true)
  23913. }
  23914. ], evt).each(function (_) {
  23915. evt.preventDefault();
  23916. });
  23917. };
  23918. var executeKeyupOverride = function (editor, evt) {
  23919. execute([
  23920. {
  23921. keyCode: VK.BACKSPACE,
  23922. action: action(paddEmptyElement, editor)
  23923. },
  23924. {
  23925. keyCode: VK.DELETE,
  23926. action: action(paddEmptyElement, editor)
  23927. }
  23928. ], evt);
  23929. };
  23930. var setup$a = function (editor, caret) {
  23931. editor.on('keydown', function (evt) {
  23932. if (evt.isDefaultPrevented() === false) {
  23933. executeKeydownOverride$2(editor, caret, evt);
  23934. }
  23935. });
  23936. editor.on('keyup', function (evt) {
  23937. if (evt.isDefaultPrevented() === false) {
  23938. executeKeyupOverride(editor, evt);
  23939. }
  23940. });
  23941. };
  23942. var firstNonWhiteSpaceNodeSibling = function (node) {
  23943. while (node) {
  23944. if (node.nodeType === 1 || node.nodeType === 3 && node.data && /[\r\n\s]/.test(node.data)) {
  23945. return node;
  23946. }
  23947. node = node.nextSibling;
  23948. }
  23949. };
  23950. var moveToCaretPosition = function (editor, root) {
  23951. var node, lastNode = root;
  23952. var dom = editor.dom;
  23953. var moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
  23954. if (!root) {
  23955. return;
  23956. }
  23957. if (/^(LI|DT|DD)$/.test(root.nodeName)) {
  23958. var firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild);
  23959. if (firstChild && /^(UL|OL|DL)$/.test(firstChild.nodeName)) {
  23960. root.insertBefore(dom.doc.createTextNode(nbsp), root.firstChild);
  23961. }
  23962. }
  23963. var rng = dom.createRng();
  23964. root.normalize();
  23965. if (root.hasChildNodes()) {
  23966. var walker = new DomTreeWalker(root, root);
  23967. while (node = walker.current()) {
  23968. if (isText$7(node)) {
  23969. rng.setStart(node, 0);
  23970. rng.setEnd(node, 0);
  23971. break;
  23972. }
  23973. if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) {
  23974. rng.setStartBefore(node);
  23975. rng.setEndBefore(node);
  23976. break;
  23977. }
  23978. lastNode = node;
  23979. node = walker.next();
  23980. }
  23981. if (!node) {
  23982. rng.setStart(lastNode, 0);
  23983. rng.setEnd(lastNode, 0);
  23984. }
  23985. } else {
  23986. if (isBr$5(root)) {
  23987. if (root.nextSibling && dom.isBlock(root.nextSibling)) {
  23988. rng.setStartBefore(root);
  23989. rng.setEndBefore(root);
  23990. } else {
  23991. rng.setStartAfter(root);
  23992. rng.setEndAfter(root);
  23993. }
  23994. } else {
  23995. rng.setStart(root, 0);
  23996. rng.setEnd(root, 0);
  23997. }
  23998. }
  23999. editor.selection.setRng(rng);
  24000. scrollRangeIntoView(editor, rng);
  24001. };
  24002. var getEditableRoot$1 = function (dom, node) {
  24003. var root = dom.getRoot();
  24004. var parent, editableRoot;
  24005. parent = node;
  24006. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  24007. if (dom.getContentEditable(parent) === 'true') {
  24008. editableRoot = parent;
  24009. }
  24010. parent = parent.parentNode;
  24011. }
  24012. return parent !== root ? editableRoot : root;
  24013. };
  24014. var getParentBlock = function (editor) {
  24015. return Optional.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
  24016. };
  24017. var getParentBlockName = function (editor) {
  24018. return getParentBlock(editor).fold(constant(''), function (parentBlock) {
  24019. return parentBlock.nodeName.toUpperCase();
  24020. });
  24021. };
  24022. var isListItemParentBlock = function (editor) {
  24023. return getParentBlock(editor).filter(function (elm) {
  24024. return isListItem(SugarElement.fromDom(elm));
  24025. }).isSome();
  24026. };
  24027. var hasFirstChild = function (elm, name) {
  24028. return elm.firstChild && elm.firstChild.nodeName === name;
  24029. };
  24030. var isFirstChild = function (elm) {
  24031. var _a;
  24032. return ((_a = elm.parentNode) === null || _a === void 0 ? void 0 : _a.firstChild) === elm;
  24033. };
  24034. var hasParent = function (elm, parentName) {
  24035. return elm && elm.parentNode && elm.parentNode.nodeName === parentName;
  24036. };
  24037. var isListBlock = function (elm) {
  24038. return elm && /^(OL|UL|LI)$/.test(elm.nodeName);
  24039. };
  24040. var isNestedList = function (elm) {
  24041. return isListBlock(elm) && isListBlock(elm.parentNode);
  24042. };
  24043. var getContainerBlock = function (containerBlock) {
  24044. var containerBlockParent = containerBlock.parentNode;
  24045. if (/^(LI|DT|DD)$/.test(containerBlockParent.nodeName)) {
  24046. return containerBlockParent;
  24047. }
  24048. return containerBlock;
  24049. };
  24050. var isFirstOrLastLi = function (containerBlock, parentBlock, first) {
  24051. var node = containerBlock[first ? 'firstChild' : 'lastChild'];
  24052. while (node) {
  24053. if (isElement$5(node)) {
  24054. break;
  24055. }
  24056. node = node[first ? 'nextSibling' : 'previousSibling'];
  24057. }
  24058. return node === parentBlock;
  24059. };
  24060. var insert$3 = function (editor, createNewBlock, containerBlock, parentBlock, newBlockName) {
  24061. var dom = editor.dom;
  24062. var rng = editor.selection.getRng();
  24063. if (containerBlock === editor.getBody()) {
  24064. return;
  24065. }
  24066. if (isNestedList(containerBlock)) {
  24067. newBlockName = 'LI';
  24068. }
  24069. var newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR');
  24070. if (isFirstOrLastLi(containerBlock, parentBlock, true) && isFirstOrLastLi(containerBlock, parentBlock, false)) {
  24071. if (hasParent(containerBlock, 'LI')) {
  24072. var containerBlockParent = getContainerBlock(containerBlock);
  24073. dom.insertAfter(newBlock, containerBlockParent);
  24074. if (isFirstChild(containerBlock)) {
  24075. dom.remove(containerBlockParent);
  24076. } else {
  24077. dom.remove(containerBlock);
  24078. }
  24079. } else {
  24080. dom.replace(newBlock, containerBlock);
  24081. }
  24082. } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
  24083. if (hasParent(containerBlock, 'LI')) {
  24084. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  24085. newBlock.appendChild(dom.doc.createTextNode(' '));
  24086. newBlock.appendChild(containerBlock);
  24087. } else {
  24088. containerBlock.parentNode.insertBefore(newBlock, containerBlock);
  24089. }
  24090. dom.remove(parentBlock);
  24091. } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
  24092. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  24093. dom.remove(parentBlock);
  24094. } else {
  24095. containerBlock = getContainerBlock(containerBlock);
  24096. var tmpRng = rng.cloneRange();
  24097. tmpRng.setStartAfter(parentBlock);
  24098. tmpRng.setEndAfter(containerBlock);
  24099. var fragment = tmpRng.extractContents();
  24100. if (newBlockName === 'LI' && hasFirstChild(fragment, 'LI')) {
  24101. newBlock = fragment.firstChild;
  24102. dom.insertAfter(fragment, containerBlock);
  24103. } else {
  24104. dom.insertAfter(fragment, containerBlock);
  24105. dom.insertAfter(newBlock, containerBlock);
  24106. }
  24107. dom.remove(parentBlock);
  24108. }
  24109. moveToCaretPosition(editor, newBlock);
  24110. };
  24111. var trimZwsp = function (fragment) {
  24112. each$k(descendants$1(SugarElement.fromDom(fragment), isText$8), function (text) {
  24113. var rawNode = text.dom;
  24114. rawNode.nodeValue = trim$2(rawNode.nodeValue);
  24115. });
  24116. };
  24117. var isEmptyAnchor = function (dom, elm) {
  24118. return elm && elm.nodeName === 'A' && dom.isEmpty(elm);
  24119. };
  24120. var isTableCell = function (node) {
  24121. return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  24122. };
  24123. var emptyBlock = function (elm) {
  24124. elm.innerHTML = '<br data-mce-bogus="1">';
  24125. };
  24126. var containerAndSiblingName = function (container, nodeName) {
  24127. return container.nodeName === nodeName || container.previousSibling && container.previousSibling.nodeName === nodeName;
  24128. };
  24129. var canSplitBlock = function (dom, node) {
  24130. return node && dom.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.getContentEditable(node) !== 'true';
  24131. };
  24132. var trimInlineElementsOnLeftSideOfBlock = function (dom, nonEmptyElementsMap, block) {
  24133. var node = block;
  24134. var firstChilds = [];
  24135. var i;
  24136. if (!node) {
  24137. return;
  24138. }
  24139. while (node = node.firstChild) {
  24140. if (dom.isBlock(node)) {
  24141. return;
  24142. }
  24143. if (isElement$5(node) && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  24144. firstChilds.push(node);
  24145. }
  24146. }
  24147. i = firstChilds.length;
  24148. while (i--) {
  24149. node = firstChilds[i];
  24150. if (!node.hasChildNodes() || node.firstChild === node.lastChild && node.firstChild.nodeValue === '') {
  24151. dom.remove(node);
  24152. } else {
  24153. if (isEmptyAnchor(dom, node)) {
  24154. dom.remove(node);
  24155. }
  24156. }
  24157. }
  24158. };
  24159. var normalizeZwspOffset = function (start, container, offset) {
  24160. if (isText$7(container) === false) {
  24161. return offset;
  24162. } else if (start) {
  24163. return offset === 1 && container.data.charAt(offset - 1) === ZWSP$1 ? 0 : offset;
  24164. } else {
  24165. return offset === container.data.length - 1 && container.data.charAt(offset) === ZWSP$1 ? container.data.length : offset;
  24166. }
  24167. };
  24168. var includeZwspInRange = function (rng) {
  24169. var newRng = rng.cloneRange();
  24170. newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
  24171. newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
  24172. return newRng;
  24173. };
  24174. var trimLeadingLineBreaks = function (node) {
  24175. do {
  24176. if (isText$7(node)) {
  24177. node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
  24178. }
  24179. node = node.firstChild;
  24180. } while (node);
  24181. };
  24182. var getEditableRoot = function (dom, node) {
  24183. var root = dom.getRoot();
  24184. var parent, editableRoot;
  24185. parent = node;
  24186. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  24187. if (dom.getContentEditable(parent) === 'true') {
  24188. editableRoot = parent;
  24189. }
  24190. parent = parent.parentNode;
  24191. }
  24192. return parent !== root ? editableRoot : root;
  24193. };
  24194. var applyAttributes = function (editor, node, forcedRootBlockAttrs) {
  24195. var dom = editor.dom;
  24196. Optional.from(forcedRootBlockAttrs.style).map(dom.parseStyle).each(function (attrStyles) {
  24197. var currentStyles = getAllRaw(SugarElement.fromDom(node));
  24198. var newStyles = __assign(__assign({}, currentStyles), attrStyles);
  24199. dom.setStyles(node, newStyles);
  24200. });
  24201. var attrClassesOpt = Optional.from(forcedRootBlockAttrs.class).map(function (attrClasses) {
  24202. return attrClasses.split(/\s+/);
  24203. });
  24204. var currentClassesOpt = Optional.from(node.className).map(function (currentClasses) {
  24205. return filter$4(currentClasses.split(/\s+/), function (clazz) {
  24206. return clazz !== '';
  24207. });
  24208. });
  24209. lift2(attrClassesOpt, currentClassesOpt, function (attrClasses, currentClasses) {
  24210. var filteredClasses = filter$4(currentClasses, function (clazz) {
  24211. return !contains$3(attrClasses, clazz);
  24212. });
  24213. var newClasses = __spreadArray(__spreadArray([], attrClasses, true), filteredClasses, true);
  24214. dom.setAttrib(node, 'class', newClasses.join(' '));
  24215. });
  24216. var appliedAttrs = [
  24217. 'style',
  24218. 'class'
  24219. ];
  24220. var remainingAttrs = filter$3(forcedRootBlockAttrs, function (_, attrs) {
  24221. return !contains$3(appliedAttrs, attrs);
  24222. });
  24223. dom.setAttribs(node, remainingAttrs);
  24224. };
  24225. var setForcedBlockAttrs = function (editor, node) {
  24226. var forcedRootBlockName = getForcedRootBlock(editor);
  24227. if (forcedRootBlockName && forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
  24228. var forcedRootBlockAttrs = getForcedRootBlockAttrs(editor);
  24229. applyAttributes(editor, node, forcedRootBlockAttrs);
  24230. }
  24231. };
  24232. var wrapSelfAndSiblingsInDefaultBlock = function (editor, newBlockName, rng, container, offset) {
  24233. var newBlock, parentBlock, startNode, node, next, rootBlockName;
  24234. var blockName = newBlockName || 'P';
  24235. var dom = editor.dom, editableRoot = getEditableRoot(dom, container);
  24236. parentBlock = dom.getParent(container, dom.isBlock);
  24237. if (!parentBlock || !canSplitBlock(dom, parentBlock)) {
  24238. parentBlock = parentBlock || editableRoot;
  24239. if (parentBlock === editor.getBody() || isTableCell(parentBlock)) {
  24240. rootBlockName = parentBlock.nodeName.toLowerCase();
  24241. } else {
  24242. rootBlockName = parentBlock.parentNode.nodeName.toLowerCase();
  24243. }
  24244. if (!parentBlock.hasChildNodes()) {
  24245. newBlock = dom.create(blockName);
  24246. setForcedBlockAttrs(editor, newBlock);
  24247. parentBlock.appendChild(newBlock);
  24248. rng.setStart(newBlock, 0);
  24249. rng.setEnd(newBlock, 0);
  24250. return newBlock;
  24251. }
  24252. node = container;
  24253. while (node.parentNode !== parentBlock) {
  24254. node = node.parentNode;
  24255. }
  24256. while (node && !dom.isBlock(node)) {
  24257. startNode = node;
  24258. node = node.previousSibling;
  24259. }
  24260. if (startNode && editor.schema.isValidChild(rootBlockName, blockName.toLowerCase())) {
  24261. newBlock = dom.create(blockName);
  24262. setForcedBlockAttrs(editor, newBlock);
  24263. startNode.parentNode.insertBefore(newBlock, startNode);
  24264. node = startNode;
  24265. while (node && !dom.isBlock(node)) {
  24266. next = node.nextSibling;
  24267. newBlock.appendChild(node);
  24268. node = next;
  24269. }
  24270. rng.setStart(container, offset);
  24271. rng.setEnd(container, offset);
  24272. }
  24273. }
  24274. return container;
  24275. };
  24276. var addBrToBlockIfNeeded = function (dom, block) {
  24277. block.normalize();
  24278. var lastChild = block.lastChild;
  24279. if (!lastChild || /^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true))) {
  24280. dom.add(block, 'br');
  24281. }
  24282. };
  24283. var insert$2 = function (editor, evt) {
  24284. var tmpRng, container, offset, parentBlock;
  24285. var newBlock, fragment, containerBlock, parentBlockName, newBlockName, isAfterLastNodeInContainer;
  24286. var dom = editor.dom;
  24287. var schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
  24288. var rng = editor.selection.getRng();
  24289. var createNewBlock = function (name) {
  24290. var node = container, block, clonedNode, caretNode;
  24291. var textInlineElements = schema.getTextInlineElements();
  24292. if (name || parentBlockName === 'TABLE' || parentBlockName === 'HR') {
  24293. block = dom.create(name || newBlockName);
  24294. } else {
  24295. block = parentBlock.cloneNode(false);
  24296. }
  24297. caretNode = block;
  24298. if (shouldKeepStyles(editor) === false) {
  24299. dom.setAttrib(block, 'style', null);
  24300. dom.setAttrib(block, 'class', null);
  24301. } else {
  24302. do {
  24303. if (textInlineElements[node.nodeName]) {
  24304. if (isCaretNode(node) || isBookmarkNode$1(node)) {
  24305. continue;
  24306. }
  24307. clonedNode = node.cloneNode(false);
  24308. dom.setAttrib(clonedNode, 'id', '');
  24309. if (block.hasChildNodes()) {
  24310. clonedNode.appendChild(block.firstChild);
  24311. block.appendChild(clonedNode);
  24312. } else {
  24313. caretNode = clonedNode;
  24314. block.appendChild(clonedNode);
  24315. }
  24316. }
  24317. } while ((node = node.parentNode) && node !== editableRoot);
  24318. }
  24319. setForcedBlockAttrs(editor, block);
  24320. emptyBlock(caretNode);
  24321. return block;
  24322. };
  24323. var isCaretAtStartOrEndOfBlock = function (start) {
  24324. var node, name;
  24325. var normalizedOffset = normalizeZwspOffset(start, container, offset);
  24326. if (isText$7(container) && (start ? normalizedOffset > 0 : normalizedOffset < container.nodeValue.length)) {
  24327. return false;
  24328. }
  24329. if (container.parentNode === parentBlock && isAfterLastNodeInContainer && !start) {
  24330. return true;
  24331. }
  24332. if (start && isElement$5(container) && container === parentBlock.firstChild) {
  24333. return true;
  24334. }
  24335. if (containerAndSiblingName(container, 'TABLE') || containerAndSiblingName(container, 'HR')) {
  24336. return isAfterLastNodeInContainer && !start || !isAfterLastNodeInContainer && start;
  24337. }
  24338. var walker = new DomTreeWalker(container, parentBlock);
  24339. if (isText$7(container)) {
  24340. if (start && normalizedOffset === 0) {
  24341. walker.prev();
  24342. } else if (!start && normalizedOffset === container.nodeValue.length) {
  24343. walker.next();
  24344. }
  24345. }
  24346. while (node = walker.current()) {
  24347. if (isElement$5(node)) {
  24348. if (!node.getAttribute('data-mce-bogus')) {
  24349. name = node.nodeName.toLowerCase();
  24350. if (nonEmptyElementsMap[name] && name !== 'br') {
  24351. return false;
  24352. }
  24353. }
  24354. } else if (isText$7(node) && !isWhitespaceText(node.nodeValue)) {
  24355. return false;
  24356. }
  24357. if (start) {
  24358. walker.prev();
  24359. } else {
  24360. walker.next();
  24361. }
  24362. }
  24363. return true;
  24364. };
  24365. var insertNewBlockAfter = function () {
  24366. if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName !== 'HGROUP') {
  24367. newBlock = createNewBlock(newBlockName);
  24368. } else {
  24369. newBlock = createNewBlock();
  24370. }
  24371. if (shouldEndContainerOnEmptyBlock(editor) && canSplitBlock(dom, containerBlock) && dom.isEmpty(parentBlock)) {
  24372. newBlock = dom.split(containerBlock, parentBlock);
  24373. } else {
  24374. dom.insertAfter(newBlock, parentBlock);
  24375. }
  24376. moveToCaretPosition(editor, newBlock);
  24377. };
  24378. normalize$2(dom, rng).each(function (normRng) {
  24379. rng.setStart(normRng.startContainer, normRng.startOffset);
  24380. rng.setEnd(normRng.endContainer, normRng.endOffset);
  24381. });
  24382. container = rng.startContainer;
  24383. offset = rng.startOffset;
  24384. newBlockName = getForcedRootBlock(editor);
  24385. var shiftKey = !!(evt && evt.shiftKey);
  24386. var ctrlKey = !!(evt && evt.ctrlKey);
  24387. if (isElement$5(container) && container.hasChildNodes()) {
  24388. isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  24389. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  24390. if (isAfterLastNodeInContainer && isText$7(container)) {
  24391. offset = container.nodeValue.length;
  24392. } else {
  24393. offset = 0;
  24394. }
  24395. }
  24396. var editableRoot = getEditableRoot(dom, container);
  24397. if (!editableRoot) {
  24398. return;
  24399. }
  24400. if (newBlockName && !shiftKey || !newBlockName && shiftKey) {
  24401. container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset);
  24402. }
  24403. parentBlock = dom.getParent(container, dom.isBlock);
  24404. containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  24405. parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : '';
  24406. var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  24407. if (containerBlockName === 'LI' && !ctrlKey) {
  24408. parentBlock = containerBlock;
  24409. containerBlock = containerBlock.parentNode;
  24410. parentBlockName = containerBlockName;
  24411. }
  24412. if (/^(LI|DT|DD)$/.test(parentBlockName)) {
  24413. if (dom.isEmpty(parentBlock)) {
  24414. insert$3(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
  24415. return;
  24416. }
  24417. }
  24418. if (newBlockName && parentBlock === editor.getBody()) {
  24419. return;
  24420. }
  24421. newBlockName = newBlockName || 'P';
  24422. if (isCaretContainerBlock$1(parentBlock)) {
  24423. newBlock = showCaretContainerBlock(parentBlock);
  24424. if (dom.isEmpty(parentBlock)) {
  24425. emptyBlock(parentBlock);
  24426. }
  24427. setForcedBlockAttrs(editor, newBlock);
  24428. moveToCaretPosition(editor, newBlock);
  24429. } else if (isCaretAtStartOrEndOfBlock()) {
  24430. insertNewBlockAfter();
  24431. } else if (isCaretAtStartOrEndOfBlock(true)) {
  24432. newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
  24433. moveToCaretPosition(editor, containerAndSiblingName(parentBlock, 'HR') ? newBlock : parentBlock);
  24434. } else {
  24435. tmpRng = includeZwspInRange(rng).cloneRange();
  24436. tmpRng.setEndAfter(parentBlock);
  24437. fragment = tmpRng.extractContents();
  24438. trimZwsp(fragment);
  24439. trimLeadingLineBreaks(fragment);
  24440. newBlock = fragment.firstChild;
  24441. dom.insertAfter(fragment, parentBlock);
  24442. trimInlineElementsOnLeftSideOfBlock(dom, nonEmptyElementsMap, newBlock);
  24443. addBrToBlockIfNeeded(dom, parentBlock);
  24444. if (dom.isEmpty(parentBlock)) {
  24445. emptyBlock(parentBlock);
  24446. }
  24447. newBlock.normalize();
  24448. if (dom.isEmpty(newBlock)) {
  24449. dom.remove(newBlock);
  24450. insertNewBlockAfter();
  24451. } else {
  24452. setForcedBlockAttrs(editor, newBlock);
  24453. moveToCaretPosition(editor, newBlock);
  24454. }
  24455. }
  24456. dom.setAttrib(newBlock, 'id', '');
  24457. editor.fire('NewBlock', { newBlock: newBlock });
  24458. };
  24459. var hasRightSideContent = function (schema, container, parentBlock) {
  24460. var walker = new DomTreeWalker(container, parentBlock);
  24461. var node;
  24462. var nonEmptyElementsMap = schema.getNonEmptyElements();
  24463. while (node = walker.next()) {
  24464. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
  24465. return true;
  24466. }
  24467. }
  24468. };
  24469. var moveSelectionToBr = function (editor, brElm, extraBr) {
  24470. var rng = editor.dom.createRng();
  24471. if (!extraBr) {
  24472. rng.setStartAfter(brElm);
  24473. rng.setEndAfter(brElm);
  24474. } else {
  24475. rng.setStartBefore(brElm);
  24476. rng.setEndBefore(brElm);
  24477. }
  24478. editor.selection.setRng(rng);
  24479. scrollRangeIntoView(editor, rng);
  24480. };
  24481. var insertBrAtCaret = function (editor, evt) {
  24482. var selection = editor.selection;
  24483. var dom = editor.dom;
  24484. var rng = selection.getRng();
  24485. var brElm;
  24486. var extraBr;
  24487. normalize$2(dom, rng).each(function (normRng) {
  24488. rng.setStart(normRng.startContainer, normRng.startOffset);
  24489. rng.setEnd(normRng.endContainer, normRng.endOffset);
  24490. });
  24491. var offset = rng.startOffset;
  24492. var container = rng.startContainer;
  24493. if (container.nodeType === 1 && container.hasChildNodes()) {
  24494. var isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  24495. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  24496. if (isAfterLastNodeInContainer && container.nodeType === 3) {
  24497. offset = container.nodeValue.length;
  24498. } else {
  24499. offset = 0;
  24500. }
  24501. }
  24502. var parentBlock = dom.getParent(container, dom.isBlock);
  24503. var containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  24504. var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  24505. var isControlKey = !!(evt && evt.ctrlKey);
  24506. if (containerBlockName === 'LI' && !isControlKey) {
  24507. parentBlock = containerBlock;
  24508. }
  24509. if (container && container.nodeType === 3 && offset >= container.nodeValue.length) {
  24510. if (!hasRightSideContent(editor.schema, container, parentBlock)) {
  24511. brElm = dom.create('br');
  24512. rng.insertNode(brElm);
  24513. rng.setStartAfter(brElm);
  24514. rng.setEndAfter(brElm);
  24515. extraBr = true;
  24516. }
  24517. }
  24518. brElm = dom.create('br');
  24519. rangeInsertNode(dom, rng, brElm);
  24520. moveSelectionToBr(editor, brElm, extraBr);
  24521. editor.undoManager.add();
  24522. };
  24523. var insertBrBefore = function (editor, inline) {
  24524. var br = SugarElement.fromTag('br');
  24525. before$4(SugarElement.fromDom(inline), br);
  24526. editor.undoManager.add();
  24527. };
  24528. var insertBrAfter = function (editor, inline) {
  24529. if (!hasBrAfter(editor.getBody(), inline)) {
  24530. after$3(SugarElement.fromDom(inline), SugarElement.fromTag('br'));
  24531. }
  24532. var br = SugarElement.fromTag('br');
  24533. after$3(SugarElement.fromDom(inline), br);
  24534. moveSelectionToBr(editor, br.dom, false);
  24535. editor.undoManager.add();
  24536. };
  24537. var isBeforeBr = function (pos) {
  24538. return isBr$5(pos.getNode());
  24539. };
  24540. var hasBrAfter = function (rootNode, startNode) {
  24541. if (isBeforeBr(CaretPosition.after(startNode))) {
  24542. return true;
  24543. } else {
  24544. return nextPosition(rootNode, CaretPosition.after(startNode)).map(function (pos) {
  24545. return isBr$5(pos.getNode());
  24546. }).getOr(false);
  24547. }
  24548. };
  24549. var isAnchorLink = function (elm) {
  24550. return elm && elm.nodeName === 'A' && 'href' in elm;
  24551. };
  24552. var isInsideAnchor = function (location) {
  24553. return location.fold(never, isAnchorLink, isAnchorLink, never);
  24554. };
  24555. var readInlineAnchorLocation = function (editor) {
  24556. var isInlineTarget$1 = curry(isInlineTarget, editor);
  24557. var position = CaretPosition.fromRangeStart(editor.selection.getRng());
  24558. return readLocation(isInlineTarget$1, editor.getBody(), position).filter(isInsideAnchor);
  24559. };
  24560. var insertBrOutsideAnchor = function (editor, location) {
  24561. location.fold(noop, curry(insertBrBefore, editor), curry(insertBrAfter, editor), noop);
  24562. };
  24563. var insert$1 = function (editor, evt) {
  24564. var anchorLocation = readInlineAnchorLocation(editor);
  24565. if (anchorLocation.isSome()) {
  24566. anchorLocation.each(curry(insertBrOutsideAnchor, editor));
  24567. } else {
  24568. insertBrAtCaret(editor, evt);
  24569. }
  24570. };
  24571. var matchesSelector = function (editor, selector) {
  24572. return getParentBlock(editor).filter(function (parentBlock) {
  24573. return selector.length > 0 && is$2(SugarElement.fromDom(parentBlock), selector);
  24574. }).isSome();
  24575. };
  24576. var shouldInsertBr = function (editor) {
  24577. return matchesSelector(editor, getBrNewLineSelector(editor));
  24578. };
  24579. var shouldBlockNewLine$1 = function (editor) {
  24580. return matchesSelector(editor, getNoNewLineSelector(editor));
  24581. };
  24582. var newLineAction = Adt.generate([
  24583. { br: [] },
  24584. { block: [] },
  24585. { none: [] }
  24586. ]);
  24587. var shouldBlockNewLine = function (editor, _shiftKey) {
  24588. return shouldBlockNewLine$1(editor);
  24589. };
  24590. var isBrMode = function (requiredState) {
  24591. return function (editor, _shiftKey) {
  24592. var brMode = getForcedRootBlock(editor) === '';
  24593. return brMode === requiredState;
  24594. };
  24595. };
  24596. var inListBlock = function (requiredState) {
  24597. return function (editor, _shiftKey) {
  24598. return isListItemParentBlock(editor) === requiredState;
  24599. };
  24600. };
  24601. var inBlock = function (blockName, requiredState) {
  24602. return function (editor, _shiftKey) {
  24603. var state = getParentBlockName(editor) === blockName.toUpperCase();
  24604. return state === requiredState;
  24605. };
  24606. };
  24607. var inPreBlock = function (requiredState) {
  24608. return inBlock('pre', requiredState);
  24609. };
  24610. var inSummaryBlock = function () {
  24611. return inBlock('summary', true);
  24612. };
  24613. var shouldPutBrInPre = function (requiredState) {
  24614. return function (editor, _shiftKey) {
  24615. return shouldPutBrInPre$1(editor) === requiredState;
  24616. };
  24617. };
  24618. var inBrContext = function (editor, _shiftKey) {
  24619. return shouldInsertBr(editor);
  24620. };
  24621. var hasShiftKey = function (_editor, shiftKey) {
  24622. return shiftKey;
  24623. };
  24624. var canInsertIntoEditableRoot = function (editor) {
  24625. var forcedRootBlock = getForcedRootBlock(editor);
  24626. var rootEditable = getEditableRoot$1(editor.dom, editor.selection.getStart());
  24627. return rootEditable && editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock ? forcedRootBlock : 'P');
  24628. };
  24629. var match = function (predicates, action) {
  24630. return function (editor, shiftKey) {
  24631. var isMatch = foldl(predicates, function (res, p) {
  24632. return res && p(editor, shiftKey);
  24633. }, true);
  24634. return isMatch ? Optional.some(action) : Optional.none();
  24635. };
  24636. };
  24637. var getAction = function (editor, evt) {
  24638. return evaluateUntil([
  24639. match([shouldBlockNewLine], newLineAction.none()),
  24640. match([inSummaryBlock()], newLineAction.br()),
  24641. match([
  24642. inPreBlock(true),
  24643. shouldPutBrInPre(false),
  24644. hasShiftKey
  24645. ], newLineAction.br()),
  24646. match([
  24647. inPreBlock(true),
  24648. shouldPutBrInPre(false)
  24649. ], newLineAction.block()),
  24650. match([
  24651. inPreBlock(true),
  24652. shouldPutBrInPre(true),
  24653. hasShiftKey
  24654. ], newLineAction.block()),
  24655. match([
  24656. inPreBlock(true),
  24657. shouldPutBrInPre(true)
  24658. ], newLineAction.br()),
  24659. match([
  24660. inListBlock(true),
  24661. hasShiftKey
  24662. ], newLineAction.br()),
  24663. match([inListBlock(true)], newLineAction.block()),
  24664. match([
  24665. isBrMode(true),
  24666. hasShiftKey,
  24667. canInsertIntoEditableRoot
  24668. ], newLineAction.block()),
  24669. match([isBrMode(true)], newLineAction.br()),
  24670. match([inBrContext], newLineAction.br()),
  24671. match([
  24672. isBrMode(false),
  24673. hasShiftKey
  24674. ], newLineAction.br()),
  24675. match([canInsertIntoEditableRoot], newLineAction.block())
  24676. ], [
  24677. editor,
  24678. !!(evt && evt.shiftKey)
  24679. ]).getOr(newLineAction.none());
  24680. };
  24681. var insert = function (editor, evt) {
  24682. getAction(editor, evt).fold(function () {
  24683. insert$1(editor, evt);
  24684. }, function () {
  24685. insert$2(editor, evt);
  24686. }, noop);
  24687. };
  24688. var handleEnterKeyEvent = function (editor, event) {
  24689. if (event.isDefaultPrevented()) {
  24690. return;
  24691. }
  24692. event.preventDefault();
  24693. endTypingLevelIgnoreLocks(editor.undoManager);
  24694. editor.undoManager.transact(function () {
  24695. if (editor.selection.isCollapsed() === false) {
  24696. editor.execCommand('Delete');
  24697. }
  24698. insert(editor, event);
  24699. });
  24700. };
  24701. var setup$9 = function (editor) {
  24702. editor.on('keydown', function (event) {
  24703. if (event.keyCode === VK.ENTER) {
  24704. handleEnterKeyEvent(editor, event);
  24705. }
  24706. });
  24707. };
  24708. var executeKeydownOverride$1 = function (editor, caret, evt) {
  24709. execute([
  24710. {
  24711. keyCode: VK.END,
  24712. action: action(moveToLineEndPoint$1, editor, true)
  24713. },
  24714. {
  24715. keyCode: VK.HOME,
  24716. action: action(moveToLineEndPoint$1, editor, false)
  24717. },
  24718. {
  24719. keyCode: VK.END,
  24720. action: action(moveToLineEndPoint, editor, true)
  24721. },
  24722. {
  24723. keyCode: VK.HOME,
  24724. action: action(moveToLineEndPoint, editor, false)
  24725. },
  24726. {
  24727. keyCode: VK.END,
  24728. action: action(moveToLineEndPoint$2, editor, true, caret)
  24729. },
  24730. {
  24731. keyCode: VK.HOME,
  24732. action: action(moveToLineEndPoint$2, editor, false, caret)
  24733. }
  24734. ], evt).each(function (_) {
  24735. evt.preventDefault();
  24736. });
  24737. };
  24738. var setup$8 = function (editor, caret) {
  24739. editor.on('keydown', function (evt) {
  24740. if (evt.isDefaultPrevented() === false) {
  24741. executeKeydownOverride$1(editor, caret, evt);
  24742. }
  24743. });
  24744. };
  24745. var browser = detect().browser;
  24746. var setupIeInput = function (editor) {
  24747. var keypressThrotter = first(function () {
  24748. if (!editor.composing) {
  24749. normalizeNbspsInEditor(editor);
  24750. }
  24751. }, 0);
  24752. if (browser.isIE()) {
  24753. editor.on('keypress', function (_e) {
  24754. keypressThrotter.throttle();
  24755. });
  24756. editor.on('remove', function (_e) {
  24757. keypressThrotter.cancel();
  24758. });
  24759. }
  24760. };
  24761. var setup$7 = function (editor) {
  24762. setupIeInput(editor);
  24763. editor.on('input', function (e) {
  24764. if (e.isComposing === false) {
  24765. normalizeNbspsInEditor(editor);
  24766. }
  24767. });
  24768. };
  24769. var platform = detect();
  24770. var executeKeyupAction = function (editor, caret, evt) {
  24771. execute([
  24772. {
  24773. keyCode: VK.PAGE_UP,
  24774. action: action(moveToLineEndPoint$2, editor, false, caret)
  24775. },
  24776. {
  24777. keyCode: VK.PAGE_DOWN,
  24778. action: action(moveToLineEndPoint$2, editor, true, caret)
  24779. }
  24780. ], evt);
  24781. };
  24782. var stopImmediatePropagation = function (e) {
  24783. return e.stopImmediatePropagation();
  24784. };
  24785. var isPageUpDown = function (evt) {
  24786. return evt.keyCode === VK.PAGE_UP || evt.keyCode === VK.PAGE_DOWN;
  24787. };
  24788. var setNodeChangeBlocker = function (blocked, editor, block) {
  24789. if (block && !blocked.get()) {
  24790. editor.on('NodeChange', stopImmediatePropagation, true);
  24791. } else if (!block && blocked.get()) {
  24792. editor.off('NodeChange', stopImmediatePropagation);
  24793. }
  24794. blocked.set(block);
  24795. };
  24796. var setup$6 = function (editor, caret) {
  24797. if (platform.os.isOSX()) {
  24798. return;
  24799. }
  24800. var blocked = Cell(false);
  24801. editor.on('keydown', function (evt) {
  24802. if (isPageUpDown(evt)) {
  24803. setNodeChangeBlocker(blocked, editor, true);
  24804. }
  24805. });
  24806. editor.on('keyup', function (evt) {
  24807. if (evt.isDefaultPrevented() === false) {
  24808. executeKeyupAction(editor, caret, evt);
  24809. }
  24810. if (isPageUpDown(evt) && blocked.get()) {
  24811. setNodeChangeBlocker(blocked, editor, false);
  24812. editor.nodeChanged();
  24813. }
  24814. });
  24815. };
  24816. var insertTextAtPosition = function (text, pos) {
  24817. var container = pos.container();
  24818. var offset = pos.offset();
  24819. if (isText$7(container)) {
  24820. container.insertData(offset, text);
  24821. return Optional.some(CaretPosition(container, offset + text.length));
  24822. } else {
  24823. return getElementFromPosition(pos).map(function (elm) {
  24824. var textNode = SugarElement.fromText(text);
  24825. if (pos.isAtEnd()) {
  24826. after$3(elm, textNode);
  24827. } else {
  24828. before$4(elm, textNode);
  24829. }
  24830. return CaretPosition(textNode.dom, text.length);
  24831. });
  24832. }
  24833. };
  24834. var insertNbspAtPosition = curry(insertTextAtPosition, nbsp);
  24835. var insertSpaceAtPosition = curry(insertTextAtPosition, ' ');
  24836. var locationToCaretPosition = function (root) {
  24837. return function (location) {
  24838. return location.fold(function (element) {
  24839. return prevPosition(root.dom, CaretPosition.before(element));
  24840. }, function (element) {
  24841. return firstPositionIn(element);
  24842. }, function (element) {
  24843. return lastPositionIn(element);
  24844. }, function (element) {
  24845. return nextPosition(root.dom, CaretPosition.after(element));
  24846. });
  24847. };
  24848. };
  24849. var insertInlineBoundarySpaceOrNbsp = function (root, pos) {
  24850. return function (checkPos) {
  24851. return needsToHaveNbsp(root, checkPos) ? insertNbspAtPosition(pos) : insertSpaceAtPosition(pos);
  24852. };
  24853. };
  24854. var setSelection = function (editor) {
  24855. return function (pos) {
  24856. editor.selection.setRng(pos.toRange());
  24857. editor.nodeChanged();
  24858. return true;
  24859. };
  24860. };
  24861. var insertSpaceOrNbspAtSelection = function (editor) {
  24862. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  24863. var root = SugarElement.fromDom(editor.getBody());
  24864. if (editor.selection.isCollapsed()) {
  24865. var isInlineTarget$1 = curry(isInlineTarget, editor);
  24866. var caretPosition = CaretPosition.fromRangeStart(editor.selection.getRng());
  24867. return readLocation(isInlineTarget$1, editor.getBody(), caretPosition).bind(locationToCaretPosition(root)).bind(insertInlineBoundarySpaceOrNbsp(root, pos)).exists(setSelection(editor));
  24868. } else {
  24869. return false;
  24870. }
  24871. };
  24872. var executeKeydownOverride = function (editor, evt) {
  24873. execute([{
  24874. keyCode: VK.SPACEBAR,
  24875. action: action(insertSpaceOrNbspAtSelection, editor)
  24876. }], evt).each(function (_) {
  24877. evt.preventDefault();
  24878. });
  24879. };
  24880. var setup$5 = function (editor) {
  24881. editor.on('keydown', function (evt) {
  24882. if (evt.isDefaultPrevented() === false) {
  24883. executeKeydownOverride(editor, evt);
  24884. }
  24885. });
  24886. };
  24887. var registerKeyboardOverrides = function (editor) {
  24888. var caret = setupSelectedState(editor);
  24889. setup$c(editor);
  24890. setup$b(editor, caret);
  24891. setup$a(editor, caret);
  24892. setup$9(editor);
  24893. setup$5(editor);
  24894. setup$7(editor);
  24895. setup$8(editor, caret);
  24896. setup$6(editor, caret);
  24897. return caret;
  24898. };
  24899. var setup$4 = function (editor) {
  24900. if (!isRtc(editor)) {
  24901. return registerKeyboardOverrides(editor);
  24902. } else {
  24903. return Cell(null);
  24904. }
  24905. };
  24906. var NodeChange = function () {
  24907. function NodeChange(editor) {
  24908. this.lastPath = [];
  24909. this.editor = editor;
  24910. var lastRng;
  24911. var self = this;
  24912. if (!('onselectionchange' in editor.getDoc())) {
  24913. editor.on('NodeChange click mouseup keyup focus', function (e) {
  24914. var nativeRng = editor.selection.getRng();
  24915. var fakeRng = {
  24916. startContainer: nativeRng.startContainer,
  24917. startOffset: nativeRng.startOffset,
  24918. endContainer: nativeRng.endContainer,
  24919. endOffset: nativeRng.endOffset
  24920. };
  24921. if (e.type === 'nodechange' || !isEq$4(fakeRng, lastRng)) {
  24922. editor.fire('SelectionChange');
  24923. }
  24924. lastRng = fakeRng;
  24925. });
  24926. }
  24927. editor.on('contextmenu', function () {
  24928. editor.fire('SelectionChange');
  24929. });
  24930. editor.on('SelectionChange', function () {
  24931. var startElm = editor.selection.getStart(true);
  24932. if (!startElm || !Env.range && editor.selection.isCollapsed()) {
  24933. return;
  24934. }
  24935. if (hasAnyRanges(editor) && !self.isSameElementPath(startElm) && editor.dom.isChildOf(startElm, editor.getBody())) {
  24936. editor.nodeChanged({ selectionChange: true });
  24937. }
  24938. });
  24939. editor.on('mouseup', function (e) {
  24940. if (!e.isDefaultPrevented() && hasAnyRanges(editor)) {
  24941. if (editor.selection.getNode().nodeName === 'IMG') {
  24942. Delay.setEditorTimeout(editor, function () {
  24943. editor.nodeChanged();
  24944. });
  24945. } else {
  24946. editor.nodeChanged();
  24947. }
  24948. }
  24949. });
  24950. }
  24951. NodeChange.prototype.nodeChanged = function (args) {
  24952. var selection = this.editor.selection;
  24953. var node, parents, root;
  24954. if (this.editor.initialized && selection && !shouldDisableNodeChange(this.editor) && !this.editor.mode.isReadOnly()) {
  24955. root = this.editor.getBody();
  24956. node = selection.getStart(true) || root;
  24957. if (node.ownerDocument !== this.editor.getDoc() || !this.editor.dom.isChildOf(node, root)) {
  24958. node = root;
  24959. }
  24960. parents = [];
  24961. this.editor.dom.getParent(node, function (node) {
  24962. if (node === root) {
  24963. return true;
  24964. }
  24965. parents.push(node);
  24966. });
  24967. args = args || {};
  24968. args.element = node;
  24969. args.parents = parents;
  24970. this.editor.fire('NodeChange', args);
  24971. }
  24972. };
  24973. NodeChange.prototype.isSameElementPath = function (startElm) {
  24974. var i;
  24975. var currentPath = this.editor.$(startElm).parentsUntil(this.editor.getBody()).add(startElm);
  24976. if (currentPath.length === this.lastPath.length) {
  24977. for (i = currentPath.length; i >= 0; i--) {
  24978. if (currentPath[i] !== this.lastPath[i]) {
  24979. break;
  24980. }
  24981. }
  24982. if (i === -1) {
  24983. this.lastPath = currentPath;
  24984. return true;
  24985. }
  24986. }
  24987. this.lastPath = currentPath;
  24988. return false;
  24989. };
  24990. return NodeChange;
  24991. }();
  24992. var preventSummaryToggle = function (editor) {
  24993. editor.on('click', function (e) {
  24994. if (editor.dom.getParent(e.target, 'details')) {
  24995. e.preventDefault();
  24996. }
  24997. });
  24998. };
  24999. var filterDetails = function (editor) {
  25000. editor.parser.addNodeFilter('details', function (elms) {
  25001. each$k(elms, function (details) {
  25002. details.attr('data-mce-open', details.attr('open'));
  25003. details.attr('open', 'open');
  25004. });
  25005. });
  25006. editor.serializer.addNodeFilter('details', function (elms) {
  25007. each$k(elms, function (details) {
  25008. var open = details.attr('data-mce-open');
  25009. details.attr('open', isString$1(open) ? open : null);
  25010. details.attr('data-mce-open', null);
  25011. });
  25012. });
  25013. };
  25014. var setup$3 = function (editor) {
  25015. preventSummaryToggle(editor);
  25016. filterDetails(editor);
  25017. };
  25018. var isTextBlockNode = function (node) {
  25019. return isElement$5(node) && isTextBlock$2(SugarElement.fromDom(node));
  25020. };
  25021. var normalizeSelection = function (editor) {
  25022. var rng = editor.selection.getRng();
  25023. var startPos = CaretPosition.fromRangeStart(rng);
  25024. var endPos = CaretPosition.fromRangeEnd(rng);
  25025. if (CaretPosition.isElementPosition(startPos)) {
  25026. var container = startPos.container();
  25027. if (isTextBlockNode(container)) {
  25028. firstPositionIn(container).each(function (pos) {
  25029. return rng.setStart(pos.container(), pos.offset());
  25030. });
  25031. }
  25032. }
  25033. if (CaretPosition.isElementPosition(endPos)) {
  25034. var container = startPos.container();
  25035. if (isTextBlockNode(container)) {
  25036. lastPositionIn(container).each(function (pos) {
  25037. return rng.setEnd(pos.container(), pos.offset());
  25038. });
  25039. }
  25040. }
  25041. editor.selection.setRng(normalize(rng));
  25042. };
  25043. var setup$2 = function (editor) {
  25044. editor.on('click', function (e) {
  25045. if (e.detail >= 3) {
  25046. normalizeSelection(editor);
  25047. }
  25048. });
  25049. };
  25050. var getAbsolutePosition = function (elm) {
  25051. var clientRect = elm.getBoundingClientRect();
  25052. var doc = elm.ownerDocument;
  25053. var docElem = doc.documentElement;
  25054. var win = doc.defaultView;
  25055. return {
  25056. top: clientRect.top + win.pageYOffset - docElem.clientTop,
  25057. left: clientRect.left + win.pageXOffset - docElem.clientLeft
  25058. };
  25059. };
  25060. var getBodyPosition = function (editor) {
  25061. return editor.inline ? getAbsolutePosition(editor.getBody()) : {
  25062. left: 0,
  25063. top: 0
  25064. };
  25065. };
  25066. var getScrollPosition = function (editor) {
  25067. var body = editor.getBody();
  25068. return editor.inline ? {
  25069. left: body.scrollLeft,
  25070. top: body.scrollTop
  25071. } : {
  25072. left: 0,
  25073. top: 0
  25074. };
  25075. };
  25076. var getBodyScroll = function (editor) {
  25077. var body = editor.getBody(), docElm = editor.getDoc().documentElement;
  25078. var inlineScroll = {
  25079. left: body.scrollLeft,
  25080. top: body.scrollTop
  25081. };
  25082. var iframeScroll = {
  25083. left: body.scrollLeft || docElm.scrollLeft,
  25084. top: body.scrollTop || docElm.scrollTop
  25085. };
  25086. return editor.inline ? inlineScroll : iframeScroll;
  25087. };
  25088. var getMousePosition = function (editor, event) {
  25089. if (event.target.ownerDocument !== editor.getDoc()) {
  25090. var iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
  25091. var scrollPosition = getBodyScroll(editor);
  25092. return {
  25093. left: event.pageX - iframePosition.left + scrollPosition.left,
  25094. top: event.pageY - iframePosition.top + scrollPosition.top
  25095. };
  25096. }
  25097. return {
  25098. left: event.pageX,
  25099. top: event.pageY
  25100. };
  25101. };
  25102. var calculatePosition = function (bodyPosition, scrollPosition, mousePosition) {
  25103. return {
  25104. pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
  25105. pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
  25106. };
  25107. };
  25108. var calc = function (editor, event) {
  25109. return calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
  25110. };
  25111. var isContentEditableFalse$1 = isContentEditableFalse$b, isContentEditableTrue$1 = isContentEditableTrue$4;
  25112. var isDraggable = function (rootElm, elm) {
  25113. return isContentEditableFalse$1(elm) && elm !== rootElm;
  25114. };
  25115. var isValidDropTarget = function (editor, targetElement, dragElement) {
  25116. if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
  25117. return false;
  25118. }
  25119. return !isContentEditableFalse$1(targetElement);
  25120. };
  25121. var cloneElement = function (elm) {
  25122. var cloneElm = elm.cloneNode(true);
  25123. cloneElm.removeAttribute('data-mce-selected');
  25124. return cloneElm;
  25125. };
  25126. var createGhost = function (editor, elm, width, height) {
  25127. var dom = editor.dom;
  25128. var clonedElm = elm.cloneNode(true);
  25129. dom.setStyles(clonedElm, {
  25130. width: width,
  25131. height: height
  25132. });
  25133. dom.setAttrib(clonedElm, 'data-mce-selected', null);
  25134. var ghostElm = dom.create('div', {
  25135. 'class': 'mce-drag-container',
  25136. 'data-mce-bogus': 'all',
  25137. 'unselectable': 'on',
  25138. 'contenteditable': 'false'
  25139. });
  25140. dom.setStyles(ghostElm, {
  25141. position: 'absolute',
  25142. opacity: 0.5,
  25143. overflow: 'hidden',
  25144. border: 0,
  25145. padding: 0,
  25146. margin: 0,
  25147. width: width,
  25148. height: height
  25149. });
  25150. dom.setStyles(clonedElm, {
  25151. margin: 0,
  25152. boxSizing: 'border-box'
  25153. });
  25154. ghostElm.appendChild(clonedElm);
  25155. return ghostElm;
  25156. };
  25157. var appendGhostToBody = function (ghostElm, bodyElm) {
  25158. if (ghostElm.parentNode !== bodyElm) {
  25159. bodyElm.appendChild(ghostElm);
  25160. }
  25161. };
  25162. var moveGhost = function (ghostElm, position, width, height, maxX, maxY) {
  25163. var overflowX = 0, overflowY = 0;
  25164. ghostElm.style.left = position.pageX + 'px';
  25165. ghostElm.style.top = position.pageY + 'px';
  25166. if (position.pageX + width > maxX) {
  25167. overflowX = position.pageX + width - maxX;
  25168. }
  25169. if (position.pageY + height > maxY) {
  25170. overflowY = position.pageY + height - maxY;
  25171. }
  25172. ghostElm.style.width = width - overflowX + 'px';
  25173. ghostElm.style.height = height - overflowY + 'px';
  25174. };
  25175. var removeElement = function (elm) {
  25176. if (elm && elm.parentNode) {
  25177. elm.parentNode.removeChild(elm);
  25178. }
  25179. };
  25180. var isLeftMouseButtonPressed = function (e) {
  25181. return e.button === 0;
  25182. };
  25183. var applyRelPos = function (state, position) {
  25184. return {
  25185. pageX: position.pageX - state.relX,
  25186. pageY: position.pageY + 5
  25187. };
  25188. };
  25189. var start = function (state, editor) {
  25190. return function (e) {
  25191. if (isLeftMouseButtonPressed(e)) {
  25192. var ceElm = find$3(editor.dom.getParents(e.target), or(isContentEditableFalse$1, isContentEditableTrue$1)).getOr(null);
  25193. if (isDraggable(editor.getBody(), ceElm)) {
  25194. var elmPos = editor.dom.getPos(ceElm);
  25195. var bodyElm = editor.getBody();
  25196. var docElm = editor.getDoc().documentElement;
  25197. state.set({
  25198. element: ceElm,
  25199. dragging: false,
  25200. screenX: e.screenX,
  25201. screenY: e.screenY,
  25202. maxX: (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2,
  25203. maxY: (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2,
  25204. relX: e.pageX - elmPos.x,
  25205. relY: e.pageY - elmPos.y,
  25206. width: ceElm.offsetWidth,
  25207. height: ceElm.offsetHeight,
  25208. ghost: createGhost(editor, ceElm, ceElm.offsetWidth, ceElm.offsetHeight)
  25209. });
  25210. }
  25211. }
  25212. };
  25213. };
  25214. var move = function (state, editor) {
  25215. var throttledPlaceCaretAt = Delay.throttle(function (clientX, clientY) {
  25216. editor._selectionOverrides.hideFakeCaret();
  25217. editor.selection.placeCaretAt(clientX, clientY);
  25218. }, 0);
  25219. editor.on('remove', throttledPlaceCaretAt.stop);
  25220. return function (e) {
  25221. return state.on(function (state) {
  25222. var movement = Math.max(Math.abs(e.screenX - state.screenX), Math.abs(e.screenY - state.screenY));
  25223. if (!state.dragging && movement > 10) {
  25224. var args = editor.fire('dragstart', { target: state.element });
  25225. if (args.isDefaultPrevented()) {
  25226. return;
  25227. }
  25228. state.dragging = true;
  25229. editor.focus();
  25230. }
  25231. if (state.dragging) {
  25232. var targetPos = applyRelPos(state, calc(editor, e));
  25233. appendGhostToBody(state.ghost, editor.getBody());
  25234. moveGhost(state.ghost, targetPos, state.width, state.height, state.maxX, state.maxY);
  25235. throttledPlaceCaretAt(e.clientX, e.clientY);
  25236. }
  25237. });
  25238. };
  25239. };
  25240. var getRawTarget = function (selection) {
  25241. var rng = selection.getSel().getRangeAt(0);
  25242. var startContainer = rng.startContainer;
  25243. return startContainer.nodeType === 3 ? startContainer.parentNode : startContainer;
  25244. };
  25245. var drop = function (state, editor) {
  25246. return function (e) {
  25247. state.on(function (state) {
  25248. if (state.dragging) {
  25249. if (isValidDropTarget(editor, getRawTarget(editor.selection), state.element)) {
  25250. var targetClone_1 = cloneElement(state.element);
  25251. var args = editor.fire('drop', {
  25252. clientX: e.clientX,
  25253. clientY: e.clientY
  25254. });
  25255. if (!args.isDefaultPrevented()) {
  25256. editor.undoManager.transact(function () {
  25257. removeElement(state.element);
  25258. editor.insertContent(editor.dom.getOuterHTML(targetClone_1));
  25259. editor._selectionOverrides.hideFakeCaret();
  25260. });
  25261. }
  25262. }
  25263. editor.fire('dragend');
  25264. }
  25265. });
  25266. removeDragState(state);
  25267. };
  25268. };
  25269. var stop = function (state, editor) {
  25270. return function () {
  25271. state.on(function (state) {
  25272. if (state.dragging) {
  25273. editor.fire('dragend');
  25274. }
  25275. });
  25276. removeDragState(state);
  25277. };
  25278. };
  25279. var removeDragState = function (state) {
  25280. state.on(function (state) {
  25281. removeElement(state.ghost);
  25282. });
  25283. state.clear();
  25284. };
  25285. var bindFakeDragEvents = function (editor) {
  25286. var state = value();
  25287. var pageDom = DOMUtils.DOM;
  25288. var rootDocument = document;
  25289. var dragStartHandler = start(state, editor);
  25290. var dragHandler = move(state, editor);
  25291. var dropHandler = drop(state, editor);
  25292. var dragEndHandler = stop(state, editor);
  25293. editor.on('mousedown', dragStartHandler);
  25294. editor.on('mousemove', dragHandler);
  25295. editor.on('mouseup', dropHandler);
  25296. pageDom.bind(rootDocument, 'mousemove', dragHandler);
  25297. pageDom.bind(rootDocument, 'mouseup', dragEndHandler);
  25298. editor.on('remove', function () {
  25299. pageDom.unbind(rootDocument, 'mousemove', dragHandler);
  25300. pageDom.unbind(rootDocument, 'mouseup', dragEndHandler);
  25301. });
  25302. editor.on('keydown', function (e) {
  25303. if (e.keyCode === VK.ESC) {
  25304. dragEndHandler();
  25305. }
  25306. });
  25307. };
  25308. var blockIeDrop = function (editor) {
  25309. editor.on('drop', function (e) {
  25310. var realTarget = typeof e.clientX !== 'undefined' ? editor.getDoc().elementFromPoint(e.clientX, e.clientY) : null;
  25311. if (isContentEditableFalse$1(realTarget) || editor.dom.getContentEditableParent(realTarget) === 'false') {
  25312. e.preventDefault();
  25313. }
  25314. });
  25315. };
  25316. var blockUnsupportedFileDrop = function (editor) {
  25317. var preventFileDrop = function (e) {
  25318. if (!e.isDefaultPrevented()) {
  25319. var dataTransfer = e.dataTransfer;
  25320. if (dataTransfer && (contains$3(dataTransfer.types, 'Files') || dataTransfer.files.length > 0)) {
  25321. e.preventDefault();
  25322. if (e.type === 'drop') {
  25323. displayError(editor, 'Dropped file type is not supported');
  25324. }
  25325. }
  25326. }
  25327. };
  25328. var preventFileDropIfUIElement = function (e) {
  25329. if (isUIElement(editor, e.target)) {
  25330. preventFileDrop(e);
  25331. }
  25332. };
  25333. var setup = function () {
  25334. var pageDom = DOMUtils.DOM;
  25335. var dom = editor.dom;
  25336. var doc = document;
  25337. var editorRoot = editor.inline ? editor.getBody() : editor.getDoc();
  25338. var eventNames = [
  25339. 'drop',
  25340. 'dragover'
  25341. ];
  25342. each$k(eventNames, function (name) {
  25343. pageDom.bind(doc, name, preventFileDropIfUIElement);
  25344. dom.bind(editorRoot, name, preventFileDrop);
  25345. });
  25346. editor.on('remove', function () {
  25347. each$k(eventNames, function (name) {
  25348. pageDom.unbind(doc, name, preventFileDropIfUIElement);
  25349. dom.unbind(editorRoot, name, preventFileDrop);
  25350. });
  25351. });
  25352. };
  25353. editor.on('init', function () {
  25354. Delay.setEditorTimeout(editor, setup, 0);
  25355. });
  25356. };
  25357. var init$2 = function (editor) {
  25358. bindFakeDragEvents(editor);
  25359. blockIeDrop(editor);
  25360. if (shouldBlockUnsupportedDrop(editor)) {
  25361. blockUnsupportedFileDrop(editor);
  25362. }
  25363. };
  25364. var setup$1 = function (editor) {
  25365. var renderFocusCaret = first(function () {
  25366. if (!editor.removed && editor.getBody().contains(document.activeElement)) {
  25367. var rng = editor.selection.getRng();
  25368. if (rng.collapsed) {
  25369. var caretRange = renderRangeCaret(editor, rng, false);
  25370. editor.selection.setRng(caretRange);
  25371. }
  25372. }
  25373. }, 0);
  25374. editor.on('focus', function () {
  25375. renderFocusCaret.throttle();
  25376. });
  25377. editor.on('blur', function () {
  25378. renderFocusCaret.cancel();
  25379. });
  25380. };
  25381. var setup = function (editor) {
  25382. editor.on('init', function () {
  25383. editor.on('focusin', function (e) {
  25384. var target = e.target;
  25385. if (isMedia$2(target)) {
  25386. var ceRoot = getContentEditableRoot$1(editor.getBody(), target);
  25387. var node = isContentEditableFalse$b(ceRoot) ? ceRoot : target;
  25388. if (editor.selection.getNode() !== node) {
  25389. selectNode(editor, node).each(function (rng) {
  25390. return editor.selection.setRng(rng);
  25391. });
  25392. }
  25393. }
  25394. });
  25395. });
  25396. };
  25397. var isContentEditableTrue = isContentEditableTrue$4;
  25398. var isContentEditableFalse = isContentEditableFalse$b;
  25399. var getContentEditableRoot = function (editor, node) {
  25400. return getContentEditableRoot$1(editor.getBody(), node);
  25401. };
  25402. var SelectionOverrides = function (editor) {
  25403. var selection = editor.selection, dom = editor.dom;
  25404. var isBlock = dom.isBlock;
  25405. var rootNode = editor.getBody();
  25406. var fakeCaret = FakeCaret(editor, rootNode, isBlock, function () {
  25407. return hasFocus(editor);
  25408. });
  25409. var realSelectionId = 'sel-' + dom.uniqueId();
  25410. var elementSelectionAttr = 'data-mce-selected';
  25411. var selectedElement;
  25412. var isFakeSelectionElement = function (node) {
  25413. return dom.hasClass(node, 'mce-offscreen-selection');
  25414. };
  25415. var isFakeSelectionTargetElement = function (node) {
  25416. return node !== rootNode && (isContentEditableFalse(node) || isMedia$2(node)) && dom.isChildOf(node, rootNode);
  25417. };
  25418. var isNearFakeSelectionElement = function (pos) {
  25419. return isBeforeContentEditableFalse(pos) || isAfterContentEditableFalse(pos) || isBeforeMedia(pos) || isAfterMedia(pos);
  25420. };
  25421. var getRealSelectionElement = function () {
  25422. var container = dom.get(realSelectionId);
  25423. return container ? container.getElementsByTagName('*')[0] : container;
  25424. };
  25425. var setRange = function (range) {
  25426. if (range) {
  25427. selection.setRng(range);
  25428. }
  25429. };
  25430. var getRange = selection.getRng;
  25431. var showCaret = function (direction, node, before, scrollIntoView) {
  25432. if (scrollIntoView === void 0) {
  25433. scrollIntoView = true;
  25434. }
  25435. var e = editor.fire('ShowCaret', {
  25436. target: node,
  25437. direction: direction,
  25438. before: before
  25439. });
  25440. if (e.isDefaultPrevented()) {
  25441. return null;
  25442. }
  25443. if (scrollIntoView) {
  25444. selection.scrollIntoView(node, direction === -1);
  25445. }
  25446. return fakeCaret.show(before, node);
  25447. };
  25448. var showBlockCaretContainer = function (blockCaretContainer) {
  25449. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  25450. showCaretContainerBlock(blockCaretContainer);
  25451. setRange(getRange());
  25452. selection.scrollIntoView(blockCaretContainer);
  25453. }
  25454. };
  25455. var registerEvents = function () {
  25456. editor.on('mouseup', function (e) {
  25457. var range = getRange();
  25458. if (range.collapsed && isXYInContentArea(editor, e.clientX, e.clientY)) {
  25459. renderCaretAtRange(editor, range, false).each(setRange);
  25460. }
  25461. });
  25462. editor.on('click', function (e) {
  25463. var contentEditableRoot = getContentEditableRoot(editor, e.target);
  25464. if (contentEditableRoot) {
  25465. if (isContentEditableFalse(contentEditableRoot)) {
  25466. e.preventDefault();
  25467. editor.focus();
  25468. }
  25469. if (isContentEditableTrue(contentEditableRoot)) {
  25470. if (dom.isChildOf(contentEditableRoot, selection.getNode())) {
  25471. removeElementSelection();
  25472. }
  25473. }
  25474. }
  25475. });
  25476. editor.on('blur NewBlock', removeElementSelection);
  25477. editor.on('ResizeWindow FullscreenStateChanged', fakeCaret.reposition);
  25478. var hasNormalCaretPosition = function (elm) {
  25479. var start = elm.firstChild;
  25480. if (isNullable(start)) {
  25481. return false;
  25482. }
  25483. var startPos = CaretPosition.before(start);
  25484. if (isBr$5(startPos.getNode()) && elm.childNodes.length === 1) {
  25485. return !isNearFakeSelectionElement(startPos);
  25486. } else {
  25487. var caretWalker = CaretWalker(elm);
  25488. var newPos = caretWalker.next(startPos);
  25489. return newPos && !isNearFakeSelectionElement(newPos);
  25490. }
  25491. };
  25492. var isInSameBlock = function (node1, node2) {
  25493. var block1 = dom.getParent(node1, isBlock);
  25494. var block2 = dom.getParent(node2, isBlock);
  25495. return block1 === block2;
  25496. };
  25497. var hasBetterMouseTarget = function (targetNode, caretNode) {
  25498. var targetBlock = dom.getParent(targetNode, isBlock);
  25499. var caretBlock = dom.getParent(caretNode, isBlock);
  25500. if (isNullable(targetBlock)) {
  25501. return false;
  25502. }
  25503. if (targetNode !== caretBlock && dom.isChildOf(targetBlock, caretBlock) && isContentEditableFalse(getContentEditableRoot(editor, targetBlock)) === false) {
  25504. return true;
  25505. }
  25506. return !dom.isChildOf(caretBlock, targetBlock) && !isInSameBlock(targetBlock, caretBlock) && hasNormalCaretPosition(targetBlock);
  25507. };
  25508. editor.on('tap', function (e) {
  25509. var targetElm = e.target;
  25510. var contentEditableRoot = getContentEditableRoot(editor, targetElm);
  25511. if (isContentEditableFalse(contentEditableRoot)) {
  25512. e.preventDefault();
  25513. selectNode(editor, contentEditableRoot).each(setElementSelection);
  25514. } else if (isFakeSelectionTargetElement(targetElm)) {
  25515. selectNode(editor, targetElm).each(setElementSelection);
  25516. }
  25517. }, true);
  25518. editor.on('mousedown', function (e) {
  25519. var targetElm = e.target;
  25520. if (targetElm !== rootNode && targetElm.nodeName !== 'HTML' && !dom.isChildOf(targetElm, rootNode)) {
  25521. return;
  25522. }
  25523. if (isXYInContentArea(editor, e.clientX, e.clientY) === false) {
  25524. return;
  25525. }
  25526. var contentEditableRoot = getContentEditableRoot(editor, targetElm);
  25527. if (contentEditableRoot) {
  25528. if (isContentEditableFalse(contentEditableRoot)) {
  25529. e.preventDefault();
  25530. selectNode(editor, contentEditableRoot).each(setElementSelection);
  25531. } else {
  25532. removeElementSelection();
  25533. if (!(isContentEditableTrue(contentEditableRoot) && e.shiftKey) && !isXYWithinRange(e.clientX, e.clientY, selection.getRng())) {
  25534. hideFakeCaret();
  25535. selection.placeCaretAt(e.clientX, e.clientY);
  25536. }
  25537. }
  25538. } else if (isFakeSelectionTargetElement(targetElm)) {
  25539. selectNode(editor, targetElm).each(setElementSelection);
  25540. } else if (isFakeCaretTarget(targetElm) === false) {
  25541. removeElementSelection();
  25542. hideFakeCaret();
  25543. var fakeCaretInfo = closestFakeCaret(rootNode, e.clientX, e.clientY);
  25544. if (fakeCaretInfo) {
  25545. if (!hasBetterMouseTarget(targetElm, fakeCaretInfo.node)) {
  25546. e.preventDefault();
  25547. var range = showCaret(1, fakeCaretInfo.node, fakeCaretInfo.before, false);
  25548. setRange(range);
  25549. editor.getBody().focus();
  25550. }
  25551. }
  25552. }
  25553. });
  25554. editor.on('keypress', function (e) {
  25555. if (VK.modifierPressed(e)) {
  25556. return;
  25557. }
  25558. if (isContentEditableFalse(selection.getNode())) {
  25559. e.preventDefault();
  25560. }
  25561. });
  25562. editor.on('GetSelectionRange', function (e) {
  25563. var rng = e.range;
  25564. if (selectedElement) {
  25565. if (!selectedElement.parentNode) {
  25566. selectedElement = null;
  25567. return;
  25568. }
  25569. rng = rng.cloneRange();
  25570. rng.selectNode(selectedElement);
  25571. e.range = rng;
  25572. }
  25573. });
  25574. editor.on('SetSelectionRange', function (e) {
  25575. e.range = normalizeShortEndedElementSelection(e.range);
  25576. var rng = setElementSelection(e.range, e.forward);
  25577. if (rng) {
  25578. e.range = rng;
  25579. }
  25580. });
  25581. var isPasteBin = function (node) {
  25582. return node.id === 'mcepastebin';
  25583. };
  25584. editor.on('AfterSetSelectionRange', function (e) {
  25585. var rng = e.range;
  25586. var parentNode = rng.startContainer.parentNode;
  25587. if (!isRangeInCaretContainer(rng) && !isPasteBin(parentNode)) {
  25588. hideFakeCaret();
  25589. }
  25590. if (!isFakeSelectionElement(parentNode)) {
  25591. removeElementSelection();
  25592. }
  25593. });
  25594. editor.on('copy', function (e) {
  25595. var clipboardData = e.clipboardData;
  25596. if (!e.isDefaultPrevented() && e.clipboardData && !Env.ie) {
  25597. var realSelectionElement = getRealSelectionElement();
  25598. if (realSelectionElement) {
  25599. e.preventDefault();
  25600. clipboardData.clearData();
  25601. clipboardData.setData('text/html', realSelectionElement.outerHTML);
  25602. clipboardData.setData('text/plain', realSelectionElement.outerText || realSelectionElement.innerText);
  25603. }
  25604. }
  25605. });
  25606. init$2(editor);
  25607. setup$1(editor);
  25608. setup(editor);
  25609. };
  25610. var isWithinCaretContainer = function (node) {
  25611. return isCaretContainer$2(node) || startsWithCaretContainer$1(node) || endsWithCaretContainer$1(node);
  25612. };
  25613. var isRangeInCaretContainer = function (rng) {
  25614. return isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
  25615. };
  25616. var normalizeShortEndedElementSelection = function (rng) {
  25617. var shortEndedElements = editor.schema.getShortEndedElements();
  25618. var newRng = dom.createRng();
  25619. var startContainer = rng.startContainer;
  25620. var startOffset = rng.startOffset;
  25621. var endContainer = rng.endContainer;
  25622. var endOffset = rng.endOffset;
  25623. if (has$2(shortEndedElements, startContainer.nodeName.toLowerCase())) {
  25624. if (startOffset === 0) {
  25625. newRng.setStartBefore(startContainer);
  25626. } else {
  25627. newRng.setStartAfter(startContainer);
  25628. }
  25629. } else {
  25630. newRng.setStart(startContainer, startOffset);
  25631. }
  25632. if (has$2(shortEndedElements, endContainer.nodeName.toLowerCase())) {
  25633. if (endOffset === 0) {
  25634. newRng.setEndBefore(endContainer);
  25635. } else {
  25636. newRng.setEndAfter(endContainer);
  25637. }
  25638. } else {
  25639. newRng.setEnd(endContainer, endOffset);
  25640. }
  25641. return newRng;
  25642. };
  25643. var setupOffscreenSelection = function (node, targetClone, origTargetClone) {
  25644. var $ = editor.$;
  25645. var $realSelectionContainer = descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).fold(function () {
  25646. return $([]);
  25647. }, function (elm) {
  25648. return $([elm.dom]);
  25649. });
  25650. if ($realSelectionContainer.length === 0) {
  25651. $realSelectionContainer = $('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>').attr('id', realSelectionId);
  25652. $realSelectionContainer.appendTo(editor.getBody());
  25653. }
  25654. var newRange = dom.createRng();
  25655. if (targetClone === origTargetClone && Env.ie) {
  25656. $realSelectionContainer.empty().append('<p style="font-size: 0" data-mce-bogus="all">\xA0</p>').append(targetClone);
  25657. newRange.setStartAfter($realSelectionContainer[0].firstChild.firstChild);
  25658. newRange.setEndAfter(targetClone);
  25659. } else {
  25660. $realSelectionContainer.empty().append(nbsp).append(targetClone).append(nbsp);
  25661. newRange.setStart($realSelectionContainer[0].firstChild, 1);
  25662. newRange.setEnd($realSelectionContainer[0].lastChild, 0);
  25663. }
  25664. $realSelectionContainer.css({ top: dom.getPos(node, editor.getBody()).y });
  25665. $realSelectionContainer[0].focus();
  25666. var sel = selection.getSel();
  25667. sel.removeAllRanges();
  25668. sel.addRange(newRange);
  25669. return newRange;
  25670. };
  25671. var selectElement = function (elm) {
  25672. var targetClone = elm.cloneNode(true);
  25673. var e = editor.fire('ObjectSelected', {
  25674. target: elm,
  25675. targetClone: targetClone
  25676. });
  25677. if (e.isDefaultPrevented()) {
  25678. return null;
  25679. }
  25680. var range = setupOffscreenSelection(elm, e.targetClone, targetClone);
  25681. var nodeElm = SugarElement.fromDom(elm);
  25682. each$k(descendants(SugarElement.fromDom(editor.getBody()), '*[data-mce-selected]'), function (elm) {
  25683. if (!eq(nodeElm, elm)) {
  25684. remove$6(elm, elementSelectionAttr);
  25685. }
  25686. });
  25687. if (!dom.getAttrib(elm, elementSelectionAttr)) {
  25688. elm.setAttribute(elementSelectionAttr, '1');
  25689. }
  25690. selectedElement = elm;
  25691. hideFakeCaret();
  25692. return range;
  25693. };
  25694. var setElementSelection = function (range, forward) {
  25695. if (!range) {
  25696. return null;
  25697. }
  25698. if (range.collapsed) {
  25699. if (!isRangeInCaretContainer(range)) {
  25700. var dir = forward ? 1 : -1;
  25701. var caretPosition = getNormalizedRangeEndPoint(dir, rootNode, range);
  25702. var beforeNode = caretPosition.getNode(!forward);
  25703. if (isFakeCaretTarget(beforeNode)) {
  25704. return showCaret(dir, beforeNode, forward ? !caretPosition.isAtEnd() : false, false);
  25705. }
  25706. var afterNode = caretPosition.getNode(forward);
  25707. if (isFakeCaretTarget(afterNode)) {
  25708. return showCaret(dir, afterNode, forward ? false : !caretPosition.isAtEnd(), false);
  25709. }
  25710. }
  25711. return null;
  25712. }
  25713. var startContainer = range.startContainer;
  25714. var startOffset = range.startOffset;
  25715. var endOffset = range.endOffset;
  25716. if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse(startContainer.parentNode)) {
  25717. startContainer = startContainer.parentNode;
  25718. startOffset = dom.nodeIndex(startContainer);
  25719. startContainer = startContainer.parentNode;
  25720. }
  25721. if (startContainer.nodeType !== 1) {
  25722. return null;
  25723. }
  25724. if (endOffset === startOffset + 1 && startContainer === range.endContainer) {
  25725. var node = startContainer.childNodes[startOffset];
  25726. if (isFakeSelectionTargetElement(node)) {
  25727. return selectElement(node);
  25728. }
  25729. }
  25730. return null;
  25731. };
  25732. var removeElementSelection = function () {
  25733. if (selectedElement) {
  25734. selectedElement.removeAttribute(elementSelectionAttr);
  25735. }
  25736. descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).each(remove$7);
  25737. selectedElement = null;
  25738. };
  25739. var destroy = function () {
  25740. fakeCaret.destroy();
  25741. selectedElement = null;
  25742. };
  25743. var hideFakeCaret = function () {
  25744. fakeCaret.hide();
  25745. };
  25746. if (Env.ceFalse && !isRtc(editor)) {
  25747. registerEvents();
  25748. }
  25749. return {
  25750. showCaret: showCaret,
  25751. showBlockCaretContainer: showBlockCaretContainer,
  25752. hideFakeCaret: hideFakeCaret,
  25753. destroy: destroy
  25754. };
  25755. };
  25756. var Quirks = function (editor) {
  25757. var each = Tools.each;
  25758. var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, parser = editor.parser;
  25759. var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit;
  25760. var mceInternalUrlPrefix = 'data:text/mce-internal,';
  25761. var mceInternalDataType = isIE ? 'Text' : 'URL';
  25762. var setEditorCommandState = function (cmd, state) {
  25763. try {
  25764. editor.getDoc().execCommand(cmd, false, state);
  25765. } catch (ex) {
  25766. }
  25767. };
  25768. var isDefaultPrevented = function (e) {
  25769. return e.isDefaultPrevented();
  25770. };
  25771. var setMceInternalContent = function (e) {
  25772. var selectionHtml, internalContent;
  25773. if (e.dataTransfer) {
  25774. if (editor.selection.isCollapsed() && e.target.tagName === 'IMG') {
  25775. selection.select(e.target);
  25776. }
  25777. selectionHtml = editor.selection.getContent();
  25778. if (selectionHtml.length > 0) {
  25779. internalContent = mceInternalUrlPrefix + escape(editor.id) + ',' + escape(selectionHtml);
  25780. e.dataTransfer.setData(mceInternalDataType, internalContent);
  25781. }
  25782. }
  25783. };
  25784. var getMceInternalContent = function (e) {
  25785. var internalContent;
  25786. if (e.dataTransfer) {
  25787. internalContent = e.dataTransfer.getData(mceInternalDataType);
  25788. if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) {
  25789. internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(',');
  25790. return {
  25791. id: unescape(internalContent[0]),
  25792. html: unescape(internalContent[1])
  25793. };
  25794. }
  25795. }
  25796. return null;
  25797. };
  25798. var insertClipboardContents = function (content, internal) {
  25799. if (editor.queryCommandSupported('mceInsertClipboardContent')) {
  25800. editor.execCommand('mceInsertClipboardContent', false, {
  25801. content: content,
  25802. internal: internal
  25803. });
  25804. } else {
  25805. editor.execCommand('mceInsertContent', false, content);
  25806. }
  25807. };
  25808. var emptyEditorWhenDeleting = function () {
  25809. var serializeRng = function (rng) {
  25810. var body = dom.create('body');
  25811. var contents = rng.cloneContents();
  25812. body.appendChild(contents);
  25813. return selection.serializer.serialize(body, { format: 'html' });
  25814. };
  25815. var allContentsSelected = function (rng) {
  25816. var selection = serializeRng(rng);
  25817. var allRng = dom.createRng();
  25818. allRng.selectNode(editor.getBody());
  25819. var allSelection = serializeRng(allRng);
  25820. return selection === allSelection;
  25821. };
  25822. editor.on('keydown', function (e) {
  25823. var keyCode = e.keyCode;
  25824. var isCollapsed, body;
  25825. if (!isDefaultPrevented(e) && (keyCode === DELETE || keyCode === BACKSPACE)) {
  25826. isCollapsed = editor.selection.isCollapsed();
  25827. body = editor.getBody();
  25828. if (isCollapsed && !dom.isEmpty(body)) {
  25829. return;
  25830. }
  25831. if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
  25832. return;
  25833. }
  25834. e.preventDefault();
  25835. editor.setContent('');
  25836. if (body.firstChild && dom.isBlock(body.firstChild)) {
  25837. editor.selection.setCursorLocation(body.firstChild, 0);
  25838. } else {
  25839. editor.selection.setCursorLocation(body, 0);
  25840. }
  25841. editor.nodeChanged();
  25842. }
  25843. });
  25844. };
  25845. var selectAll = function () {
  25846. editor.shortcuts.add('meta+a', null, 'SelectAll');
  25847. };
  25848. var documentElementEditingFocus = function () {
  25849. if (!editor.inline) {
  25850. dom.bind(editor.getDoc(), 'mousedown mouseup', function (e) {
  25851. var rng;
  25852. if (e.target === editor.getDoc().documentElement) {
  25853. rng = selection.getRng();
  25854. editor.getBody().focus();
  25855. if (e.type === 'mousedown') {
  25856. if (isCaretContainer$2(rng.startContainer)) {
  25857. return;
  25858. }
  25859. selection.placeCaretAt(e.clientX, e.clientY);
  25860. } else {
  25861. selection.setRng(rng);
  25862. }
  25863. }
  25864. });
  25865. }
  25866. };
  25867. var removeHrOnBackspace = function () {
  25868. editor.on('keydown', function (e) {
  25869. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25870. if (!editor.getBody().getElementsByTagName('hr').length) {
  25871. return;
  25872. }
  25873. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25874. var node = selection.getNode();
  25875. var previousSibling = node.previousSibling;
  25876. if (node.nodeName === 'HR') {
  25877. dom.remove(node);
  25878. e.preventDefault();
  25879. return;
  25880. }
  25881. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'hr') {
  25882. dom.remove(previousSibling);
  25883. e.preventDefault();
  25884. }
  25885. }
  25886. }
  25887. });
  25888. };
  25889. var focusBody = function () {
  25890. if (!Range.prototype.getClientRects) {
  25891. editor.on('mousedown', function (e) {
  25892. if (!isDefaultPrevented(e) && e.target.nodeName === 'HTML') {
  25893. var body_1 = editor.getBody();
  25894. body_1.blur();
  25895. Delay.setEditorTimeout(editor, function () {
  25896. body_1.focus();
  25897. });
  25898. }
  25899. });
  25900. }
  25901. };
  25902. var selectControlElements = function () {
  25903. editor.on('click', function (e) {
  25904. var target = e.target;
  25905. if (/^(IMG|HR)$/.test(target.nodeName) && dom.getContentEditableParent(target) !== 'false') {
  25906. e.preventDefault();
  25907. editor.selection.select(target);
  25908. editor.nodeChanged();
  25909. }
  25910. if (target.nodeName === 'A' && dom.hasClass(target, 'mce-item-anchor')) {
  25911. e.preventDefault();
  25912. selection.select(target);
  25913. }
  25914. });
  25915. };
  25916. var removeStylesWhenDeletingAcrossBlockElements = function () {
  25917. var getAttributeApplyFunction = function () {
  25918. var template = dom.getAttribs(selection.getStart().cloneNode(false));
  25919. return function () {
  25920. var target = selection.getStart();
  25921. if (target !== editor.getBody()) {
  25922. dom.setAttrib(target, 'style', null);
  25923. each(template, function (attr) {
  25924. target.setAttributeNode(attr.cloneNode(true));
  25925. });
  25926. }
  25927. };
  25928. };
  25929. var isSelectionAcrossElements = function () {
  25930. return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock);
  25931. };
  25932. editor.on('keypress', function (e) {
  25933. var applyAttributes;
  25934. if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) {
  25935. applyAttributes = getAttributeApplyFunction();
  25936. editor.getDoc().execCommand('delete', false, null);
  25937. applyAttributes();
  25938. e.preventDefault();
  25939. return false;
  25940. }
  25941. });
  25942. dom.bind(editor.getDoc(), 'cut', function (e) {
  25943. var applyAttributes;
  25944. if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
  25945. applyAttributes = getAttributeApplyFunction();
  25946. Delay.setEditorTimeout(editor, function () {
  25947. applyAttributes();
  25948. });
  25949. }
  25950. });
  25951. };
  25952. var disableBackspaceIntoATable = function () {
  25953. editor.on('keydown', function (e) {
  25954. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25955. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25956. var previousSibling = selection.getNode().previousSibling;
  25957. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'table') {
  25958. e.preventDefault();
  25959. return false;
  25960. }
  25961. }
  25962. }
  25963. });
  25964. };
  25965. var removeBlockQuoteOnBackSpace = function () {
  25966. editor.on('keydown', function (e) {
  25967. var rng, parent;
  25968. if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) {
  25969. return;
  25970. }
  25971. rng = selection.getRng();
  25972. var container = rng.startContainer;
  25973. var offset = rng.startOffset;
  25974. var root = dom.getRoot();
  25975. parent = container;
  25976. if (!rng.collapsed || offset !== 0) {
  25977. return;
  25978. }
  25979. while (parent && parent.parentNode && parent.parentNode.firstChild === parent && parent.parentNode !== root) {
  25980. parent = parent.parentNode;
  25981. }
  25982. if (parent.tagName === 'BLOCKQUOTE') {
  25983. editor.formatter.toggle('blockquote', null, parent);
  25984. rng = dom.createRng();
  25985. rng.setStart(container, 0);
  25986. rng.setEnd(container, 0);
  25987. selection.setRng(rng);
  25988. }
  25989. });
  25990. };
  25991. var setGeckoEditingOptions = function () {
  25992. var setOpts = function () {
  25993. setEditorCommandState('StyleWithCSS', false);
  25994. setEditorCommandState('enableInlineTableEditing', false);
  25995. if (!getObjectResizing(editor)) {
  25996. setEditorCommandState('enableObjectResizing', false);
  25997. }
  25998. };
  25999. if (!isReadOnly$1(editor)) {
  26000. editor.on('BeforeExecCommand mousedown', setOpts);
  26001. }
  26002. };
  26003. var addBrAfterLastLinks = function () {
  26004. var fixLinks = function () {
  26005. each(dom.select('a'), function (node) {
  26006. var parentNode = node.parentNode;
  26007. var root = dom.getRoot();
  26008. if (parentNode.lastChild === node) {
  26009. while (parentNode && !dom.isBlock(parentNode)) {
  26010. if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
  26011. return;
  26012. }
  26013. parentNode = parentNode.parentNode;
  26014. }
  26015. dom.add(parentNode, 'br', { 'data-mce-bogus': 1 });
  26016. }
  26017. });
  26018. };
  26019. editor.on('SetContent ExecCommand', function (e) {
  26020. if (e.type === 'setcontent' || e.command === 'mceInsertLink') {
  26021. fixLinks();
  26022. }
  26023. });
  26024. };
  26025. var setDefaultBlockType = function () {
  26026. if (getForcedRootBlock(editor)) {
  26027. editor.on('init', function () {
  26028. setEditorCommandState('DefaultParagraphSeparator', getForcedRootBlock(editor));
  26029. });
  26030. }
  26031. };
  26032. var normalizeSelection = function () {
  26033. editor.on('keyup focusin mouseup', function (e) {
  26034. if (!VK.modifierPressed(e)) {
  26035. selection.normalize();
  26036. }
  26037. }, true);
  26038. };
  26039. var showBrokenImageIcon = function () {
  26040. editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}');
  26041. };
  26042. var restoreFocusOnKeyDown = function () {
  26043. if (!editor.inline) {
  26044. editor.on('keydown', function () {
  26045. if (document.activeElement === document.body) {
  26046. editor.getWin().focus();
  26047. }
  26048. });
  26049. }
  26050. };
  26051. var bodyHeight = function () {
  26052. if (!editor.inline) {
  26053. editor.contentStyles.push('body {min-height: 150px}');
  26054. editor.on('click', function (e) {
  26055. var rng;
  26056. if (e.target.nodeName === 'HTML') {
  26057. if (Env.ie > 11) {
  26058. editor.getBody().focus();
  26059. return;
  26060. }
  26061. rng = editor.selection.getRng();
  26062. editor.getBody().focus();
  26063. editor.selection.setRng(rng);
  26064. editor.selection.normalize();
  26065. editor.nodeChanged();
  26066. }
  26067. });
  26068. }
  26069. };
  26070. var blockCmdArrowNavigation = function () {
  26071. if (Env.mac) {
  26072. editor.on('keydown', function (e) {
  26073. if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) {
  26074. e.preventDefault();
  26075. var selection_1 = editor.selection.getSel();
  26076. selection_1.modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary');
  26077. }
  26078. });
  26079. }
  26080. };
  26081. var disableAutoUrlDetect = function () {
  26082. setEditorCommandState('AutoUrlDetect', false);
  26083. };
  26084. var tapLinksAndImages = function () {
  26085. editor.on('click', function (e) {
  26086. var elm = e.target;
  26087. do {
  26088. if (elm.tagName === 'A') {
  26089. e.preventDefault();
  26090. return;
  26091. }
  26092. } while (elm = elm.parentNode);
  26093. });
  26094. editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
  26095. };
  26096. var blockFormSubmitInsideEditor = function () {
  26097. editor.on('init', function () {
  26098. editor.dom.bind(editor.getBody(), 'submit', function (e) {
  26099. e.preventDefault();
  26100. });
  26101. });
  26102. };
  26103. var removeAppleInterchangeBrs = function () {
  26104. parser.addNodeFilter('br', function (nodes) {
  26105. var i = nodes.length;
  26106. while (i--) {
  26107. if (nodes[i].attr('class') === 'Apple-interchange-newline') {
  26108. nodes[i].remove();
  26109. }
  26110. }
  26111. });
  26112. };
  26113. var ieInternalDragAndDrop = function () {
  26114. editor.on('dragstart', function (e) {
  26115. setMceInternalContent(e);
  26116. });
  26117. editor.on('drop', function (e) {
  26118. if (!isDefaultPrevented(e)) {
  26119. var internalContent = getMceInternalContent(e);
  26120. if (internalContent && internalContent.id !== editor.id) {
  26121. e.preventDefault();
  26122. var rng = fromPoint(e.x, e.y, editor.getDoc());
  26123. selection.setRng(rng);
  26124. insertClipboardContents(internalContent.html, true);
  26125. }
  26126. }
  26127. });
  26128. };
  26129. var refreshContentEditable = noop;
  26130. var isHidden = function () {
  26131. if (!isGecko || editor.removed) {
  26132. return false;
  26133. }
  26134. var sel = editor.selection.getSel();
  26135. return !sel || !sel.rangeCount || sel.rangeCount === 0;
  26136. };
  26137. var setupRtc = function () {
  26138. if (isWebKit) {
  26139. documentElementEditingFocus();
  26140. selectControlElements();
  26141. blockFormSubmitInsideEditor();
  26142. selectAll();
  26143. if (Env.iOS) {
  26144. restoreFocusOnKeyDown();
  26145. bodyHeight();
  26146. tapLinksAndImages();
  26147. }
  26148. }
  26149. if (isGecko) {
  26150. focusBody();
  26151. setGeckoEditingOptions();
  26152. showBrokenImageIcon();
  26153. blockCmdArrowNavigation();
  26154. }
  26155. };
  26156. var setup = function () {
  26157. removeBlockQuoteOnBackSpace();
  26158. emptyEditorWhenDeleting();
  26159. if (!Env.windowsPhone) {
  26160. normalizeSelection();
  26161. }
  26162. if (isWebKit) {
  26163. documentElementEditingFocus();
  26164. selectControlElements();
  26165. setDefaultBlockType();
  26166. blockFormSubmitInsideEditor();
  26167. disableBackspaceIntoATable();
  26168. removeAppleInterchangeBrs();
  26169. if (Env.iOS) {
  26170. restoreFocusOnKeyDown();
  26171. bodyHeight();
  26172. tapLinksAndImages();
  26173. } else {
  26174. selectAll();
  26175. }
  26176. }
  26177. if (Env.ie >= 11) {
  26178. bodyHeight();
  26179. disableBackspaceIntoATable();
  26180. }
  26181. if (Env.ie) {
  26182. selectAll();
  26183. disableAutoUrlDetect();
  26184. ieInternalDragAndDrop();
  26185. }
  26186. if (isGecko) {
  26187. removeHrOnBackspace();
  26188. focusBody();
  26189. removeStylesWhenDeletingAcrossBlockElements();
  26190. setGeckoEditingOptions();
  26191. addBrAfterLastLinks();
  26192. showBrokenImageIcon();
  26193. blockCmdArrowNavigation();
  26194. disableBackspaceIntoATable();
  26195. }
  26196. };
  26197. if (isRtc(editor)) {
  26198. setupRtc();
  26199. } else {
  26200. setup();
  26201. }
  26202. return {
  26203. refreshContentEditable: refreshContentEditable,
  26204. isHidden: isHidden
  26205. };
  26206. };
  26207. var DOM$6 = DOMUtils.DOM;
  26208. var appendStyle = function (editor, text) {
  26209. var body = SugarElement.fromDom(editor.getBody());
  26210. var container = getStyleContainer(getRootNode(body));
  26211. var style = SugarElement.fromTag('style');
  26212. set$1(style, 'type', 'text/css');
  26213. append$1(style, SugarElement.fromText(text));
  26214. append$1(container, style);
  26215. editor.on('remove', function () {
  26216. remove$7(style);
  26217. });
  26218. };
  26219. var getRootName = function (editor) {
  26220. return editor.inline ? editor.getElement().nodeName.toLowerCase() : undefined;
  26221. };
  26222. var removeUndefined = function (obj) {
  26223. return filter$3(obj, function (v) {
  26224. return isUndefined(v) === false;
  26225. });
  26226. };
  26227. var mkSchemaSettings = function (editor) {
  26228. var settings = editor.settings;
  26229. return removeUndefined({
  26230. block_elements: settings.block_elements,
  26231. boolean_attributes: settings.boolean_attributes,
  26232. custom_elements: settings.custom_elements,
  26233. extended_valid_elements: settings.extended_valid_elements,
  26234. invalid_elements: settings.invalid_elements,
  26235. invalid_styles: settings.invalid_styles,
  26236. move_caret_before_on_enter_elements: settings.move_caret_before_on_enter_elements,
  26237. non_empty_elements: settings.non_empty_elements,
  26238. schema: settings.schema,
  26239. self_closing_elements: settings.self_closing_elements,
  26240. short_ended_elements: settings.short_ended_elements,
  26241. special: settings.special,
  26242. text_block_elements: settings.text_block_elements,
  26243. text_inline_elements: settings.text_inline_elements,
  26244. valid_children: settings.valid_children,
  26245. valid_classes: settings.valid_classes,
  26246. valid_elements: settings.valid_elements,
  26247. valid_styles: settings.valid_styles,
  26248. verify_html: settings.verify_html,
  26249. whitespace_elements: settings.whitespace_elements,
  26250. padd_empty_block_inline_children: settings.format_empty_lines
  26251. });
  26252. };
  26253. var mkParserSettings = function (editor) {
  26254. var settings = editor.settings;
  26255. var blobCache = editor.editorUpload.blobCache;
  26256. return removeUndefined({
  26257. allow_conditional_comments: settings.allow_conditional_comments,
  26258. allow_html_data_urls: settings.allow_html_data_urls,
  26259. allow_svg_data_urls: settings.allow_svg_data_urls,
  26260. allow_html_in_named_anchor: settings.allow_html_in_named_anchor,
  26261. allow_script_urls: settings.allow_script_urls,
  26262. allow_unsafe_link_target: settings.allow_unsafe_link_target,
  26263. convert_fonts_to_spans: settings.convert_fonts_to_spans,
  26264. fix_list_elements: settings.fix_list_elements,
  26265. font_size_legacy_values: settings.font_size_legacy_values,
  26266. forced_root_block: settings.forced_root_block,
  26267. forced_root_block_attrs: settings.forced_root_block_attrs,
  26268. padd_empty_with_br: settings.padd_empty_with_br,
  26269. preserve_cdata: settings.preserve_cdata,
  26270. remove_trailing_brs: settings.remove_trailing_brs,
  26271. inline_styles: settings.inline_styles,
  26272. root_name: getRootName(editor),
  26273. validate: true,
  26274. blob_cache: blobCache,
  26275. document: editor.getDoc(),
  26276. images_dataimg_filter: settings.images_dataimg_filter
  26277. });
  26278. };
  26279. var mkSerializerSettings = function (editor) {
  26280. var settings = editor.settings;
  26281. return __assign(__assign(__assign({}, mkParserSettings(editor)), mkSchemaSettings(editor)), removeUndefined({
  26282. url_converter: settings.url_converter,
  26283. url_converter_scope: settings.url_converter_scope,
  26284. element_format: settings.element_format,
  26285. entities: settings.entities,
  26286. entity_encoding: settings.entity_encoding,
  26287. indent: settings.indent,
  26288. indent_after: settings.indent_after,
  26289. indent_before: settings.indent_before
  26290. }));
  26291. };
  26292. var createParser = function (editor) {
  26293. var parser = DomParser(mkParserSettings(editor), editor.schema);
  26294. parser.addAttributeFilter('src,href,style,tabindex', function (nodes, name) {
  26295. var i = nodes.length, node, value;
  26296. var dom = editor.dom;
  26297. var internalName = 'data-mce-' + name;
  26298. while (i--) {
  26299. node = nodes[i];
  26300. value = node.attr(name);
  26301. if (value && !node.attr(internalName)) {
  26302. if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) {
  26303. continue;
  26304. }
  26305. if (name === 'style') {
  26306. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  26307. if (!value.length) {
  26308. value = null;
  26309. }
  26310. node.attr(internalName, value);
  26311. node.attr(name, value);
  26312. } else if (name === 'tabindex') {
  26313. node.attr(internalName, value);
  26314. node.attr(name, null);
  26315. } else {
  26316. node.attr(internalName, editor.convertURL(value, name, node.name));
  26317. }
  26318. }
  26319. }
  26320. });
  26321. parser.addNodeFilter('script', function (nodes) {
  26322. var i = nodes.length;
  26323. while (i--) {
  26324. var node = nodes[i];
  26325. var type = node.attr('type') || 'no/type';
  26326. if (type.indexOf('mce-') !== 0) {
  26327. node.attr('type', 'mce-' + type);
  26328. }
  26329. }
  26330. });
  26331. if (editor.settings.preserve_cdata) {
  26332. parser.addNodeFilter('#cdata', function (nodes) {
  26333. var i = nodes.length;
  26334. while (i--) {
  26335. var node = nodes[i];
  26336. node.type = 8;
  26337. node.name = '#comment';
  26338. node.value = '[CDATA[' + editor.dom.encode(node.value) + ']]';
  26339. }
  26340. });
  26341. }
  26342. parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function (nodes) {
  26343. var i = nodes.length;
  26344. var nonEmptyElements = editor.schema.getNonEmptyElements();
  26345. while (i--) {
  26346. var node = nodes[i];
  26347. if (node.isEmpty(nonEmptyElements) && node.getAll('br').length === 0) {
  26348. node.append(new AstNode('br', 1)).shortEnded = true;
  26349. }
  26350. }
  26351. });
  26352. return parser;
  26353. };
  26354. var autoFocus = function (editor) {
  26355. if (editor.settings.auto_focus) {
  26356. Delay.setEditorTimeout(editor, function () {
  26357. var focusEditor;
  26358. if (editor.settings.auto_focus === true) {
  26359. focusEditor = editor;
  26360. } else {
  26361. focusEditor = editor.editorManager.get(editor.settings.auto_focus);
  26362. }
  26363. if (!focusEditor.destroyed) {
  26364. focusEditor.focus();
  26365. }
  26366. }, 100);
  26367. }
  26368. };
  26369. var moveSelectionToFirstCaretPosition = function (editor) {
  26370. var root = editor.dom.getRoot();
  26371. if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) {
  26372. firstPositionIn(root).each(function (pos) {
  26373. var node = pos.getNode();
  26374. var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  26375. if (Env.browser.isIE()) {
  26376. storeNative(editor, caretPos.toRange());
  26377. } else {
  26378. editor.selection.setRng(caretPos.toRange());
  26379. }
  26380. });
  26381. }
  26382. };
  26383. var initEditor = function (editor) {
  26384. editor.bindPendingEventDelegates();
  26385. editor.initialized = true;
  26386. fireInit(editor);
  26387. editor.focus(true);
  26388. moveSelectionToFirstCaretPosition(editor);
  26389. editor.nodeChanged({ initial: true });
  26390. editor.execCallback('init_instance_callback', editor);
  26391. autoFocus(editor);
  26392. };
  26393. var getStyleSheetLoader$1 = function (editor) {
  26394. return editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader;
  26395. };
  26396. var makeStylesheetLoadingPromises = function (editor, css, framedFonts) {
  26397. var promises = [new promiseObj(function (resolve, reject) {
  26398. return getStyleSheetLoader$1(editor).loadAll(css, resolve, reject);
  26399. })];
  26400. if (editor.inline) {
  26401. return promises;
  26402. } else {
  26403. return promises.concat([new promiseObj(function (resolve, reject) {
  26404. return editor.ui.styleSheetLoader.loadAll(framedFonts, resolve, reject);
  26405. })]);
  26406. }
  26407. };
  26408. var loadContentCss = function (editor) {
  26409. var styleSheetLoader = getStyleSheetLoader$1(editor);
  26410. var fontCss = getFontCss(editor);
  26411. var css = editor.contentCSS;
  26412. var removeCss = function () {
  26413. styleSheetLoader.unloadAll(css);
  26414. if (!editor.inline) {
  26415. editor.ui.styleSheetLoader.unloadAll(fontCss);
  26416. }
  26417. };
  26418. var loaded = function () {
  26419. if (editor.removed) {
  26420. removeCss();
  26421. } else {
  26422. editor.on('remove', removeCss);
  26423. }
  26424. };
  26425. if (editor.contentStyles.length > 0) {
  26426. var contentCssText_1 = '';
  26427. Tools.each(editor.contentStyles, function (style) {
  26428. contentCssText_1 += style + '\r\n';
  26429. });
  26430. editor.dom.addStyle(contentCssText_1);
  26431. }
  26432. var allStylesheets = promiseObj.all(makeStylesheetLoadingPromises(editor, css, fontCss)).then(loaded).catch(loaded);
  26433. if (editor.settings.content_style) {
  26434. appendStyle(editor, editor.settings.content_style);
  26435. }
  26436. return allStylesheets;
  26437. };
  26438. var preInit = function (editor) {
  26439. var settings = editor.settings, doc = editor.getDoc(), body = editor.getBody();
  26440. firePreInit(editor);
  26441. if (!settings.browser_spellcheck && !settings.gecko_spellcheck) {
  26442. doc.body.spellcheck = false;
  26443. DOM$6.setAttrib(body, 'spellcheck', 'false');
  26444. }
  26445. editor.quirks = Quirks(editor);
  26446. firePostRender(editor);
  26447. var directionality = getDirectionality(editor);
  26448. if (directionality !== undefined) {
  26449. body.dir = directionality;
  26450. }
  26451. if (settings.protect) {
  26452. editor.on('BeforeSetContent', function (e) {
  26453. Tools.each(settings.protect, function (pattern) {
  26454. e.content = e.content.replace(pattern, function (str) {
  26455. return '<!--mce:protected ' + escape(str) + '-->';
  26456. });
  26457. });
  26458. });
  26459. }
  26460. editor.on('SetContent', function () {
  26461. editor.addVisual(editor.getBody());
  26462. });
  26463. editor.on('compositionstart compositionend', function (e) {
  26464. editor.composing = e.type === 'compositionstart';
  26465. });
  26466. };
  26467. var loadInitialContent = function (editor) {
  26468. if (!isRtc(editor)) {
  26469. editor.load({
  26470. initial: true,
  26471. format: 'html'
  26472. });
  26473. }
  26474. editor.startContent = editor.getContent({ format: 'raw' });
  26475. };
  26476. var initEditorWithInitialContent = function (editor) {
  26477. if (editor.removed !== true) {
  26478. loadInitialContent(editor);
  26479. initEditor(editor);
  26480. }
  26481. };
  26482. var initContentBody = function (editor, skipWrite) {
  26483. var settings = editor.settings;
  26484. var targetElm = editor.getElement();
  26485. var doc = editor.getDoc();
  26486. if (!settings.inline) {
  26487. editor.getElement().style.visibility = editor.orgVisibility;
  26488. }
  26489. if (!skipWrite && !editor.inline) {
  26490. doc.open();
  26491. doc.write(editor.iframeHTML);
  26492. doc.close();
  26493. }
  26494. if (editor.inline) {
  26495. DOM$6.addClass(targetElm, 'mce-content-body');
  26496. editor.contentDocument = doc = document;
  26497. editor.contentWindow = window;
  26498. editor.bodyElement = targetElm;
  26499. editor.contentAreaContainer = targetElm;
  26500. }
  26501. var body = editor.getBody();
  26502. body.disabled = true;
  26503. editor.readonly = !!settings.readonly;
  26504. if (!editor.readonly) {
  26505. if (editor.inline && DOM$6.getStyle(body, 'position', true) === 'static') {
  26506. body.style.position = 'relative';
  26507. }
  26508. body.contentEditable = editor.getParam('content_editable_state', true);
  26509. }
  26510. body.disabled = false;
  26511. editor.editorUpload = EditorUpload(editor);
  26512. editor.schema = Schema(mkSchemaSettings(editor));
  26513. editor.dom = DOMUtils(doc, {
  26514. keep_values: true,
  26515. url_converter: editor.convertURL,
  26516. url_converter_scope: editor,
  26517. hex_colors: settings.force_hex_style_colors,
  26518. update_styles: true,
  26519. root_element: editor.inline ? editor.getBody() : null,
  26520. collect: function () {
  26521. return editor.inline;
  26522. },
  26523. schema: editor.schema,
  26524. contentCssCors: shouldUseContentCssCors(editor),
  26525. referrerPolicy: getReferrerPolicy(editor),
  26526. onSetAttrib: function (e) {
  26527. editor.fire('SetAttrib', e);
  26528. }
  26529. });
  26530. editor.parser = createParser(editor);
  26531. editor.serializer = DomSerializer(mkSerializerSettings(editor), editor);
  26532. editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor);
  26533. editor.annotator = Annotator(editor);
  26534. editor.formatter = Formatter(editor);
  26535. editor.undoManager = UndoManager(editor);
  26536. editor._nodeChangeDispatcher = new NodeChange(editor);
  26537. editor._selectionOverrides = SelectionOverrides(editor);
  26538. setup$e(editor);
  26539. setup$3(editor);
  26540. if (!isRtc(editor)) {
  26541. setup$2(editor);
  26542. }
  26543. var caret = setup$4(editor);
  26544. setup$f(editor, caret);
  26545. setup$d(editor);
  26546. setup$g(editor);
  26547. var setupRtcThunk = setup$i(editor);
  26548. preInit(editor);
  26549. setupRtcThunk.fold(function () {
  26550. loadContentCss(editor).then(function () {
  26551. return initEditorWithInitialContent(editor);
  26552. });
  26553. }, function (setupRtc) {
  26554. editor.setProgressState(true);
  26555. loadContentCss(editor).then(function () {
  26556. setupRtc().then(function (_rtcMode) {
  26557. editor.setProgressState(false);
  26558. initEditorWithInitialContent(editor);
  26559. }, function (err) {
  26560. editor.notificationManager.open({
  26561. type: 'error',
  26562. text: String(err)
  26563. });
  26564. initEditorWithInitialContent(editor);
  26565. });
  26566. });
  26567. });
  26568. };
  26569. var DOM$5 = DOMUtils.DOM;
  26570. var relaxDomain = function (editor, ifr) {
  26571. if (document.domain !== window.location.hostname && Env.browser.isIE()) {
  26572. var bodyUuid = uuid('mce');
  26573. editor[bodyUuid] = function () {
  26574. initContentBody(editor);
  26575. };
  26576. 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);})()';
  26577. DOM$5.setAttrib(ifr, 'src', domainRelaxUrl);
  26578. return true;
  26579. }
  26580. return false;
  26581. };
  26582. var createIframeElement = function (id, title, height, customAttrs) {
  26583. var iframe = SugarElement.fromTag('iframe');
  26584. setAll$1(iframe, customAttrs);
  26585. setAll$1(iframe, {
  26586. id: id + '_ifr',
  26587. frameBorder: '0',
  26588. allowTransparency: 'true',
  26589. title: title
  26590. });
  26591. add$1(iframe, 'tox-edit-area__iframe');
  26592. return iframe;
  26593. };
  26594. var getIframeHtml = function (editor) {
  26595. var iframeHTML = getDocType(editor) + '<html><head>';
  26596. if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
  26597. iframeHTML += '<base href="' + editor.documentBaseURI.getURI() + '" />';
  26598. }
  26599. iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
  26600. var bodyId = getBodyId(editor);
  26601. var bodyClass = getBodyClass(editor);
  26602. var translatedAriaText = editor.translate(getIframeAriaText(editor));
  26603. if (getContentSecurityPolicy(editor)) {
  26604. iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + getContentSecurityPolicy(editor) + '" />';
  26605. }
  26606. iframeHTML += '</head>' + ('<body id="' + bodyId + '" class="mce-content-body ' + bodyClass + '" data-id="' + editor.id + '" aria-label="' + translatedAriaText + '">') + '<br>' + '</body></html>';
  26607. return iframeHTML;
  26608. };
  26609. var createIframe = function (editor, o) {
  26610. var iframeTitle = editor.translate('Rich Text Area');
  26611. var ifr = createIframeElement(editor.id, iframeTitle, o.height, getIframeAttrs(editor)).dom;
  26612. ifr.onload = function () {
  26613. ifr.onload = null;
  26614. editor.fire('load');
  26615. };
  26616. var isDomainRelaxed = relaxDomain(editor, ifr);
  26617. editor.contentAreaContainer = o.iframeContainer;
  26618. editor.iframeElement = ifr;
  26619. editor.iframeHTML = getIframeHtml(editor);
  26620. DOM$5.add(o.iframeContainer, ifr);
  26621. return isDomainRelaxed;
  26622. };
  26623. var init$1 = function (editor, boxInfo) {
  26624. var isDomainRelaxed = createIframe(editor, boxInfo);
  26625. if (boxInfo.editorContainer) {
  26626. DOM$5.get(boxInfo.editorContainer).style.display = editor.orgDisplay;
  26627. editor.hidden = DOM$5.isHidden(boxInfo.editorContainer);
  26628. }
  26629. editor.getElement().style.display = 'none';
  26630. DOM$5.setAttrib(editor.id, 'aria-hidden', 'true');
  26631. if (!isDomainRelaxed) {
  26632. initContentBody(editor);
  26633. }
  26634. };
  26635. var DOM$4 = DOMUtils.DOM;
  26636. var initPlugin = function (editor, initializedPlugins, plugin) {
  26637. var Plugin = PluginManager.get(plugin);
  26638. var pluginUrl = PluginManager.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, '');
  26639. plugin = Tools.trim(plugin);
  26640. if (Plugin && Tools.inArray(initializedPlugins, plugin) === -1) {
  26641. Tools.each(PluginManager.dependencies(plugin), function (dep) {
  26642. initPlugin(editor, initializedPlugins, dep);
  26643. });
  26644. if (editor.plugins[plugin]) {
  26645. return;
  26646. }
  26647. try {
  26648. var pluginInstance = new Plugin(editor, pluginUrl, editor.$);
  26649. editor.plugins[plugin] = pluginInstance;
  26650. if (pluginInstance.init) {
  26651. pluginInstance.init(editor, pluginUrl);
  26652. initializedPlugins.push(plugin);
  26653. }
  26654. } catch (e) {
  26655. pluginInitError(editor, plugin, e);
  26656. }
  26657. }
  26658. };
  26659. var trimLegacyPrefix = function (name) {
  26660. return name.replace(/^\-/, '');
  26661. };
  26662. var initPlugins = function (editor) {
  26663. var initializedPlugins = [];
  26664. Tools.each(getPlugins(editor).split(/[ ,]/), function (name) {
  26665. initPlugin(editor, initializedPlugins, trimLegacyPrefix(name));
  26666. });
  26667. };
  26668. var initIcons = function (editor) {
  26669. var iconPackName = Tools.trim(getIconPackName(editor));
  26670. var currentIcons = editor.ui.registry.getAll().icons;
  26671. var loadIcons = __assign(__assign({}, IconManager.get('default').icons), IconManager.get(iconPackName).icons);
  26672. each$j(loadIcons, function (svgData, icon) {
  26673. if (!has$2(currentIcons, icon)) {
  26674. editor.ui.registry.addIcon(icon, svgData);
  26675. }
  26676. });
  26677. };
  26678. var initTheme = function (editor) {
  26679. var theme = getTheme(editor);
  26680. if (isString$1(theme)) {
  26681. editor.settings.theme = trimLegacyPrefix(theme);
  26682. var Theme = ThemeManager.get(theme);
  26683. editor.theme = new Theme(editor, ThemeManager.urls[theme]);
  26684. if (editor.theme.init) {
  26685. editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ''), editor.$);
  26686. }
  26687. } else {
  26688. editor.theme = {};
  26689. }
  26690. };
  26691. var renderFromLoadedTheme = function (editor) {
  26692. return editor.theme.renderUI();
  26693. };
  26694. var renderFromThemeFunc = function (editor) {
  26695. var elm = editor.getElement();
  26696. var theme = getTheme(editor);
  26697. var info = theme(editor, elm);
  26698. if (info.editorContainer.nodeType) {
  26699. info.editorContainer.id = info.editorContainer.id || editor.id + '_parent';
  26700. }
  26701. if (info.iframeContainer && info.iframeContainer.nodeType) {
  26702. info.iframeContainer.id = info.iframeContainer.id || editor.id + '_iframecontainer';
  26703. }
  26704. info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
  26705. return info;
  26706. };
  26707. var createThemeFalseResult = function (element) {
  26708. return {
  26709. editorContainer: element,
  26710. iframeContainer: element,
  26711. api: {}
  26712. };
  26713. };
  26714. var renderThemeFalseIframe = function (targetElement) {
  26715. var iframeContainer = DOM$4.create('div');
  26716. DOM$4.insertAfter(iframeContainer, targetElement);
  26717. return createThemeFalseResult(iframeContainer);
  26718. };
  26719. var renderThemeFalse = function (editor) {
  26720. var targetElement = editor.getElement();
  26721. return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
  26722. };
  26723. var renderThemeUi = function (editor) {
  26724. var elm = editor.getElement();
  26725. editor.orgDisplay = elm.style.display;
  26726. if (isString$1(getTheme(editor))) {
  26727. return renderFromLoadedTheme(editor);
  26728. } else if (isFunction(getTheme(editor))) {
  26729. return renderFromThemeFunc(editor);
  26730. } else {
  26731. return renderThemeFalse(editor);
  26732. }
  26733. };
  26734. var augmentEditorUiApi = function (editor, api) {
  26735. var uiApiFacade = {
  26736. show: Optional.from(api.show).getOr(noop),
  26737. hide: Optional.from(api.hide).getOr(noop),
  26738. disable: Optional.from(api.disable).getOr(noop),
  26739. isDisabled: Optional.from(api.isDisabled).getOr(never),
  26740. enable: function () {
  26741. if (!editor.mode.isReadOnly()) {
  26742. Optional.from(api.enable).map(call);
  26743. }
  26744. }
  26745. };
  26746. editor.ui = __assign(__assign({}, editor.ui), uiApiFacade);
  26747. };
  26748. var init = function (editor) {
  26749. editor.fire('ScriptsLoaded');
  26750. initIcons(editor);
  26751. initTheme(editor);
  26752. initPlugins(editor);
  26753. var renderInfo = renderThemeUi(editor);
  26754. augmentEditorUiApi(editor, Optional.from(renderInfo.api).getOr({}));
  26755. var boxInfo = {
  26756. editorContainer: renderInfo.editorContainer,
  26757. iframeContainer: renderInfo.iframeContainer
  26758. };
  26759. editor.editorContainer = boxInfo.editorContainer ? boxInfo.editorContainer : null;
  26760. appendContentCssFromSettings(editor);
  26761. if (editor.inline) {
  26762. return initContentBody(editor);
  26763. } else {
  26764. return init$1(editor, boxInfo);
  26765. }
  26766. };
  26767. var DOM$3 = DOMUtils.DOM;
  26768. var hasSkipLoadPrefix = function (name) {
  26769. return name.charAt(0) === '-';
  26770. };
  26771. var loadLanguage = function (scriptLoader, editor) {
  26772. var languageCode = getLanguageCode(editor);
  26773. var languageUrl = getLanguageUrl(editor);
  26774. if (I18n.hasCode(languageCode) === false && languageCode !== 'en') {
  26775. var url_1 = languageUrl !== '' ? languageUrl : editor.editorManager.baseURL + '/langs/' + languageCode + '.js';
  26776. scriptLoader.add(url_1, noop, undefined, function () {
  26777. languageLoadError(editor, url_1, languageCode);
  26778. });
  26779. }
  26780. };
  26781. var loadTheme = function (scriptLoader, editor, suffix, callback) {
  26782. var theme = getTheme(editor);
  26783. if (isString$1(theme)) {
  26784. if (!hasSkipLoadPrefix(theme) && !has$2(ThemeManager.urls, theme)) {
  26785. var themeUrl = getThemeUrl(editor);
  26786. if (themeUrl) {
  26787. ThemeManager.load(theme, editor.documentBaseURI.toAbsolute(themeUrl));
  26788. } else {
  26789. ThemeManager.load(theme, 'themes/' + theme + '/theme' + suffix + '.js');
  26790. }
  26791. }
  26792. scriptLoader.loadQueue(function () {
  26793. ThemeManager.waitFor(theme, callback);
  26794. });
  26795. } else {
  26796. callback();
  26797. }
  26798. };
  26799. var getIconsUrlMetaFromUrl = function (editor) {
  26800. return Optional.from(getIconsUrl(editor)).filter(function (url) {
  26801. return url.length > 0;
  26802. }).map(function (url) {
  26803. return {
  26804. url: url,
  26805. name: Optional.none()
  26806. };
  26807. });
  26808. };
  26809. var getIconsUrlMetaFromName = function (editor, name, suffix) {
  26810. return Optional.from(name).filter(function (name) {
  26811. return name.length > 0 && !IconManager.has(name);
  26812. }).map(function (name) {
  26813. return {
  26814. url: editor.editorManager.baseURL + '/icons/' + name + '/icons' + suffix + '.js',
  26815. name: Optional.some(name)
  26816. };
  26817. });
  26818. };
  26819. var loadIcons = function (scriptLoader, editor, suffix) {
  26820. var defaultIconsUrl = getIconsUrlMetaFromName(editor, 'default', suffix);
  26821. var customIconsUrl = getIconsUrlMetaFromUrl(editor).orThunk(function () {
  26822. return getIconsUrlMetaFromName(editor, getIconPackName(editor), '');
  26823. });
  26824. each$k(cat([
  26825. defaultIconsUrl,
  26826. customIconsUrl
  26827. ]), function (urlMeta) {
  26828. scriptLoader.add(urlMeta.url, noop, undefined, function () {
  26829. iconsLoadError(editor, urlMeta.url, urlMeta.name.getOrUndefined());
  26830. });
  26831. });
  26832. };
  26833. var loadPlugins = function (editor, suffix) {
  26834. Tools.each(getExternalPlugins$1(editor), function (url, name) {
  26835. PluginManager.load(name, url, noop, undefined, function () {
  26836. pluginLoadError(editor, url, name);
  26837. });
  26838. editor.settings.plugins += ' ' + name;
  26839. });
  26840. Tools.each(getPlugins(editor).split(/[ ,]/), function (plugin) {
  26841. plugin = Tools.trim(plugin);
  26842. if (plugin && !PluginManager.urls[plugin]) {
  26843. if (hasSkipLoadPrefix(plugin)) {
  26844. plugin = plugin.substr(1, plugin.length);
  26845. var dependencies = PluginManager.dependencies(plugin);
  26846. Tools.each(dependencies, function (depPlugin) {
  26847. var defaultSettings = {
  26848. prefix: 'plugins/',
  26849. resource: depPlugin,
  26850. suffix: '/plugin' + suffix + '.js'
  26851. };
  26852. var dep = PluginManager.createUrl(defaultSettings, depPlugin);
  26853. PluginManager.load(dep.resource, dep, noop, undefined, function () {
  26854. pluginLoadError(editor, dep.prefix + dep.resource + dep.suffix, dep.resource);
  26855. });
  26856. });
  26857. } else {
  26858. var url_2 = {
  26859. prefix: 'plugins/',
  26860. resource: plugin,
  26861. suffix: '/plugin' + suffix + '.js'
  26862. };
  26863. PluginManager.load(plugin, url_2, noop, undefined, function () {
  26864. pluginLoadError(editor, url_2.prefix + url_2.resource + url_2.suffix, plugin);
  26865. });
  26866. }
  26867. }
  26868. });
  26869. };
  26870. var loadScripts = function (editor, suffix) {
  26871. var scriptLoader = ScriptLoader.ScriptLoader;
  26872. loadTheme(scriptLoader, editor, suffix, function () {
  26873. loadLanguage(scriptLoader, editor);
  26874. loadIcons(scriptLoader, editor, suffix);
  26875. loadPlugins(editor, suffix);
  26876. scriptLoader.loadQueue(function () {
  26877. if (!editor.removed) {
  26878. init(editor);
  26879. }
  26880. }, editor, function () {
  26881. if (!editor.removed) {
  26882. init(editor);
  26883. }
  26884. });
  26885. });
  26886. };
  26887. var getStyleSheetLoader = function (element, editor) {
  26888. return instance.forElement(element, {
  26889. contentCssCors: hasContentCssCors(editor),
  26890. referrerPolicy: getReferrerPolicy(editor)
  26891. });
  26892. };
  26893. var render = function (editor) {
  26894. var id = editor.id;
  26895. I18n.setCode(getLanguageCode(editor));
  26896. var readyHandler = function () {
  26897. DOM$3.unbind(window, 'ready', readyHandler);
  26898. editor.render();
  26899. };
  26900. if (!EventUtils.Event.domLoaded) {
  26901. DOM$3.bind(window, 'ready', readyHandler);
  26902. return;
  26903. }
  26904. if (!editor.getElement()) {
  26905. return;
  26906. }
  26907. if (!Env.contentEditable) {
  26908. return;
  26909. }
  26910. var element = SugarElement.fromDom(editor.getElement());
  26911. var snapshot = clone$3(element);
  26912. editor.on('remove', function () {
  26913. eachr(element.dom.attributes, function (attr) {
  26914. return remove$6(element, attr.name);
  26915. });
  26916. setAll$1(element, snapshot);
  26917. });
  26918. editor.ui.styleSheetLoader = getStyleSheetLoader(element, editor);
  26919. if (!isInline(editor)) {
  26920. editor.orgVisibility = editor.getElement().style.visibility;
  26921. editor.getElement().style.visibility = 'hidden';
  26922. } else {
  26923. editor.inline = true;
  26924. }
  26925. var form = editor.getElement().form || DOM$3.getParent(id, 'form');
  26926. if (form) {
  26927. editor.formElement = form;
  26928. if (hasHiddenInput(editor) && !isTextareaOrInput(editor.getElement())) {
  26929. DOM$3.insertAfter(DOM$3.create('input', {
  26930. type: 'hidden',
  26931. name: id
  26932. }), id);
  26933. editor.hasHiddenInput = true;
  26934. }
  26935. editor.formEventDelegate = function (e) {
  26936. editor.fire(e.type, e);
  26937. };
  26938. DOM$3.bind(form, 'submit reset', editor.formEventDelegate);
  26939. editor.on('reset', function () {
  26940. editor.resetContent();
  26941. });
  26942. if (shouldPatchSubmit(editor) && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
  26943. form._mceOldSubmit = form.submit;
  26944. form.submit = function () {
  26945. editor.editorManager.triggerSave();
  26946. editor.setDirty(false);
  26947. return form._mceOldSubmit(form);
  26948. };
  26949. }
  26950. }
  26951. editor.windowManager = WindowManager(editor);
  26952. editor.notificationManager = NotificationManager(editor);
  26953. if (isEncodingXml(editor)) {
  26954. editor.on('GetContent', function (e) {
  26955. if (e.save) {
  26956. e.content = DOM$3.encode(e.content);
  26957. }
  26958. });
  26959. }
  26960. if (shouldAddFormSubmitTrigger(editor)) {
  26961. editor.on('submit', function () {
  26962. if (editor.initialized) {
  26963. editor.save();
  26964. }
  26965. });
  26966. }
  26967. if (shouldAddUnloadTrigger(editor)) {
  26968. editor._beforeUnload = function () {
  26969. if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
  26970. editor.save({
  26971. format: 'raw',
  26972. no_events: true,
  26973. set_dirty: false
  26974. });
  26975. }
  26976. };
  26977. editor.editorManager.on('BeforeUnload', editor._beforeUnload);
  26978. }
  26979. editor.editorManager.add(editor);
  26980. loadScripts(editor, editor.suffix);
  26981. };
  26982. var addVisual = function (editor, elm) {
  26983. return addVisual$1(editor, elm);
  26984. };
  26985. var legacyPropNames = {
  26986. 'font-size': 'size',
  26987. 'font-family': 'face'
  26988. };
  26989. var getSpecifiedFontProp = function (propName, rootElm, elm) {
  26990. var getProperty = function (elm) {
  26991. return getRaw(elm, propName).orThunk(function () {
  26992. if (name(elm) === 'font') {
  26993. return get$9(legacyPropNames, propName).bind(function (legacyPropName) {
  26994. return getOpt(elm, legacyPropName);
  26995. });
  26996. } else {
  26997. return Optional.none();
  26998. }
  26999. });
  27000. };
  27001. var isRoot = function (elm) {
  27002. return eq(SugarElement.fromDom(rootElm), elm);
  27003. };
  27004. return closest$1(SugarElement.fromDom(elm), function (elm) {
  27005. return getProperty(elm);
  27006. }, isRoot);
  27007. };
  27008. var normalizeFontFamily = function (fontFamily) {
  27009. return fontFamily.replace(/[\'\"\\]/g, '').replace(/,\s+/g, ',');
  27010. };
  27011. var getComputedFontProp = function (propName, elm) {
  27012. return Optional.from(DOMUtils.DOM.getStyle(elm, propName, true));
  27013. };
  27014. var getFontProp = function (propName) {
  27015. return function (rootElm, elm) {
  27016. return Optional.from(elm).map(SugarElement.fromDom).filter(isElement$6).bind(function (element) {
  27017. return getSpecifiedFontProp(propName, rootElm, element.dom).or(getComputedFontProp(propName, element.dom));
  27018. }).getOr('');
  27019. };
  27020. };
  27021. var getFontSize = getFontProp('font-size');
  27022. var getFontFamily = compose(normalizeFontFamily, getFontProp('font-family'));
  27023. var findFirstCaretElement = function (editor) {
  27024. return firstPositionIn(editor.getBody()).map(function (caret) {
  27025. var container = caret.container();
  27026. return isText$7(container) ? container.parentNode : container;
  27027. });
  27028. };
  27029. var getCaretElement = function (editor) {
  27030. return Optional.from(editor.selection.getRng()).bind(function (rng) {
  27031. var root = editor.getBody();
  27032. var atStartOfNode = rng.startContainer === root && rng.startOffset === 0;
  27033. return atStartOfNode ? Optional.none() : Optional.from(editor.selection.getStart(true));
  27034. });
  27035. };
  27036. var bindRange = function (editor, binder) {
  27037. return getCaretElement(editor).orThunk(curry(findFirstCaretElement, editor)).map(SugarElement.fromDom).filter(isElement$6).bind(binder);
  27038. };
  27039. var mapRange = function (editor, mapper) {
  27040. return bindRange(editor, compose1(Optional.some, mapper));
  27041. };
  27042. var fromFontSizeNumber = function (editor, value) {
  27043. if (/^[0-9.]+$/.test(value)) {
  27044. var fontSizeNumber = parseInt(value, 10);
  27045. if (fontSizeNumber >= 1 && fontSizeNumber <= 7) {
  27046. var fontSizes = getFontStyleValues(editor);
  27047. var fontClasses = getFontSizeClasses(editor);
  27048. if (fontClasses) {
  27049. return fontClasses[fontSizeNumber - 1] || value;
  27050. } else {
  27051. return fontSizes[fontSizeNumber - 1] || value;
  27052. }
  27053. } else {
  27054. return value;
  27055. }
  27056. } else {
  27057. return value;
  27058. }
  27059. };
  27060. var normalizeFontNames = function (font) {
  27061. var fonts = font.split(/\s*,\s*/);
  27062. return map$3(fonts, function (font) {
  27063. if (font.indexOf(' ') !== -1 && !(startsWith(font, '"') || startsWith(font, '\''))) {
  27064. return '\'' + font + '\'';
  27065. } else {
  27066. return font;
  27067. }
  27068. }).join(',');
  27069. };
  27070. var fontNameAction = function (editor, value) {
  27071. var font = fromFontSizeNumber(editor, value);
  27072. editor.formatter.toggle('fontname', { value: normalizeFontNames(font) });
  27073. editor.nodeChanged();
  27074. };
  27075. var fontNameQuery = function (editor) {
  27076. return mapRange(editor, function (elm) {
  27077. return getFontFamily(editor.getBody(), elm.dom);
  27078. }).getOr('');
  27079. };
  27080. var fontSizeAction = function (editor, value) {
  27081. editor.formatter.toggle('fontsize', { value: fromFontSizeNumber(editor, value) });
  27082. editor.nodeChanged();
  27083. };
  27084. var fontSizeQuery = function (editor) {
  27085. return mapRange(editor, function (elm) {
  27086. return getFontSize(editor.getBody(), elm.dom);
  27087. }).getOr('');
  27088. };
  27089. var lineHeightQuery = function (editor) {
  27090. return mapRange(editor, function (elm) {
  27091. var root = SugarElement.fromDom(editor.getBody());
  27092. var specifiedStyle = closest$1(elm, function (elm) {
  27093. return getRaw(elm, 'line-height');
  27094. }, curry(eq, root));
  27095. var computedStyle = function () {
  27096. var lineHeight = parseFloat(get$5(elm, 'line-height'));
  27097. var fontSize = parseFloat(get$5(elm, 'font-size'));
  27098. return String(lineHeight / fontSize);
  27099. };
  27100. return specifiedStyle.getOrThunk(computedStyle);
  27101. }).getOr('');
  27102. };
  27103. var lineHeightAction = function (editor, lineHeight) {
  27104. editor.formatter.toggle('lineheight', { value: String(lineHeight) });
  27105. editor.nodeChanged();
  27106. };
  27107. var processValue = function (value) {
  27108. if (typeof value !== 'string') {
  27109. var details = Tools.extend({
  27110. paste: value.paste,
  27111. data: { paste: value.paste }
  27112. }, value);
  27113. return {
  27114. content: value.content,
  27115. details: details
  27116. };
  27117. }
  27118. return {
  27119. content: value,
  27120. details: {}
  27121. };
  27122. };
  27123. var insertAtCaret = function (editor, value) {
  27124. var result = processValue(value);
  27125. insertContent(editor, result.content, result.details);
  27126. };
  27127. var each$4 = Tools.each;
  27128. var map = Tools.map, inArray = Tools.inArray;
  27129. var EditorCommands = function () {
  27130. function EditorCommands(editor) {
  27131. this.commands = {
  27132. state: {},
  27133. exec: {},
  27134. value: {}
  27135. };
  27136. this.editor = editor;
  27137. this.setupCommands(editor);
  27138. }
  27139. EditorCommands.prototype.execCommand = function (command, ui, value, args) {
  27140. var func, state = false;
  27141. var self = this;
  27142. if (self.editor.removed) {
  27143. return;
  27144. }
  27145. if (command.toLowerCase() !== 'mcefocus') {
  27146. if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) {
  27147. self.editor.focus();
  27148. } else {
  27149. restore(self.editor);
  27150. }
  27151. }
  27152. args = self.editor.fire('BeforeExecCommand', {
  27153. command: command,
  27154. ui: ui,
  27155. value: value
  27156. });
  27157. if (args.isDefaultPrevented()) {
  27158. return false;
  27159. }
  27160. var customCommand = command.toLowerCase();
  27161. if (func = self.commands.exec[customCommand]) {
  27162. func(customCommand, ui, value);
  27163. self.editor.fire('ExecCommand', {
  27164. command: command,
  27165. ui: ui,
  27166. value: value
  27167. });
  27168. return true;
  27169. }
  27170. each$4(this.editor.plugins, function (p) {
  27171. if (p.execCommand && p.execCommand(command, ui, value)) {
  27172. self.editor.fire('ExecCommand', {
  27173. command: command,
  27174. ui: ui,
  27175. value: value
  27176. });
  27177. state = true;
  27178. return false;
  27179. }
  27180. });
  27181. if (state) {
  27182. return state;
  27183. }
  27184. if (self.editor.theme && self.editor.theme.execCommand && self.editor.theme.execCommand(command, ui, value)) {
  27185. self.editor.fire('ExecCommand', {
  27186. command: command,
  27187. ui: ui,
  27188. value: value
  27189. });
  27190. return true;
  27191. }
  27192. try {
  27193. state = self.editor.getDoc().execCommand(command, ui, value);
  27194. } catch (ex) {
  27195. }
  27196. if (state) {
  27197. self.editor.fire('ExecCommand', {
  27198. command: command,
  27199. ui: ui,
  27200. value: value
  27201. });
  27202. return true;
  27203. }
  27204. return false;
  27205. };
  27206. EditorCommands.prototype.queryCommandState = function (command) {
  27207. var func;
  27208. if (this.editor.quirks.isHidden() || this.editor.removed) {
  27209. return;
  27210. }
  27211. command = command.toLowerCase();
  27212. if (func = this.commands.state[command]) {
  27213. return func(command);
  27214. }
  27215. try {
  27216. return this.editor.getDoc().queryCommandState(command);
  27217. } catch (ex) {
  27218. }
  27219. return false;
  27220. };
  27221. EditorCommands.prototype.queryCommandValue = function (command) {
  27222. var func;
  27223. if (this.editor.quirks.isHidden() || this.editor.removed) {
  27224. return;
  27225. }
  27226. command = command.toLowerCase();
  27227. if (func = this.commands.value[command]) {
  27228. return func(command);
  27229. }
  27230. try {
  27231. return this.editor.getDoc().queryCommandValue(command);
  27232. } catch (ex) {
  27233. }
  27234. };
  27235. EditorCommands.prototype.addCommands = function (commandList, type) {
  27236. if (type === void 0) {
  27237. type = 'exec';
  27238. }
  27239. var self = this;
  27240. each$4(commandList, function (callback, command) {
  27241. each$4(command.toLowerCase().split(','), function (command) {
  27242. self.commands[type][command] = callback;
  27243. });
  27244. });
  27245. };
  27246. EditorCommands.prototype.addCommand = function (command, callback, scope) {
  27247. var _this = this;
  27248. command = command.toLowerCase();
  27249. this.commands.exec[command] = function (command, ui, value, args) {
  27250. return callback.call(scope || _this.editor, ui, value, args);
  27251. };
  27252. };
  27253. EditorCommands.prototype.queryCommandSupported = function (command) {
  27254. command = command.toLowerCase();
  27255. if (this.commands.exec[command]) {
  27256. return true;
  27257. }
  27258. try {
  27259. return this.editor.getDoc().queryCommandSupported(command);
  27260. } catch (ex) {
  27261. }
  27262. return false;
  27263. };
  27264. EditorCommands.prototype.addQueryStateHandler = function (command, callback, scope) {
  27265. var _this = this;
  27266. command = command.toLowerCase();
  27267. this.commands.state[command] = function () {
  27268. return callback.call(scope || _this.editor);
  27269. };
  27270. };
  27271. EditorCommands.prototype.addQueryValueHandler = function (command, callback, scope) {
  27272. var _this = this;
  27273. command = command.toLowerCase();
  27274. this.commands.value[command] = function () {
  27275. return callback.call(scope || _this.editor);
  27276. };
  27277. };
  27278. EditorCommands.prototype.hasCustomCommand = function (command) {
  27279. command = command.toLowerCase();
  27280. return !!this.commands.exec[command];
  27281. };
  27282. EditorCommands.prototype.execNativeCommand = function (command, ui, value) {
  27283. if (ui === undefined) {
  27284. ui = false;
  27285. }
  27286. if (value === undefined) {
  27287. value = null;
  27288. }
  27289. return this.editor.getDoc().execCommand(command, ui, value);
  27290. };
  27291. EditorCommands.prototype.isFormatMatch = function (name) {
  27292. return this.editor.formatter.match(name);
  27293. };
  27294. EditorCommands.prototype.toggleFormat = function (name, value) {
  27295. this.editor.formatter.toggle(name, value);
  27296. this.editor.nodeChanged();
  27297. };
  27298. EditorCommands.prototype.storeSelection = function (type) {
  27299. this.selectionBookmark = this.editor.selection.getBookmark(type);
  27300. };
  27301. EditorCommands.prototype.restoreSelection = function () {
  27302. this.editor.selection.moveToBookmark(this.selectionBookmark);
  27303. };
  27304. EditorCommands.prototype.setupCommands = function (editor) {
  27305. var self = this;
  27306. this.addCommands({
  27307. 'mceResetDesignMode,mceBeginUndoLevel': noop,
  27308. 'mceEndUndoLevel,mceAddUndoLevel': function () {
  27309. editor.undoManager.add();
  27310. },
  27311. 'mceFocus': function (_command, _ui, value) {
  27312. focus(editor, value);
  27313. },
  27314. 'Cut,Copy,Paste': function (command) {
  27315. var doc = editor.getDoc();
  27316. var failed;
  27317. try {
  27318. self.execNativeCommand(command);
  27319. } catch (ex) {
  27320. failed = true;
  27321. }
  27322. if (command === 'paste' && !doc.queryCommandEnabled(command)) {
  27323. failed = true;
  27324. }
  27325. if (failed || !doc.queryCommandSupported(command)) {
  27326. var msg = editor.translate('Your browser doesn\'t support direct access to the clipboard. ' + 'Please use the Ctrl+X/C/V keyboard shortcuts instead.');
  27327. if (Env.mac) {
  27328. msg = msg.replace(/Ctrl\+/g, '\u2318+');
  27329. }
  27330. editor.notificationManager.open({
  27331. text: msg,
  27332. type: 'error'
  27333. });
  27334. }
  27335. },
  27336. 'unlink': function () {
  27337. if (editor.selection.isCollapsed()) {
  27338. var elm = editor.dom.getParent(editor.selection.getStart(), 'a');
  27339. if (elm) {
  27340. editor.dom.remove(elm, true);
  27341. }
  27342. return;
  27343. }
  27344. editor.formatter.remove('link');
  27345. },
  27346. 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone': function (command) {
  27347. var align = command.substring(7);
  27348. if (align === 'full') {
  27349. align = 'justify';
  27350. }
  27351. each$4('left,center,right,justify'.split(','), function (name) {
  27352. if (align !== name) {
  27353. editor.formatter.remove('align' + name);
  27354. }
  27355. });
  27356. if (align !== 'none') {
  27357. self.toggleFormat('align' + align);
  27358. }
  27359. },
  27360. 'InsertUnorderedList,InsertOrderedList': function (command) {
  27361. var listParent;
  27362. self.execNativeCommand(command);
  27363. var listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
  27364. if (listElm) {
  27365. listParent = listElm.parentNode;
  27366. if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
  27367. self.storeSelection();
  27368. editor.dom.split(listParent, listElm);
  27369. self.restoreSelection();
  27370. }
  27371. }
  27372. },
  27373. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  27374. self.toggleFormat(command);
  27375. },
  27376. 'ForeColor,HiliteColor': function (command, ui, value) {
  27377. self.toggleFormat(command, { value: value });
  27378. },
  27379. 'FontName': function (command, ui, value) {
  27380. fontNameAction(editor, value);
  27381. },
  27382. 'FontSize': function (command, ui, value) {
  27383. fontSizeAction(editor, value);
  27384. },
  27385. 'LineHeight': function (command, ui, value) {
  27386. lineHeightAction(editor, value);
  27387. },
  27388. 'Lang': function (command, ui, lang) {
  27389. self.toggleFormat(command, {
  27390. value: lang.code,
  27391. customValue: lang.customCode
  27392. });
  27393. },
  27394. 'RemoveFormat': function (command) {
  27395. editor.formatter.remove(command);
  27396. },
  27397. 'mceBlockQuote': function () {
  27398. self.toggleFormat('blockquote');
  27399. },
  27400. 'FormatBlock': function (command, ui, value) {
  27401. return self.toggleFormat(value || 'p');
  27402. },
  27403. 'mceCleanup': function () {
  27404. var bookmark = editor.selection.getBookmark();
  27405. editor.setContent(editor.getContent());
  27406. editor.selection.moveToBookmark(bookmark);
  27407. },
  27408. 'mceRemoveNode': function (command, ui, value) {
  27409. var node = value || editor.selection.getNode();
  27410. if (node !== editor.getBody()) {
  27411. self.storeSelection();
  27412. editor.dom.remove(node, true);
  27413. self.restoreSelection();
  27414. }
  27415. },
  27416. 'mceSelectNodeDepth': function (command, ui, value) {
  27417. var counter = 0;
  27418. editor.dom.getParent(editor.selection.getNode(), function (node) {
  27419. if (node.nodeType === 1 && counter++ === value) {
  27420. editor.selection.select(node);
  27421. return false;
  27422. }
  27423. }, editor.getBody());
  27424. },
  27425. 'mceSelectNode': function (command, ui, value) {
  27426. editor.selection.select(value);
  27427. },
  27428. 'mceInsertContent': function (command, ui, value) {
  27429. insertAtCaret(editor, value);
  27430. },
  27431. 'mceInsertRawHTML': function (command, ui, value) {
  27432. editor.selection.setContent('tiny_mce_marker');
  27433. var content = editor.getContent();
  27434. editor.setContent(content.replace(/tiny_mce_marker/g, function () {
  27435. return value;
  27436. }));
  27437. },
  27438. 'mceInsertNewLine': function (command, ui, value) {
  27439. insert(editor, value);
  27440. },
  27441. 'mceToggleFormat': function (command, ui, value) {
  27442. self.toggleFormat(value);
  27443. },
  27444. 'mceSetContent': function (command, ui, value) {
  27445. editor.setContent(value);
  27446. },
  27447. 'Indent,Outdent': function (command) {
  27448. handle(editor, command);
  27449. },
  27450. 'mceRepaint': noop,
  27451. 'InsertHorizontalRule': function () {
  27452. editor.execCommand('mceInsertContent', false, '<hr />');
  27453. },
  27454. 'mceToggleVisualAid': function () {
  27455. editor.hasVisual = !editor.hasVisual;
  27456. editor.addVisual();
  27457. },
  27458. 'mceReplaceContent': function (command, ui, value) {
  27459. editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, editor.selection.getContent({ format: 'text' })));
  27460. },
  27461. 'mceInsertLink': function (command, ui, value) {
  27462. if (typeof value === 'string') {
  27463. value = { href: value };
  27464. }
  27465. var anchor = editor.dom.getParent(editor.selection.getNode(), 'a');
  27466. value.href = value.href.replace(/ /g, '%20');
  27467. if (!anchor || !value.href) {
  27468. editor.formatter.remove('link');
  27469. }
  27470. if (value.href) {
  27471. editor.formatter.apply('link', value, anchor);
  27472. }
  27473. },
  27474. 'selectAll': function () {
  27475. var editingHost = editor.dom.getParent(editor.selection.getStart(), isContentEditableTrue$4);
  27476. if (editingHost) {
  27477. var rng = editor.dom.createRng();
  27478. rng.selectNodeContents(editingHost);
  27479. editor.selection.setRng(rng);
  27480. }
  27481. },
  27482. 'mceNewDocument': function () {
  27483. editor.setContent('');
  27484. },
  27485. 'InsertLineBreak': function (command, ui, value) {
  27486. insert$1(editor, value);
  27487. return true;
  27488. }
  27489. });
  27490. var alignStates = function (name) {
  27491. return function () {
  27492. var selection = editor.selection;
  27493. var nodes = selection.isCollapsed() ? [editor.dom.getParent(selection.getNode(), editor.dom.isBlock)] : selection.getSelectedBlocks();
  27494. var matches = map(nodes, function (node) {
  27495. return !!editor.formatter.matchNode(node, name);
  27496. });
  27497. return inArray(matches, true) !== -1;
  27498. };
  27499. };
  27500. self.addCommands({
  27501. 'JustifyLeft': alignStates('alignleft'),
  27502. 'JustifyCenter': alignStates('aligncenter'),
  27503. 'JustifyRight': alignStates('alignright'),
  27504. 'JustifyFull': alignStates('alignjustify'),
  27505. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  27506. return self.isFormatMatch(command);
  27507. },
  27508. 'mceBlockQuote': function () {
  27509. return self.isFormatMatch('blockquote');
  27510. },
  27511. 'Outdent': function () {
  27512. return canOutdent(editor);
  27513. },
  27514. 'InsertUnorderedList,InsertOrderedList': function (command) {
  27515. var list = editor.dom.getParent(editor.selection.getNode(), 'ul,ol');
  27516. return list && (command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL');
  27517. }
  27518. }, 'state');
  27519. self.addCommands({
  27520. Undo: function () {
  27521. editor.undoManager.undo();
  27522. },
  27523. Redo: function () {
  27524. editor.undoManager.redo();
  27525. }
  27526. });
  27527. self.addQueryValueHandler('FontName', function () {
  27528. return fontNameQuery(editor);
  27529. }, this);
  27530. self.addQueryValueHandler('FontSize', function () {
  27531. return fontSizeQuery(editor);
  27532. }, this);
  27533. self.addQueryValueHandler('LineHeight', function () {
  27534. return lineHeightQuery(editor);
  27535. }, this);
  27536. };
  27537. return EditorCommands;
  27538. }();
  27539. var internalContentEditableAttr = 'data-mce-contenteditable';
  27540. var toggleClass = function (elm, cls, state) {
  27541. if (has(elm, cls) && state === false) {
  27542. remove$3(elm, cls);
  27543. } else if (state) {
  27544. add$1(elm, cls);
  27545. }
  27546. };
  27547. var setEditorCommandState = function (editor, cmd, state) {
  27548. try {
  27549. editor.getDoc().execCommand(cmd, false, String(state));
  27550. } catch (ex) {
  27551. }
  27552. };
  27553. var setContentEditable = function (elm, state) {
  27554. elm.dom.contentEditable = state ? 'true' : 'false';
  27555. };
  27556. var switchOffContentEditableTrue = function (elm) {
  27557. each$k(descendants(elm, '*[contenteditable="true"]'), function (elm) {
  27558. set$1(elm, internalContentEditableAttr, 'true');
  27559. setContentEditable(elm, false);
  27560. });
  27561. };
  27562. var switchOnContentEditableTrue = function (elm) {
  27563. each$k(descendants(elm, '*[' + internalContentEditableAttr + '="true"]'), function (elm) {
  27564. remove$6(elm, internalContentEditableAttr);
  27565. setContentEditable(elm, true);
  27566. });
  27567. };
  27568. var removeFakeSelection = function (editor) {
  27569. Optional.from(editor.selection.getNode()).each(function (elm) {
  27570. elm.removeAttribute('data-mce-selected');
  27571. });
  27572. };
  27573. var restoreFakeSelection = function (editor) {
  27574. editor.selection.setRng(editor.selection.getRng());
  27575. };
  27576. var toggleReadOnly = function (editor, state) {
  27577. var body = SugarElement.fromDom(editor.getBody());
  27578. toggleClass(body, 'mce-content-readonly', state);
  27579. if (state) {
  27580. editor.selection.controlSelection.hideResizeRect();
  27581. editor._selectionOverrides.hideFakeCaret();
  27582. removeFakeSelection(editor);
  27583. editor.readonly = true;
  27584. setContentEditable(body, false);
  27585. switchOffContentEditableTrue(body);
  27586. } else {
  27587. editor.readonly = false;
  27588. setContentEditable(body, true);
  27589. switchOnContentEditableTrue(body);
  27590. setEditorCommandState(editor, 'StyleWithCSS', false);
  27591. setEditorCommandState(editor, 'enableInlineTableEditing', false);
  27592. setEditorCommandState(editor, 'enableObjectResizing', false);
  27593. if (hasEditorOrUiFocus(editor)) {
  27594. editor.focus();
  27595. }
  27596. restoreFakeSelection(editor);
  27597. editor.nodeChanged();
  27598. }
  27599. };
  27600. var isReadOnly = function (editor) {
  27601. return editor.readonly;
  27602. };
  27603. var registerFilters = function (editor) {
  27604. editor.parser.addAttributeFilter('contenteditable', function (nodes) {
  27605. if (isReadOnly(editor)) {
  27606. each$k(nodes, function (node) {
  27607. node.attr(internalContentEditableAttr, node.attr('contenteditable'));
  27608. node.attr('contenteditable', 'false');
  27609. });
  27610. }
  27611. });
  27612. editor.serializer.addAttributeFilter(internalContentEditableAttr, function (nodes) {
  27613. if (isReadOnly(editor)) {
  27614. each$k(nodes, function (node) {
  27615. node.attr('contenteditable', node.attr(internalContentEditableAttr));
  27616. });
  27617. }
  27618. });
  27619. editor.serializer.addTempAttr(internalContentEditableAttr);
  27620. };
  27621. var registerReadOnlyContentFilters = function (editor) {
  27622. if (editor.serializer) {
  27623. registerFilters(editor);
  27624. } else {
  27625. editor.on('PreInit', function () {
  27626. registerFilters(editor);
  27627. });
  27628. }
  27629. };
  27630. var isClickEvent = function (e) {
  27631. return e.type === 'click';
  27632. };
  27633. var getAnchorHrefOpt = function (editor, elm) {
  27634. var isRoot = function (elm) {
  27635. return eq(elm, SugarElement.fromDom(editor.getBody()));
  27636. };
  27637. return closest$2(elm, 'a', isRoot).bind(function (a) {
  27638. return getOpt(a, 'href');
  27639. });
  27640. };
  27641. var processReadonlyEvents = function (editor, e) {
  27642. if (isClickEvent(e) && !VK.metaKeyPressed(e)) {
  27643. var elm = SugarElement.fromDom(e.target);
  27644. getAnchorHrefOpt(editor, elm).each(function (href) {
  27645. e.preventDefault();
  27646. if (/^#/.test(href)) {
  27647. var targetEl = editor.dom.select(href + ',[name="' + removeLeading(href, '#') + '"]');
  27648. if (targetEl.length) {
  27649. editor.selection.scrollIntoView(targetEl[0], true);
  27650. }
  27651. } else {
  27652. window.open(href, '_blank', 'rel=noopener noreferrer,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes,scrollbars=yes');
  27653. }
  27654. });
  27655. }
  27656. };
  27657. var registerReadOnlySelectionBlockers = function (editor) {
  27658. editor.on('ShowCaret', function (e) {
  27659. if (isReadOnly(editor)) {
  27660. e.preventDefault();
  27661. }
  27662. });
  27663. editor.on('ObjectSelected', function (e) {
  27664. if (isReadOnly(editor)) {
  27665. e.preventDefault();
  27666. }
  27667. });
  27668. };
  27669. 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', ' ');
  27670. var EventDispatcher = function () {
  27671. function EventDispatcher(settings) {
  27672. this.bindings = {};
  27673. this.settings = settings || {};
  27674. this.scope = this.settings.scope || this;
  27675. this.toggleEvent = this.settings.toggleEvent || never;
  27676. }
  27677. EventDispatcher.isNative = function (name) {
  27678. return !!nativeEvents[name.toLowerCase()];
  27679. };
  27680. EventDispatcher.prototype.fire = function (name, args) {
  27681. var lcName = name.toLowerCase();
  27682. var event = normalize$3(lcName, args || {}, this.scope);
  27683. if (this.settings.beforeFire) {
  27684. this.settings.beforeFire(event);
  27685. }
  27686. var handlers = this.bindings[lcName];
  27687. if (handlers) {
  27688. for (var i = 0, l = handlers.length; i < l; i++) {
  27689. var callback = handlers[i];
  27690. if (callback.removed) {
  27691. continue;
  27692. }
  27693. if (callback.once) {
  27694. this.off(lcName, callback.func);
  27695. }
  27696. if (event.isImmediatePropagationStopped()) {
  27697. return event;
  27698. }
  27699. if (callback.func.call(this.scope, event) === false) {
  27700. event.preventDefault();
  27701. return event;
  27702. }
  27703. }
  27704. }
  27705. return event;
  27706. };
  27707. EventDispatcher.prototype.on = function (name, callback, prepend, extra) {
  27708. if (callback === false) {
  27709. callback = never;
  27710. }
  27711. if (callback) {
  27712. var wrappedCallback = {
  27713. func: callback,
  27714. removed: false
  27715. };
  27716. if (extra) {
  27717. Tools.extend(wrappedCallback, extra);
  27718. }
  27719. var names = name.toLowerCase().split(' ');
  27720. var i = names.length;
  27721. while (i--) {
  27722. var currentName = names[i];
  27723. var handlers = this.bindings[currentName];
  27724. if (!handlers) {
  27725. handlers = [];
  27726. this.toggleEvent(currentName, true);
  27727. }
  27728. if (prepend) {
  27729. handlers = __spreadArray([wrappedCallback], handlers, true);
  27730. } else {
  27731. handlers = __spreadArray(__spreadArray([], handlers, true), [wrappedCallback], false);
  27732. }
  27733. this.bindings[currentName] = handlers;
  27734. }
  27735. }
  27736. return this;
  27737. };
  27738. EventDispatcher.prototype.off = function (name, callback) {
  27739. var _this = this;
  27740. if (name) {
  27741. var names = name.toLowerCase().split(' ');
  27742. var i = names.length;
  27743. while (i--) {
  27744. var currentName = names[i];
  27745. var handlers = this.bindings[currentName];
  27746. if (!currentName) {
  27747. each$j(this.bindings, function (_value, bindingName) {
  27748. _this.toggleEvent(bindingName, false);
  27749. delete _this.bindings[bindingName];
  27750. });
  27751. return this;
  27752. }
  27753. if (handlers) {
  27754. if (!callback) {
  27755. handlers.length = 0;
  27756. } else {
  27757. var filteredHandlers = partition(handlers, function (handler) {
  27758. return handler.func === callback;
  27759. });
  27760. handlers = filteredHandlers.fail;
  27761. this.bindings[currentName] = handlers;
  27762. each$k(filteredHandlers.pass, function (handler) {
  27763. handler.removed = true;
  27764. });
  27765. }
  27766. if (!handlers.length) {
  27767. this.toggleEvent(name, false);
  27768. delete this.bindings[currentName];
  27769. }
  27770. }
  27771. }
  27772. } else {
  27773. each$j(this.bindings, function (_value, name) {
  27774. _this.toggleEvent(name, false);
  27775. });
  27776. this.bindings = {};
  27777. }
  27778. return this;
  27779. };
  27780. EventDispatcher.prototype.once = function (name, callback, prepend) {
  27781. return this.on(name, callback, prepend, { once: true });
  27782. };
  27783. EventDispatcher.prototype.has = function (name) {
  27784. name = name.toLowerCase();
  27785. return !(!this.bindings[name] || this.bindings[name].length === 0);
  27786. };
  27787. return EventDispatcher;
  27788. }();
  27789. var getEventDispatcher = function (obj) {
  27790. if (!obj._eventDispatcher) {
  27791. obj._eventDispatcher = new EventDispatcher({
  27792. scope: obj,
  27793. toggleEvent: function (name, state) {
  27794. if (EventDispatcher.isNative(name) && obj.toggleNativeEvent) {
  27795. obj.toggleNativeEvent(name, state);
  27796. }
  27797. }
  27798. });
  27799. }
  27800. return obj._eventDispatcher;
  27801. };
  27802. var Observable = {
  27803. fire: function (name, args, bubble) {
  27804. var self = this;
  27805. if (self.removed && name !== 'remove' && name !== 'detach') {
  27806. return args;
  27807. }
  27808. var dispatcherArgs = getEventDispatcher(self).fire(name, args);
  27809. if (bubble !== false && self.parent) {
  27810. var parent_1 = self.parent();
  27811. while (parent_1 && !dispatcherArgs.isPropagationStopped()) {
  27812. parent_1.fire(name, dispatcherArgs, false);
  27813. parent_1 = parent_1.parent();
  27814. }
  27815. }
  27816. return dispatcherArgs;
  27817. },
  27818. on: function (name, callback, prepend) {
  27819. return getEventDispatcher(this).on(name, callback, prepend);
  27820. },
  27821. off: function (name, callback) {
  27822. return getEventDispatcher(this).off(name, callback);
  27823. },
  27824. once: function (name, callback) {
  27825. return getEventDispatcher(this).once(name, callback);
  27826. },
  27827. hasEventListeners: function (name) {
  27828. return getEventDispatcher(this).has(name);
  27829. }
  27830. };
  27831. var DOM$2 = DOMUtils.DOM;
  27832. var customEventRootDelegates;
  27833. var getEventTarget = function (editor, eventName) {
  27834. if (eventName === 'selectionchange') {
  27835. return editor.getDoc();
  27836. }
  27837. if (!editor.inline && /^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(eventName)) {
  27838. return editor.getDoc().documentElement;
  27839. }
  27840. var eventRoot = getEventRoot(editor);
  27841. if (eventRoot) {
  27842. if (!editor.eventRoot) {
  27843. editor.eventRoot = DOM$2.select(eventRoot)[0];
  27844. }
  27845. return editor.eventRoot;
  27846. }
  27847. return editor.getBody();
  27848. };
  27849. var isListening = function (editor) {
  27850. return !editor.hidden && !isReadOnly(editor);
  27851. };
  27852. var fireEvent = function (editor, eventName, e) {
  27853. if (isListening(editor)) {
  27854. editor.fire(eventName, e);
  27855. } else if (isReadOnly(editor)) {
  27856. processReadonlyEvents(editor, e);
  27857. }
  27858. };
  27859. var bindEventDelegate = function (editor, eventName) {
  27860. var delegate;
  27861. if (!editor.delegates) {
  27862. editor.delegates = {};
  27863. }
  27864. if (editor.delegates[eventName] || editor.removed) {
  27865. return;
  27866. }
  27867. var eventRootElm = getEventTarget(editor, eventName);
  27868. if (getEventRoot(editor)) {
  27869. if (!customEventRootDelegates) {
  27870. customEventRootDelegates = {};
  27871. editor.editorManager.on('removeEditor', function () {
  27872. if (!editor.editorManager.activeEditor) {
  27873. if (customEventRootDelegates) {
  27874. each$j(customEventRootDelegates, function (_value, name) {
  27875. editor.dom.unbind(getEventTarget(editor, name));
  27876. });
  27877. customEventRootDelegates = null;
  27878. }
  27879. }
  27880. });
  27881. }
  27882. if (customEventRootDelegates[eventName]) {
  27883. return;
  27884. }
  27885. delegate = function (e) {
  27886. var target = e.target;
  27887. var editors = editor.editorManager.get();
  27888. var i = editors.length;
  27889. while (i--) {
  27890. var body = editors[i].getBody();
  27891. if (body === target || DOM$2.isChildOf(target, body)) {
  27892. fireEvent(editors[i], eventName, e);
  27893. }
  27894. }
  27895. };
  27896. customEventRootDelegates[eventName] = delegate;
  27897. DOM$2.bind(eventRootElm, eventName, delegate);
  27898. } else {
  27899. delegate = function (e) {
  27900. fireEvent(editor, eventName, e);
  27901. };
  27902. DOM$2.bind(eventRootElm, eventName, delegate);
  27903. editor.delegates[eventName] = delegate;
  27904. }
  27905. };
  27906. var EditorObservable = __assign(__assign({}, Observable), {
  27907. bindPendingEventDelegates: function () {
  27908. var self = this;
  27909. Tools.each(self._pendingNativeEvents, function (name) {
  27910. bindEventDelegate(self, name);
  27911. });
  27912. },
  27913. toggleNativeEvent: function (name, state) {
  27914. var self = this;
  27915. if (name === 'focus' || name === 'blur') {
  27916. return;
  27917. }
  27918. if (self.removed) {
  27919. return;
  27920. }
  27921. if (state) {
  27922. if (self.initialized) {
  27923. bindEventDelegate(self, name);
  27924. } else {
  27925. if (!self._pendingNativeEvents) {
  27926. self._pendingNativeEvents = [name];
  27927. } else {
  27928. self._pendingNativeEvents.push(name);
  27929. }
  27930. }
  27931. } else if (self.initialized) {
  27932. self.dom.unbind(getEventTarget(self, name), name, self.delegates[name]);
  27933. delete self.delegates[name];
  27934. }
  27935. },
  27936. unbindAllNativeEvents: function () {
  27937. var self = this;
  27938. var body = self.getBody();
  27939. var dom = self.dom;
  27940. if (self.delegates) {
  27941. each$j(self.delegates, function (value, name) {
  27942. self.dom.unbind(getEventTarget(self, name), name, value);
  27943. });
  27944. delete self.delegates;
  27945. }
  27946. if (!self.inline && body && dom) {
  27947. body.onload = null;
  27948. dom.unbind(self.getWin());
  27949. dom.unbind(self.getDoc());
  27950. }
  27951. if (dom) {
  27952. dom.unbind(body);
  27953. dom.unbind(self.getContainer());
  27954. }
  27955. }
  27956. });
  27957. var defaultModes = [
  27958. 'design',
  27959. 'readonly'
  27960. ];
  27961. var switchToMode = function (editor, activeMode, availableModes, mode) {
  27962. var oldMode = availableModes[activeMode.get()];
  27963. var newMode = availableModes[mode];
  27964. try {
  27965. newMode.activate();
  27966. } catch (e) {
  27967. console.error('problem while activating editor mode ' + mode + ':', e);
  27968. return;
  27969. }
  27970. oldMode.deactivate();
  27971. if (oldMode.editorReadOnly !== newMode.editorReadOnly) {
  27972. toggleReadOnly(editor, newMode.editorReadOnly);
  27973. }
  27974. activeMode.set(mode);
  27975. fireSwitchMode(editor, mode);
  27976. };
  27977. var setMode = function (editor, availableModes, activeMode, mode) {
  27978. if (mode === activeMode.get()) {
  27979. return;
  27980. } else if (!has$2(availableModes, mode)) {
  27981. throw new Error('Editor mode \'' + mode + '\' is invalid');
  27982. }
  27983. if (editor.initialized) {
  27984. switchToMode(editor, activeMode, availableModes, mode);
  27985. } else {
  27986. editor.on('init', function () {
  27987. return switchToMode(editor, activeMode, availableModes, mode);
  27988. });
  27989. }
  27990. };
  27991. var registerMode = function (availableModes, mode, api) {
  27992. var _a;
  27993. if (contains$3(defaultModes, mode)) {
  27994. throw new Error('Cannot override default mode ' + mode);
  27995. }
  27996. return __assign(__assign({}, availableModes), (_a = {}, _a[mode] = __assign(__assign({}, api), {
  27997. deactivate: function () {
  27998. try {
  27999. api.deactivate();
  28000. } catch (e) {
  28001. console.error('problem while deactivating editor mode ' + mode + ':', e);
  28002. }
  28003. }
  28004. }), _a));
  28005. };
  28006. var create$4 = function (editor) {
  28007. var activeMode = Cell('design');
  28008. var availableModes = Cell({
  28009. design: {
  28010. activate: noop,
  28011. deactivate: noop,
  28012. editorReadOnly: false
  28013. },
  28014. readonly: {
  28015. activate: noop,
  28016. deactivate: noop,
  28017. editorReadOnly: true
  28018. }
  28019. });
  28020. registerReadOnlyContentFilters(editor);
  28021. registerReadOnlySelectionBlockers(editor);
  28022. return {
  28023. isReadOnly: function () {
  28024. return isReadOnly(editor);
  28025. },
  28026. set: function (mode) {
  28027. return setMode(editor, availableModes.get(), activeMode, mode);
  28028. },
  28029. get: function () {
  28030. return activeMode.get();
  28031. },
  28032. register: function (mode, api) {
  28033. availableModes.set(registerMode(availableModes.get(), mode, api));
  28034. }
  28035. };
  28036. };
  28037. var each$3 = Tools.each, explode$1 = Tools.explode;
  28038. var keyCodeLookup = {
  28039. f1: 112,
  28040. f2: 113,
  28041. f3: 114,
  28042. f4: 115,
  28043. f5: 116,
  28044. f6: 117,
  28045. f7: 118,
  28046. f8: 119,
  28047. f9: 120,
  28048. f10: 121,
  28049. f11: 122,
  28050. f12: 123
  28051. };
  28052. var modifierNames = Tools.makeMap('alt,ctrl,shift,meta,access');
  28053. var parseShortcut = function (pattern) {
  28054. var key;
  28055. var shortcut = {};
  28056. each$3(explode$1(pattern.toLowerCase(), '+'), function (value) {
  28057. if (value in modifierNames) {
  28058. shortcut[value] = true;
  28059. } else {
  28060. if (/^[0-9]{2,}$/.test(value)) {
  28061. shortcut.keyCode = parseInt(value, 10);
  28062. } else {
  28063. shortcut.charCode = value.charCodeAt(0);
  28064. shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);
  28065. }
  28066. }
  28067. });
  28068. var id = [shortcut.keyCode];
  28069. for (key in modifierNames) {
  28070. if (shortcut[key]) {
  28071. id.push(key);
  28072. } else {
  28073. shortcut[key] = false;
  28074. }
  28075. }
  28076. shortcut.id = id.join(',');
  28077. if (shortcut.access) {
  28078. shortcut.alt = true;
  28079. if (Env.mac) {
  28080. shortcut.ctrl = true;
  28081. } else {
  28082. shortcut.shift = true;
  28083. }
  28084. }
  28085. if (shortcut.meta) {
  28086. if (Env.mac) {
  28087. shortcut.meta = true;
  28088. } else {
  28089. shortcut.ctrl = true;
  28090. shortcut.meta = false;
  28091. }
  28092. }
  28093. return shortcut;
  28094. };
  28095. var Shortcuts = function () {
  28096. function Shortcuts(editor) {
  28097. this.shortcuts = {};
  28098. this.pendingPatterns = [];
  28099. this.editor = editor;
  28100. var self = this;
  28101. editor.on('keyup keypress keydown', function (e) {
  28102. if ((self.hasModifier(e) || self.isFunctionKey(e)) && !e.isDefaultPrevented()) {
  28103. each$3(self.shortcuts, function (shortcut) {
  28104. if (self.matchShortcut(e, shortcut)) {
  28105. self.pendingPatterns = shortcut.subpatterns.slice(0);
  28106. if (e.type === 'keydown') {
  28107. self.executeShortcutAction(shortcut);
  28108. }
  28109. return true;
  28110. }
  28111. });
  28112. if (self.matchShortcut(e, self.pendingPatterns[0])) {
  28113. if (self.pendingPatterns.length === 1) {
  28114. if (e.type === 'keydown') {
  28115. self.executeShortcutAction(self.pendingPatterns[0]);
  28116. }
  28117. }
  28118. self.pendingPatterns.shift();
  28119. }
  28120. }
  28121. });
  28122. }
  28123. Shortcuts.prototype.add = function (pattern, desc, cmdFunc, scope) {
  28124. var self = this;
  28125. var func = self.normalizeCommandFunc(cmdFunc);
  28126. each$3(explode$1(Tools.trim(pattern)), function (pattern) {
  28127. var shortcut = self.createShortcut(pattern, desc, func, scope);
  28128. self.shortcuts[shortcut.id] = shortcut;
  28129. });
  28130. return true;
  28131. };
  28132. Shortcuts.prototype.remove = function (pattern) {
  28133. var shortcut = this.createShortcut(pattern);
  28134. if (this.shortcuts[shortcut.id]) {
  28135. delete this.shortcuts[shortcut.id];
  28136. return true;
  28137. }
  28138. return false;
  28139. };
  28140. Shortcuts.prototype.normalizeCommandFunc = function (cmdFunc) {
  28141. var self = this;
  28142. var cmd = cmdFunc;
  28143. if (typeof cmd === 'string') {
  28144. return function () {
  28145. self.editor.execCommand(cmd, false, null);
  28146. };
  28147. } else if (Tools.isArray(cmd)) {
  28148. return function () {
  28149. self.editor.execCommand(cmd[0], cmd[1], cmd[2]);
  28150. };
  28151. } else {
  28152. return cmd;
  28153. }
  28154. };
  28155. Shortcuts.prototype.createShortcut = function (pattern, desc, cmdFunc, scope) {
  28156. var shortcuts = Tools.map(explode$1(pattern, '>'), parseShortcut);
  28157. shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {
  28158. func: cmdFunc,
  28159. scope: scope || this.editor
  28160. });
  28161. return Tools.extend(shortcuts[0], {
  28162. desc: this.editor.translate(desc),
  28163. subpatterns: shortcuts.slice(1)
  28164. });
  28165. };
  28166. Shortcuts.prototype.hasModifier = function (e) {
  28167. return e.altKey || e.ctrlKey || e.metaKey;
  28168. };
  28169. Shortcuts.prototype.isFunctionKey = function (e) {
  28170. return e.type === 'keydown' && e.keyCode >= 112 && e.keyCode <= 123;
  28171. };
  28172. Shortcuts.prototype.matchShortcut = function (e, shortcut) {
  28173. if (!shortcut) {
  28174. return false;
  28175. }
  28176. if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
  28177. return false;
  28178. }
  28179. if (shortcut.alt !== e.altKey || shortcut.shift !== e.shiftKey) {
  28180. return false;
  28181. }
  28182. if (e.keyCode === shortcut.keyCode || e.charCode && e.charCode === shortcut.charCode) {
  28183. e.preventDefault();
  28184. return true;
  28185. }
  28186. return false;
  28187. };
  28188. Shortcuts.prototype.executeShortcutAction = function (shortcut) {
  28189. return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
  28190. };
  28191. return Shortcuts;
  28192. }();
  28193. var create$3 = function () {
  28194. var buttons = {};
  28195. var menuItems = {};
  28196. var popups = {};
  28197. var icons = {};
  28198. var contextMenus = {};
  28199. var contextToolbars = {};
  28200. var sidebars = {};
  28201. var add = function (collection, type) {
  28202. return function (name, spec) {
  28203. return collection[name.toLowerCase()] = __assign(__assign({}, spec), { type: type });
  28204. };
  28205. };
  28206. var addIcon = function (name, svgData) {
  28207. return icons[name.toLowerCase()] = svgData;
  28208. };
  28209. return {
  28210. addButton: add(buttons, 'button'),
  28211. addGroupToolbarButton: add(buttons, 'grouptoolbarbutton'),
  28212. addToggleButton: add(buttons, 'togglebutton'),
  28213. addMenuButton: add(buttons, 'menubutton'),
  28214. addSplitButton: add(buttons, 'splitbutton'),
  28215. addMenuItem: add(menuItems, 'menuitem'),
  28216. addNestedMenuItem: add(menuItems, 'nestedmenuitem'),
  28217. addToggleMenuItem: add(menuItems, 'togglemenuitem'),
  28218. addAutocompleter: add(popups, 'autocompleter'),
  28219. addContextMenu: add(contextMenus, 'contextmenu'),
  28220. addContextToolbar: add(contextToolbars, 'contexttoolbar'),
  28221. addContextForm: add(contextToolbars, 'contextform'),
  28222. addSidebar: add(sidebars, 'sidebar'),
  28223. addIcon: addIcon,
  28224. getAll: function () {
  28225. return {
  28226. buttons: buttons,
  28227. menuItems: menuItems,
  28228. icons: icons,
  28229. popups: popups,
  28230. contextMenus: contextMenus,
  28231. contextToolbars: contextToolbars,
  28232. sidebars: sidebars
  28233. };
  28234. }
  28235. };
  28236. };
  28237. var registry = function () {
  28238. var bridge = create$3();
  28239. return {
  28240. addAutocompleter: bridge.addAutocompleter,
  28241. addButton: bridge.addButton,
  28242. addContextForm: bridge.addContextForm,
  28243. addContextMenu: bridge.addContextMenu,
  28244. addContextToolbar: bridge.addContextToolbar,
  28245. addIcon: bridge.addIcon,
  28246. addMenuButton: bridge.addMenuButton,
  28247. addMenuItem: bridge.addMenuItem,
  28248. addNestedMenuItem: bridge.addNestedMenuItem,
  28249. addSidebar: bridge.addSidebar,
  28250. addSplitButton: bridge.addSplitButton,
  28251. addToggleButton: bridge.addToggleButton,
  28252. addGroupToolbarButton: bridge.addGroupToolbarButton,
  28253. addToggleMenuItem: bridge.addToggleMenuItem,
  28254. getAll: bridge.getAll
  28255. };
  28256. };
  28257. var DOM$1 = DOMUtils.DOM;
  28258. var extend$3 = Tools.extend, each$2 = Tools.each;
  28259. var resolve = Tools.resolve;
  28260. var ie = Env.ie;
  28261. var Editor = function () {
  28262. function Editor(id, settings, editorManager) {
  28263. var _this = this;
  28264. this.plugins = {};
  28265. this.contentCSS = [];
  28266. this.contentStyles = [];
  28267. this.loadedCSS = {};
  28268. this.isNotDirty = false;
  28269. this.editorManager = editorManager;
  28270. this.documentBaseUrl = editorManager.documentBaseURL;
  28271. extend$3(this, EditorObservable);
  28272. this.settings = getEditorSettings(this, id, this.documentBaseUrl, editorManager.defaultSettings, settings);
  28273. if (this.settings.suffix) {
  28274. editorManager.suffix = this.settings.suffix;
  28275. }
  28276. this.suffix = editorManager.suffix;
  28277. if (this.settings.base_url) {
  28278. editorManager._setBaseUrl(this.settings.base_url);
  28279. }
  28280. this.baseUri = editorManager.baseURI;
  28281. if (this.settings.referrer_policy) {
  28282. ScriptLoader.ScriptLoader._setReferrerPolicy(this.settings.referrer_policy);
  28283. DOMUtils.DOM.styleSheetLoader._setReferrerPolicy(this.settings.referrer_policy);
  28284. }
  28285. AddOnManager.languageLoad = this.settings.language_load;
  28286. AddOnManager.baseURL = editorManager.baseURL;
  28287. this.id = id;
  28288. this.setDirty(false);
  28289. this.documentBaseURI = new URI(this.settings.document_base_url, { base_uri: this.baseUri });
  28290. this.baseURI = this.baseUri;
  28291. this.inline = !!this.settings.inline;
  28292. this.shortcuts = new Shortcuts(this);
  28293. this.editorCommands = new EditorCommands(this);
  28294. if (this.settings.cache_suffix) {
  28295. Env.cacheSuffix = this.settings.cache_suffix.replace(/^[\?\&]+/, '');
  28296. }
  28297. this.ui = {
  28298. registry: registry(),
  28299. styleSheetLoader: undefined,
  28300. show: noop,
  28301. hide: noop,
  28302. enable: noop,
  28303. disable: noop,
  28304. isDisabled: never
  28305. };
  28306. var self = this;
  28307. var modeInstance = create$4(self);
  28308. this.mode = modeInstance;
  28309. this.setMode = modeInstance.set;
  28310. editorManager.fire('SetupEditor', { editor: this });
  28311. this.execCallback('setup', this);
  28312. this.$ = DomQuery.overrideDefaults(function () {
  28313. return {
  28314. context: _this.inline ? _this.getBody() : _this.getDoc(),
  28315. element: _this.getBody()
  28316. };
  28317. });
  28318. }
  28319. Editor.prototype.render = function () {
  28320. render(this);
  28321. };
  28322. Editor.prototype.focus = function (skipFocus) {
  28323. this.execCommand('mceFocus', false, skipFocus);
  28324. };
  28325. Editor.prototype.hasFocus = function () {
  28326. return hasFocus(this);
  28327. };
  28328. Editor.prototype.execCallback = function (name) {
  28329. var x = [];
  28330. for (var _i = 1; _i < arguments.length; _i++) {
  28331. x[_i - 1] = arguments[_i];
  28332. }
  28333. var self = this;
  28334. var callback = self.settings[name], scope;
  28335. if (!callback) {
  28336. return;
  28337. }
  28338. if (self.callbackLookup && (scope = self.callbackLookup[name])) {
  28339. callback = scope.func;
  28340. scope = scope.scope;
  28341. }
  28342. if (typeof callback === 'string') {
  28343. scope = callback.replace(/\.\w+$/, '');
  28344. scope = scope ? resolve(scope) : 0;
  28345. callback = resolve(callback);
  28346. self.callbackLookup = self.callbackLookup || {};
  28347. self.callbackLookup[name] = {
  28348. func: callback,
  28349. scope: scope
  28350. };
  28351. }
  28352. return callback.apply(scope || self, x);
  28353. };
  28354. Editor.prototype.translate = function (text) {
  28355. return I18n.translate(text);
  28356. };
  28357. Editor.prototype.getParam = function (name, defaultVal, type) {
  28358. return getParam(this, name, defaultVal, type);
  28359. };
  28360. Editor.prototype.hasPlugin = function (name, loaded) {
  28361. var hasPlugin = contains$3(getPlugins(this).split(/[ ,]/), name);
  28362. if (hasPlugin) {
  28363. return loaded ? PluginManager.get(name) !== undefined : true;
  28364. } else {
  28365. return false;
  28366. }
  28367. };
  28368. Editor.prototype.nodeChanged = function (args) {
  28369. this._nodeChangeDispatcher.nodeChanged(args);
  28370. };
  28371. Editor.prototype.addCommand = function (name, callback, scope) {
  28372. this.editorCommands.addCommand(name, callback, scope);
  28373. };
  28374. Editor.prototype.addQueryStateHandler = function (name, callback, scope) {
  28375. this.editorCommands.addQueryStateHandler(name, callback, scope);
  28376. };
  28377. Editor.prototype.addQueryValueHandler = function (name, callback, scope) {
  28378. this.editorCommands.addQueryValueHandler(name, callback, scope);
  28379. };
  28380. Editor.prototype.addShortcut = function (pattern, desc, cmdFunc, scope) {
  28381. this.shortcuts.add(pattern, desc, cmdFunc, scope);
  28382. };
  28383. Editor.prototype.execCommand = function (cmd, ui, value, args) {
  28384. return this.editorCommands.execCommand(cmd, ui, value, args);
  28385. };
  28386. Editor.prototype.queryCommandState = function (cmd) {
  28387. return this.editorCommands.queryCommandState(cmd);
  28388. };
  28389. Editor.prototype.queryCommandValue = function (cmd) {
  28390. return this.editorCommands.queryCommandValue(cmd);
  28391. };
  28392. Editor.prototype.queryCommandSupported = function (cmd) {
  28393. return this.editorCommands.queryCommandSupported(cmd);
  28394. };
  28395. Editor.prototype.show = function () {
  28396. var self = this;
  28397. if (self.hidden) {
  28398. self.hidden = false;
  28399. if (self.inline) {
  28400. self.getBody().contentEditable = 'true';
  28401. } else {
  28402. DOM$1.show(self.getContainer());
  28403. DOM$1.hide(self.id);
  28404. }
  28405. self.load();
  28406. self.fire('show');
  28407. }
  28408. };
  28409. Editor.prototype.hide = function () {
  28410. var self = this, doc = self.getDoc();
  28411. if (!self.hidden) {
  28412. if (ie && doc && !self.inline) {
  28413. doc.execCommand('SelectAll');
  28414. }
  28415. self.save();
  28416. if (self.inline) {
  28417. self.getBody().contentEditable = 'false';
  28418. if (self === self.editorManager.focusedEditor) {
  28419. self.editorManager.focusedEditor = null;
  28420. }
  28421. } else {
  28422. DOM$1.hide(self.getContainer());
  28423. DOM$1.setStyle(self.id, 'display', self.orgDisplay);
  28424. }
  28425. self.hidden = true;
  28426. self.fire('hide');
  28427. }
  28428. };
  28429. Editor.prototype.isHidden = function () {
  28430. return !!this.hidden;
  28431. };
  28432. Editor.prototype.setProgressState = function (state, time) {
  28433. this.fire('ProgressState', {
  28434. state: state,
  28435. time: time
  28436. });
  28437. };
  28438. Editor.prototype.load = function (args) {
  28439. var self = this;
  28440. var elm = self.getElement(), html;
  28441. if (self.removed) {
  28442. return '';
  28443. }
  28444. if (elm) {
  28445. args = args || {};
  28446. args.load = true;
  28447. var value = isTextareaOrInput(elm) ? elm.value : elm.innerHTML;
  28448. html = self.setContent(value, args);
  28449. args.element = elm;
  28450. if (!args.no_events) {
  28451. self.fire('LoadContent', args);
  28452. }
  28453. args.element = elm = null;
  28454. return html;
  28455. }
  28456. };
  28457. Editor.prototype.save = function (args) {
  28458. var self = this;
  28459. var elm = self.getElement(), html, form;
  28460. if (!elm || !self.initialized || self.removed) {
  28461. return;
  28462. }
  28463. args = args || {};
  28464. args.save = true;
  28465. args.element = elm;
  28466. html = args.content = self.getContent(args);
  28467. if (!args.no_events) {
  28468. self.fire('SaveContent', args);
  28469. }
  28470. if (args.format === 'raw') {
  28471. self.fire('RawSaveContent', args);
  28472. }
  28473. html = args.content;
  28474. if (!isTextareaOrInput(elm)) {
  28475. if (args.is_removing || !self.inline) {
  28476. elm.innerHTML = html;
  28477. }
  28478. if (form = DOM$1.getParent(self.id, 'form')) {
  28479. each$2(form.elements, function (elm) {
  28480. if (elm.name === self.id) {
  28481. elm.value = html;
  28482. return false;
  28483. }
  28484. });
  28485. }
  28486. } else {
  28487. elm.value = html;
  28488. }
  28489. args.element = elm = null;
  28490. if (args.set_dirty !== false) {
  28491. self.setDirty(false);
  28492. }
  28493. return html;
  28494. };
  28495. Editor.prototype.setContent = function (content, args) {
  28496. return setContent(this, content, args);
  28497. };
  28498. Editor.prototype.getContent = function (args) {
  28499. return getContent(this, args);
  28500. };
  28501. Editor.prototype.insertContent = function (content, args) {
  28502. if (args) {
  28503. content = extend$3({ content: content }, args);
  28504. }
  28505. this.execCommand('mceInsertContent', false, content);
  28506. };
  28507. Editor.prototype.resetContent = function (initialContent) {
  28508. if (initialContent === undefined) {
  28509. setContent(this, this.startContent, { format: 'raw' });
  28510. } else {
  28511. setContent(this, initialContent);
  28512. }
  28513. this.undoManager.reset();
  28514. this.setDirty(false);
  28515. this.nodeChanged();
  28516. };
  28517. Editor.prototype.isDirty = function () {
  28518. return !this.isNotDirty;
  28519. };
  28520. Editor.prototype.setDirty = function (state) {
  28521. var oldState = !this.isNotDirty;
  28522. this.isNotDirty = !state;
  28523. if (state && state !== oldState) {
  28524. this.fire('dirty');
  28525. }
  28526. };
  28527. Editor.prototype.getContainer = function () {
  28528. var self = this;
  28529. if (!self.container) {
  28530. self.container = DOM$1.get(self.editorContainer || self.id + '_parent');
  28531. }
  28532. return self.container;
  28533. };
  28534. Editor.prototype.getContentAreaContainer = function () {
  28535. return this.contentAreaContainer;
  28536. };
  28537. Editor.prototype.getElement = function () {
  28538. if (!this.targetElm) {
  28539. this.targetElm = DOM$1.get(this.id);
  28540. }
  28541. return this.targetElm;
  28542. };
  28543. Editor.prototype.getWin = function () {
  28544. var self = this;
  28545. var elm;
  28546. if (!self.contentWindow) {
  28547. elm = self.iframeElement;
  28548. if (elm) {
  28549. self.contentWindow = elm.contentWindow;
  28550. }
  28551. }
  28552. return self.contentWindow;
  28553. };
  28554. Editor.prototype.getDoc = function () {
  28555. var self = this;
  28556. var win;
  28557. if (!self.contentDocument) {
  28558. win = self.getWin();
  28559. if (win) {
  28560. self.contentDocument = win.document;
  28561. }
  28562. }
  28563. return self.contentDocument;
  28564. };
  28565. Editor.prototype.getBody = function () {
  28566. var doc = this.getDoc();
  28567. return this.bodyElement || (doc ? doc.body : null);
  28568. };
  28569. Editor.prototype.convertURL = function (url, name, elm) {
  28570. var self = this, settings = self.settings;
  28571. if (settings.urlconverter_callback) {
  28572. return self.execCallback('urlconverter_callback', url, elm, true, name);
  28573. }
  28574. if (!settings.convert_urls || elm && elm.nodeName === 'LINK' || url.indexOf('file:') === 0 || url.length === 0) {
  28575. return url;
  28576. }
  28577. if (settings.relative_urls) {
  28578. return self.documentBaseURI.toRelative(url);
  28579. }
  28580. url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host);
  28581. return url;
  28582. };
  28583. Editor.prototype.addVisual = function (elm) {
  28584. addVisual(this, elm);
  28585. };
  28586. Editor.prototype.remove = function () {
  28587. remove(this);
  28588. };
  28589. Editor.prototype.destroy = function (automatic) {
  28590. destroy(this, automatic);
  28591. };
  28592. Editor.prototype.uploadImages = function (callback) {
  28593. return this.editorUpload.uploadImages(callback);
  28594. };
  28595. Editor.prototype._scanForImages = function () {
  28596. return this.editorUpload.scanForImages();
  28597. };
  28598. Editor.prototype.addButton = function () {
  28599. 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');
  28600. };
  28601. Editor.prototype.addSidebar = function () {
  28602. throw new Error('editor.addSidebar has been removed in tinymce 5x, use editor.ui.registry.addSidebar instead');
  28603. };
  28604. Editor.prototype.addMenuItem = function () {
  28605. throw new Error('editor.addMenuItem has been removed in tinymce 5x, use editor.ui.registry.addMenuItem instead');
  28606. };
  28607. Editor.prototype.addContextToolbar = function () {
  28608. throw new Error('editor.addContextToolbar has been removed in tinymce 5x, use editor.ui.registry.addContextToolbar instead');
  28609. };
  28610. return Editor;
  28611. }();
  28612. var DOM = DOMUtils.DOM;
  28613. var explode = Tools.explode, each$1 = Tools.each, extend$2 = Tools.extend;
  28614. var instanceCounter = 0, boundGlobalEvents = false;
  28615. var beforeUnloadDelegate;
  28616. var legacyEditors = [];
  28617. var editors = [];
  28618. var isValidLegacyKey = function (id) {
  28619. return id !== 'length';
  28620. };
  28621. var globalEventDelegate = function (e) {
  28622. var type = e.type;
  28623. each$1(EditorManager.get(), function (editor) {
  28624. switch (type) {
  28625. case 'scroll':
  28626. editor.fire('ScrollWindow', e);
  28627. break;
  28628. case 'resize':
  28629. editor.fire('ResizeWindow', e);
  28630. break;
  28631. }
  28632. });
  28633. };
  28634. var toggleGlobalEvents = function (state) {
  28635. if (state !== boundGlobalEvents) {
  28636. if (state) {
  28637. DomQuery(window).on('resize scroll', globalEventDelegate);
  28638. } else {
  28639. DomQuery(window).off('resize scroll', globalEventDelegate);
  28640. }
  28641. boundGlobalEvents = state;
  28642. }
  28643. };
  28644. var removeEditorFromList = function (targetEditor) {
  28645. var oldEditors = editors;
  28646. delete legacyEditors[targetEditor.id];
  28647. for (var i = 0; i < legacyEditors.length; i++) {
  28648. if (legacyEditors[i] === targetEditor) {
  28649. legacyEditors.splice(i, 1);
  28650. break;
  28651. }
  28652. }
  28653. editors = filter$4(editors, function (editor) {
  28654. return targetEditor !== editor;
  28655. });
  28656. if (EditorManager.activeEditor === targetEditor) {
  28657. EditorManager.activeEditor = editors.length > 0 ? editors[0] : null;
  28658. }
  28659. if (EditorManager.focusedEditor === targetEditor) {
  28660. EditorManager.focusedEditor = null;
  28661. }
  28662. return oldEditors.length !== editors.length;
  28663. };
  28664. var purgeDestroyedEditor = function (editor) {
  28665. if (editor && editor.initialized && !(editor.getContainer() || editor.getBody()).parentNode) {
  28666. removeEditorFromList(editor);
  28667. editor.unbindAllNativeEvents();
  28668. editor.destroy(true);
  28669. editor.removed = true;
  28670. editor = null;
  28671. }
  28672. return editor;
  28673. };
  28674. var isQuirksMode = document.compatMode !== 'CSS1Compat';
  28675. var EditorManager = __assign(__assign({}, Observable), {
  28676. baseURI: null,
  28677. baseURL: null,
  28678. defaultSettings: {},
  28679. documentBaseURL: null,
  28680. suffix: null,
  28681. $: DomQuery,
  28682. majorVersion: '5',
  28683. minorVersion: '10.5',
  28684. releaseDate: '2022-05-25',
  28685. editors: legacyEditors,
  28686. i18n: I18n,
  28687. activeEditor: null,
  28688. focusedEditor: null,
  28689. settings: {},
  28690. setup: function () {
  28691. var self = this;
  28692. var baseURL, documentBaseURL, suffix = '';
  28693. documentBaseURL = URI.getDocumentBaseUrl(document.location);
  28694. if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
  28695. documentBaseURL = documentBaseURL.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  28696. if (!/[\/\\]$/.test(documentBaseURL)) {
  28697. documentBaseURL += '/';
  28698. }
  28699. }
  28700. var preInit = window.tinymce || window.tinyMCEPreInit;
  28701. if (preInit) {
  28702. baseURL = preInit.base || preInit.baseURL;
  28703. suffix = preInit.suffix;
  28704. } else {
  28705. var scripts = document.getElementsByTagName('script');
  28706. for (var i = 0; i < scripts.length; i++) {
  28707. var src = scripts[i].src || '';
  28708. if (src === '') {
  28709. continue;
  28710. }
  28711. var srcScript = src.substring(src.lastIndexOf('/'));
  28712. if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
  28713. if (srcScript.indexOf('.min') !== -1) {
  28714. suffix = '.min';
  28715. }
  28716. baseURL = src.substring(0, src.lastIndexOf('/'));
  28717. break;
  28718. }
  28719. }
  28720. if (!baseURL && document.currentScript) {
  28721. var src = document.currentScript.src;
  28722. if (src.indexOf('.min') !== -1) {
  28723. suffix = '.min';
  28724. }
  28725. baseURL = src.substring(0, src.lastIndexOf('/'));
  28726. }
  28727. }
  28728. self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
  28729. self.documentBaseURL = documentBaseURL;
  28730. self.baseURI = new URI(self.baseURL);
  28731. self.suffix = suffix;
  28732. setup$l(self);
  28733. },
  28734. overrideDefaults: function (defaultSettings) {
  28735. var baseUrl = defaultSettings.base_url;
  28736. if (baseUrl) {
  28737. this._setBaseUrl(baseUrl);
  28738. }
  28739. var suffix = defaultSettings.suffix;
  28740. if (defaultSettings.suffix) {
  28741. this.suffix = suffix;
  28742. }
  28743. this.defaultSettings = defaultSettings;
  28744. var pluginBaseUrls = defaultSettings.plugin_base_urls;
  28745. if (pluginBaseUrls !== undefined) {
  28746. each$j(pluginBaseUrls, function (pluginBaseUrl, pluginName) {
  28747. AddOnManager.PluginManager.urls[pluginName] = pluginBaseUrl;
  28748. });
  28749. }
  28750. },
  28751. init: function (settings) {
  28752. var self = this;
  28753. var result;
  28754. 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', ' ');
  28755. var isInvalidInlineTarget = function (settings, elm) {
  28756. return settings.inline && elm.tagName.toLowerCase() in invalidInlineTargets;
  28757. };
  28758. var createId = function (elm) {
  28759. var id = elm.id;
  28760. if (!id) {
  28761. id = get$9(elm, 'name').filter(function (name) {
  28762. return !DOM.get(name);
  28763. }).getOrThunk(DOM.uniqueId);
  28764. elm.setAttribute('id', id);
  28765. }
  28766. return id;
  28767. };
  28768. var execCallback = function (name) {
  28769. var callback = settings[name];
  28770. if (!callback) {
  28771. return;
  28772. }
  28773. return callback.apply(self, []);
  28774. };
  28775. var hasClass = function (elm, className) {
  28776. return className.constructor === RegExp ? className.test(elm.className) : DOM.hasClass(elm, className);
  28777. };
  28778. var findTargets = function (settings) {
  28779. var targets = [];
  28780. if (Env.browser.isIE() && Env.browser.version.major < 11) {
  28781. 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/');
  28782. return [];
  28783. } else if (isQuirksMode) {
  28784. initError('Failed to initialize the editor as the document is not in standards mode. ' + 'TinyMCE requires standards mode.');
  28785. return [];
  28786. }
  28787. if (settings.types) {
  28788. each$1(settings.types, function (type) {
  28789. targets = targets.concat(DOM.select(type.selector));
  28790. });
  28791. return targets;
  28792. } else if (settings.selector) {
  28793. return DOM.select(settings.selector);
  28794. } else if (settings.target) {
  28795. return [settings.target];
  28796. }
  28797. switch (settings.mode) {
  28798. case 'exact':
  28799. var l = settings.elements || '';
  28800. if (l.length > 0) {
  28801. each$1(explode(l), function (id) {
  28802. var elm = DOM.get(id);
  28803. if (elm) {
  28804. targets.push(elm);
  28805. } else {
  28806. each$1(document.forms, function (f) {
  28807. each$1(f.elements, function (e) {
  28808. if (e.name === id) {
  28809. id = 'mce_editor_' + instanceCounter++;
  28810. DOM.setAttrib(e, 'id', id);
  28811. targets.push(e);
  28812. }
  28813. });
  28814. });
  28815. }
  28816. });
  28817. }
  28818. break;
  28819. case 'textareas':
  28820. case 'specific_textareas':
  28821. each$1(DOM.select('textarea'), function (elm) {
  28822. if (settings.editor_deselector && hasClass(elm, settings.editor_deselector)) {
  28823. return;
  28824. }
  28825. if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) {
  28826. targets.push(elm);
  28827. }
  28828. });
  28829. break;
  28830. }
  28831. return targets;
  28832. };
  28833. var provideResults = function (editors) {
  28834. result = editors;
  28835. };
  28836. var initEditors = function () {
  28837. var initCount = 0;
  28838. var editors = [];
  28839. var targets;
  28840. var createEditor = function (id, settings, targetElm) {
  28841. var editor = new Editor(id, settings, self);
  28842. editors.push(editor);
  28843. editor.on('init', function () {
  28844. if (++initCount === targets.length) {
  28845. provideResults(editors);
  28846. }
  28847. });
  28848. editor.targetElm = editor.targetElm || targetElm;
  28849. editor.render();
  28850. };
  28851. DOM.unbind(window, 'ready', initEditors);
  28852. execCallback('onpageload');
  28853. targets = DomQuery.unique(findTargets(settings));
  28854. if (settings.types) {
  28855. each$1(settings.types, function (type) {
  28856. Tools.each(targets, function (elm) {
  28857. if (DOM.is(elm, type.selector)) {
  28858. createEditor(createId(elm), extend$2({}, settings, type), elm);
  28859. return false;
  28860. }
  28861. return true;
  28862. });
  28863. });
  28864. return;
  28865. }
  28866. Tools.each(targets, function (elm) {
  28867. purgeDestroyedEditor(self.get(elm.id));
  28868. });
  28869. targets = Tools.grep(targets, function (elm) {
  28870. return !self.get(elm.id);
  28871. });
  28872. if (targets.length === 0) {
  28873. provideResults([]);
  28874. } else {
  28875. each$1(targets, function (elm) {
  28876. if (isInvalidInlineTarget(settings, elm)) {
  28877. initError('Could not initialize inline editor on invalid inline target element', elm);
  28878. } else {
  28879. createEditor(createId(elm), settings, elm);
  28880. }
  28881. });
  28882. }
  28883. };
  28884. self.settings = settings;
  28885. DOM.bind(window, 'ready', initEditors);
  28886. return new promiseObj(function (resolve) {
  28887. if (result) {
  28888. resolve(result);
  28889. } else {
  28890. provideResults = function (editors) {
  28891. resolve(editors);
  28892. };
  28893. }
  28894. });
  28895. },
  28896. get: function (id) {
  28897. if (arguments.length === 0) {
  28898. return editors.slice(0);
  28899. } else if (isString$1(id)) {
  28900. return find$3(editors, function (editor) {
  28901. return editor.id === id;
  28902. }).getOr(null);
  28903. } else if (isNumber(id)) {
  28904. return editors[id] ? editors[id] : null;
  28905. } else {
  28906. return null;
  28907. }
  28908. },
  28909. add: function (editor) {
  28910. var self = this;
  28911. var existingEditor = legacyEditors[editor.id];
  28912. if (existingEditor === editor) {
  28913. return editor;
  28914. }
  28915. if (self.get(editor.id) === null) {
  28916. if (isValidLegacyKey(editor.id)) {
  28917. legacyEditors[editor.id] = editor;
  28918. }
  28919. legacyEditors.push(editor);
  28920. editors.push(editor);
  28921. }
  28922. toggleGlobalEvents(true);
  28923. self.activeEditor = editor;
  28924. self.fire('AddEditor', { editor: editor });
  28925. if (!beforeUnloadDelegate) {
  28926. beforeUnloadDelegate = function (e) {
  28927. var event = self.fire('BeforeUnload');
  28928. if (event.returnValue) {
  28929. e.preventDefault();
  28930. e.returnValue = event.returnValue;
  28931. return event.returnValue;
  28932. }
  28933. };
  28934. window.addEventListener('beforeunload', beforeUnloadDelegate);
  28935. }
  28936. return editor;
  28937. },
  28938. createEditor: function (id, settings) {
  28939. return this.add(new Editor(id, settings, this));
  28940. },
  28941. remove: function (selector) {
  28942. var self = this;
  28943. var i, editor;
  28944. if (!selector) {
  28945. for (i = editors.length - 1; i >= 0; i--) {
  28946. self.remove(editors[i]);
  28947. }
  28948. return;
  28949. }
  28950. if (isString$1(selector)) {
  28951. each$1(DOM.select(selector), function (elm) {
  28952. editor = self.get(elm.id);
  28953. if (editor) {
  28954. self.remove(editor);
  28955. }
  28956. });
  28957. return;
  28958. }
  28959. editor = selector;
  28960. if (isNull(self.get(editor.id))) {
  28961. return null;
  28962. }
  28963. if (removeEditorFromList(editor)) {
  28964. self.fire('RemoveEditor', { editor: editor });
  28965. }
  28966. if (editors.length === 0) {
  28967. window.removeEventListener('beforeunload', beforeUnloadDelegate);
  28968. }
  28969. editor.remove();
  28970. toggleGlobalEvents(editors.length > 0);
  28971. return editor;
  28972. },
  28973. execCommand: function (cmd, ui, value) {
  28974. var self = this, editor = self.get(value);
  28975. switch (cmd) {
  28976. case 'mceAddEditor':
  28977. if (!self.get(value)) {
  28978. new Editor(value, self.settings, self).render();
  28979. }
  28980. return true;
  28981. case 'mceRemoveEditor':
  28982. if (editor) {
  28983. editor.remove();
  28984. }
  28985. return true;
  28986. case 'mceToggleEditor':
  28987. if (!editor) {
  28988. self.execCommand('mceAddEditor', false, value);
  28989. return true;
  28990. }
  28991. if (editor.isHidden()) {
  28992. editor.show();
  28993. } else {
  28994. editor.hide();
  28995. }
  28996. return true;
  28997. }
  28998. if (self.activeEditor) {
  28999. return self.activeEditor.execCommand(cmd, ui, value);
  29000. }
  29001. return false;
  29002. },
  29003. triggerSave: function () {
  29004. each$1(editors, function (editor) {
  29005. editor.save();
  29006. });
  29007. },
  29008. addI18n: function (code, items) {
  29009. I18n.add(code, items);
  29010. },
  29011. translate: function (text) {
  29012. return I18n.translate(text);
  29013. },
  29014. setActive: function (editor) {
  29015. var activeEditor = this.activeEditor;
  29016. if (this.activeEditor !== editor) {
  29017. if (activeEditor) {
  29018. activeEditor.fire('deactivate', { relatedTarget: editor });
  29019. }
  29020. editor.fire('activate', { relatedTarget: activeEditor });
  29021. }
  29022. this.activeEditor = editor;
  29023. },
  29024. _setBaseUrl: function (baseUrl) {
  29025. this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ''));
  29026. this.baseURI = new URI(this.baseURL);
  29027. }
  29028. });
  29029. EditorManager.setup();
  29030. var min$1 = Math.min, max$1 = Math.max, round$1 = Math.round;
  29031. var relativePosition = function (rect, targetRect, rel) {
  29032. var x = targetRect.x;
  29033. var y = targetRect.y;
  29034. var w = rect.w;
  29035. var h = rect.h;
  29036. var targetW = targetRect.w;
  29037. var targetH = targetRect.h;
  29038. var relChars = (rel || '').split('');
  29039. if (relChars[0] === 'b') {
  29040. y += targetH;
  29041. }
  29042. if (relChars[1] === 'r') {
  29043. x += targetW;
  29044. }
  29045. if (relChars[0] === 'c') {
  29046. y += round$1(targetH / 2);
  29047. }
  29048. if (relChars[1] === 'c') {
  29049. x += round$1(targetW / 2);
  29050. }
  29051. if (relChars[3] === 'b') {
  29052. y -= h;
  29053. }
  29054. if (relChars[4] === 'r') {
  29055. x -= w;
  29056. }
  29057. if (relChars[3] === 'c') {
  29058. y -= round$1(h / 2);
  29059. }
  29060. if (relChars[4] === 'c') {
  29061. x -= round$1(w / 2);
  29062. }
  29063. return create$2(x, y, w, h);
  29064. };
  29065. var findBestRelativePosition = function (rect, targetRect, constrainRect, rels) {
  29066. var pos, i;
  29067. for (i = 0; i < rels.length; i++) {
  29068. pos = relativePosition(rect, targetRect, rels[i]);
  29069. 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) {
  29070. return rels[i];
  29071. }
  29072. }
  29073. return null;
  29074. };
  29075. var inflate = function (rect, w, h) {
  29076. return create$2(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2);
  29077. };
  29078. var intersect = function (rect, cropRect) {
  29079. var x1 = max$1(rect.x, cropRect.x);
  29080. var y1 = max$1(rect.y, cropRect.y);
  29081. var x2 = min$1(rect.x + rect.w, cropRect.x + cropRect.w);
  29082. var y2 = min$1(rect.y + rect.h, cropRect.y + cropRect.h);
  29083. if (x2 - x1 < 0 || y2 - y1 < 0) {
  29084. return null;
  29085. }
  29086. return create$2(x1, y1, x2 - x1, y2 - y1);
  29087. };
  29088. var clamp = function (rect, clampRect, fixedSize) {
  29089. var x1 = rect.x;
  29090. var y1 = rect.y;
  29091. var x2 = rect.x + rect.w;
  29092. var y2 = rect.y + rect.h;
  29093. var cx2 = clampRect.x + clampRect.w;
  29094. var cy2 = clampRect.y + clampRect.h;
  29095. var underflowX1 = max$1(0, clampRect.x - x1);
  29096. var underflowY1 = max$1(0, clampRect.y - y1);
  29097. var overflowX2 = max$1(0, x2 - cx2);
  29098. var overflowY2 = max$1(0, y2 - cy2);
  29099. x1 += underflowX1;
  29100. y1 += underflowY1;
  29101. if (fixedSize) {
  29102. x2 += underflowX1;
  29103. y2 += underflowY1;
  29104. x1 -= overflowX2;
  29105. y1 -= overflowY2;
  29106. }
  29107. x2 -= overflowX2;
  29108. y2 -= overflowY2;
  29109. return create$2(x1, y1, x2 - x1, y2 - y1);
  29110. };
  29111. var create$2 = function (x, y, w, h) {
  29112. return {
  29113. x: x,
  29114. y: y,
  29115. w: w,
  29116. h: h
  29117. };
  29118. };
  29119. var fromClientRect = function (clientRect) {
  29120. return create$2(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
  29121. };
  29122. var Rect = {
  29123. inflate: inflate,
  29124. relativePosition: relativePosition,
  29125. findBestRelativePosition: findBestRelativePosition,
  29126. intersect: intersect,
  29127. clamp: clamp,
  29128. create: create$2,
  29129. fromClientRect: fromClientRect
  29130. };
  29131. var awaiter = function (resolveCb, rejectCb, timeout) {
  29132. if (timeout === void 0) {
  29133. timeout = 1000;
  29134. }
  29135. var done = false;
  29136. var timer = null;
  29137. var complete = function (completer) {
  29138. return function () {
  29139. var args = [];
  29140. for (var _i = 0; _i < arguments.length; _i++) {
  29141. args[_i] = arguments[_i];
  29142. }
  29143. if (!done) {
  29144. done = true;
  29145. if (timer !== null) {
  29146. clearTimeout(timer);
  29147. timer = null;
  29148. }
  29149. completer.apply(null, args);
  29150. }
  29151. };
  29152. };
  29153. var resolve = complete(resolveCb);
  29154. var reject = complete(rejectCb);
  29155. var start = function () {
  29156. var args = [];
  29157. for (var _i = 0; _i < arguments.length; _i++) {
  29158. args[_i] = arguments[_i];
  29159. }
  29160. if (!done && timer === null) {
  29161. timer = setTimeout(function () {
  29162. return reject.apply(null, args);
  29163. }, timeout);
  29164. }
  29165. };
  29166. return {
  29167. start: start,
  29168. resolve: resolve,
  29169. reject: reject
  29170. };
  29171. };
  29172. var create$1 = function () {
  29173. var tasks = {};
  29174. var resultFns = {};
  29175. var load = function (id, url) {
  29176. var loadErrMsg = 'Script at URL "' + url + '" failed to load';
  29177. var runErrMsg = 'Script at URL "' + url + '" did not call `tinymce.Resource.add(\'' + id + '\', data)` within 1 second';
  29178. if (tasks[id] !== undefined) {
  29179. return tasks[id];
  29180. } else {
  29181. var task = new promiseObj(function (resolve, reject) {
  29182. var waiter = awaiter(resolve, reject);
  29183. resultFns[id] = waiter.resolve;
  29184. ScriptLoader.ScriptLoader.loadScript(url, function () {
  29185. return waiter.start(runErrMsg);
  29186. }, function () {
  29187. return waiter.reject(loadErrMsg);
  29188. });
  29189. });
  29190. tasks[id] = task;
  29191. return task;
  29192. }
  29193. };
  29194. var add = function (id, data) {
  29195. if (resultFns[id] !== undefined) {
  29196. resultFns[id](data);
  29197. delete resultFns[id];
  29198. }
  29199. tasks[id] = promiseObj.resolve(data);
  29200. };
  29201. return {
  29202. load: load,
  29203. add: add
  29204. };
  29205. };
  29206. var Resource = create$1();
  29207. var each = Tools.each, extend$1 = Tools.extend;
  29208. var extendClass, initializing;
  29209. var Class = function () {
  29210. };
  29211. Class.extend = extendClass = function (props) {
  29212. var self = this;
  29213. var _super = self.prototype;
  29214. var Class = function () {
  29215. var i, mixins, mixin;
  29216. var self = this;
  29217. if (!initializing) {
  29218. if (self.init) {
  29219. self.init.apply(self, arguments);
  29220. }
  29221. mixins = self.Mixins;
  29222. if (mixins) {
  29223. i = mixins.length;
  29224. while (i--) {
  29225. mixin = mixins[i];
  29226. if (mixin.init) {
  29227. mixin.init.apply(self, arguments);
  29228. }
  29229. }
  29230. }
  29231. }
  29232. };
  29233. var dummy = function () {
  29234. return this;
  29235. };
  29236. var createMethod = function (name, fn) {
  29237. return function () {
  29238. var self = this;
  29239. var tmp = self._super;
  29240. self._super = _super[name];
  29241. var ret = fn.apply(self, arguments);
  29242. self._super = tmp;
  29243. return ret;
  29244. };
  29245. };
  29246. initializing = true;
  29247. var prototype = new self();
  29248. initializing = false;
  29249. if (props.Mixins) {
  29250. each(props.Mixins, function (mixin) {
  29251. for (var name_1 in mixin) {
  29252. if (name_1 !== 'init') {
  29253. props[name_1] = mixin[name_1];
  29254. }
  29255. }
  29256. });
  29257. if (_super.Mixins) {
  29258. props.Mixins = _super.Mixins.concat(props.Mixins);
  29259. }
  29260. }
  29261. if (props.Methods) {
  29262. each(props.Methods.split(','), function (name) {
  29263. props[name] = dummy;
  29264. });
  29265. }
  29266. if (props.Properties) {
  29267. each(props.Properties.split(','), function (name) {
  29268. var fieldName = '_' + name;
  29269. props[name] = function (value) {
  29270. var self = this;
  29271. if (value !== undefined) {
  29272. self[fieldName] = value;
  29273. return self;
  29274. }
  29275. return self[fieldName];
  29276. };
  29277. });
  29278. }
  29279. if (props.Statics) {
  29280. each(props.Statics, function (func, name) {
  29281. Class[name] = func;
  29282. });
  29283. }
  29284. if (props.Defaults && _super.Defaults) {
  29285. props.Defaults = extend$1({}, _super.Defaults, props.Defaults);
  29286. }
  29287. each$j(props, function (member, name) {
  29288. if (typeof member === 'function' && _super[name]) {
  29289. prototype[name] = createMethod(name, member);
  29290. } else {
  29291. prototype[name] = member;
  29292. }
  29293. });
  29294. Class.prototype = prototype;
  29295. Class.constructor = Class;
  29296. Class.extend = extendClass;
  29297. return Class;
  29298. };
  29299. var min = Math.min, max = Math.max, round = Math.round;
  29300. var Color = function (value) {
  29301. var self = {};
  29302. var r = 0, g = 0, b = 0;
  29303. var rgb2hsv = function (r, g, b) {
  29304. var h, s, v;
  29305. h = 0;
  29306. s = 0;
  29307. v = 0;
  29308. r = r / 255;
  29309. g = g / 255;
  29310. b = b / 255;
  29311. var minRGB = min(r, min(g, b));
  29312. var maxRGB = max(r, max(g, b));
  29313. if (minRGB === maxRGB) {
  29314. v = minRGB;
  29315. return {
  29316. h: 0,
  29317. s: 0,
  29318. v: v * 100
  29319. };
  29320. }
  29321. var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  29322. h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  29323. h = 60 * (h - d / (maxRGB - minRGB));
  29324. s = (maxRGB - minRGB) / maxRGB;
  29325. v = maxRGB;
  29326. return {
  29327. h: round(h),
  29328. s: round(s * 100),
  29329. v: round(v * 100)
  29330. };
  29331. };
  29332. var hsvToRgb = function (hue, saturation, brightness) {
  29333. hue = (parseInt(hue, 10) || 0) % 360;
  29334. saturation = parseInt(saturation, 10) / 100;
  29335. brightness = parseInt(brightness, 10) / 100;
  29336. saturation = max(0, min(saturation, 1));
  29337. brightness = max(0, min(brightness, 1));
  29338. if (saturation === 0) {
  29339. r = g = b = round(255 * brightness);
  29340. return;
  29341. }
  29342. var side = hue / 60;
  29343. var chroma = brightness * saturation;
  29344. var x = chroma * (1 - Math.abs(side % 2 - 1));
  29345. var match = brightness - chroma;
  29346. switch (Math.floor(side)) {
  29347. case 0:
  29348. r = chroma;
  29349. g = x;
  29350. b = 0;
  29351. break;
  29352. case 1:
  29353. r = x;
  29354. g = chroma;
  29355. b = 0;
  29356. break;
  29357. case 2:
  29358. r = 0;
  29359. g = chroma;
  29360. b = x;
  29361. break;
  29362. case 3:
  29363. r = 0;
  29364. g = x;
  29365. b = chroma;
  29366. break;
  29367. case 4:
  29368. r = x;
  29369. g = 0;
  29370. b = chroma;
  29371. break;
  29372. case 5:
  29373. r = chroma;
  29374. g = 0;
  29375. b = x;
  29376. break;
  29377. default:
  29378. r = g = b = 0;
  29379. }
  29380. r = round(255 * (r + match));
  29381. g = round(255 * (g + match));
  29382. b = round(255 * (b + match));
  29383. };
  29384. var toHex = function () {
  29385. var hex = function (val) {
  29386. val = parseInt(val, 10).toString(16);
  29387. return val.length > 1 ? val : '0' + val;
  29388. };
  29389. return '#' + hex(r) + hex(g) + hex(b);
  29390. };
  29391. var toRgb = function () {
  29392. return {
  29393. r: r,
  29394. g: g,
  29395. b: b
  29396. };
  29397. };
  29398. var toHsv = function () {
  29399. return rgb2hsv(r, g, b);
  29400. };
  29401. var parse = function (value) {
  29402. var matches;
  29403. if (typeof value === 'object') {
  29404. if ('r' in value) {
  29405. r = value.r;
  29406. g = value.g;
  29407. b = value.b;
  29408. } else if ('v' in value) {
  29409. hsvToRgb(value.h, value.s, value.v);
  29410. }
  29411. } else {
  29412. if (matches = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)[^\)]*\)/gi.exec(value)) {
  29413. r = parseInt(matches[1], 10);
  29414. g = parseInt(matches[2], 10);
  29415. b = parseInt(matches[3], 10);
  29416. } else if (matches = /#([0-F]{2})([0-F]{2})([0-F]{2})/gi.exec(value)) {
  29417. r = parseInt(matches[1], 16);
  29418. g = parseInt(matches[2], 16);
  29419. b = parseInt(matches[3], 16);
  29420. } else if (matches = /#([0-F])([0-F])([0-F])/gi.exec(value)) {
  29421. r = parseInt(matches[1] + matches[1], 16);
  29422. g = parseInt(matches[2] + matches[2], 16);
  29423. b = parseInt(matches[3] + matches[3], 16);
  29424. }
  29425. }
  29426. r = r < 0 ? 0 : r > 255 ? 255 : r;
  29427. g = g < 0 ? 0 : g > 255 ? 255 : g;
  29428. b = b < 0 ? 0 : b > 255 ? 255 : b;
  29429. return self;
  29430. };
  29431. if (value) {
  29432. parse(value);
  29433. }
  29434. self.toRgb = toRgb;
  29435. self.toHsv = toHsv;
  29436. self.toHex = toHex;
  29437. self.parse = parse;
  29438. return self;
  29439. };
  29440. var serialize = function (obj) {
  29441. var data = JSON.stringify(obj);
  29442. if (!isString$1(data)) {
  29443. return data;
  29444. }
  29445. return data.replace(/[\u0080-\uFFFF]/g, function (match) {
  29446. var hexCode = match.charCodeAt(0).toString(16);
  29447. return '\\u' + '0000'.substring(hexCode.length) + hexCode;
  29448. });
  29449. };
  29450. var JSONUtils = {
  29451. serialize: serialize,
  29452. parse: function (text) {
  29453. try {
  29454. return JSON.parse(text);
  29455. } catch (ex) {
  29456. }
  29457. }
  29458. };
  29459. var JSONP = {
  29460. callbacks: {},
  29461. count: 0,
  29462. send: function (settings) {
  29463. var self = this, dom = DOMUtils.DOM, count = settings.count !== undefined ? settings.count : self.count;
  29464. var id = 'tinymce_jsonp_' + count;
  29465. self.callbacks[count] = function (json) {
  29466. dom.remove(id);
  29467. delete self.callbacks[count];
  29468. settings.callback(json);
  29469. };
  29470. dom.add(dom.doc.body, 'script', {
  29471. id: id,
  29472. src: settings.url,
  29473. type: 'text/javascript'
  29474. });
  29475. self.count++;
  29476. }
  29477. };
  29478. var XHR = __assign(__assign({}, Observable), {
  29479. send: function (settings) {
  29480. var xhr, count = 0;
  29481. var ready = function () {
  29482. if (!settings.async || xhr.readyState === 4 || count++ > 10000) {
  29483. if (settings.success && count < 10000 && xhr.status === 200) {
  29484. settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings);
  29485. } else if (settings.error) {
  29486. settings.error.call(settings.error_scope, count > 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings);
  29487. }
  29488. xhr = null;
  29489. } else {
  29490. Delay.setTimeout(ready, 10);
  29491. }
  29492. };
  29493. settings.scope = settings.scope || this;
  29494. settings.success_scope = settings.success_scope || settings.scope;
  29495. settings.error_scope = settings.error_scope || settings.scope;
  29496. settings.async = settings.async !== false;
  29497. settings.data = settings.data || '';
  29498. XHR.fire('beforeInitialize', { settings: settings });
  29499. xhr = new XMLHttpRequest();
  29500. if (xhr.overrideMimeType) {
  29501. xhr.overrideMimeType(settings.content_type);
  29502. }
  29503. xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async);
  29504. if (settings.crossDomain) {
  29505. xhr.withCredentials = true;
  29506. }
  29507. if (settings.content_type) {
  29508. xhr.setRequestHeader('Content-Type', settings.content_type);
  29509. }
  29510. if (settings.requestheaders) {
  29511. Tools.each(settings.requestheaders, function (header) {
  29512. xhr.setRequestHeader(header.key, header.value);
  29513. });
  29514. }
  29515. xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  29516. xhr = XHR.fire('beforeSend', {
  29517. xhr: xhr,
  29518. settings: settings
  29519. }).xhr;
  29520. xhr.send(settings.data);
  29521. if (!settings.async) {
  29522. return ready();
  29523. }
  29524. Delay.setTimeout(ready, 10);
  29525. }
  29526. });
  29527. var extend = Tools.extend;
  29528. var JSONRequest = function () {
  29529. function JSONRequest(settings) {
  29530. this.settings = extend({}, settings);
  29531. this.count = 0;
  29532. }
  29533. JSONRequest.sendRPC = function (o) {
  29534. return new JSONRequest().send(o);
  29535. };
  29536. JSONRequest.prototype.send = function (args) {
  29537. var ecb = args.error, scb = args.success;
  29538. var xhrArgs = extend(this.settings, args);
  29539. xhrArgs.success = function (c, x) {
  29540. c = JSONUtils.parse(c);
  29541. if (typeof c === 'undefined') {
  29542. c = { error: 'JSON Parse error.' };
  29543. }
  29544. if (c.error) {
  29545. ecb.call(xhrArgs.error_scope || xhrArgs.scope, c.error, x);
  29546. } else {
  29547. scb.call(xhrArgs.success_scope || xhrArgs.scope, c.result);
  29548. }
  29549. };
  29550. xhrArgs.error = function (ty, x) {
  29551. if (ecb) {
  29552. ecb.call(xhrArgs.error_scope || xhrArgs.scope, ty, x);
  29553. }
  29554. };
  29555. xhrArgs.data = JSONUtils.serialize({
  29556. id: args.id || 'c' + this.count++,
  29557. method: args.method,
  29558. params: args.params
  29559. });
  29560. xhrArgs.content_type = 'application/json';
  29561. XHR.send(xhrArgs);
  29562. };
  29563. return JSONRequest;
  29564. }();
  29565. var create = function () {
  29566. return function () {
  29567. var data = {};
  29568. var keys = [];
  29569. var storage = {
  29570. getItem: function (key) {
  29571. var item = data[key];
  29572. return item ? item : null;
  29573. },
  29574. setItem: function (key, value) {
  29575. keys.push(key);
  29576. data[key] = String(value);
  29577. },
  29578. key: function (index) {
  29579. return keys[index];
  29580. },
  29581. removeItem: function (key) {
  29582. keys = keys.filter(function (k) {
  29583. return k === key;
  29584. });
  29585. delete data[key];
  29586. },
  29587. clear: function () {
  29588. keys = [];
  29589. data = {};
  29590. },
  29591. length: 0
  29592. };
  29593. Object.defineProperty(storage, 'length', {
  29594. get: function () {
  29595. return keys.length;
  29596. },
  29597. configurable: false,
  29598. enumerable: false
  29599. });
  29600. return storage;
  29601. }();
  29602. };
  29603. var localStorage;
  29604. try {
  29605. var test = '__storage_test__';
  29606. localStorage = window.localStorage;
  29607. localStorage.setItem(test, test);
  29608. localStorage.removeItem(test);
  29609. } catch (e) {
  29610. localStorage = create();
  29611. }
  29612. var LocalStorage = localStorage;
  29613. var publicApi = {
  29614. geom: { Rect: Rect },
  29615. util: {
  29616. Promise: promiseObj,
  29617. Delay: Delay,
  29618. Tools: Tools,
  29619. VK: VK,
  29620. URI: URI,
  29621. Class: Class,
  29622. EventDispatcher: EventDispatcher,
  29623. Observable: Observable,
  29624. I18n: I18n,
  29625. XHR: XHR,
  29626. JSON: JSONUtils,
  29627. JSONRequest: JSONRequest,
  29628. JSONP: JSONP,
  29629. LocalStorage: LocalStorage,
  29630. Color: Color,
  29631. ImageUploader: ImageUploader
  29632. },
  29633. dom: {
  29634. EventUtils: EventUtils,
  29635. Sizzle: Sizzle,
  29636. DomQuery: DomQuery,
  29637. TreeWalker: DomTreeWalker,
  29638. TextSeeker: TextSeeker,
  29639. DOMUtils: DOMUtils,
  29640. ScriptLoader: ScriptLoader,
  29641. RangeUtils: RangeUtils,
  29642. Serializer: DomSerializer,
  29643. StyleSheetLoader: StyleSheetLoader,
  29644. ControlSelection: ControlSelection,
  29645. BookmarkManager: BookmarkManager,
  29646. Selection: EditorSelection,
  29647. Event: EventUtils.Event
  29648. },
  29649. html: {
  29650. Styles: Styles,
  29651. Entities: Entities,
  29652. Node: AstNode,
  29653. Schema: Schema,
  29654. SaxParser: SaxParser,
  29655. DomParser: DomParser,
  29656. Writer: Writer,
  29657. Serializer: HtmlSerializer
  29658. },
  29659. Env: Env,
  29660. AddOnManager: AddOnManager,
  29661. Annotator: Annotator,
  29662. Formatter: Formatter,
  29663. UndoManager: UndoManager,
  29664. EditorCommands: EditorCommands,
  29665. WindowManager: WindowManager,
  29666. NotificationManager: NotificationManager,
  29667. EditorObservable: EditorObservable,
  29668. Shortcuts: Shortcuts,
  29669. Editor: Editor,
  29670. FocusManager: FocusManager,
  29671. EditorManager: EditorManager,
  29672. DOM: DOMUtils.DOM,
  29673. ScriptLoader: ScriptLoader.ScriptLoader,
  29674. PluginManager: PluginManager,
  29675. ThemeManager: ThemeManager,
  29676. IconManager: IconManager,
  29677. Resource: Resource,
  29678. trim: Tools.trim,
  29679. isArray: Tools.isArray,
  29680. is: Tools.is,
  29681. toArray: Tools.toArray,
  29682. makeMap: Tools.makeMap,
  29683. each: Tools.each,
  29684. map: Tools.map,
  29685. grep: Tools.grep,
  29686. inArray: Tools.inArray,
  29687. extend: Tools.extend,
  29688. create: Tools.create,
  29689. walk: Tools.walk,
  29690. createNS: Tools.createNS,
  29691. resolve: Tools.resolve,
  29692. explode: Tools.explode,
  29693. _addCacheSuffix: Tools._addCacheSuffix,
  29694. isOpera: Env.opera,
  29695. isWebKit: Env.webkit,
  29696. isIE: Env.ie,
  29697. isGecko: Env.gecko,
  29698. isMac: Env.mac
  29699. };
  29700. var tinymce = Tools.extend(EditorManager, publicApi);
  29701. var exportToModuleLoaders = function (tinymce) {
  29702. if (typeof module === 'object') {
  29703. try {
  29704. module.exports = tinymce;
  29705. } catch (_) {
  29706. }
  29707. }
  29708. };
  29709. var exportToWindowGlobal = function (tinymce) {
  29710. window.tinymce = tinymce;
  29711. window.tinyMCE = tinymce;
  29712. };
  29713. exportToWindowGlobal(tinymce);
  29714. exportToModuleLoaders(tinymce);
  29715. }());