tinymce.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048
  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.0 (2021-10-11)
  8. */
  9. (function () {
  10. 'use strict';
  11. var typeOf$1 = function (x) {
  12. if (x === null) {
  13. return 'null';
  14. }
  15. if (x === undefined) {
  16. return 'undefined';
  17. }
  18. var t = typeof x;
  19. if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  20. return 'array';
  21. }
  22. if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  23. return 'string';
  24. }
  25. return t;
  26. };
  27. var isEquatableType = function (x) {
  28. return [
  29. 'undefined',
  30. 'boolean',
  31. 'number',
  32. 'string',
  33. 'function',
  34. 'xml',
  35. 'null'
  36. ].indexOf(x) !== -1;
  37. };
  38. var sort$1 = function (xs, compareFn) {
  39. var clone = Array.prototype.slice.call(xs);
  40. return clone.sort(compareFn);
  41. };
  42. var contramap = function (eqa, f) {
  43. return eq$2(function (x, y) {
  44. return eqa.eq(f(x), f(y));
  45. });
  46. };
  47. var eq$2 = function (f) {
  48. return { eq: f };
  49. };
  50. var tripleEq = eq$2(function (x, y) {
  51. return x === y;
  52. });
  53. var eqString = tripleEq;
  54. var eqArray = function (eqa) {
  55. return eq$2(function (x, y) {
  56. if (x.length !== y.length) {
  57. return false;
  58. }
  59. var len = x.length;
  60. for (var i = 0; i < len; i++) {
  61. if (!eqa.eq(x[i], y[i])) {
  62. return false;
  63. }
  64. }
  65. return true;
  66. });
  67. };
  68. var eqSortedArray = function (eqa, compareFn) {
  69. return contramap(eqArray(eqa), function (xs) {
  70. return sort$1(xs, compareFn);
  71. });
  72. };
  73. var eqRecord = function (eqa) {
  74. return eq$2(function (x, y) {
  75. var kx = Object.keys(x);
  76. var ky = Object.keys(y);
  77. if (!eqSortedArray(eqString).eq(kx, ky)) {
  78. return false;
  79. }
  80. var len = kx.length;
  81. for (var i = 0; i < len; i++) {
  82. var q = kx[i];
  83. if (!eqa.eq(x[q], y[q])) {
  84. return false;
  85. }
  86. }
  87. return true;
  88. });
  89. };
  90. var eqAny = eq$2(function (x, y) {
  91. if (x === y) {
  92. return true;
  93. }
  94. var tx = typeOf$1(x);
  95. var ty = typeOf$1(y);
  96. if (tx !== ty) {
  97. return false;
  98. }
  99. if (isEquatableType(tx)) {
  100. return x === y;
  101. } else if (tx === 'array') {
  102. return eqArray(eqAny).eq(x, y);
  103. } else if (tx === 'object') {
  104. return eqRecord(eqAny).eq(x, y);
  105. }
  106. return false;
  107. });
  108. var typeOf = function (x) {
  109. var t = typeof x;
  110. if (x === null) {
  111. return 'null';
  112. } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  113. return 'array';
  114. } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  115. return 'string';
  116. } else {
  117. return t;
  118. }
  119. };
  120. var isType$1 = function (type) {
  121. return function (value) {
  122. return typeOf(value) === type;
  123. };
  124. };
  125. var isSimpleType = function (type) {
  126. return function (value) {
  127. return typeof value === type;
  128. };
  129. };
  130. var eq$1 = function (t) {
  131. return function (a) {
  132. return t === a;
  133. };
  134. };
  135. var isString$1 = isType$1('string');
  136. var isObject = isType$1('object');
  137. var isArray$1 = isType$1('array');
  138. var isNull = eq$1(null);
  139. var isBoolean = isSimpleType('boolean');
  140. var isUndefined = eq$1(undefined);
  141. var isNullable = function (a) {
  142. return a === null || a === undefined;
  143. };
  144. var isNonNullable = function (a) {
  145. return !isNullable(a);
  146. };
  147. var isFunction = isSimpleType('function');
  148. var isNumber = isSimpleType('number');
  149. var noop = function () {
  150. };
  151. var compose = function (fa, fb) {
  152. return function () {
  153. var args = [];
  154. for (var _i = 0; _i < arguments.length; _i++) {
  155. args[_i] = arguments[_i];
  156. }
  157. return fa(fb.apply(null, args));
  158. };
  159. };
  160. var compose1 = function (fbc, fab) {
  161. return function (a) {
  162. return fbc(fab(a));
  163. };
  164. };
  165. var constant = function (value) {
  166. return function () {
  167. return value;
  168. };
  169. };
  170. var identity = function (x) {
  171. return x;
  172. };
  173. var tripleEquals = function (a, b) {
  174. return a === b;
  175. };
  176. function curry(fn) {
  177. var initialArgs = [];
  178. for (var _i = 1; _i < arguments.length; _i++) {
  179. initialArgs[_i - 1] = arguments[_i];
  180. }
  181. return function () {
  182. var restArgs = [];
  183. for (var _i = 0; _i < arguments.length; _i++) {
  184. restArgs[_i] = arguments[_i];
  185. }
  186. var all = initialArgs.concat(restArgs);
  187. return fn.apply(null, all);
  188. };
  189. }
  190. var not = function (f) {
  191. return function (t) {
  192. return !f(t);
  193. };
  194. };
  195. var die = function (msg) {
  196. return function () {
  197. throw new Error(msg);
  198. };
  199. };
  200. var apply = function (f) {
  201. return f();
  202. };
  203. var call = function (f) {
  204. f();
  205. };
  206. var never = constant(false);
  207. var always = constant(true);
  208. var none = function () {
  209. return NONE;
  210. };
  211. var NONE = function () {
  212. var call = function (thunk) {
  213. return thunk();
  214. };
  215. var id = identity;
  216. var me = {
  217. fold: function (n, _s) {
  218. return n();
  219. },
  220. isSome: never,
  221. isNone: always,
  222. getOr: id,
  223. getOrThunk: call,
  224. getOrDie: function (msg) {
  225. throw new Error(msg || 'error: getOrDie called on none.');
  226. },
  227. getOrNull: constant(null),
  228. getOrUndefined: constant(undefined),
  229. or: id,
  230. orThunk: call,
  231. map: none,
  232. each: noop,
  233. bind: none,
  234. exists: never,
  235. forall: always,
  236. filter: function () {
  237. return none();
  238. },
  239. toArray: function () {
  240. return [];
  241. },
  242. toString: constant('none()')
  243. };
  244. return me;
  245. }();
  246. var some = function (a) {
  247. var constant_a = constant(a);
  248. var self = function () {
  249. return me;
  250. };
  251. var bind = function (f) {
  252. return f(a);
  253. };
  254. var me = {
  255. fold: function (n, s) {
  256. return s(a);
  257. },
  258. isSome: always,
  259. isNone: never,
  260. getOr: constant_a,
  261. getOrThunk: constant_a,
  262. getOrDie: constant_a,
  263. getOrNull: constant_a,
  264. getOrUndefined: constant_a,
  265. or: self,
  266. orThunk: self,
  267. map: function (f) {
  268. return some(f(a));
  269. },
  270. each: function (f) {
  271. f(a);
  272. },
  273. bind: bind,
  274. exists: bind,
  275. forall: bind,
  276. filter: function (f) {
  277. return f(a) ? me : NONE;
  278. },
  279. toArray: function () {
  280. return [a];
  281. },
  282. toString: function () {
  283. return 'some(' + a + ')';
  284. }
  285. };
  286. return me;
  287. };
  288. var from$1 = function (value) {
  289. return value === null || value === undefined ? NONE : some(value);
  290. };
  291. var Optional = {
  292. some: some,
  293. none: none,
  294. from: from$1
  295. };
  296. var nativeSlice = Array.prototype.slice;
  297. var nativeIndexOf = Array.prototype.indexOf;
  298. var nativePush = Array.prototype.push;
  299. var rawIndexOf = function (ts, t) {
  300. return nativeIndexOf.call(ts, t);
  301. };
  302. var indexOf$2 = function (xs, x) {
  303. var r = rawIndexOf(xs, x);
  304. return r === -1 ? Optional.none() : Optional.some(r);
  305. };
  306. var contains$3 = function (xs, x) {
  307. return rawIndexOf(xs, x) > -1;
  308. };
  309. var exists = function (xs, pred) {
  310. for (var i = 0, len = xs.length; i < len; i++) {
  311. var x = xs[i];
  312. if (pred(x, i)) {
  313. return true;
  314. }
  315. }
  316. return false;
  317. };
  318. var map$3 = function (xs, f) {
  319. var len = xs.length;
  320. var r = new Array(len);
  321. for (var i = 0; i < len; i++) {
  322. var x = xs[i];
  323. r[i] = f(x, i);
  324. }
  325. return r;
  326. };
  327. var each$k = function (xs, f) {
  328. for (var i = 0, len = xs.length; i < len; i++) {
  329. var x = xs[i];
  330. f(x, i);
  331. }
  332. };
  333. var eachr = function (xs, f) {
  334. for (var i = xs.length - 1; i >= 0; i--) {
  335. var x = xs[i];
  336. f(x, i);
  337. }
  338. };
  339. var partition = function (xs, pred) {
  340. var pass = [];
  341. var fail = [];
  342. for (var i = 0, len = xs.length; i < len; i++) {
  343. var x = xs[i];
  344. var arr = pred(x, i) ? pass : fail;
  345. arr.push(x);
  346. }
  347. return {
  348. pass: pass,
  349. fail: fail
  350. };
  351. };
  352. var filter$4 = function (xs, pred) {
  353. var r = [];
  354. for (var i = 0, len = xs.length; i < len; i++) {
  355. var x = xs[i];
  356. if (pred(x, i)) {
  357. r.push(x);
  358. }
  359. }
  360. return r;
  361. };
  362. var foldr = function (xs, f, acc) {
  363. eachr(xs, function (x, i) {
  364. acc = f(acc, x, i);
  365. });
  366. return acc;
  367. };
  368. var foldl = function (xs, f, acc) {
  369. each$k(xs, function (x, i) {
  370. acc = f(acc, x, i);
  371. });
  372. return acc;
  373. };
  374. var findUntil$1 = function (xs, pred, until) {
  375. for (var i = 0, len = xs.length; i < len; i++) {
  376. var x = xs[i];
  377. if (pred(x, i)) {
  378. return Optional.some(x);
  379. } else if (until(x, i)) {
  380. break;
  381. }
  382. }
  383. return Optional.none();
  384. };
  385. var find$3 = function (xs, pred) {
  386. return findUntil$1(xs, pred, never);
  387. };
  388. var findIndex$2 = function (xs, pred) {
  389. for (var i = 0, len = xs.length; i < len; i++) {
  390. var x = xs[i];
  391. if (pred(x, i)) {
  392. return Optional.some(i);
  393. }
  394. }
  395. return Optional.none();
  396. };
  397. var flatten = function (xs) {
  398. var r = [];
  399. for (var i = 0, len = xs.length; i < len; ++i) {
  400. if (!isArray$1(xs[i])) {
  401. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  402. }
  403. nativePush.apply(r, xs[i]);
  404. }
  405. return r;
  406. };
  407. var bind = function (xs, f) {
  408. return flatten(map$3(xs, f));
  409. };
  410. var forall = function (xs, pred) {
  411. for (var i = 0, len = xs.length; i < len; ++i) {
  412. var x = xs[i];
  413. if (pred(x, i) !== true) {
  414. return false;
  415. }
  416. }
  417. return true;
  418. };
  419. var reverse = function (xs) {
  420. var r = nativeSlice.call(xs, 0);
  421. r.reverse();
  422. return r;
  423. };
  424. var difference = function (a1, a2) {
  425. return filter$4(a1, function (x) {
  426. return !contains$3(a2, x);
  427. });
  428. };
  429. var mapToObject = function (xs, f) {
  430. var r = {};
  431. for (var i = 0, len = xs.length; i < len; i++) {
  432. var x = xs[i];
  433. r[String(x)] = f(x, i);
  434. }
  435. return r;
  436. };
  437. var sort = function (xs, comparator) {
  438. var copy = nativeSlice.call(xs, 0);
  439. copy.sort(comparator);
  440. return copy;
  441. };
  442. var get$a = function (xs, i) {
  443. return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
  444. };
  445. var head = function (xs) {
  446. return get$a(xs, 0);
  447. };
  448. var last$2 = function (xs) {
  449. return get$a(xs, xs.length - 1);
  450. };
  451. var from = isFunction(Array.from) ? Array.from : function (x) {
  452. return nativeSlice.call(x);
  453. };
  454. var findMap = function (arr, f) {
  455. for (var i = 0; i < arr.length; i++) {
  456. var r = f(arr[i], i);
  457. if (r.isSome()) {
  458. return r;
  459. }
  460. }
  461. return Optional.none();
  462. };
  463. var keys = Object.keys;
  464. var hasOwnProperty$1 = Object.hasOwnProperty;
  465. var each$j = function (obj, f) {
  466. var props = keys(obj);
  467. for (var k = 0, len = props.length; k < len; k++) {
  468. var i = props[k];
  469. var x = obj[i];
  470. f(x, i);
  471. }
  472. };
  473. var map$2 = function (obj, f) {
  474. return tupleMap(obj, function (x, i) {
  475. return {
  476. k: i,
  477. v: f(x, i)
  478. };
  479. });
  480. };
  481. var tupleMap = function (obj, f) {
  482. var r = {};
  483. each$j(obj, function (x, i) {
  484. var tuple = f(x, i);
  485. r[tuple.k] = tuple.v;
  486. });
  487. return r;
  488. };
  489. var objAcc = function (r) {
  490. return function (x, i) {
  491. r[i] = x;
  492. };
  493. };
  494. var internalFilter = function (obj, pred, onTrue, onFalse) {
  495. var r = {};
  496. each$j(obj, function (x, i) {
  497. (pred(x, i) ? onTrue : onFalse)(x, i);
  498. });
  499. return r;
  500. };
  501. var bifilter = function (obj, pred) {
  502. var t = {};
  503. var f = {};
  504. internalFilter(obj, pred, objAcc(t), objAcc(f));
  505. return {
  506. t: t,
  507. f: f
  508. };
  509. };
  510. var filter$3 = function (obj, pred) {
  511. var t = {};
  512. internalFilter(obj, pred, objAcc(t), noop);
  513. return t;
  514. };
  515. var mapToArray = function (obj, f) {
  516. var r = [];
  517. each$j(obj, function (value, name) {
  518. r.push(f(value, name));
  519. });
  520. return r;
  521. };
  522. var values = function (obj) {
  523. return mapToArray(obj, identity);
  524. };
  525. var get$9 = function (obj, key) {
  526. return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
  527. };
  528. var has$2 = function (obj, key) {
  529. return hasOwnProperty$1.call(obj, key);
  530. };
  531. var hasNonNullableKey = function (obj, key) {
  532. return has$2(obj, key) && obj[key] !== undefined && obj[key] !== null;
  533. };
  534. var equal$1 = function (a1, a2, eq) {
  535. if (eq === void 0) {
  536. eq = eqAny;
  537. }
  538. return eqRecord(eq).eq(a1, a2);
  539. };
  540. var isArray = Array.isArray;
  541. var toArray$1 = function (obj) {
  542. if (!isArray(obj)) {
  543. var array = [];
  544. for (var i = 0, l = obj.length; i < l; i++) {
  545. array[i] = obj[i];
  546. }
  547. return array;
  548. } else {
  549. return obj;
  550. }
  551. };
  552. var each$i = function (o, cb, s) {
  553. var n, l;
  554. if (!o) {
  555. return false;
  556. }
  557. s = s || o;
  558. if (o.length !== undefined) {
  559. for (n = 0, l = o.length; n < l; n++) {
  560. if (cb.call(s, o[n], n, o) === false) {
  561. return false;
  562. }
  563. }
  564. } else {
  565. for (n in o) {
  566. if (has$2(o, n)) {
  567. if (cb.call(s, o[n], n, o) === false) {
  568. return false;
  569. }
  570. }
  571. }
  572. }
  573. return true;
  574. };
  575. var map$1 = function (array, callback) {
  576. var out = [];
  577. each$i(array, function (item, index) {
  578. out.push(callback(item, index, array));
  579. });
  580. return out;
  581. };
  582. var filter$2 = function (a, f) {
  583. var o = [];
  584. each$i(a, function (v, index) {
  585. if (!f || f(v, index, a)) {
  586. o.push(v);
  587. }
  588. });
  589. return o;
  590. };
  591. var indexOf$1 = function (a, v) {
  592. if (a) {
  593. for (var i = 0, l = a.length; i < l; i++) {
  594. if (a[i] === v) {
  595. return i;
  596. }
  597. }
  598. }
  599. return -1;
  600. };
  601. var reduce = function (collection, iteratee, accumulator, thisArg) {
  602. var acc = isUndefined(accumulator) ? collection[0] : accumulator;
  603. for (var i = 0; i < collection.length; i++) {
  604. acc = iteratee.call(thisArg, acc, collection[i], i);
  605. }
  606. return acc;
  607. };
  608. var findIndex$1 = function (array, predicate, thisArg) {
  609. var i, l;
  610. for (i = 0, l = array.length; i < l; i++) {
  611. if (predicate.call(thisArg, array[i], i, array)) {
  612. return i;
  613. }
  614. }
  615. return -1;
  616. };
  617. var last$1 = function (collection) {
  618. return collection[collection.length - 1];
  619. };
  620. var __assign = function () {
  621. __assign = Object.assign || function __assign(t) {
  622. for (var s, i = 1, n = arguments.length; i < n; i++) {
  623. s = arguments[i];
  624. for (var p in s)
  625. if (Object.prototype.hasOwnProperty.call(s, p))
  626. t[p] = s[p];
  627. }
  628. return t;
  629. };
  630. return __assign.apply(this, arguments);
  631. };
  632. function __rest(s, e) {
  633. var t = {};
  634. for (var p in s)
  635. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  636. t[p] = s[p];
  637. if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  638. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  639. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  640. t[p[i]] = s[p[i]];
  641. }
  642. return t;
  643. }
  644. function __spreadArray(to, from, pack) {
  645. if (pack || arguments.length === 2)
  646. for (var i = 0, l = from.length, ar; i < l; i++) {
  647. if (ar || !(i in from)) {
  648. if (!ar)
  649. ar = Array.prototype.slice.call(from, 0, i);
  650. ar[i] = from[i];
  651. }
  652. }
  653. return to.concat(ar || Array.prototype.slice.call(from));
  654. }
  655. var cached = function (f) {
  656. var called = false;
  657. var r;
  658. return function () {
  659. var args = [];
  660. for (var _i = 0; _i < arguments.length; _i++) {
  661. args[_i] = arguments[_i];
  662. }
  663. if (!called) {
  664. called = true;
  665. r = f.apply(null, args);
  666. }
  667. return r;
  668. };
  669. };
  670. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  671. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  672. var isiPhone = os.isiOS() && !isiPad;
  673. var isMobile = os.isiOS() || os.isAndroid();
  674. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  675. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  676. var isPhone = isiPhone || isMobile && !isTablet;
  677. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  678. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  679. return {
  680. isiPad: constant(isiPad),
  681. isiPhone: constant(isiPhone),
  682. isTablet: constant(isTablet),
  683. isPhone: constant(isPhone),
  684. isTouch: constant(isTouch),
  685. isAndroid: os.isAndroid,
  686. isiOS: os.isiOS,
  687. isWebView: constant(iOSwebview),
  688. isDesktop: constant(isDesktop)
  689. };
  690. };
  691. var firstMatch = function (regexes, s) {
  692. for (var i = 0; i < regexes.length; i++) {
  693. var x = regexes[i];
  694. if (x.test(s)) {
  695. return x;
  696. }
  697. }
  698. return undefined;
  699. };
  700. var find$2 = function (regexes, agent) {
  701. var r = firstMatch(regexes, agent);
  702. if (!r) {
  703. return {
  704. major: 0,
  705. minor: 0
  706. };
  707. }
  708. var group = function (i) {
  709. return Number(agent.replace(r, '$' + i));
  710. };
  711. return nu$4(group(1), group(2));
  712. };
  713. var detect$3 = function (versionRegexes, agent) {
  714. var cleanedAgent = String(agent).toLowerCase();
  715. if (versionRegexes.length === 0) {
  716. return unknown$2();
  717. }
  718. return find$2(versionRegexes, cleanedAgent);
  719. };
  720. var unknown$2 = function () {
  721. return nu$4(0, 0);
  722. };
  723. var nu$4 = function (major, minor) {
  724. return {
  725. major: major,
  726. minor: minor
  727. };
  728. };
  729. var Version = {
  730. nu: nu$4,
  731. detect: detect$3,
  732. unknown: unknown$2
  733. };
  734. var detectBrowser$1 = function (browsers, userAgentData) {
  735. return findMap(userAgentData.brands, function (uaBrand) {
  736. var lcBrand = uaBrand.brand.toLowerCase();
  737. return find$3(browsers, function (browser) {
  738. var _a;
  739. return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
  740. }).map(function (info) {
  741. return {
  742. current: info.name,
  743. version: Version.nu(parseInt(uaBrand.version, 10), 0)
  744. };
  745. });
  746. });
  747. };
  748. var detect$2 = function (candidates, userAgent) {
  749. var agent = String(userAgent).toLowerCase();
  750. return find$3(candidates, function (candidate) {
  751. return candidate.search(agent);
  752. });
  753. };
  754. var detectBrowser = function (browsers, userAgent) {
  755. return detect$2(browsers, userAgent).map(function (browser) {
  756. var version = Version.detect(browser.versionRegexes, userAgent);
  757. return {
  758. current: browser.name,
  759. version: version
  760. };
  761. });
  762. };
  763. var detectOs = function (oses, userAgent) {
  764. return detect$2(oses, userAgent).map(function (os) {
  765. var version = Version.detect(os.versionRegexes, userAgent);
  766. return {
  767. current: os.name,
  768. version: version
  769. };
  770. });
  771. };
  772. var removeFromStart = function (str, numChars) {
  773. return str.substring(numChars);
  774. };
  775. var checkRange = function (str, substr, start) {
  776. return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  777. };
  778. var removeLeading = function (str, prefix) {
  779. return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
  780. };
  781. var contains$2 = function (str, substr) {
  782. return str.indexOf(substr) !== -1;
  783. };
  784. var startsWith = function (str, prefix) {
  785. return checkRange(str, prefix, 0);
  786. };
  787. var blank = function (r) {
  788. return function (s) {
  789. return s.replace(r, '');
  790. };
  791. };
  792. var trim$4 = blank(/^\s+|\s+$/g);
  793. var lTrim = blank(/^\s+/g);
  794. var rTrim = blank(/\s+$/g);
  795. var isNotEmpty = function (s) {
  796. return s.length > 0;
  797. };
  798. var isEmpty$3 = function (s) {
  799. return !isNotEmpty(s);
  800. };
  801. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  802. var checkContains = function (target) {
  803. return function (uastring) {
  804. return contains$2(uastring, target);
  805. };
  806. };
  807. var browsers = [
  808. {
  809. name: 'Edge',
  810. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  811. search: function (uastring) {
  812. return contains$2(uastring, 'edge/') && contains$2(uastring, 'chrome') && contains$2(uastring, 'safari') && contains$2(uastring, 'applewebkit');
  813. }
  814. },
  815. {
  816. name: 'Chrome',
  817. brand: 'Chromium',
  818. versionRegexes: [
  819. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  820. normalVersionRegex
  821. ],
  822. search: function (uastring) {
  823. return contains$2(uastring, 'chrome') && !contains$2(uastring, 'chromeframe');
  824. }
  825. },
  826. {
  827. name: 'IE',
  828. versionRegexes: [
  829. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  830. /.*?rv:([0-9]+)\.([0-9]+).*/
  831. ],
  832. search: function (uastring) {
  833. return contains$2(uastring, 'msie') || contains$2(uastring, 'trident');
  834. }
  835. },
  836. {
  837. name: 'Opera',
  838. versionRegexes: [
  839. normalVersionRegex,
  840. /.*?opera\/([0-9]+)\.([0-9]+).*/
  841. ],
  842. search: checkContains('opera')
  843. },
  844. {
  845. name: 'Firefox',
  846. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  847. search: checkContains('firefox')
  848. },
  849. {
  850. name: 'Safari',
  851. versionRegexes: [
  852. normalVersionRegex,
  853. /.*?cpu os ([0-9]+)_([0-9]+).*/
  854. ],
  855. search: function (uastring) {
  856. return (contains$2(uastring, 'safari') || contains$2(uastring, 'mobile/')) && contains$2(uastring, 'applewebkit');
  857. }
  858. }
  859. ];
  860. var oses = [
  861. {
  862. name: 'Windows',
  863. search: checkContains('win'),
  864. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  865. },
  866. {
  867. name: 'iOS',
  868. search: function (uastring) {
  869. return contains$2(uastring, 'iphone') || contains$2(uastring, 'ipad');
  870. },
  871. versionRegexes: [
  872. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  873. /.*cpu os ([0-9]+)_([0-9]+).*/,
  874. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  875. ]
  876. },
  877. {
  878. name: 'Android',
  879. search: checkContains('android'),
  880. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  881. },
  882. {
  883. name: 'OSX',
  884. search: checkContains('mac os x'),
  885. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  886. },
  887. {
  888. name: 'Linux',
  889. search: checkContains('linux'),
  890. versionRegexes: []
  891. },
  892. {
  893. name: 'Solaris',
  894. search: checkContains('sunos'),
  895. versionRegexes: []
  896. },
  897. {
  898. name: 'FreeBSD',
  899. search: checkContains('freebsd'),
  900. versionRegexes: []
  901. },
  902. {
  903. name: 'ChromeOS',
  904. search: checkContains('cros'),
  905. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  906. }
  907. ];
  908. var PlatformInfo = {
  909. browsers: constant(browsers),
  910. oses: constant(oses)
  911. };
  912. var edge = 'Edge';
  913. var chrome = 'Chrome';
  914. var ie$1 = 'IE';
  915. var opera = 'Opera';
  916. var firefox = 'Firefox';
  917. var safari = 'Safari';
  918. var unknown$1 = function () {
  919. return nu$3({
  920. current: undefined,
  921. version: Version.unknown()
  922. });
  923. };
  924. var nu$3 = function (info) {
  925. var current = info.current;
  926. var version = info.version;
  927. var isBrowser = function (name) {
  928. return function () {
  929. return current === name;
  930. };
  931. };
  932. return {
  933. current: current,
  934. version: version,
  935. isEdge: isBrowser(edge),
  936. isChrome: isBrowser(chrome),
  937. isIE: isBrowser(ie$1),
  938. isOpera: isBrowser(opera),
  939. isFirefox: isBrowser(firefox),
  940. isSafari: isBrowser(safari)
  941. };
  942. };
  943. var Browser = {
  944. unknown: unknown$1,
  945. nu: nu$3,
  946. edge: constant(edge),
  947. chrome: constant(chrome),
  948. ie: constant(ie$1),
  949. opera: constant(opera),
  950. firefox: constant(firefox),
  951. safari: constant(safari)
  952. };
  953. var windows = 'Windows';
  954. var ios = 'iOS';
  955. var android = 'Android';
  956. var linux = 'Linux';
  957. var osx = 'OSX';
  958. var solaris = 'Solaris';
  959. var freebsd = 'FreeBSD';
  960. var chromeos = 'ChromeOS';
  961. var unknown = function () {
  962. return nu$2({
  963. current: undefined,
  964. version: Version.unknown()
  965. });
  966. };
  967. var nu$2 = function (info) {
  968. var current = info.current;
  969. var version = info.version;
  970. var isOS = function (name) {
  971. return function () {
  972. return current === name;
  973. };
  974. };
  975. return {
  976. current: current,
  977. version: version,
  978. isWindows: isOS(windows),
  979. isiOS: isOS(ios),
  980. isAndroid: isOS(android),
  981. isOSX: isOS(osx),
  982. isLinux: isOS(linux),
  983. isSolaris: isOS(solaris),
  984. isFreeBSD: isOS(freebsd),
  985. isChromeOS: isOS(chromeos)
  986. };
  987. };
  988. var OperatingSystem = {
  989. unknown: unknown,
  990. nu: nu$2,
  991. windows: constant(windows),
  992. ios: constant(ios),
  993. android: constant(android),
  994. linux: constant(linux),
  995. osx: constant(osx),
  996. solaris: constant(solaris),
  997. freebsd: constant(freebsd),
  998. chromeos: constant(chromeos)
  999. };
  1000. var detect$1 = function (userAgent, userAgentDataOpt, mediaMatch) {
  1001. var browsers = PlatformInfo.browsers();
  1002. var oses = PlatformInfo.oses();
  1003. var browser = userAgentDataOpt.bind(function (userAgentData) {
  1004. return detectBrowser$1(browsers, userAgentData);
  1005. }).orThunk(function () {
  1006. return detectBrowser(browsers, userAgent);
  1007. }).fold(Browser.unknown, Browser.nu);
  1008. var os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  1009. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  1010. return {
  1011. browser: browser,
  1012. os: os,
  1013. deviceType: deviceType
  1014. };
  1015. };
  1016. var PlatformDetection = { detect: detect$1 };
  1017. var mediaMatch = function (query) {
  1018. return window.matchMedia(query).matches;
  1019. };
  1020. var platform$2 = cached(function () {
  1021. return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
  1022. });
  1023. var detect = function () {
  1024. return platform$2();
  1025. };
  1026. var userAgent = navigator.userAgent;
  1027. var platform$1 = detect();
  1028. var browser$4 = platform$1.browser;
  1029. var os = platform$1.os;
  1030. var deviceType = platform$1.deviceType;
  1031. var webkit = /WebKit/.test(userAgent) && !browser$4.isEdge();
  1032. var fileApi = 'FormData' in window && 'FileReader' in window && 'URL' in window && !!URL.createObjectURL;
  1033. var windowsPhone = userAgent.indexOf('Windows Phone') !== -1;
  1034. var Env = {
  1035. opera: browser$4.isOpera(),
  1036. webkit: webkit,
  1037. ie: browser$4.isIE() || browser$4.isEdge() ? browser$4.version.major : false,
  1038. gecko: browser$4.isFirefox(),
  1039. mac: os.isOSX() || os.isiOS(),
  1040. iOS: deviceType.isiPad() || deviceType.isiPhone(),
  1041. android: os.isAndroid(),
  1042. contentEditable: true,
  1043. transparentSrc: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
  1044. caretAfter: true,
  1045. range: window.getSelection && 'Range' in window,
  1046. documentMode: browser$4.isIE() ? document.documentMode || 7 : 10,
  1047. fileApi: fileApi,
  1048. ceFalse: true,
  1049. cacheSuffix: null,
  1050. container: null,
  1051. experimentalShadowDom: false,
  1052. canHaveCSP: !browser$4.isIE(),
  1053. desktop: deviceType.isDesktop(),
  1054. windowsPhone: windowsPhone,
  1055. browser: {
  1056. current: browser$4.current,
  1057. version: browser$4.version,
  1058. isChrome: browser$4.isChrome,
  1059. isEdge: browser$4.isEdge,
  1060. isFirefox: browser$4.isFirefox,
  1061. isIE: browser$4.isIE,
  1062. isOpera: browser$4.isOpera,
  1063. isSafari: browser$4.isSafari
  1064. },
  1065. os: {
  1066. current: os.current,
  1067. version: os.version,
  1068. isAndroid: os.isAndroid,
  1069. isChromeOS: os.isChromeOS,
  1070. isFreeBSD: os.isFreeBSD,
  1071. isiOS: os.isiOS,
  1072. isLinux: os.isLinux,
  1073. isOSX: os.isOSX,
  1074. isSolaris: os.isSolaris,
  1075. isWindows: os.isWindows
  1076. },
  1077. deviceType: {
  1078. isDesktop: deviceType.isDesktop,
  1079. isiPad: deviceType.isiPad,
  1080. isiPhone: deviceType.isiPhone,
  1081. isPhone: deviceType.isPhone,
  1082. isTablet: deviceType.isTablet,
  1083. isTouch: deviceType.isTouch,
  1084. isWebView: deviceType.isWebView
  1085. }
  1086. };
  1087. var whiteSpaceRegExp$2 = /^\s*|\s*$/g;
  1088. var trim$3 = function (str) {
  1089. return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp$2, '');
  1090. };
  1091. var is$3 = function (obj, type) {
  1092. if (!type) {
  1093. return obj !== undefined;
  1094. }
  1095. if (type === 'array' && isArray(obj)) {
  1096. return true;
  1097. }
  1098. return typeof obj === type;
  1099. };
  1100. var makeMap$4 = function (items, delim, map) {
  1101. var i;
  1102. items = items || [];
  1103. delim = delim || ',';
  1104. if (typeof items === 'string') {
  1105. items = items.split(delim);
  1106. }
  1107. map = map || {};
  1108. i = items.length;
  1109. while (i--) {
  1110. map[items[i]] = {};
  1111. }
  1112. return map;
  1113. };
  1114. var hasOwnProperty = has$2;
  1115. var create$9 = function (s, p, root) {
  1116. var self = this;
  1117. var sp, scn, c, de = 0;
  1118. s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
  1119. var cn = s[3].match(/(^|\.)(\w+)$/i)[2];
  1120. var ns = self.createNS(s[3].replace(/\.\w+$/, ''), root);
  1121. if (ns[cn]) {
  1122. return;
  1123. }
  1124. if (s[2] === 'static') {
  1125. ns[cn] = p;
  1126. if (this.onCreate) {
  1127. this.onCreate(s[2], s[3], ns[cn]);
  1128. }
  1129. return;
  1130. }
  1131. if (!p[cn]) {
  1132. p[cn] = function () {
  1133. };
  1134. de = 1;
  1135. }
  1136. ns[cn] = p[cn];
  1137. self.extend(ns[cn].prototype, p);
  1138. if (s[5]) {
  1139. sp = self.resolve(s[5]).prototype;
  1140. scn = s[5].match(/\.(\w+)$/i)[1];
  1141. c = ns[cn];
  1142. if (de) {
  1143. ns[cn] = function () {
  1144. return sp[scn].apply(this, arguments);
  1145. };
  1146. } else {
  1147. ns[cn] = function () {
  1148. this.parent = sp[scn];
  1149. return c.apply(this, arguments);
  1150. };
  1151. }
  1152. ns[cn].prototype[cn] = ns[cn];
  1153. self.each(sp, function (f, n) {
  1154. ns[cn].prototype[n] = sp[n];
  1155. });
  1156. self.each(p, function (f, n) {
  1157. if (sp[n]) {
  1158. ns[cn].prototype[n] = function () {
  1159. this.parent = sp[n];
  1160. return f.apply(this, arguments);
  1161. };
  1162. } else {
  1163. if (n !== cn) {
  1164. ns[cn].prototype[n] = f;
  1165. }
  1166. }
  1167. });
  1168. }
  1169. self.each(p.static, function (f, n) {
  1170. ns[cn][n] = f;
  1171. });
  1172. };
  1173. var extend$6 = function (obj) {
  1174. var exts = [];
  1175. for (var _i = 1; _i < arguments.length; _i++) {
  1176. exts[_i - 1] = arguments[_i];
  1177. }
  1178. for (var i = 0; i < exts.length; i++) {
  1179. var ext = exts[i];
  1180. for (var name_1 in ext) {
  1181. if (has$2(ext, name_1)) {
  1182. var value = ext[name_1];
  1183. if (value !== undefined) {
  1184. obj[name_1] = value;
  1185. }
  1186. }
  1187. }
  1188. }
  1189. return obj;
  1190. };
  1191. var walk$3 = function (o, f, n, s) {
  1192. s = s || this;
  1193. if (o) {
  1194. if (n) {
  1195. o = o[n];
  1196. }
  1197. each$i(o, function (o, i) {
  1198. if (f.call(s, o, i, n) === false) {
  1199. return false;
  1200. }
  1201. walk$3(o, f, n, s);
  1202. });
  1203. }
  1204. };
  1205. var createNS = function (n, o) {
  1206. var i, v;
  1207. o = o || window;
  1208. n = n.split('.');
  1209. for (i = 0; i < n.length; i++) {
  1210. v = n[i];
  1211. if (!o[v]) {
  1212. o[v] = {};
  1213. }
  1214. o = o[v];
  1215. }
  1216. return o;
  1217. };
  1218. var resolve$3 = function (n, o) {
  1219. var i, l;
  1220. o = o || window;
  1221. n = n.split('.');
  1222. for (i = 0, l = n.length; i < l; i++) {
  1223. o = o[n[i]];
  1224. if (!o) {
  1225. break;
  1226. }
  1227. }
  1228. return o;
  1229. };
  1230. var explode$4 = function (s, d) {
  1231. if (!s || is$3(s, 'array')) {
  1232. return s;
  1233. }
  1234. return map$1(s.split(d || ','), trim$3);
  1235. };
  1236. var _addCacheSuffix = function (url) {
  1237. var cacheSuffix = Env.cacheSuffix;
  1238. if (cacheSuffix) {
  1239. url += (url.indexOf('?') === -1 ? '?' : '&') + cacheSuffix;
  1240. }
  1241. return url;
  1242. };
  1243. var Tools = {
  1244. trim: trim$3,
  1245. isArray: isArray,
  1246. is: is$3,
  1247. toArray: toArray$1,
  1248. makeMap: makeMap$4,
  1249. each: each$i,
  1250. map: map$1,
  1251. grep: filter$2,
  1252. inArray: indexOf$1,
  1253. hasOwn: hasOwnProperty,
  1254. extend: extend$6,
  1255. create: create$9,
  1256. walk: walk$3,
  1257. createNS: createNS,
  1258. resolve: resolve$3,
  1259. explode: explode$4,
  1260. _addCacheSuffix: _addCacheSuffix
  1261. };
  1262. var fromHtml$1 = function (html, scope) {
  1263. var doc = scope || document;
  1264. var div = doc.createElement('div');
  1265. div.innerHTML = html;
  1266. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  1267. console.error('HTML does not have a single root node', html);
  1268. throw new Error('HTML must have a single root node');
  1269. }
  1270. return fromDom$2(div.childNodes[0]);
  1271. };
  1272. var fromTag = function (tag, scope) {
  1273. var doc = scope || document;
  1274. var node = doc.createElement(tag);
  1275. return fromDom$2(node);
  1276. };
  1277. var fromText = function (text, scope) {
  1278. var doc = scope || document;
  1279. var node = doc.createTextNode(text);
  1280. return fromDom$2(node);
  1281. };
  1282. var fromDom$2 = function (node) {
  1283. if (node === null || node === undefined) {
  1284. throw new Error('Node cannot be null or undefined');
  1285. }
  1286. return { dom: node };
  1287. };
  1288. var fromPoint$1 = function (docElm, x, y) {
  1289. return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom$2);
  1290. };
  1291. var SugarElement = {
  1292. fromHtml: fromHtml$1,
  1293. fromTag: fromTag,
  1294. fromText: fromText,
  1295. fromDom: fromDom$2,
  1296. fromPoint: fromPoint$1
  1297. };
  1298. var toArray = function (target, f) {
  1299. var r = [];
  1300. var recurse = function (e) {
  1301. r.push(e);
  1302. return f(e);
  1303. };
  1304. var cur = f(target);
  1305. do {
  1306. cur = cur.bind(recurse);
  1307. } while (cur.isSome());
  1308. return r;
  1309. };
  1310. var compareDocumentPosition = function (a, b, match) {
  1311. return (a.compareDocumentPosition(b) & match) !== 0;
  1312. };
  1313. var documentPositionContainedBy = function (a, b) {
  1314. return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
  1315. };
  1316. var COMMENT = 8;
  1317. var DOCUMENT = 9;
  1318. var DOCUMENT_FRAGMENT = 11;
  1319. var ELEMENT = 1;
  1320. var TEXT = 3;
  1321. var is$2 = function (element, selector) {
  1322. var dom = element.dom;
  1323. if (dom.nodeType !== ELEMENT) {
  1324. return false;
  1325. } else {
  1326. var elem = dom;
  1327. if (elem.matches !== undefined) {
  1328. return elem.matches(selector);
  1329. } else if (elem.msMatchesSelector !== undefined) {
  1330. return elem.msMatchesSelector(selector);
  1331. } else if (elem.webkitMatchesSelector !== undefined) {
  1332. return elem.webkitMatchesSelector(selector);
  1333. } else if (elem.mozMatchesSelector !== undefined) {
  1334. return elem.mozMatchesSelector(selector);
  1335. } else {
  1336. throw new Error('Browser lacks native selectors');
  1337. }
  1338. }
  1339. };
  1340. var bypassSelector = function (dom) {
  1341. return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  1342. };
  1343. var all = function (selector, scope) {
  1344. var base = scope === undefined ? document : scope.dom;
  1345. return bypassSelector(base) ? [] : map$3(base.querySelectorAll(selector), SugarElement.fromDom);
  1346. };
  1347. var one = function (selector, scope) {
  1348. var base = scope === undefined ? document : scope.dom;
  1349. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  1350. };
  1351. var eq = function (e1, e2) {
  1352. return e1.dom === e2.dom;
  1353. };
  1354. var regularContains = function (e1, e2) {
  1355. var d1 = e1.dom;
  1356. var d2 = e2.dom;
  1357. return d1 === d2 ? false : d1.contains(d2);
  1358. };
  1359. var ieContains = function (e1, e2) {
  1360. return documentPositionContainedBy(e1.dom, e2.dom);
  1361. };
  1362. var contains$1 = function (e1, e2) {
  1363. return detect().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
  1364. };
  1365. typeof window !== 'undefined' ? window : Function('return this;')();
  1366. var name = function (element) {
  1367. var r = element.dom.nodeName;
  1368. return r.toLowerCase();
  1369. };
  1370. var type = function (element) {
  1371. return element.dom.nodeType;
  1372. };
  1373. var isType = function (t) {
  1374. return function (element) {
  1375. return type(element) === t;
  1376. };
  1377. };
  1378. var isComment$1 = function (element) {
  1379. return type(element) === COMMENT || name(element) === '#comment';
  1380. };
  1381. var isElement$6 = isType(ELEMENT);
  1382. var isText$8 = isType(TEXT);
  1383. var isDocument$2 = isType(DOCUMENT);
  1384. var isDocumentFragment$1 = isType(DOCUMENT_FRAGMENT);
  1385. var isTag = function (tag) {
  1386. return function (e) {
  1387. return isElement$6(e) && name(e) === tag;
  1388. };
  1389. };
  1390. var owner$1 = function (element) {
  1391. return SugarElement.fromDom(element.dom.ownerDocument);
  1392. };
  1393. var documentOrOwner = function (dos) {
  1394. return isDocument$2(dos) ? dos : owner$1(dos);
  1395. };
  1396. var documentElement = function (element) {
  1397. return SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
  1398. };
  1399. var defaultView = function (element) {
  1400. return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  1401. };
  1402. var parent = function (element) {
  1403. return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  1404. };
  1405. var parents$1 = function (element, isRoot) {
  1406. var stop = isFunction(isRoot) ? isRoot : never;
  1407. var dom = element.dom;
  1408. var ret = [];
  1409. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  1410. var rawParent = dom.parentNode;
  1411. var p = SugarElement.fromDom(rawParent);
  1412. ret.push(p);
  1413. if (stop(p) === true) {
  1414. break;
  1415. } else {
  1416. dom = rawParent;
  1417. }
  1418. }
  1419. return ret;
  1420. };
  1421. var siblings = function (element) {
  1422. var filterSelf = function (elements) {
  1423. return filter$4(elements, function (x) {
  1424. return !eq(element, x);
  1425. });
  1426. };
  1427. return parent(element).map(children).map(filterSelf).getOr([]);
  1428. };
  1429. var prevSibling = function (element) {
  1430. return Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
  1431. };
  1432. var nextSibling = function (element) {
  1433. return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  1434. };
  1435. var prevSiblings = function (element) {
  1436. return reverse(toArray(element, prevSibling));
  1437. };
  1438. var nextSiblings = function (element) {
  1439. return toArray(element, nextSibling);
  1440. };
  1441. var children = function (element) {
  1442. return map$3(element.dom.childNodes, SugarElement.fromDom);
  1443. };
  1444. var child$1 = function (element, index) {
  1445. var cs = element.dom.childNodes;
  1446. return Optional.from(cs[index]).map(SugarElement.fromDom);
  1447. };
  1448. var firstChild = function (element) {
  1449. return child$1(element, 0);
  1450. };
  1451. var lastChild = function (element) {
  1452. return child$1(element, element.dom.childNodes.length - 1);
  1453. };
  1454. var childNodesCount = function (element) {
  1455. return element.dom.childNodes.length;
  1456. };
  1457. var getHead = function (doc) {
  1458. var b = doc.dom.head;
  1459. if (b === null || b === undefined) {
  1460. throw new Error('Head is not available yet');
  1461. }
  1462. return SugarElement.fromDom(b);
  1463. };
  1464. var isShadowRoot = function (dos) {
  1465. return isDocumentFragment$1(dos) && isNonNullable(dos.dom.host);
  1466. };
  1467. var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  1468. var isSupported$1 = constant(supported);
  1469. var getRootNode = supported ? function (e) {
  1470. return SugarElement.fromDom(e.dom.getRootNode());
  1471. } : documentOrOwner;
  1472. var getStyleContainer = function (dos) {
  1473. return isShadowRoot(dos) ? dos : getHead(documentOrOwner(dos));
  1474. };
  1475. var getShadowRoot = function (e) {
  1476. var r = getRootNode(e);
  1477. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  1478. };
  1479. var getShadowHost = function (e) {
  1480. return SugarElement.fromDom(e.dom.host);
  1481. };
  1482. var getOriginalEventTarget = function (event) {
  1483. if (isSupported$1() && isNonNullable(event.target)) {
  1484. var el = SugarElement.fromDom(event.target);
  1485. if (isElement$6(el) && isOpenShadowHost(el)) {
  1486. if (event.composed && event.composedPath) {
  1487. var composedPath = event.composedPath();
  1488. if (composedPath) {
  1489. return head(composedPath);
  1490. }
  1491. }
  1492. }
  1493. }
  1494. return Optional.from(event.target);
  1495. };
  1496. var isOpenShadowHost = function (element) {
  1497. return isNonNullable(element.dom.shadowRoot);
  1498. };
  1499. var before$4 = function (marker, element) {
  1500. var parent$1 = parent(marker);
  1501. parent$1.each(function (v) {
  1502. v.dom.insertBefore(element.dom, marker.dom);
  1503. });
  1504. };
  1505. var after$3 = function (marker, element) {
  1506. var sibling = nextSibling(marker);
  1507. sibling.fold(function () {
  1508. var parent$1 = parent(marker);
  1509. parent$1.each(function (v) {
  1510. append$1(v, element);
  1511. });
  1512. }, function (v) {
  1513. before$4(v, element);
  1514. });
  1515. };
  1516. var prepend = function (parent, element) {
  1517. var firstChild$1 = firstChild(parent);
  1518. firstChild$1.fold(function () {
  1519. append$1(parent, element);
  1520. }, function (v) {
  1521. parent.dom.insertBefore(element.dom, v.dom);
  1522. });
  1523. };
  1524. var append$1 = function (parent, element) {
  1525. parent.dom.appendChild(element.dom);
  1526. };
  1527. var wrap$3 = function (element, wrapper) {
  1528. before$4(element, wrapper);
  1529. append$1(wrapper, element);
  1530. };
  1531. var before$3 = function (marker, elements) {
  1532. each$k(elements, function (x) {
  1533. before$4(marker, x);
  1534. });
  1535. };
  1536. var append = function (parent, elements) {
  1537. each$k(elements, function (x) {
  1538. append$1(parent, x);
  1539. });
  1540. };
  1541. var empty = function (element) {
  1542. element.dom.textContent = '';
  1543. each$k(children(element), function (rogue) {
  1544. remove$7(rogue);
  1545. });
  1546. };
  1547. var remove$7 = function (element) {
  1548. var dom = element.dom;
  1549. if (dom.parentNode !== null) {
  1550. dom.parentNode.removeChild(dom);
  1551. }
  1552. };
  1553. var unwrap = function (wrapper) {
  1554. var children$1 = children(wrapper);
  1555. if (children$1.length > 0) {
  1556. before$3(wrapper, children$1);
  1557. }
  1558. remove$7(wrapper);
  1559. };
  1560. var inBody = function (element) {
  1561. var dom = isText$8(element) ? element.dom.parentNode : element.dom;
  1562. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1563. return false;
  1564. }
  1565. var doc = dom.ownerDocument;
  1566. return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  1567. return doc.body.contains(dom);
  1568. }, compose1(inBody, getShadowHost));
  1569. };
  1570. var r = function (left, top) {
  1571. var translate = function (x, y) {
  1572. return r(left + x, top + y);
  1573. };
  1574. return {
  1575. left: left,
  1576. top: top,
  1577. translate: translate
  1578. };
  1579. };
  1580. var SugarPosition = r;
  1581. var boxPosition = function (dom) {
  1582. var box = dom.getBoundingClientRect();
  1583. return SugarPosition(box.left, box.top);
  1584. };
  1585. var firstDefinedOrZero = function (a, b) {
  1586. if (a !== undefined) {
  1587. return a;
  1588. } else {
  1589. return b !== undefined ? b : 0;
  1590. }
  1591. };
  1592. var absolute = function (element) {
  1593. var doc = element.dom.ownerDocument;
  1594. var body = doc.body;
  1595. var win = doc.defaultView;
  1596. var html = doc.documentElement;
  1597. if (body === element.dom) {
  1598. return SugarPosition(body.offsetLeft, body.offsetTop);
  1599. }
  1600. var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
  1601. var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
  1602. var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  1603. var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  1604. return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  1605. };
  1606. var viewport = function (element) {
  1607. var dom = element.dom;
  1608. var doc = dom.ownerDocument;
  1609. var body = doc.body;
  1610. if (body === dom) {
  1611. return SugarPosition(body.offsetLeft, body.offsetTop);
  1612. }
  1613. if (!inBody(element)) {
  1614. return SugarPosition(0, 0);
  1615. }
  1616. return boxPosition(dom);
  1617. };
  1618. var get$8 = function (_DOC) {
  1619. var doc = _DOC !== undefined ? _DOC.dom : document;
  1620. var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  1621. var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  1622. return SugarPosition(x, y);
  1623. };
  1624. var to = function (x, y, _DOC) {
  1625. var doc = _DOC !== undefined ? _DOC.dom : document;
  1626. var win = doc.defaultView;
  1627. if (win) {
  1628. win.scrollTo(x, y);
  1629. }
  1630. };
  1631. var intoView = function (element, alignToTop) {
  1632. var isSafari = detect().browser.isSafari();
  1633. if (isSafari && isFunction(element.dom.scrollIntoViewIfNeeded)) {
  1634. element.dom.scrollIntoViewIfNeeded(false);
  1635. } else {
  1636. element.dom.scrollIntoView(alignToTop);
  1637. }
  1638. };
  1639. var get$7 = function (_win) {
  1640. var win = _win === undefined ? window : _win;
  1641. if (detect().browser.isFirefox()) {
  1642. return Optional.none();
  1643. } else {
  1644. return Optional.from(win['visualViewport']);
  1645. }
  1646. };
  1647. var bounds = function (x, y, width, height) {
  1648. return {
  1649. x: x,
  1650. y: y,
  1651. width: width,
  1652. height: height,
  1653. right: x + width,
  1654. bottom: y + height
  1655. };
  1656. };
  1657. var getBounds = function (_win) {
  1658. var win = _win === undefined ? window : _win;
  1659. var doc = win.document;
  1660. var scroll = get$8(SugarElement.fromDom(doc));
  1661. return get$7(win).fold(function () {
  1662. var html = win.document.documentElement;
  1663. var width = html.clientWidth;
  1664. var height = html.clientHeight;
  1665. return bounds(scroll.left, scroll.top, width, height);
  1666. }, function (visualViewport) {
  1667. return bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
  1668. });
  1669. };
  1670. var isNodeType = function (type) {
  1671. return function (node) {
  1672. return !!node && node.nodeType === type;
  1673. };
  1674. };
  1675. var isRestrictedNode = function (node) {
  1676. return !!node && !Object.getPrototypeOf(node);
  1677. };
  1678. var isElement$5 = isNodeType(1);
  1679. var matchNodeNames = function (names) {
  1680. var lowercasedNames = names.map(function (s) {
  1681. return s.toLowerCase();
  1682. });
  1683. return function (node) {
  1684. if (node && node.nodeName) {
  1685. var nodeName = node.nodeName.toLowerCase();
  1686. return contains$3(lowercasedNames, nodeName);
  1687. }
  1688. return false;
  1689. };
  1690. };
  1691. var matchStyleValues = function (name, values) {
  1692. var items = values.toLowerCase().split(' ');
  1693. return function (node) {
  1694. if (isElement$5(node)) {
  1695. for (var i = 0; i < items.length; i++) {
  1696. var computed = node.ownerDocument.defaultView.getComputedStyle(node, null);
  1697. var cssValue = computed ? computed.getPropertyValue(name) : null;
  1698. if (cssValue === items[i]) {
  1699. return true;
  1700. }
  1701. }
  1702. }
  1703. return false;
  1704. };
  1705. };
  1706. var hasAttribute = function (attrName) {
  1707. return function (node) {
  1708. return isElement$5(node) && node.hasAttribute(attrName);
  1709. };
  1710. };
  1711. var hasAttributeValue = function (attrName, attrValue) {
  1712. return function (node) {
  1713. return isElement$5(node) && node.getAttribute(attrName) === attrValue;
  1714. };
  1715. };
  1716. var isBogus$2 = function (node) {
  1717. return isElement$5(node) && node.hasAttribute('data-mce-bogus');
  1718. };
  1719. var isBogusAll$1 = function (node) {
  1720. return isElement$5(node) && node.getAttribute('data-mce-bogus') === 'all';
  1721. };
  1722. var isTable$3 = function (node) {
  1723. return isElement$5(node) && node.tagName === 'TABLE';
  1724. };
  1725. var hasContentEditableState = function (value) {
  1726. return function (node) {
  1727. if (isElement$5(node)) {
  1728. if (node.contentEditable === value) {
  1729. return true;
  1730. }
  1731. if (node.getAttribute('data-mce-contenteditable') === value) {
  1732. return true;
  1733. }
  1734. }
  1735. return false;
  1736. };
  1737. };
  1738. var isTextareaOrInput = matchNodeNames([
  1739. 'textarea',
  1740. 'input'
  1741. ]);
  1742. var isText$7 = isNodeType(3);
  1743. var isComment = isNodeType(8);
  1744. var isDocument$1 = isNodeType(9);
  1745. var isDocumentFragment = isNodeType(11);
  1746. var isBr$5 = matchNodeNames(['br']);
  1747. var isImg = matchNodeNames(['img']);
  1748. var isContentEditableTrue$4 = hasContentEditableState('true');
  1749. var isContentEditableFalse$b = hasContentEditableState('false');
  1750. var isTableCell$5 = matchNodeNames([
  1751. 'td',
  1752. 'th'
  1753. ]);
  1754. var isMedia$2 = matchNodeNames([
  1755. 'video',
  1756. 'audio',
  1757. 'object',
  1758. 'embed'
  1759. ]);
  1760. var is$1 = function (lhs, rhs, comparator) {
  1761. if (comparator === void 0) {
  1762. comparator = tripleEquals;
  1763. }
  1764. return lhs.exists(function (left) {
  1765. return comparator(left, rhs);
  1766. });
  1767. };
  1768. var cat = function (arr) {
  1769. var r = [];
  1770. var push = function (x) {
  1771. r.push(x);
  1772. };
  1773. for (var i = 0; i < arr.length; i++) {
  1774. arr[i].each(push);
  1775. }
  1776. return r;
  1777. };
  1778. var lift2 = function (oa, ob, f) {
  1779. return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  1780. };
  1781. var lift3 = function (oa, ob, oc, f) {
  1782. return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
  1783. };
  1784. var someIf = function (b, a) {
  1785. return b ? Optional.some(a) : Optional.none();
  1786. };
  1787. var isSupported = function (dom) {
  1788. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  1789. };
  1790. var rawSet = function (dom, key, value) {
  1791. if (isString$1(value) || isBoolean(value) || isNumber(value)) {
  1792. dom.setAttribute(key, value + '');
  1793. } else {
  1794. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1795. throw new Error('Attribute value was not simple');
  1796. }
  1797. };
  1798. var set$1 = function (element, key, value) {
  1799. rawSet(element.dom, key, value);
  1800. };
  1801. var setAll$1 = function (element, attrs) {
  1802. var dom = element.dom;
  1803. each$j(attrs, function (v, k) {
  1804. rawSet(dom, k, v);
  1805. });
  1806. };
  1807. var get$6 = function (element, key) {
  1808. var v = element.dom.getAttribute(key);
  1809. return v === null ? undefined : v;
  1810. };
  1811. var getOpt = function (element, key) {
  1812. return Optional.from(get$6(element, key));
  1813. };
  1814. var has$1 = function (element, key) {
  1815. var dom = element.dom;
  1816. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  1817. };
  1818. var remove$6 = function (element, key) {
  1819. element.dom.removeAttribute(key);
  1820. };
  1821. var clone$3 = function (element) {
  1822. return foldl(element.dom.attributes, function (acc, attr) {
  1823. acc[attr.name] = attr.value;
  1824. return acc;
  1825. }, {});
  1826. };
  1827. var internalSet = function (dom, property, value) {
  1828. if (!isString$1(value)) {
  1829. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  1830. throw new Error('CSS value must be a string: ' + value);
  1831. }
  1832. if (isSupported(dom)) {
  1833. dom.style.setProperty(property, value);
  1834. }
  1835. };
  1836. var setAll = function (element, css) {
  1837. var dom = element.dom;
  1838. each$j(css, function (v, k) {
  1839. internalSet(dom, k, v);
  1840. });
  1841. };
  1842. var get$5 = function (element, property) {
  1843. var dom = element.dom;
  1844. var styles = window.getComputedStyle(dom);
  1845. var r = styles.getPropertyValue(property);
  1846. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  1847. };
  1848. var getUnsafeProperty = function (dom, property) {
  1849. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  1850. };
  1851. var getRaw = function (element, property) {
  1852. var dom = element.dom;
  1853. var raw = getUnsafeProperty(dom, property);
  1854. return Optional.from(raw).filter(function (r) {
  1855. return r.length > 0;
  1856. });
  1857. };
  1858. var getAllRaw = function (element) {
  1859. var css = {};
  1860. var dom = element.dom;
  1861. if (isSupported(dom)) {
  1862. for (var i = 0; i < dom.style.length; i++) {
  1863. var ruleName = dom.style.item(i);
  1864. css[ruleName] = dom.style[ruleName];
  1865. }
  1866. }
  1867. return css;
  1868. };
  1869. var reflow = function (e) {
  1870. return e.dom.offsetWidth;
  1871. };
  1872. var browser$3 = detect().browser;
  1873. var firstElement = function (nodes) {
  1874. return find$3(nodes, isElement$6);
  1875. };
  1876. var getTableCaptionDeltaY = function (elm) {
  1877. if (browser$3.isFirefox() && name(elm) === 'table') {
  1878. return firstElement(children(elm)).filter(function (elm) {
  1879. return name(elm) === 'caption';
  1880. }).bind(function (caption) {
  1881. return firstElement(nextSiblings(caption)).map(function (body) {
  1882. var bodyTop = body.dom.offsetTop;
  1883. var captionTop = caption.dom.offsetTop;
  1884. var captionHeight = caption.dom.offsetHeight;
  1885. return bodyTop <= captionTop ? -captionHeight : 0;
  1886. });
  1887. }).getOr(0);
  1888. } else {
  1889. return 0;
  1890. }
  1891. };
  1892. var hasChild = function (elm, child) {
  1893. return elm.children && contains$3(elm.children, child);
  1894. };
  1895. var getPos = function (body, elm, rootElm) {
  1896. var x = 0, y = 0;
  1897. var doc = body.ownerDocument;
  1898. rootElm = rootElm ? rootElm : body;
  1899. if (elm) {
  1900. if (rootElm === body && elm.getBoundingClientRect && get$5(SugarElement.fromDom(body), 'position') === 'static') {
  1901. var pos = elm.getBoundingClientRect();
  1902. x = pos.left + (doc.documentElement.scrollLeft || body.scrollLeft) - doc.documentElement.clientLeft;
  1903. y = pos.top + (doc.documentElement.scrollTop || body.scrollTop) - doc.documentElement.clientTop;
  1904. return {
  1905. x: x,
  1906. y: y
  1907. };
  1908. }
  1909. var offsetParent = elm;
  1910. while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  1911. var castOffsetParent = offsetParent;
  1912. x += castOffsetParent.offsetLeft || 0;
  1913. y += castOffsetParent.offsetTop || 0;
  1914. offsetParent = castOffsetParent.offsetParent;
  1915. }
  1916. offsetParent = elm.parentNode;
  1917. while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  1918. x -= offsetParent.scrollLeft || 0;
  1919. y -= offsetParent.scrollTop || 0;
  1920. offsetParent = offsetParent.parentNode;
  1921. }
  1922. y += getTableCaptionDeltaY(SugarElement.fromDom(elm));
  1923. }
  1924. return {
  1925. x: x,
  1926. y: y
  1927. };
  1928. };
  1929. var exports$1 = {}, module$1 = { exports: exports$1 };
  1930. (function (define, exports, module, require) {
  1931. (function (global, factory) {
  1932. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.EphoxContactWrapper = factory());
  1933. }(this, function () {
  1934. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  1935. var promise = { exports: {} };
  1936. (function (module) {
  1937. (function (root) {
  1938. var setTimeoutFunc = setTimeout;
  1939. function noop() {
  1940. }
  1941. function bind(fn, thisArg) {
  1942. return function () {
  1943. fn.apply(thisArg, arguments);
  1944. };
  1945. }
  1946. function Promise(fn) {
  1947. if (typeof this !== 'object')
  1948. throw new TypeError('Promises must be constructed via new');
  1949. if (typeof fn !== 'function')
  1950. throw new TypeError('not a function');
  1951. this._state = 0;
  1952. this._handled = false;
  1953. this._value = undefined;
  1954. this._deferreds = [];
  1955. doResolve(fn, this);
  1956. }
  1957. function handle(self, deferred) {
  1958. while (self._state === 3) {
  1959. self = self._value;
  1960. }
  1961. if (self._state === 0) {
  1962. self._deferreds.push(deferred);
  1963. return;
  1964. }
  1965. self._handled = true;
  1966. Promise._immediateFn(function () {
  1967. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  1968. if (cb === null) {
  1969. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  1970. return;
  1971. }
  1972. var ret;
  1973. try {
  1974. ret = cb(self._value);
  1975. } catch (e) {
  1976. reject(deferred.promise, e);
  1977. return;
  1978. }
  1979. resolve(deferred.promise, ret);
  1980. });
  1981. }
  1982. function resolve(self, newValue) {
  1983. try {
  1984. if (newValue === self)
  1985. throw new TypeError('A promise cannot be resolved with itself.');
  1986. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  1987. var then = newValue.then;
  1988. if (newValue instanceof Promise) {
  1989. self._state = 3;
  1990. self._value = newValue;
  1991. finale(self);
  1992. return;
  1993. } else if (typeof then === 'function') {
  1994. doResolve(bind(then, newValue), self);
  1995. return;
  1996. }
  1997. }
  1998. self._state = 1;
  1999. self._value = newValue;
  2000. finale(self);
  2001. } catch (e) {
  2002. reject(self, e);
  2003. }
  2004. }
  2005. function reject(self, newValue) {
  2006. self._state = 2;
  2007. self._value = newValue;
  2008. finale(self);
  2009. }
  2010. function finale(self) {
  2011. if (self._state === 2 && self._deferreds.length === 0) {
  2012. Promise._immediateFn(function () {
  2013. if (!self._handled) {
  2014. Promise._unhandledRejectionFn(self._value);
  2015. }
  2016. });
  2017. }
  2018. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  2019. handle(self, self._deferreds[i]);
  2020. }
  2021. self._deferreds = null;
  2022. }
  2023. function Handler(onFulfilled, onRejected, promise) {
  2024. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  2025. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  2026. this.promise = promise;
  2027. }
  2028. function doResolve(fn, self) {
  2029. var done = false;
  2030. try {
  2031. fn(function (value) {
  2032. if (done)
  2033. return;
  2034. done = true;
  2035. resolve(self, value);
  2036. }, function (reason) {
  2037. if (done)
  2038. return;
  2039. done = true;
  2040. reject(self, reason);
  2041. });
  2042. } catch (ex) {
  2043. if (done)
  2044. return;
  2045. done = true;
  2046. reject(self, ex);
  2047. }
  2048. }
  2049. Promise.prototype['catch'] = function (onRejected) {
  2050. return this.then(null, onRejected);
  2051. };
  2052. Promise.prototype.then = function (onFulfilled, onRejected) {
  2053. var prom = new this.constructor(noop);
  2054. handle(this, new Handler(onFulfilled, onRejected, prom));
  2055. return prom;
  2056. };
  2057. Promise.all = function (arr) {
  2058. var args = Array.prototype.slice.call(arr);
  2059. return new Promise(function (resolve, reject) {
  2060. if (args.length === 0)
  2061. return resolve([]);
  2062. var remaining = args.length;
  2063. function res(i, val) {
  2064. try {
  2065. if (val && (typeof val === 'object' || typeof val === 'function')) {
  2066. var then = val.then;
  2067. if (typeof then === 'function') {
  2068. then.call(val, function (val) {
  2069. res(i, val);
  2070. }, reject);
  2071. return;
  2072. }
  2073. }
  2074. args[i] = val;
  2075. if (--remaining === 0) {
  2076. resolve(args);
  2077. }
  2078. } catch (ex) {
  2079. reject(ex);
  2080. }
  2081. }
  2082. for (var i = 0; i < args.length; i++) {
  2083. res(i, args[i]);
  2084. }
  2085. });
  2086. };
  2087. Promise.resolve = function (value) {
  2088. if (value && typeof value === 'object' && value.constructor === Promise) {
  2089. return value;
  2090. }
  2091. return new Promise(function (resolve) {
  2092. resolve(value);
  2093. });
  2094. };
  2095. Promise.reject = function (value) {
  2096. return new Promise(function (resolve, reject) {
  2097. reject(value);
  2098. });
  2099. };
  2100. Promise.race = function (values) {
  2101. return new Promise(function (resolve, reject) {
  2102. for (var i = 0, len = values.length; i < len; i++) {
  2103. values[i].then(resolve, reject);
  2104. }
  2105. });
  2106. };
  2107. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  2108. setImmediate(fn);
  2109. } : function (fn) {
  2110. setTimeoutFunc(fn, 0);
  2111. };
  2112. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  2113. if (typeof console !== 'undefined' && console) {
  2114. console.warn('Possible Unhandled Promise Rejection:', err);
  2115. }
  2116. };
  2117. Promise._setImmediateFn = function _setImmediateFn(fn) {
  2118. Promise._immediateFn = fn;
  2119. };
  2120. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  2121. Promise._unhandledRejectionFn = fn;
  2122. };
  2123. if (module.exports) {
  2124. module.exports = Promise;
  2125. } else if (!root.Promise) {
  2126. root.Promise = Promise;
  2127. }
  2128. }(commonjsGlobal));
  2129. }(promise));
  2130. var promisePolyfill = promise.exports;
  2131. var Global = function () {
  2132. if (typeof window !== 'undefined') {
  2133. return window;
  2134. } else {
  2135. return Function('return this;')();
  2136. }
  2137. }();
  2138. var promisePolyfill_1 = { boltExport: Global.Promise || promisePolyfill };
  2139. return promisePolyfill_1;
  2140. }));
  2141. }(undefined, exports$1, module$1));
  2142. var Promise$1 = module$1.exports.boltExport;
  2143. var nu$1 = function (baseFn) {
  2144. var data = Optional.none();
  2145. var callbacks = [];
  2146. var map = function (f) {
  2147. return nu$1(function (nCallback) {
  2148. get(function (data) {
  2149. nCallback(f(data));
  2150. });
  2151. });
  2152. };
  2153. var get = function (nCallback) {
  2154. if (isReady()) {
  2155. call(nCallback);
  2156. } else {
  2157. callbacks.push(nCallback);
  2158. }
  2159. };
  2160. var set = function (x) {
  2161. if (!isReady()) {
  2162. data = Optional.some(x);
  2163. run(callbacks);
  2164. callbacks = [];
  2165. }
  2166. };
  2167. var isReady = function () {
  2168. return data.isSome();
  2169. };
  2170. var run = function (cbs) {
  2171. each$k(cbs, call);
  2172. };
  2173. var call = function (cb) {
  2174. data.each(function (x) {
  2175. setTimeout(function () {
  2176. cb(x);
  2177. }, 0);
  2178. });
  2179. };
  2180. baseFn(set);
  2181. return {
  2182. get: get,
  2183. map: map,
  2184. isReady: isReady
  2185. };
  2186. };
  2187. var pure$1 = function (a) {
  2188. return nu$1(function (callback) {
  2189. callback(a);
  2190. });
  2191. };
  2192. var LazyValue = {
  2193. nu: nu$1,
  2194. pure: pure$1
  2195. };
  2196. var errorReporter = function (err) {
  2197. setTimeout(function () {
  2198. throw err;
  2199. }, 0);
  2200. };
  2201. var make = function (run) {
  2202. var get = function (callback) {
  2203. run().then(callback, errorReporter);
  2204. };
  2205. var map = function (fab) {
  2206. return make(function () {
  2207. return run().then(fab);
  2208. });
  2209. };
  2210. var bind = function (aFutureB) {
  2211. return make(function () {
  2212. return run().then(function (v) {
  2213. return aFutureB(v).toPromise();
  2214. });
  2215. });
  2216. };
  2217. var anonBind = function (futureB) {
  2218. return make(function () {
  2219. return run().then(function () {
  2220. return futureB.toPromise();
  2221. });
  2222. });
  2223. };
  2224. var toLazy = function () {
  2225. return LazyValue.nu(get);
  2226. };
  2227. var toCached = function () {
  2228. var cache = null;
  2229. return make(function () {
  2230. if (cache === null) {
  2231. cache = run();
  2232. }
  2233. return cache;
  2234. });
  2235. };
  2236. var toPromise = run;
  2237. return {
  2238. map: map,
  2239. bind: bind,
  2240. anonBind: anonBind,
  2241. toLazy: toLazy,
  2242. toCached: toCached,
  2243. toPromise: toPromise,
  2244. get: get
  2245. };
  2246. };
  2247. var nu = function (baseFn) {
  2248. return make(function () {
  2249. return new Promise$1(baseFn);
  2250. });
  2251. };
  2252. var pure = function (a) {
  2253. return make(function () {
  2254. return Promise$1.resolve(a);
  2255. });
  2256. };
  2257. var Future = {
  2258. nu: nu,
  2259. pure: pure
  2260. };
  2261. var par$1 = function (asyncValues, nu) {
  2262. return nu(function (callback) {
  2263. var r = [];
  2264. var count = 0;
  2265. var cb = function (i) {
  2266. return function (value) {
  2267. r[i] = value;
  2268. count++;
  2269. if (count >= asyncValues.length) {
  2270. callback(r);
  2271. }
  2272. };
  2273. };
  2274. if (asyncValues.length === 0) {
  2275. callback([]);
  2276. } else {
  2277. each$k(asyncValues, function (asyncValue, i) {
  2278. asyncValue.get(cb(i));
  2279. });
  2280. }
  2281. });
  2282. };
  2283. var par = function (futures) {
  2284. return par$1(futures, Future.nu);
  2285. };
  2286. var value$1 = function (o) {
  2287. var or = function (_opt) {
  2288. return value$1(o);
  2289. };
  2290. var orThunk = function (_f) {
  2291. return value$1(o);
  2292. };
  2293. var map = function (f) {
  2294. return value$1(f(o));
  2295. };
  2296. var mapError = function (_f) {
  2297. return value$1(o);
  2298. };
  2299. var each = function (f) {
  2300. f(o);
  2301. };
  2302. var bind = function (f) {
  2303. return f(o);
  2304. };
  2305. var fold = function (_, onValue) {
  2306. return onValue(o);
  2307. };
  2308. var exists = function (f) {
  2309. return f(o);
  2310. };
  2311. var forall = function (f) {
  2312. return f(o);
  2313. };
  2314. var toOptional = function () {
  2315. return Optional.some(o);
  2316. };
  2317. return {
  2318. isValue: always,
  2319. isError: never,
  2320. getOr: constant(o),
  2321. getOrThunk: constant(o),
  2322. getOrDie: constant(o),
  2323. or: or,
  2324. orThunk: orThunk,
  2325. fold: fold,
  2326. map: map,
  2327. mapError: mapError,
  2328. each: each,
  2329. bind: bind,
  2330. exists: exists,
  2331. forall: forall,
  2332. toOptional: toOptional
  2333. };
  2334. };
  2335. var error = function (message) {
  2336. var getOrThunk = function (f) {
  2337. return f();
  2338. };
  2339. var getOrDie = function () {
  2340. return die(String(message))();
  2341. };
  2342. var or = identity;
  2343. var orThunk = function (f) {
  2344. return f();
  2345. };
  2346. var map = function (_f) {
  2347. return error(message);
  2348. };
  2349. var mapError = function (f) {
  2350. return error(f(message));
  2351. };
  2352. var bind = function (_f) {
  2353. return error(message);
  2354. };
  2355. var fold = function (onError, _) {
  2356. return onError(message);
  2357. };
  2358. return {
  2359. isValue: never,
  2360. isError: always,
  2361. getOr: identity,
  2362. getOrThunk: getOrThunk,
  2363. getOrDie: getOrDie,
  2364. or: or,
  2365. orThunk: orThunk,
  2366. fold: fold,
  2367. map: map,
  2368. mapError: mapError,
  2369. each: noop,
  2370. bind: bind,
  2371. exists: never,
  2372. forall: always,
  2373. toOptional: Optional.none
  2374. };
  2375. };
  2376. var fromOption = function (opt, err) {
  2377. return opt.fold(function () {
  2378. return error(err);
  2379. }, value$1);
  2380. };
  2381. var Result = {
  2382. value: value$1,
  2383. error: error,
  2384. fromOption: fromOption
  2385. };
  2386. var generate$1 = function (cases) {
  2387. if (!isArray$1(cases)) {
  2388. throw new Error('cases must be an array');
  2389. }
  2390. if (cases.length === 0) {
  2391. throw new Error('there must be at least one case');
  2392. }
  2393. var constructors = [];
  2394. var adt = {};
  2395. each$k(cases, function (acase, count) {
  2396. var keys$1 = keys(acase);
  2397. if (keys$1.length !== 1) {
  2398. throw new Error('one and only one name per case');
  2399. }
  2400. var key = keys$1[0];
  2401. var value = acase[key];
  2402. if (adt[key] !== undefined) {
  2403. throw new Error('duplicate key detected:' + key);
  2404. } else if (key === 'cata') {
  2405. throw new Error('cannot have a case named cata (sorry)');
  2406. } else if (!isArray$1(value)) {
  2407. throw new Error('case arguments must be an array');
  2408. }
  2409. constructors.push(key);
  2410. adt[key] = function () {
  2411. var args = [];
  2412. for (var _i = 0; _i < arguments.length; _i++) {
  2413. args[_i] = arguments[_i];
  2414. }
  2415. var argLength = args.length;
  2416. if (argLength !== value.length) {
  2417. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  2418. }
  2419. var match = function (branches) {
  2420. var branchKeys = keys(branches);
  2421. if (constructors.length !== branchKeys.length) {
  2422. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  2423. }
  2424. var allReqd = forall(constructors, function (reqKey) {
  2425. return contains$3(branchKeys, reqKey);
  2426. });
  2427. if (!allReqd) {
  2428. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  2429. }
  2430. return branches[key].apply(null, args);
  2431. };
  2432. return {
  2433. fold: function () {
  2434. var foldArgs = [];
  2435. for (var _i = 0; _i < arguments.length; _i++) {
  2436. foldArgs[_i] = arguments[_i];
  2437. }
  2438. if (foldArgs.length !== cases.length) {
  2439. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  2440. }
  2441. var target = foldArgs[count];
  2442. return target.apply(null, args);
  2443. },
  2444. match: match,
  2445. log: function (label) {
  2446. console.log(label, {
  2447. constructors: constructors,
  2448. constructor: key,
  2449. params: args
  2450. });
  2451. }
  2452. };
  2453. };
  2454. });
  2455. return adt;
  2456. };
  2457. var Adt = { generate: generate$1 };
  2458. Adt.generate([
  2459. {
  2460. bothErrors: [
  2461. 'error1',
  2462. 'error2'
  2463. ]
  2464. },
  2465. {
  2466. firstError: [
  2467. 'error1',
  2468. 'value2'
  2469. ]
  2470. },
  2471. {
  2472. secondError: [
  2473. 'value1',
  2474. 'error2'
  2475. ]
  2476. },
  2477. {
  2478. bothValues: [
  2479. 'value1',
  2480. 'value2'
  2481. ]
  2482. }
  2483. ]);
  2484. var unite = function (result) {
  2485. return result.fold(identity, identity);
  2486. };
  2487. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  2488. if (is(scope, a)) {
  2489. return Optional.some(scope);
  2490. } else if (isFunction(isRoot) && isRoot(scope)) {
  2491. return Optional.none();
  2492. } else {
  2493. return ancestor(scope, a, isRoot);
  2494. }
  2495. }
  2496. var ancestor$3 = function (scope, predicate, isRoot) {
  2497. var element = scope.dom;
  2498. var stop = isFunction(isRoot) ? isRoot : never;
  2499. while (element.parentNode) {
  2500. element = element.parentNode;
  2501. var el = SugarElement.fromDom(element);
  2502. if (predicate(el)) {
  2503. return Optional.some(el);
  2504. } else if (stop(el)) {
  2505. break;
  2506. }
  2507. }
  2508. return Optional.none();
  2509. };
  2510. var closest$3 = function (scope, predicate, isRoot) {
  2511. var is = function (s, test) {
  2512. return test(s);
  2513. };
  2514. return ClosestOrAncestor(is, ancestor$3, scope, predicate, isRoot);
  2515. };
  2516. var sibling$2 = function (scope, predicate) {
  2517. var element = scope.dom;
  2518. if (!element.parentNode) {
  2519. return Optional.none();
  2520. }
  2521. return child(SugarElement.fromDom(element.parentNode), function (x) {
  2522. return !eq(scope, x) && predicate(x);
  2523. });
  2524. };
  2525. var child = function (scope, predicate) {
  2526. var pred = function (node) {
  2527. return predicate(SugarElement.fromDom(node));
  2528. };
  2529. var result = find$3(scope.dom.childNodes, pred);
  2530. return result.map(SugarElement.fromDom);
  2531. };
  2532. var ancestor$2 = function (scope, selector, isRoot) {
  2533. return ancestor$3(scope, function (e) {
  2534. return is$2(e, selector);
  2535. }, isRoot);
  2536. };
  2537. var descendant = function (scope, selector) {
  2538. return one(selector, scope);
  2539. };
  2540. var closest$2 = function (scope, selector, isRoot) {
  2541. var is = function (element, selector) {
  2542. return is$2(element, selector);
  2543. };
  2544. return ClosestOrAncestor(is, ancestor$2, scope, selector, isRoot);
  2545. };
  2546. var promiseObj = window.Promise ? window.Promise : Promise$1;
  2547. var requestAnimationFramePromise;
  2548. var requestAnimationFrame = function (callback, element) {
  2549. var requestAnimationFrameFunc = window.requestAnimationFrame;
  2550. var vendors = [
  2551. 'ms',
  2552. 'moz',
  2553. 'webkit'
  2554. ];
  2555. var featurefill = function (cb) {
  2556. window.setTimeout(cb, 0);
  2557. };
  2558. for (var i = 0; i < vendors.length && !requestAnimationFrameFunc; i++) {
  2559. requestAnimationFrameFunc = window[vendors[i] + 'RequestAnimationFrame'];
  2560. }
  2561. if (!requestAnimationFrameFunc) {
  2562. requestAnimationFrameFunc = featurefill;
  2563. }
  2564. requestAnimationFrameFunc(callback, element);
  2565. };
  2566. var wrappedSetTimeout = function (callback, time) {
  2567. if (typeof time !== 'number') {
  2568. time = 0;
  2569. }
  2570. return setTimeout(callback, time);
  2571. };
  2572. var wrappedSetInterval = function (callback, time) {
  2573. if (typeof time !== 'number') {
  2574. time = 1;
  2575. }
  2576. return setInterval(callback, time);
  2577. };
  2578. var wrappedClearTimeout = function (id) {
  2579. return clearTimeout(id);
  2580. };
  2581. var wrappedClearInterval = function (id) {
  2582. return clearInterval(id);
  2583. };
  2584. var debounce = function (callback, time) {
  2585. var timer;
  2586. var func = function () {
  2587. var args = [];
  2588. for (var _i = 0; _i < arguments.length; _i++) {
  2589. args[_i] = arguments[_i];
  2590. }
  2591. clearTimeout(timer);
  2592. timer = wrappedSetTimeout(function () {
  2593. callback.apply(this, args);
  2594. }, time);
  2595. };
  2596. func.stop = function () {
  2597. clearTimeout(timer);
  2598. };
  2599. return func;
  2600. };
  2601. var Delay = {
  2602. requestAnimationFrame: function (callback, element) {
  2603. if (requestAnimationFramePromise) {
  2604. requestAnimationFramePromise.then(callback);
  2605. return;
  2606. }
  2607. requestAnimationFramePromise = new promiseObj(function (resolve) {
  2608. if (!element) {
  2609. element = document.body;
  2610. }
  2611. requestAnimationFrame(resolve, element);
  2612. }).then(callback);
  2613. },
  2614. setTimeout: wrappedSetTimeout,
  2615. setInterval: wrappedSetInterval,
  2616. setEditorTimeout: function (editor, callback, time) {
  2617. return wrappedSetTimeout(function () {
  2618. if (!editor.removed) {
  2619. callback();
  2620. }
  2621. }, time);
  2622. },
  2623. setEditorInterval: function (editor, callback, time) {
  2624. var timer = wrappedSetInterval(function () {
  2625. if (!editor.removed) {
  2626. callback();
  2627. } else {
  2628. clearInterval(timer);
  2629. }
  2630. }, time);
  2631. return timer;
  2632. },
  2633. debounce: debounce,
  2634. throttle: debounce,
  2635. clearInterval: wrappedClearInterval,
  2636. clearTimeout: wrappedClearTimeout
  2637. };
  2638. var StyleSheetLoader = function (documentOrShadowRoot, settings) {
  2639. if (settings === void 0) {
  2640. settings = {};
  2641. }
  2642. var idCount = 0;
  2643. var loadedStates = {};
  2644. var edos = SugarElement.fromDom(documentOrShadowRoot);
  2645. var doc = documentOrOwner(edos);
  2646. var maxLoadTime = settings.maxLoadTime || 5000;
  2647. var _setReferrerPolicy = function (referrerPolicy) {
  2648. settings.referrerPolicy = referrerPolicy;
  2649. };
  2650. var addStyle = function (element) {
  2651. append$1(getStyleContainer(edos), element);
  2652. };
  2653. var removeStyle = function (id) {
  2654. var styleContainer = getStyleContainer(edos);
  2655. descendant(styleContainer, '#' + id).each(remove$7);
  2656. };
  2657. var getOrCreateState = function (url) {
  2658. return get$9(loadedStates, url).getOrThunk(function () {
  2659. return {
  2660. id: 'mce-u' + idCount++,
  2661. passed: [],
  2662. failed: [],
  2663. count: 0
  2664. };
  2665. });
  2666. };
  2667. var load = function (url, success, failure) {
  2668. var link;
  2669. var urlWithSuffix = Tools._addCacheSuffix(url);
  2670. var state = getOrCreateState(urlWithSuffix);
  2671. loadedStates[urlWithSuffix] = state;
  2672. state.count++;
  2673. var resolve = function (callbacks, status) {
  2674. var i = callbacks.length;
  2675. while (i--) {
  2676. callbacks[i]();
  2677. }
  2678. state.status = status;
  2679. state.passed = [];
  2680. state.failed = [];
  2681. if (link) {
  2682. link.onload = null;
  2683. link.onerror = null;
  2684. link = null;
  2685. }
  2686. };
  2687. var passed = function () {
  2688. return resolve(state.passed, 2);
  2689. };
  2690. var failed = function () {
  2691. return resolve(state.failed, 3);
  2692. };
  2693. var wait = function (testCallback, waitCallback) {
  2694. if (!testCallback()) {
  2695. if (Date.now() - startTime < maxLoadTime) {
  2696. Delay.setTimeout(waitCallback);
  2697. } else {
  2698. failed();
  2699. }
  2700. }
  2701. };
  2702. var waitForWebKitLinkLoaded = function () {
  2703. wait(function () {
  2704. var styleSheets = documentOrShadowRoot.styleSheets;
  2705. var i = styleSheets.length;
  2706. while (i--) {
  2707. var styleSheet = styleSheets[i];
  2708. var owner = styleSheet.ownerNode;
  2709. if (owner && owner.id === link.id) {
  2710. passed();
  2711. return true;
  2712. }
  2713. }
  2714. return false;
  2715. }, waitForWebKitLinkLoaded);
  2716. };
  2717. if (success) {
  2718. state.passed.push(success);
  2719. }
  2720. if (failure) {
  2721. state.failed.push(failure);
  2722. }
  2723. if (state.status === 1) {
  2724. return;
  2725. }
  2726. if (state.status === 2) {
  2727. passed();
  2728. return;
  2729. }
  2730. if (state.status === 3) {
  2731. failed();
  2732. return;
  2733. }
  2734. state.status = 1;
  2735. var linkElem = SugarElement.fromTag('link', doc.dom);
  2736. setAll$1(linkElem, {
  2737. rel: 'stylesheet',
  2738. type: 'text/css',
  2739. id: state.id
  2740. });
  2741. var startTime = Date.now();
  2742. if (settings.contentCssCors) {
  2743. set$1(linkElem, 'crossOrigin', 'anonymous');
  2744. }
  2745. if (settings.referrerPolicy) {
  2746. set$1(linkElem, 'referrerpolicy', settings.referrerPolicy);
  2747. }
  2748. link = linkElem.dom;
  2749. link.onload = waitForWebKitLinkLoaded;
  2750. link.onerror = failed;
  2751. addStyle(linkElem);
  2752. set$1(linkElem, 'href', urlWithSuffix);
  2753. };
  2754. var loadF = function (url) {
  2755. return Future.nu(function (resolve) {
  2756. load(url, compose(resolve, constant(Result.value(url))), compose(resolve, constant(Result.error(url))));
  2757. });
  2758. };
  2759. var loadAll = function (urls, success, failure) {
  2760. par(map$3(urls, loadF)).get(function (result) {
  2761. var parts = partition(result, function (r) {
  2762. return r.isValue();
  2763. });
  2764. if (parts.fail.length > 0) {
  2765. failure(parts.fail.map(unite));
  2766. } else {
  2767. success(parts.pass.map(unite));
  2768. }
  2769. });
  2770. };
  2771. var unload = function (url) {
  2772. var urlWithSuffix = Tools._addCacheSuffix(url);
  2773. get$9(loadedStates, urlWithSuffix).each(function (state) {
  2774. var count = --state.count;
  2775. if (count === 0) {
  2776. delete loadedStates[urlWithSuffix];
  2777. removeStyle(state.id);
  2778. }
  2779. });
  2780. };
  2781. var unloadAll = function (urls) {
  2782. each$k(urls, function (url) {
  2783. unload(url);
  2784. });
  2785. };
  2786. return {
  2787. load: load,
  2788. loadAll: loadAll,
  2789. unload: unload,
  2790. unloadAll: unloadAll,
  2791. _setReferrerPolicy: _setReferrerPolicy
  2792. };
  2793. };
  2794. var create$8 = function () {
  2795. var map = new WeakMap();
  2796. var forElement = function (referenceElement, settings) {
  2797. var root = getRootNode(referenceElement);
  2798. var rootDom = root.dom;
  2799. return Optional.from(map.get(rootDom)).getOrThunk(function () {
  2800. var sl = StyleSheetLoader(rootDom, settings);
  2801. map.set(rootDom, sl);
  2802. return sl;
  2803. });
  2804. };
  2805. return { forElement: forElement };
  2806. };
  2807. var instance = create$8();
  2808. var DomTreeWalker = function () {
  2809. function DomTreeWalker(startNode, rootNode) {
  2810. this.node = startNode;
  2811. this.rootNode = rootNode;
  2812. this.current = this.current.bind(this);
  2813. this.next = this.next.bind(this);
  2814. this.prev = this.prev.bind(this);
  2815. this.prev2 = this.prev2.bind(this);
  2816. }
  2817. DomTreeWalker.prototype.current = function () {
  2818. return this.node;
  2819. };
  2820. DomTreeWalker.prototype.next = function (shallow) {
  2821. this.node = this.findSibling(this.node, 'firstChild', 'nextSibling', shallow);
  2822. return this.node;
  2823. };
  2824. DomTreeWalker.prototype.prev = function (shallow) {
  2825. this.node = this.findSibling(this.node, 'lastChild', 'previousSibling', shallow);
  2826. return this.node;
  2827. };
  2828. DomTreeWalker.prototype.prev2 = function (shallow) {
  2829. this.node = this.findPreviousNode(this.node, 'lastChild', 'previousSibling', shallow);
  2830. return this.node;
  2831. };
  2832. DomTreeWalker.prototype.findSibling = function (node, startName, siblingName, shallow) {
  2833. var sibling, parent;
  2834. if (node) {
  2835. if (!shallow && node[startName]) {
  2836. return node[startName];
  2837. }
  2838. if (node !== this.rootNode) {
  2839. sibling = node[siblingName];
  2840. if (sibling) {
  2841. return sibling;
  2842. }
  2843. for (parent = node.parentNode; parent && parent !== this.rootNode; parent = parent.parentNode) {
  2844. sibling = parent[siblingName];
  2845. if (sibling) {
  2846. return sibling;
  2847. }
  2848. }
  2849. }
  2850. }
  2851. };
  2852. DomTreeWalker.prototype.findPreviousNode = function (node, startName, siblingName, shallow) {
  2853. var sibling, parent, child;
  2854. if (node) {
  2855. sibling = node[siblingName];
  2856. if (this.rootNode && sibling === this.rootNode) {
  2857. return;
  2858. }
  2859. if (sibling) {
  2860. if (!shallow) {
  2861. for (child = sibling[startName]; child; child = child[startName]) {
  2862. if (!child[startName]) {
  2863. return child;
  2864. }
  2865. }
  2866. }
  2867. return sibling;
  2868. }
  2869. parent = node.parentNode;
  2870. if (parent && parent !== this.rootNode) {
  2871. return parent;
  2872. }
  2873. }
  2874. };
  2875. return DomTreeWalker;
  2876. }();
  2877. var blocks = [
  2878. 'article',
  2879. 'aside',
  2880. 'details',
  2881. 'div',
  2882. 'dt',
  2883. 'figcaption',
  2884. 'footer',
  2885. 'form',
  2886. 'fieldset',
  2887. 'header',
  2888. 'hgroup',
  2889. 'html',
  2890. 'main',
  2891. 'nav',
  2892. 'section',
  2893. 'summary',
  2894. 'body',
  2895. 'p',
  2896. 'dl',
  2897. 'multicol',
  2898. 'dd',
  2899. 'figure',
  2900. 'address',
  2901. 'center',
  2902. 'blockquote',
  2903. 'h1',
  2904. 'h2',
  2905. 'h3',
  2906. 'h4',
  2907. 'h5',
  2908. 'h6',
  2909. 'listing',
  2910. 'xmp',
  2911. 'pre',
  2912. 'plaintext',
  2913. 'menu',
  2914. 'dir',
  2915. 'ul',
  2916. 'ol',
  2917. 'li',
  2918. 'hr',
  2919. 'table',
  2920. 'tbody',
  2921. 'thead',
  2922. 'tfoot',
  2923. 'th',
  2924. 'tr',
  2925. 'td',
  2926. 'caption'
  2927. ];
  2928. var tableCells = [
  2929. 'td',
  2930. 'th'
  2931. ];
  2932. var tableSections = [
  2933. 'thead',
  2934. 'tbody',
  2935. 'tfoot'
  2936. ];
  2937. var textBlocks = [
  2938. 'h1',
  2939. 'h2',
  2940. 'h3',
  2941. 'h4',
  2942. 'h5',
  2943. 'h6',
  2944. 'p',
  2945. 'div',
  2946. 'address',
  2947. 'pre',
  2948. 'form',
  2949. 'blockquote',
  2950. 'center',
  2951. 'dir',
  2952. 'fieldset',
  2953. 'header',
  2954. 'footer',
  2955. 'article',
  2956. 'section',
  2957. 'hgroup',
  2958. 'aside',
  2959. 'nav',
  2960. 'figure'
  2961. ];
  2962. var headings = [
  2963. 'h1',
  2964. 'h2',
  2965. 'h3',
  2966. 'h4',
  2967. 'h5',
  2968. 'h6'
  2969. ];
  2970. var listItems$1 = [
  2971. 'li',
  2972. 'dd',
  2973. 'dt'
  2974. ];
  2975. var lists = [
  2976. 'ul',
  2977. 'ol',
  2978. 'dl'
  2979. ];
  2980. var wsElements = [
  2981. 'pre',
  2982. 'script',
  2983. 'textarea',
  2984. 'style'
  2985. ];
  2986. var lazyLookup = function (items) {
  2987. var lookup;
  2988. return function (node) {
  2989. lookup = lookup ? lookup : mapToObject(items, always);
  2990. return has$2(lookup, name(node));
  2991. };
  2992. };
  2993. var isHeading = lazyLookup(headings);
  2994. var isBlock$2 = lazyLookup(blocks);
  2995. var isTable$2 = function (node) {
  2996. return name(node) === 'table';
  2997. };
  2998. var isInline$1 = function (node) {
  2999. return isElement$6(node) && !isBlock$2(node);
  3000. };
  3001. var isBr$4 = function (node) {
  3002. return isElement$6(node) && name(node) === 'br';
  3003. };
  3004. var isTextBlock$2 = lazyLookup(textBlocks);
  3005. var isList = lazyLookup(lists);
  3006. var isListItem = lazyLookup(listItems$1);
  3007. var isTableSection = lazyLookup(tableSections);
  3008. var isTableCell$4 = lazyLookup(tableCells);
  3009. var isWsPreserveElement = lazyLookup(wsElements);
  3010. var ancestor$1 = function (scope, selector, isRoot) {
  3011. return ancestor$2(scope, selector, isRoot).isSome();
  3012. };
  3013. var zeroWidth = '\uFEFF';
  3014. var nbsp = '\xA0';
  3015. var isZwsp$1 = function (char) {
  3016. return char === zeroWidth;
  3017. };
  3018. var removeZwsp = function (s) {
  3019. return s.replace(/\uFEFF/g, '');
  3020. };
  3021. var ZWSP$1 = zeroWidth;
  3022. var isZwsp = isZwsp$1;
  3023. var trim$2 = removeZwsp;
  3024. var isElement$4 = isElement$5;
  3025. var isText$6 = isText$7;
  3026. var isCaretContainerBlock$1 = function (node) {
  3027. if (isText$6(node)) {
  3028. node = node.parentNode;
  3029. }
  3030. return isElement$4(node) && node.hasAttribute('data-mce-caret');
  3031. };
  3032. var isCaretContainerInline = function (node) {
  3033. return isText$6(node) && isZwsp(node.data);
  3034. };
  3035. var isCaretContainer$2 = function (node) {
  3036. return isCaretContainerBlock$1(node) || isCaretContainerInline(node);
  3037. };
  3038. var hasContent = function (node) {
  3039. return node.firstChild !== node.lastChild || !isBr$5(node.firstChild);
  3040. };
  3041. var insertInline$1 = function (node, before) {
  3042. var doc = node.ownerDocument;
  3043. var textNode = doc.createTextNode(ZWSP$1);
  3044. var parentNode = node.parentNode;
  3045. if (!before) {
  3046. var sibling = node.nextSibling;
  3047. if (isText$6(sibling)) {
  3048. if (isCaretContainer$2(sibling)) {
  3049. return sibling;
  3050. }
  3051. if (startsWithCaretContainer$1(sibling)) {
  3052. sibling.splitText(1);
  3053. return sibling;
  3054. }
  3055. }
  3056. if (node.nextSibling) {
  3057. parentNode.insertBefore(textNode, node.nextSibling);
  3058. } else {
  3059. parentNode.appendChild(textNode);
  3060. }
  3061. } else {
  3062. var sibling = node.previousSibling;
  3063. if (isText$6(sibling)) {
  3064. if (isCaretContainer$2(sibling)) {
  3065. return sibling;
  3066. }
  3067. if (endsWithCaretContainer$1(sibling)) {
  3068. return sibling.splitText(sibling.data.length - 1);
  3069. }
  3070. }
  3071. parentNode.insertBefore(textNode, node);
  3072. }
  3073. return textNode;
  3074. };
  3075. var isBeforeInline = function (pos) {
  3076. var container = pos.container();
  3077. if (!isText$7(container)) {
  3078. return false;
  3079. }
  3080. return container.data.charAt(pos.offset()) === ZWSP$1 || pos.isAtStart() && isCaretContainerInline(container.previousSibling);
  3081. };
  3082. var isAfterInline = function (pos) {
  3083. var container = pos.container();
  3084. if (!isText$7(container)) {
  3085. return false;
  3086. }
  3087. return container.data.charAt(pos.offset() - 1) === ZWSP$1 || pos.isAtEnd() && isCaretContainerInline(container.nextSibling);
  3088. };
  3089. var createBogusBr = function () {
  3090. var br = document.createElement('br');
  3091. br.setAttribute('data-mce-bogus', '1');
  3092. return br;
  3093. };
  3094. var insertBlock$1 = function (blockName, node, before) {
  3095. var doc = node.ownerDocument;
  3096. var blockNode = doc.createElement(blockName);
  3097. blockNode.setAttribute('data-mce-caret', before ? 'before' : 'after');
  3098. blockNode.setAttribute('data-mce-bogus', 'all');
  3099. blockNode.appendChild(createBogusBr());
  3100. var parentNode = node.parentNode;
  3101. if (!before) {
  3102. if (node.nextSibling) {
  3103. parentNode.insertBefore(blockNode, node.nextSibling);
  3104. } else {
  3105. parentNode.appendChild(blockNode);
  3106. }
  3107. } else {
  3108. parentNode.insertBefore(blockNode, node);
  3109. }
  3110. return blockNode;
  3111. };
  3112. var startsWithCaretContainer$1 = function (node) {
  3113. return isText$6(node) && node.data[0] === ZWSP$1;
  3114. };
  3115. var endsWithCaretContainer$1 = function (node) {
  3116. return isText$6(node) && node.data[node.data.length - 1] === ZWSP$1;
  3117. };
  3118. var trimBogusBr = function (elm) {
  3119. var brs = elm.getElementsByTagName('br');
  3120. var lastBr = brs[brs.length - 1];
  3121. if (isBogus$2(lastBr)) {
  3122. lastBr.parentNode.removeChild(lastBr);
  3123. }
  3124. };
  3125. var showCaretContainerBlock = function (caretContainer) {
  3126. if (caretContainer && caretContainer.hasAttribute('data-mce-caret')) {
  3127. trimBogusBr(caretContainer);
  3128. caretContainer.removeAttribute('data-mce-caret');
  3129. caretContainer.removeAttribute('data-mce-bogus');
  3130. caretContainer.removeAttribute('style');
  3131. caretContainer.removeAttribute('_moz_abspos');
  3132. return caretContainer;
  3133. }
  3134. return null;
  3135. };
  3136. var isRangeInCaretContainerBlock = function (range) {
  3137. return isCaretContainerBlock$1(range.startContainer);
  3138. };
  3139. var isContentEditableTrue$3 = isContentEditableTrue$4;
  3140. var isContentEditableFalse$a = isContentEditableFalse$b;
  3141. var isBr$3 = isBr$5;
  3142. var isText$5 = isText$7;
  3143. var isInvalidTextElement = matchNodeNames([
  3144. 'script',
  3145. 'style',
  3146. 'textarea'
  3147. ]);
  3148. var isAtomicInline = matchNodeNames([
  3149. 'img',
  3150. 'input',
  3151. 'textarea',
  3152. 'hr',
  3153. 'iframe',
  3154. 'video',
  3155. 'audio',
  3156. 'object',
  3157. 'embed'
  3158. ]);
  3159. var isTable$1 = matchNodeNames(['table']);
  3160. var isCaretContainer$1 = isCaretContainer$2;
  3161. var isCaretCandidate$3 = function (node) {
  3162. if (isCaretContainer$1(node)) {
  3163. return false;
  3164. }
  3165. if (isText$5(node)) {
  3166. return !isInvalidTextElement(node.parentNode);
  3167. }
  3168. return isAtomicInline(node) || isBr$3(node) || isTable$1(node) || isNonUiContentEditableFalse(node);
  3169. };
  3170. var isUnselectable = function (node) {
  3171. return isElement$5(node) && node.getAttribute('unselectable') === 'true';
  3172. };
  3173. var isNonUiContentEditableFalse = function (node) {
  3174. return isUnselectable(node) === false && isContentEditableFalse$a(node);
  3175. };
  3176. var isInEditable = function (node, root) {
  3177. for (node = node.parentNode; node && node !== root; node = node.parentNode) {
  3178. if (isNonUiContentEditableFalse(node)) {
  3179. return false;
  3180. }
  3181. if (isContentEditableTrue$3(node)) {
  3182. return true;
  3183. }
  3184. }
  3185. return true;
  3186. };
  3187. var isAtomicContentEditableFalse = function (node) {
  3188. if (!isNonUiContentEditableFalse(node)) {
  3189. return false;
  3190. }
  3191. return foldl(from(node.getElementsByTagName('*')), function (result, elm) {
  3192. return result || isContentEditableTrue$3(elm);
  3193. }, false) !== true;
  3194. };
  3195. var isAtomic$1 = function (node) {
  3196. return isAtomicInline(node) || isAtomicContentEditableFalse(node);
  3197. };
  3198. var isEditableCaretCandidate$1 = function (node, root) {
  3199. return isCaretCandidate$3(node) && isInEditable(node, root);
  3200. };
  3201. var whiteSpaceRegExp$1 = /^[ \t\r\n]*$/;
  3202. var isWhitespaceText = function (text) {
  3203. return whiteSpaceRegExp$1.test(text);
  3204. };
  3205. var hasWhitespacePreserveParent = function (node, rootNode) {
  3206. var rootElement = SugarElement.fromDom(rootNode);
  3207. var startNode = SugarElement.fromDom(node);
  3208. return ancestor$1(startNode, 'pre,code', curry(eq, rootElement));
  3209. };
  3210. var isWhitespace = function (node, rootNode) {
  3211. return isText$7(node) && isWhitespaceText(node.data) && hasWhitespacePreserveParent(node, rootNode) === false;
  3212. };
  3213. var isNamedAnchor = function (node) {
  3214. return isElement$5(node) && node.nodeName === 'A' && !node.hasAttribute('href') && (node.hasAttribute('name') || node.hasAttribute('id'));
  3215. };
  3216. var isContent$1 = function (node, rootNode) {
  3217. return isCaretCandidate$3(node) && isWhitespace(node, rootNode) === false || isNamedAnchor(node) || isBookmark(node);
  3218. };
  3219. var isBookmark = hasAttribute('data-mce-bookmark');
  3220. var isBogus$1 = hasAttribute('data-mce-bogus');
  3221. var isBogusAll = hasAttributeValue('data-mce-bogus', 'all');
  3222. var isEmptyNode = function (targetNode, skipBogus) {
  3223. var brCount = 0;
  3224. if (isContent$1(targetNode, targetNode)) {
  3225. return false;
  3226. } else {
  3227. var node = targetNode.firstChild;
  3228. if (!node) {
  3229. return true;
  3230. }
  3231. var walker = new DomTreeWalker(node, targetNode);
  3232. do {
  3233. if (skipBogus) {
  3234. if (isBogusAll(node)) {
  3235. node = walker.next(true);
  3236. continue;
  3237. }
  3238. if (isBogus$1(node)) {
  3239. node = walker.next();
  3240. continue;
  3241. }
  3242. }
  3243. if (isBr$5(node)) {
  3244. brCount++;
  3245. node = walker.next();
  3246. continue;
  3247. }
  3248. if (isContent$1(node, targetNode)) {
  3249. return false;
  3250. }
  3251. node = walker.next();
  3252. } while (node);
  3253. return brCount <= 1;
  3254. }
  3255. };
  3256. var isEmpty$2 = function (elm, skipBogus) {
  3257. if (skipBogus === void 0) {
  3258. skipBogus = true;
  3259. }
  3260. return isEmptyNode(elm.dom, skipBogus);
  3261. };
  3262. var isSpan = function (node) {
  3263. return node.nodeName.toLowerCase() === 'span';
  3264. };
  3265. var isInlineContent = function (node, root) {
  3266. return isNonNullable(node) && (isContent$1(node, root) || isInline$1(SugarElement.fromDom(node)));
  3267. };
  3268. var surroundedByInlineContent = function (node, root) {
  3269. var prev = new DomTreeWalker(node, root).prev(false);
  3270. var next = new DomTreeWalker(node, root).next(false);
  3271. var prevIsInline = isUndefined(prev) || isInlineContent(prev, root);
  3272. var nextIsInline = isUndefined(next) || isInlineContent(next, root);
  3273. return prevIsInline && nextIsInline;
  3274. };
  3275. var isBookmarkNode$2 = function (node) {
  3276. return isSpan(node) && node.getAttribute('data-mce-type') === 'bookmark';
  3277. };
  3278. var isKeepTextNode = function (node, root) {
  3279. return isText$7(node) && node.data.length > 0 && surroundedByInlineContent(node, root);
  3280. };
  3281. var isKeepElement = function (node) {
  3282. return isElement$5(node) ? node.childNodes.length > 0 : false;
  3283. };
  3284. var isDocument = function (node) {
  3285. return isDocumentFragment(node) || isDocument$1(node);
  3286. };
  3287. var trimNode = function (dom, node, root) {
  3288. var rootNode = root || node;
  3289. if (isElement$5(node) && isBookmarkNode$2(node)) {
  3290. return node;
  3291. }
  3292. var children = node.childNodes;
  3293. for (var i = children.length - 1; i >= 0; i--) {
  3294. trimNode(dom, children[i], rootNode);
  3295. }
  3296. if (isElement$5(node)) {
  3297. var currentChildren = node.childNodes;
  3298. if (currentChildren.length === 1 && isBookmarkNode$2(currentChildren[0])) {
  3299. node.parentNode.insertBefore(currentChildren[0], node);
  3300. }
  3301. }
  3302. if (!isDocument(node) && !isContent$1(node, rootNode) && !isKeepElement(node) && !isKeepTextNode(node, rootNode)) {
  3303. dom.remove(node);
  3304. }
  3305. return node;
  3306. };
  3307. var makeMap$3 = Tools.makeMap;
  3308. var attrsCharsRegExp = /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  3309. var textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  3310. var rawCharsRegExp = /[<>&\"\']/g;
  3311. var entityRegExp = /&#([a-z0-9]+);?|&([a-z0-9]+);/gi;
  3312. var asciiMap = {
  3313. 128: '\u20AC',
  3314. 130: '\u201A',
  3315. 131: '\u0192',
  3316. 132: '\u201E',
  3317. 133: '\u2026',
  3318. 134: '\u2020',
  3319. 135: '\u2021',
  3320. 136: '\u02c6',
  3321. 137: '\u2030',
  3322. 138: '\u0160',
  3323. 139: '\u2039',
  3324. 140: '\u0152',
  3325. 142: '\u017d',
  3326. 145: '\u2018',
  3327. 146: '\u2019',
  3328. 147: '\u201C',
  3329. 148: '\u201D',
  3330. 149: '\u2022',
  3331. 150: '\u2013',
  3332. 151: '\u2014',
  3333. 152: '\u02DC',
  3334. 153: '\u2122',
  3335. 154: '\u0161',
  3336. 155: '\u203A',
  3337. 156: '\u0153',
  3338. 158: '\u017e',
  3339. 159: '\u0178'
  3340. };
  3341. var baseEntities = {
  3342. '"': '&quot;',
  3343. '\'': '&#39;',
  3344. '<': '&lt;',
  3345. '>': '&gt;',
  3346. '&': '&amp;',
  3347. '`': '&#96;'
  3348. };
  3349. var reverseEntities = {
  3350. '&lt;': '<',
  3351. '&gt;': '>',
  3352. '&amp;': '&',
  3353. '&quot;': '"',
  3354. '&apos;': '\''
  3355. };
  3356. var nativeDecode = function (text) {
  3357. var elm = SugarElement.fromTag('div').dom;
  3358. elm.innerHTML = text;
  3359. return elm.textContent || elm.innerText || text;
  3360. };
  3361. var buildEntitiesLookup = function (items, radix) {
  3362. var i, chr, entity;
  3363. var lookup = {};
  3364. if (items) {
  3365. items = items.split(',');
  3366. radix = radix || 10;
  3367. for (i = 0; i < items.length; i += 2) {
  3368. chr = String.fromCharCode(parseInt(items[i], radix));
  3369. if (!baseEntities[chr]) {
  3370. entity = '&' + items[i + 1] + ';';
  3371. lookup[chr] = entity;
  3372. lookup[entity] = chr;
  3373. }
  3374. }
  3375. return lookup;
  3376. }
  3377. };
  3378. var namedEntities = buildEntitiesLookup('50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' + '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' + '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' + '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' + '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' + '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' + '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' + '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' + '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' + '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' + 'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' + 'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' + 't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' + 'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' + 'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' + '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' + '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' + '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' + '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' + '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' + 'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' + 'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' + 'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' + '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' + '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro', 32);
  3379. var encodeRaw = function (text, attr) {
  3380. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3381. return baseEntities[chr] || chr;
  3382. });
  3383. };
  3384. var encodeAllRaw = function (text) {
  3385. return ('' + text).replace(rawCharsRegExp, function (chr) {
  3386. return baseEntities[chr] || chr;
  3387. });
  3388. };
  3389. var encodeNumeric = function (text, attr) {
  3390. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3391. if (chr.length > 1) {
  3392. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  3393. }
  3394. return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
  3395. });
  3396. };
  3397. var encodeNamed = function (text, attr, entities) {
  3398. entities = entities || namedEntities;
  3399. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3400. return baseEntities[chr] || entities[chr] || chr;
  3401. });
  3402. };
  3403. var getEncodeFunc = function (name, entities) {
  3404. var entitiesMap = buildEntitiesLookup(entities) || namedEntities;
  3405. var encodeNamedAndNumeric = function (text, attr) {
  3406. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3407. if (baseEntities[chr] !== undefined) {
  3408. return baseEntities[chr];
  3409. }
  3410. if (entitiesMap[chr] !== undefined) {
  3411. return entitiesMap[chr];
  3412. }
  3413. if (chr.length > 1) {
  3414. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  3415. }
  3416. return '&#' + chr.charCodeAt(0) + ';';
  3417. });
  3418. };
  3419. var encodeCustomNamed = function (text, attr) {
  3420. return encodeNamed(text, attr, entitiesMap);
  3421. };
  3422. var nameMap = makeMap$3(name.replace(/\+/g, ','));
  3423. if (nameMap.named && nameMap.numeric) {
  3424. return encodeNamedAndNumeric;
  3425. }
  3426. if (nameMap.named) {
  3427. if (entities) {
  3428. return encodeCustomNamed;
  3429. }
  3430. return encodeNamed;
  3431. }
  3432. if (nameMap.numeric) {
  3433. return encodeNumeric;
  3434. }
  3435. return encodeRaw;
  3436. };
  3437. var decode = function (text) {
  3438. return text.replace(entityRegExp, function (all, numeric) {
  3439. if (numeric) {
  3440. if (numeric.charAt(0).toLowerCase() === 'x') {
  3441. numeric = parseInt(numeric.substr(1), 16);
  3442. } else {
  3443. numeric = parseInt(numeric, 10);
  3444. }
  3445. if (numeric > 65535) {
  3446. numeric -= 65536;
  3447. return String.fromCharCode(55296 + (numeric >> 10), 56320 + (numeric & 1023));
  3448. }
  3449. return asciiMap[numeric] || String.fromCharCode(numeric);
  3450. }
  3451. return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
  3452. });
  3453. };
  3454. var Entities = {
  3455. encodeRaw: encodeRaw,
  3456. encodeAllRaw: encodeAllRaw,
  3457. encodeNumeric: encodeNumeric,
  3458. encodeNamed: encodeNamed,
  3459. getEncodeFunc: getEncodeFunc,
  3460. decode: decode
  3461. };
  3462. var mapCache = {}, dummyObj = {};
  3463. var makeMap$2 = Tools.makeMap, each$h = Tools.each, extend$5 = Tools.extend, explode$3 = Tools.explode, inArray$2 = Tools.inArray;
  3464. var split$1 = function (items, delim) {
  3465. items = Tools.trim(items);
  3466. return items ? items.split(delim || ' ') : [];
  3467. };
  3468. var compileSchema = function (type) {
  3469. var schema = {};
  3470. var globalAttributes, blockContent;
  3471. var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
  3472. var add = function (name, attributes, children) {
  3473. var ni, attributesOrder, element;
  3474. var arrayToMap = function (array, obj) {
  3475. var map = {};
  3476. var i, l;
  3477. for (i = 0, l = array.length; i < l; i++) {
  3478. map[array[i]] = obj || {};
  3479. }
  3480. return map;
  3481. };
  3482. children = children || [];
  3483. attributes = attributes || '';
  3484. if (typeof children === 'string') {
  3485. children = split$1(children);
  3486. }
  3487. var names = split$1(name);
  3488. ni = names.length;
  3489. while (ni--) {
  3490. attributesOrder = split$1([
  3491. globalAttributes,
  3492. attributes
  3493. ].join(' '));
  3494. element = {
  3495. attributes: arrayToMap(attributesOrder),
  3496. attributesOrder: attributesOrder,
  3497. children: arrayToMap(children, dummyObj)
  3498. };
  3499. schema[names[ni]] = element;
  3500. }
  3501. };
  3502. var addAttrs = function (name, attributes) {
  3503. var ni, schemaItem, i, l;
  3504. var names = split$1(name);
  3505. ni = names.length;
  3506. var attrs = split$1(attributes);
  3507. while (ni--) {
  3508. schemaItem = schema[names[ni]];
  3509. for (i = 0, l = attrs.length; i < l; i++) {
  3510. schemaItem.attributes[attrs[i]] = {};
  3511. schemaItem.attributesOrder.push(attrs[i]);
  3512. }
  3513. }
  3514. };
  3515. if (mapCache[type]) {
  3516. return mapCache[type];
  3517. }
  3518. globalAttributes = 'id accesskey class dir lang style tabindex title role';
  3519. blockContent = 'address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul';
  3520. phrasingContent = 'a abbr b bdo br button cite code del dfn em embed i iframe img input ins kbd ' + 'label map noscript object q s samp script select small span strong sub sup ' + 'textarea u var #text #comment';
  3521. if (type !== 'html4') {
  3522. globalAttributes += ' contenteditable contextmenu draggable dropzone ' + 'hidden spellcheck translate';
  3523. blockContent += ' article aside details dialog figure main header footer hgroup section nav';
  3524. phrasingContent += ' audio canvas command datalist mark meter output picture ' + 'progress time wbr video ruby bdi keygen';
  3525. }
  3526. if (type !== 'html5-strict') {
  3527. globalAttributes += ' xml:lang';
  3528. html4PhrasingContent = 'acronym applet basefont big font strike tt';
  3529. phrasingContent = [
  3530. phrasingContent,
  3531. html4PhrasingContent
  3532. ].join(' ');
  3533. each$h(split$1(html4PhrasingContent), function (name) {
  3534. add(name, '', phrasingContent);
  3535. });
  3536. html4BlockContent = 'center dir isindex noframes';
  3537. blockContent = [
  3538. blockContent,
  3539. html4BlockContent
  3540. ].join(' ');
  3541. flowContent = [
  3542. blockContent,
  3543. phrasingContent
  3544. ].join(' ');
  3545. each$h(split$1(html4BlockContent), function (name) {
  3546. add(name, '', flowContent);
  3547. });
  3548. }
  3549. flowContent = flowContent || [
  3550. blockContent,
  3551. phrasingContent
  3552. ].join(' ');
  3553. add('html', 'manifest', 'head body');
  3554. add('head', '', 'base command link meta noscript script style title');
  3555. add('title hr noscript br');
  3556. add('base', 'href target');
  3557. add('link', 'href rel media hreflang type sizes hreflang');
  3558. add('meta', 'name http-equiv content charset');
  3559. add('style', 'media type scoped');
  3560. add('script', 'src async defer type charset');
  3561. add('body', 'onafterprint onbeforeprint onbeforeunload onblur onerror onfocus ' + 'onhashchange onload onmessage onoffline ononline onpagehide onpageshow ' + 'onpopstate onresize onscroll onstorage onunload', flowContent);
  3562. add('address dt dd div caption', '', flowContent);
  3563. add('h1 h2 h3 h4 h5 h6 pre p abbr code var samp kbd sub sup i b u bdo span legend em strong small s cite dfn', '', phrasingContent);
  3564. add('blockquote', 'cite', flowContent);
  3565. add('ol', 'reversed start type', 'li');
  3566. add('ul', '', 'li');
  3567. add('li', 'value', flowContent);
  3568. add('dl', '', 'dt dd');
  3569. add('a', 'href target rel media hreflang type', phrasingContent);
  3570. add('q', 'cite', phrasingContent);
  3571. add('ins del', 'cite datetime', flowContent);
  3572. add('img', 'src sizes srcset alt usemap ismap width height');
  3573. add('iframe', 'src name width height', flowContent);
  3574. add('embed', 'src type width height');
  3575. add('object', 'data type typemustmatch name usemap form width height', [
  3576. flowContent,
  3577. 'param'
  3578. ].join(' '));
  3579. add('param', 'name value');
  3580. add('map', 'name', [
  3581. flowContent,
  3582. 'area'
  3583. ].join(' '));
  3584. add('area', 'alt coords shape href target rel media hreflang type');
  3585. add('table', 'border', 'caption colgroup thead tfoot tbody tr' + (type === 'html4' ? ' col' : ''));
  3586. add('colgroup', 'span', 'col');
  3587. add('col', 'span');
  3588. add('tbody thead tfoot', '', 'tr');
  3589. add('tr', '', 'td th');
  3590. add('td', 'colspan rowspan headers', flowContent);
  3591. add('th', 'colspan rowspan headers scope abbr', flowContent);
  3592. add('form', 'accept-charset action autocomplete enctype method name novalidate target', flowContent);
  3593. add('fieldset', 'disabled form name', [
  3594. flowContent,
  3595. 'legend'
  3596. ].join(' '));
  3597. add('label', 'form for', phrasingContent);
  3598. add('input', 'accept alt autocomplete checked dirname disabled form formaction formenctype formmethod formnovalidate ' + 'formtarget height list max maxlength min multiple name pattern readonly required size src step type value width');
  3599. add('button', 'disabled form formaction formenctype formmethod formnovalidate formtarget name type value', type === 'html4' ? flowContent : phrasingContent);
  3600. add('select', 'disabled form multiple name required size', 'option optgroup');
  3601. add('optgroup', 'disabled label', 'option');
  3602. add('option', 'disabled label selected value');
  3603. add('textarea', 'cols dirname disabled form maxlength name readonly required rows wrap');
  3604. add('menu', 'type label', [
  3605. flowContent,
  3606. 'li'
  3607. ].join(' '));
  3608. add('noscript', '', flowContent);
  3609. if (type !== 'html4') {
  3610. add('wbr');
  3611. add('ruby', '', [
  3612. phrasingContent,
  3613. 'rt rp'
  3614. ].join(' '));
  3615. add('figcaption', '', flowContent);
  3616. add('mark rt rp summary bdi', '', phrasingContent);
  3617. add('canvas', 'width height', flowContent);
  3618. add('video', 'src crossorigin poster preload autoplay mediagroup loop ' + 'muted controls width height buffered', [
  3619. flowContent,
  3620. 'track source'
  3621. ].join(' '));
  3622. add('audio', 'src crossorigin preload autoplay mediagroup loop muted controls ' + 'buffered volume', [
  3623. flowContent,
  3624. 'track source'
  3625. ].join(' '));
  3626. add('picture', '', 'img source');
  3627. add('source', 'src srcset type media sizes');
  3628. add('track', 'kind src srclang label default');
  3629. add('datalist', '', [
  3630. phrasingContent,
  3631. 'option'
  3632. ].join(' '));
  3633. add('article section nav aside main header footer', '', flowContent);
  3634. add('hgroup', '', 'h1 h2 h3 h4 h5 h6');
  3635. add('figure', '', [
  3636. flowContent,
  3637. 'figcaption'
  3638. ].join(' '));
  3639. add('time', 'datetime', phrasingContent);
  3640. add('dialog', 'open', flowContent);
  3641. add('command', 'type label icon disabled checked radiogroup command');
  3642. add('output', 'for form name', phrasingContent);
  3643. add('progress', 'value max', phrasingContent);
  3644. add('meter', 'value min max low high optimum', phrasingContent);
  3645. add('details', 'open', [
  3646. flowContent,
  3647. 'summary'
  3648. ].join(' '));
  3649. add('keygen', 'autofocus challenge disabled form keytype name');
  3650. }
  3651. if (type !== 'html5-strict') {
  3652. addAttrs('script', 'language xml:space');
  3653. addAttrs('style', 'xml:space');
  3654. addAttrs('object', 'declare classid code codebase codetype archive standby align border hspace vspace');
  3655. addAttrs('embed', 'align name hspace vspace');
  3656. addAttrs('param', 'valuetype type');
  3657. addAttrs('a', 'charset name rev shape coords');
  3658. addAttrs('br', 'clear');
  3659. addAttrs('applet', 'codebase archive code object alt name width height align hspace vspace');
  3660. addAttrs('img', 'name longdesc align border hspace vspace');
  3661. addAttrs('iframe', 'longdesc frameborder marginwidth marginheight scrolling align');
  3662. addAttrs('font basefont', 'size color face');
  3663. addAttrs('input', 'usemap align');
  3664. addAttrs('select');
  3665. addAttrs('textarea');
  3666. addAttrs('h1 h2 h3 h4 h5 h6 div p legend caption', 'align');
  3667. addAttrs('ul', 'type compact');
  3668. addAttrs('li', 'type');
  3669. addAttrs('ol dl menu dir', 'compact');
  3670. addAttrs('pre', 'width xml:space');
  3671. addAttrs('hr', 'align noshade size width');
  3672. addAttrs('isindex', 'prompt');
  3673. addAttrs('table', 'summary width frame rules cellspacing cellpadding align bgcolor');
  3674. addAttrs('col', 'width align char charoff valign');
  3675. addAttrs('colgroup', 'width align char charoff valign');
  3676. addAttrs('thead', 'align char charoff valign');
  3677. addAttrs('tr', 'align char charoff valign bgcolor');
  3678. addAttrs('th', 'axis align char charoff valign nowrap bgcolor width height');
  3679. addAttrs('form', 'accept');
  3680. addAttrs('td', 'abbr axis scope align char charoff valign nowrap bgcolor width height');
  3681. addAttrs('tfoot', 'align char charoff valign');
  3682. addAttrs('tbody', 'align char charoff valign');
  3683. addAttrs('area', 'nohref');
  3684. addAttrs('body', 'background bgcolor text link vlink alink');
  3685. }
  3686. if (type !== 'html4') {
  3687. addAttrs('input button select textarea', 'autofocus');
  3688. addAttrs('input textarea', 'placeholder');
  3689. addAttrs('a', 'download');
  3690. addAttrs('link script img', 'crossorigin');
  3691. addAttrs('img', 'loading');
  3692. addAttrs('iframe', 'sandbox seamless allowfullscreen loading');
  3693. }
  3694. each$h(split$1('a form meter progress dfn'), function (name) {
  3695. if (schema[name]) {
  3696. delete schema[name].children[name];
  3697. }
  3698. });
  3699. delete schema.caption.children.table;
  3700. delete schema.script;
  3701. mapCache[type] = schema;
  3702. return schema;
  3703. };
  3704. var compileElementMap = function (value, mode) {
  3705. var styles;
  3706. if (value) {
  3707. styles = {};
  3708. if (typeof value === 'string') {
  3709. value = { '*': value };
  3710. }
  3711. each$h(value, function (value, key) {
  3712. styles[key] = styles[key.toUpperCase()] = mode === 'map' ? makeMap$2(value, /[, ]/) : explode$3(value, /[, ]/);
  3713. });
  3714. }
  3715. return styles;
  3716. };
  3717. var Schema = function (settings) {
  3718. var elements = {};
  3719. var children = {};
  3720. var patternElements = [];
  3721. var customElementsMap = {}, specialElements = {};
  3722. var createLookupTable = function (option, defaultValue, extendWith) {
  3723. var value = settings[option];
  3724. if (!value) {
  3725. value = mapCache[option];
  3726. if (!value) {
  3727. value = makeMap$2(defaultValue, ' ', makeMap$2(defaultValue.toUpperCase(), ' '));
  3728. value = extend$5(value, extendWith);
  3729. mapCache[option] = value;
  3730. }
  3731. } else {
  3732. value = makeMap$2(value, /[, ]/, makeMap$2(value.toUpperCase(), /[, ]/));
  3733. }
  3734. return value;
  3735. };
  3736. settings = settings || {};
  3737. var schemaItems = compileSchema(settings.schema);
  3738. if (settings.verify_html === false) {
  3739. settings.valid_elements = '*[*]';
  3740. }
  3741. var validStyles = compileElementMap(settings.valid_styles);
  3742. var invalidStyles = compileElementMap(settings.invalid_styles, 'map');
  3743. var validClasses = compileElementMap(settings.valid_classes, 'map');
  3744. var whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object code');
  3745. var selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
  3746. var shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link ' + 'meta param embed source wbr track');
  3747. var boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + 'noshade nowrap readonly selected autoplay loop controls');
  3748. var nonEmptyOrMoveCaretBeforeOnEnter = 'td th iframe video audio object script code';
  3749. var nonEmptyElementsMap = createLookupTable('non_empty_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' pre', shortEndedElementsMap);
  3750. var moveCaretBeforeOnEnterElementsMap = createLookupTable('move_caret_before_on_enter_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' table', shortEndedElementsMap);
  3751. var textBlockElementsMap = createLookupTable('text_block_elements', 'h1 h2 h3 h4 h5 h6 p div address pre form ' + 'blockquote center dir fieldset header footer article section hgroup aside main nav figure');
  3752. var blockElementsMap = createLookupTable('block_elements', 'hr table tbody thead tfoot ' + 'th tr td li ol ul caption dl dt dd noscript menu isindex option ' + 'datalist select optgroup figcaption details summary', textBlockElementsMap);
  3753. var textInlineElementsMap = createLookupTable('text_inline_elements', 'span strong b em i font strike u var cite ' + 'dfn code mark q sup sub samp');
  3754. each$h((settings.special || 'script noscript iframe noframes noembed title style textarea xmp').split(' '), function (name) {
  3755. specialElements[name] = new RegExp('</' + name + '[^>]*>', 'gi');
  3756. });
  3757. var patternToRegExp = function (str) {
  3758. return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
  3759. };
  3760. var addValidElements = function (validElements) {
  3761. var ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, value;
  3762. var elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/, attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/;
  3763. if (validElements) {
  3764. var validElementsArr = split$1(validElements, ',');
  3765. if (elements['@']) {
  3766. globalAttributes = elements['@'].attributes;
  3767. globalAttributesOrder = elements['@'].attributesOrder;
  3768. }
  3769. for (ei = 0, el = validElementsArr.length; ei < el; ei++) {
  3770. matches = elementRuleRegExp.exec(validElementsArr[ei]);
  3771. if (matches) {
  3772. prefix = matches[1];
  3773. elementName = matches[2];
  3774. outputName = matches[3];
  3775. attrData = matches[5];
  3776. attributes = {};
  3777. attributesOrder = [];
  3778. element = {
  3779. attributes: attributes,
  3780. attributesOrder: attributesOrder
  3781. };
  3782. if (prefix === '#') {
  3783. element.paddEmpty = true;
  3784. }
  3785. if (prefix === '-') {
  3786. element.removeEmpty = true;
  3787. }
  3788. if (matches[4] === '!') {
  3789. element.removeEmptyAttrs = true;
  3790. }
  3791. if (globalAttributes) {
  3792. each$j(globalAttributes, function (value, key) {
  3793. attributes[key] = value;
  3794. });
  3795. attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
  3796. }
  3797. if (attrData) {
  3798. attrData = split$1(attrData, '|');
  3799. for (ai = 0, al = attrData.length; ai < al; ai++) {
  3800. matches = attrRuleRegExp.exec(attrData[ai]);
  3801. if (matches) {
  3802. attr = {};
  3803. attrType = matches[1];
  3804. attrName = matches[2].replace(/[\\:]:/g, ':');
  3805. prefix = matches[3];
  3806. value = matches[4];
  3807. if (attrType === '!') {
  3808. element.attributesRequired = element.attributesRequired || [];
  3809. element.attributesRequired.push(attrName);
  3810. attr.required = true;
  3811. }
  3812. if (attrType === '-') {
  3813. delete attributes[attrName];
  3814. attributesOrder.splice(inArray$2(attributesOrder, attrName), 1);
  3815. continue;
  3816. }
  3817. if (prefix) {
  3818. if (prefix === '=') {
  3819. element.attributesDefault = element.attributesDefault || [];
  3820. element.attributesDefault.push({
  3821. name: attrName,
  3822. value: value
  3823. });
  3824. attr.defaultValue = value;
  3825. }
  3826. if (prefix === ':') {
  3827. element.attributesForced = element.attributesForced || [];
  3828. element.attributesForced.push({
  3829. name: attrName,
  3830. value: value
  3831. });
  3832. attr.forcedValue = value;
  3833. }
  3834. if (prefix === '<') {
  3835. attr.validValues = makeMap$2(value, '?');
  3836. }
  3837. }
  3838. if (hasPatternsRegExp.test(attrName)) {
  3839. element.attributePatterns = element.attributePatterns || [];
  3840. attr.pattern = patternToRegExp(attrName);
  3841. element.attributePatterns.push(attr);
  3842. } else {
  3843. if (!attributes[attrName]) {
  3844. attributesOrder.push(attrName);
  3845. }
  3846. attributes[attrName] = attr;
  3847. }
  3848. }
  3849. }
  3850. }
  3851. if (!globalAttributes && elementName === '@') {
  3852. globalAttributes = attributes;
  3853. globalAttributesOrder = attributesOrder;
  3854. }
  3855. if (outputName) {
  3856. element.outputName = elementName;
  3857. elements[outputName] = element;
  3858. }
  3859. if (hasPatternsRegExp.test(elementName)) {
  3860. element.pattern = patternToRegExp(elementName);
  3861. patternElements.push(element);
  3862. } else {
  3863. elements[elementName] = element;
  3864. }
  3865. }
  3866. }
  3867. }
  3868. };
  3869. var setValidElements = function (validElements) {
  3870. elements = {};
  3871. patternElements = [];
  3872. addValidElements(validElements);
  3873. each$h(schemaItems, function (element, name) {
  3874. children[name] = element.children;
  3875. });
  3876. };
  3877. var addCustomElements = function (customElements) {
  3878. var customElementRegExp = /^(~)?(.+)$/;
  3879. if (customElements) {
  3880. mapCache.text_block_elements = mapCache.block_elements = null;
  3881. each$h(split$1(customElements, ','), function (rule) {
  3882. var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2];
  3883. children[name] = children[cloneName];
  3884. customElementsMap[name] = cloneName;
  3885. if (!inline) {
  3886. blockElementsMap[name.toUpperCase()] = {};
  3887. blockElementsMap[name] = {};
  3888. }
  3889. if (!elements[name]) {
  3890. var customRule = elements[cloneName];
  3891. customRule = extend$5({}, customRule);
  3892. delete customRule.removeEmptyAttrs;
  3893. delete customRule.removeEmpty;
  3894. elements[name] = customRule;
  3895. }
  3896. each$h(children, function (element, elmName) {
  3897. if (element[cloneName]) {
  3898. children[elmName] = element = extend$5({}, children[elmName]);
  3899. element[name] = element[cloneName];
  3900. }
  3901. });
  3902. });
  3903. }
  3904. };
  3905. var addValidChildren = function (validChildren) {
  3906. var childRuleRegExp = /^([+\-]?)([A-Za-z0-9_\-.\u00b7\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]+)\[([^\]]+)]$/;
  3907. mapCache[settings.schema] = null;
  3908. if (validChildren) {
  3909. each$h(split$1(validChildren, ','), function (rule) {
  3910. var matches = childRuleRegExp.exec(rule);
  3911. var parent, prefix;
  3912. if (matches) {
  3913. prefix = matches[1];
  3914. if (prefix) {
  3915. parent = children[matches[2]];
  3916. } else {
  3917. parent = children[matches[2]] = { '#comment': {} };
  3918. }
  3919. parent = children[matches[2]];
  3920. each$h(split$1(matches[3], '|'), function (child) {
  3921. if (prefix === '-') {
  3922. delete parent[child];
  3923. } else {
  3924. parent[child] = {};
  3925. }
  3926. });
  3927. }
  3928. });
  3929. }
  3930. };
  3931. var getElementRule = function (name) {
  3932. var element = elements[name], i;
  3933. if (element) {
  3934. return element;
  3935. }
  3936. i = patternElements.length;
  3937. while (i--) {
  3938. element = patternElements[i];
  3939. if (element.pattern.test(name)) {
  3940. return element;
  3941. }
  3942. }
  3943. };
  3944. if (!settings.valid_elements) {
  3945. each$h(schemaItems, function (element, name) {
  3946. elements[name] = {
  3947. attributes: element.attributes,
  3948. attributesOrder: element.attributesOrder
  3949. };
  3950. children[name] = element.children;
  3951. });
  3952. if (settings.schema !== 'html5') {
  3953. each$h(split$1('strong/b em/i'), function (item) {
  3954. var items = split$1(item, '/');
  3955. elements[items[1]].outputName = items[0];
  3956. });
  3957. }
  3958. each$h(split$1('ol ul sub sup blockquote span font a table tbody strong em b i'), function (name) {
  3959. if (elements[name]) {
  3960. elements[name].removeEmpty = true;
  3961. }
  3962. });
  3963. each$h(split$1('p h1 h2 h3 h4 h5 h6 th td pre div address caption li'), function (name) {
  3964. elements[name].paddEmpty = true;
  3965. });
  3966. each$h(split$1('span'), function (name) {
  3967. elements[name].removeEmptyAttrs = true;
  3968. });
  3969. } else {
  3970. setValidElements(settings.valid_elements);
  3971. }
  3972. addCustomElements(settings.custom_elements);
  3973. addValidChildren(settings.valid_children);
  3974. addValidElements(settings.extended_valid_elements);
  3975. addValidChildren('+ol[ul|ol],+ul[ul|ol]');
  3976. each$h({
  3977. dd: 'dl',
  3978. dt: 'dl',
  3979. li: 'ul ol',
  3980. td: 'tr',
  3981. th: 'tr',
  3982. tr: 'tbody thead tfoot',
  3983. tbody: 'table',
  3984. thead: 'table',
  3985. tfoot: 'table',
  3986. legend: 'fieldset',
  3987. area: 'map',
  3988. param: 'video audio object'
  3989. }, function (parents, item) {
  3990. if (elements[item]) {
  3991. elements[item].parentsRequired = split$1(parents);
  3992. }
  3993. });
  3994. if (settings.invalid_elements) {
  3995. each$h(explode$3(settings.invalid_elements), function (item) {
  3996. if (elements[item]) {
  3997. delete elements[item];
  3998. }
  3999. });
  4000. }
  4001. if (!getElementRule('span')) {
  4002. addValidElements('span[!data-mce-type|*]');
  4003. }
  4004. var getValidStyles = constant(validStyles);
  4005. var getInvalidStyles = constant(invalidStyles);
  4006. var getValidClasses = constant(validClasses);
  4007. var getBoolAttrs = constant(boolAttrMap);
  4008. var getBlockElements = constant(blockElementsMap);
  4009. var getTextBlockElements = constant(textBlockElementsMap);
  4010. var getTextInlineElements = constant(textInlineElementsMap);
  4011. var getShortEndedElements = constant(shortEndedElementsMap);
  4012. var getSelfClosingElements = constant(selfClosingElementsMap);
  4013. var getNonEmptyElements = constant(nonEmptyElementsMap);
  4014. var getMoveCaretBeforeOnEnterElements = constant(moveCaretBeforeOnEnterElementsMap);
  4015. var getWhiteSpaceElements = constant(whiteSpaceElementsMap);
  4016. var getSpecialElements = constant(specialElements);
  4017. var isValidChild = function (name, child) {
  4018. var parent = children[name.toLowerCase()];
  4019. return !!(parent && parent[child.toLowerCase()]);
  4020. };
  4021. var isValid = function (name, attr) {
  4022. var attrPatterns, i;
  4023. var rule = getElementRule(name);
  4024. if (rule) {
  4025. if (attr) {
  4026. if (rule.attributes[attr]) {
  4027. return true;
  4028. }
  4029. attrPatterns = rule.attributePatterns;
  4030. if (attrPatterns) {
  4031. i = attrPatterns.length;
  4032. while (i--) {
  4033. if (attrPatterns[i].pattern.test(name)) {
  4034. return true;
  4035. }
  4036. }
  4037. }
  4038. } else {
  4039. return true;
  4040. }
  4041. }
  4042. return false;
  4043. };
  4044. var getCustomElements = constant(customElementsMap);
  4045. return {
  4046. children: children,
  4047. elements: elements,
  4048. getValidStyles: getValidStyles,
  4049. getValidClasses: getValidClasses,
  4050. getBlockElements: getBlockElements,
  4051. getInvalidStyles: getInvalidStyles,
  4052. getShortEndedElements: getShortEndedElements,
  4053. getTextBlockElements: getTextBlockElements,
  4054. getTextInlineElements: getTextInlineElements,
  4055. getBoolAttrs: getBoolAttrs,
  4056. getElementRule: getElementRule,
  4057. getSelfClosingElements: getSelfClosingElements,
  4058. getNonEmptyElements: getNonEmptyElements,
  4059. getMoveCaretBeforeOnEnterElements: getMoveCaretBeforeOnEnterElements,
  4060. getWhiteSpaceElements: getWhiteSpaceElements,
  4061. getSpecialElements: getSpecialElements,
  4062. isValidChild: isValidChild,
  4063. isValid: isValid,
  4064. getCustomElements: getCustomElements,
  4065. addValidElements: addValidElements,
  4066. setValidElements: setValidElements,
  4067. addCustomElements: addCustomElements,
  4068. addValidChildren: addValidChildren
  4069. };
  4070. };
  4071. var toHex = function (match, r, g, b) {
  4072. var hex = function (val) {
  4073. val = parseInt(val, 10).toString(16);
  4074. return val.length > 1 ? val : '0' + val;
  4075. };
  4076. return '#' + hex(r) + hex(g) + hex(b);
  4077. };
  4078. var Styles = function (settings, schema) {
  4079. var _this = this;
  4080. var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
  4081. var urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
  4082. var styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
  4083. var trimRightRegExp = /\s+$/;
  4084. var i;
  4085. var encodingLookup = {};
  4086. var validStyles;
  4087. var invalidStyles;
  4088. var invisibleChar = zeroWidth;
  4089. settings = settings || {};
  4090. if (schema) {
  4091. validStyles = schema.getValidStyles();
  4092. invalidStyles = schema.getInvalidStyles();
  4093. }
  4094. var encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' ');
  4095. for (i = 0; i < encodingItems.length; i++) {
  4096. encodingLookup[encodingItems[i]] = invisibleChar + i;
  4097. encodingLookup[invisibleChar + i] = encodingItems[i];
  4098. }
  4099. return {
  4100. toHex: function (color) {
  4101. return color.replace(rgbRegExp, toHex);
  4102. },
  4103. parse: function (css) {
  4104. var styles = {};
  4105. var matches, name, value, isEncoded;
  4106. var urlConverter = settings.url_converter;
  4107. var urlConverterScope = settings.url_converter_scope || _this;
  4108. var compress = function (prefix, suffix, noJoin) {
  4109. var top = styles[prefix + '-top' + suffix];
  4110. if (!top) {
  4111. return;
  4112. }
  4113. var right = styles[prefix + '-right' + suffix];
  4114. if (!right) {
  4115. return;
  4116. }
  4117. var bottom = styles[prefix + '-bottom' + suffix];
  4118. if (!bottom) {
  4119. return;
  4120. }
  4121. var left = styles[prefix + '-left' + suffix];
  4122. if (!left) {
  4123. return;
  4124. }
  4125. var box = [
  4126. top,
  4127. right,
  4128. bottom,
  4129. left
  4130. ];
  4131. i = box.length - 1;
  4132. while (i--) {
  4133. if (box[i] !== box[i + 1]) {
  4134. break;
  4135. }
  4136. }
  4137. if (i > -1 && noJoin) {
  4138. return;
  4139. }
  4140. styles[prefix + suffix] = i === -1 ? box[0] : box.join(' ');
  4141. delete styles[prefix + '-top' + suffix];
  4142. delete styles[prefix + '-right' + suffix];
  4143. delete styles[prefix + '-bottom' + suffix];
  4144. delete styles[prefix + '-left' + suffix];
  4145. };
  4146. var canCompress = function (key) {
  4147. var value = styles[key], i;
  4148. if (!value) {
  4149. return;
  4150. }
  4151. value = value.split(' ');
  4152. i = value.length;
  4153. while (i--) {
  4154. if (value[i] !== value[0]) {
  4155. return false;
  4156. }
  4157. }
  4158. styles[key] = value[0];
  4159. return true;
  4160. };
  4161. var compress2 = function (target, a, b, c) {
  4162. if (!canCompress(a)) {
  4163. return;
  4164. }
  4165. if (!canCompress(b)) {
  4166. return;
  4167. }
  4168. if (!canCompress(c)) {
  4169. return;
  4170. }
  4171. styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
  4172. delete styles[a];
  4173. delete styles[b];
  4174. delete styles[c];
  4175. };
  4176. var encode = function (str) {
  4177. isEncoded = true;
  4178. return encodingLookup[str];
  4179. };
  4180. var decode = function (str, keepSlashes) {
  4181. if (isEncoded) {
  4182. str = str.replace(/\uFEFF[0-9]/g, function (str) {
  4183. return encodingLookup[str];
  4184. });
  4185. }
  4186. if (!keepSlashes) {
  4187. str = str.replace(/\\([\'\";:])/g, '$1');
  4188. }
  4189. return str;
  4190. };
  4191. var decodeSingleHexSequence = function (escSeq) {
  4192. return String.fromCharCode(parseInt(escSeq.slice(1), 16));
  4193. };
  4194. var decodeHexSequences = function (value) {
  4195. return value.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
  4196. };
  4197. var processUrl = function (match, url, url2, url3, str, str2) {
  4198. str = str || str2;
  4199. if (str) {
  4200. str = decode(str);
  4201. return '\'' + str.replace(/\'/g, '\\\'') + '\'';
  4202. }
  4203. url = decode(url || url2 || url3);
  4204. if (!settings.allow_script_urls) {
  4205. var scriptUrl = url.replace(/[\s\r\n]+/g, '');
  4206. if (/(java|vb)script:/i.test(scriptUrl)) {
  4207. return '';
  4208. }
  4209. if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
  4210. return '';
  4211. }
  4212. }
  4213. if (urlConverter) {
  4214. url = urlConverter.call(urlConverterScope, url, 'style');
  4215. }
  4216. return 'url(\'' + url.replace(/\'/g, '\\\'') + '\')';
  4217. };
  4218. if (css) {
  4219. css = css.replace(/[\u0000-\u001F]/g, '');
  4220. css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function (str) {
  4221. return str.replace(/[;:]/g, encode);
  4222. });
  4223. while (matches = styleRegExp.exec(css)) {
  4224. styleRegExp.lastIndex = matches.index + matches[0].length;
  4225. name = matches[1].replace(trimRightRegExp, '').toLowerCase();
  4226. value = matches[2].replace(trimRightRegExp, '');
  4227. if (name && value) {
  4228. name = decodeHexSequences(name);
  4229. value = decodeHexSequences(value);
  4230. if (name.indexOf(invisibleChar) !== -1 || name.indexOf('"') !== -1) {
  4231. continue;
  4232. }
  4233. if (!settings.allow_script_urls && (name === 'behavior' || /expression\s*\(|\/\*|\*\//.test(value))) {
  4234. continue;
  4235. }
  4236. if (name === 'font-weight' && value === '700') {
  4237. value = 'bold';
  4238. } else if (name === 'color' || name === 'background-color') {
  4239. value = value.toLowerCase();
  4240. }
  4241. value = value.replace(rgbRegExp, toHex);
  4242. value = value.replace(urlOrStrRegExp, processUrl);
  4243. styles[name] = isEncoded ? decode(value, true) : value;
  4244. }
  4245. }
  4246. compress('border', '', true);
  4247. compress('border', '-width');
  4248. compress('border', '-color');
  4249. compress('border', '-style');
  4250. compress('padding', '');
  4251. compress('margin', '');
  4252. compress2('border', 'border-width', 'border-style', 'border-color');
  4253. if (styles.border === 'medium none') {
  4254. delete styles.border;
  4255. }
  4256. if (styles['border-image'] === 'none') {
  4257. delete styles['border-image'];
  4258. }
  4259. }
  4260. return styles;
  4261. },
  4262. serialize: function (styles, elementName) {
  4263. var css = '';
  4264. var serializeStyles = function (name) {
  4265. var value;
  4266. var styleList = validStyles[name];
  4267. if (styleList) {
  4268. for (var i_1 = 0, l = styleList.length; i_1 < l; i_1++) {
  4269. name = styleList[i_1];
  4270. value = styles[name];
  4271. if (value) {
  4272. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4273. }
  4274. }
  4275. }
  4276. };
  4277. var isValid = function (name, elementName) {
  4278. var styleMap = invalidStyles['*'];
  4279. if (styleMap && styleMap[name]) {
  4280. return false;
  4281. }
  4282. styleMap = invalidStyles[elementName];
  4283. return !(styleMap && styleMap[name]);
  4284. };
  4285. if (elementName && validStyles) {
  4286. serializeStyles('*');
  4287. serializeStyles(elementName);
  4288. } else {
  4289. each$j(styles, function (value, name) {
  4290. if (value && (!invalidStyles || isValid(name, elementName))) {
  4291. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4292. }
  4293. });
  4294. }
  4295. return css;
  4296. }
  4297. };
  4298. };
  4299. var deprecated = {
  4300. keyLocation: true,
  4301. layerX: true,
  4302. layerY: true,
  4303. returnValue: true,
  4304. webkitMovementX: true,
  4305. webkitMovementY: true,
  4306. keyIdentifier: true,
  4307. mozPressure: true
  4308. };
  4309. var isNativeEvent = function (event) {
  4310. return event instanceof Event || isFunction(event.initEvent);
  4311. };
  4312. var hasIsDefaultPrevented = function (event) {
  4313. return event.isDefaultPrevented === always || event.isDefaultPrevented === never;
  4314. };
  4315. var needsNormalizing = function (event) {
  4316. return isNullable(event.preventDefault) || isNativeEvent(event);
  4317. };
  4318. var clone$2 = function (originalEvent, data) {
  4319. var event = data !== null && data !== void 0 ? data : {};
  4320. for (var name_1 in originalEvent) {
  4321. if (!has$2(deprecated, name_1)) {
  4322. event[name_1] = originalEvent[name_1];
  4323. }
  4324. }
  4325. if (isNonNullable(event.composedPath)) {
  4326. event.composedPath = function () {
  4327. return originalEvent.composedPath();
  4328. };
  4329. }
  4330. return event;
  4331. };
  4332. var normalize$3 = function (type, originalEvent, fallbackTarget, data) {
  4333. var _a;
  4334. var event = clone$2(originalEvent, data);
  4335. event.type = type;
  4336. if (isNullable(event.target)) {
  4337. event.target = (_a = event.srcElement) !== null && _a !== void 0 ? _a : fallbackTarget;
  4338. }
  4339. if (needsNormalizing(originalEvent)) {
  4340. event.preventDefault = function () {
  4341. event.defaultPrevented = true;
  4342. event.isDefaultPrevented = always;
  4343. if (isFunction(originalEvent.preventDefault)) {
  4344. originalEvent.preventDefault();
  4345. } else if (isNativeEvent(originalEvent)) {
  4346. originalEvent.returnValue = false;
  4347. }
  4348. };
  4349. event.stopPropagation = function () {
  4350. event.cancelBubble = true;
  4351. event.isPropagationStopped = always;
  4352. if (isFunction(originalEvent.stopPropagation)) {
  4353. originalEvent.stopPropagation();
  4354. } else if (isNativeEvent(originalEvent)) {
  4355. originalEvent.cancelBubble = true;
  4356. }
  4357. };
  4358. event.stopImmediatePropagation = function () {
  4359. event.isImmediatePropagationStopped = always;
  4360. event.stopPropagation();
  4361. };
  4362. if (!hasIsDefaultPrevented(event)) {
  4363. event.isDefaultPrevented = event.defaultPrevented === true ? always : never;
  4364. event.isPropagationStopped = event.cancelBubble === true ? always : never;
  4365. event.isImmediatePropagationStopped = never;
  4366. }
  4367. }
  4368. return event;
  4369. };
  4370. var eventExpandoPrefix = 'mce-data-';
  4371. var mouseEventRe = /^(?:mouse|contextmenu)|click/;
  4372. var addEvent = function (target, name, callback, capture) {
  4373. if (target.addEventListener) {
  4374. target.addEventListener(name, callback, capture || false);
  4375. } else if (target.attachEvent) {
  4376. target.attachEvent('on' + name, callback);
  4377. }
  4378. };
  4379. var removeEvent = function (target, name, callback, capture) {
  4380. if (target.removeEventListener) {
  4381. target.removeEventListener(name, callback, capture || false);
  4382. } else if (target.detachEvent) {
  4383. target.detachEvent('on' + name, callback);
  4384. }
  4385. };
  4386. var isMouseEvent = function (event) {
  4387. return isNonNullable(event) && mouseEventRe.test(event.type);
  4388. };
  4389. var fix = function (originalEvent, data) {
  4390. var event = normalize$3(originalEvent.type, originalEvent, document, data);
  4391. if (isMouseEvent(originalEvent) && isUndefined(originalEvent.pageX) && !isUndefined(originalEvent.clientX)) {
  4392. var eventDoc = event.target.ownerDocument || document;
  4393. var doc = eventDoc.documentElement;
  4394. var body = eventDoc.body;
  4395. var mouseEvent = event;
  4396. mouseEvent.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  4397. mouseEvent.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  4398. }
  4399. if (isUndefined(event.metaKey)) {
  4400. event.metaKey = false;
  4401. }
  4402. return event;
  4403. };
  4404. var bindOnReady = function (win, callback, eventUtils) {
  4405. var doc = win.document, event = { type: 'ready' };
  4406. if (eventUtils.domLoaded) {
  4407. callback(event);
  4408. return;
  4409. }
  4410. var isDocReady = function () {
  4411. return doc.readyState === 'complete' || doc.readyState === 'interactive' && doc.body;
  4412. };
  4413. var readyHandler = function () {
  4414. removeEvent(win, 'DOMContentLoaded', readyHandler);
  4415. removeEvent(win, 'load', readyHandler);
  4416. if (!eventUtils.domLoaded) {
  4417. eventUtils.domLoaded = true;
  4418. callback(event);
  4419. }
  4420. win = null;
  4421. };
  4422. if (isDocReady()) {
  4423. readyHandler();
  4424. } else {
  4425. addEvent(win, 'DOMContentLoaded', readyHandler);
  4426. }
  4427. if (!eventUtils.domLoaded) {
  4428. addEvent(win, 'load', readyHandler);
  4429. }
  4430. };
  4431. var EventUtils = function () {
  4432. function EventUtils() {
  4433. this.domLoaded = false;
  4434. this.events = {};
  4435. this.count = 1;
  4436. this.expando = eventExpandoPrefix + (+new Date()).toString(32);
  4437. this.hasMouseEnterLeave = 'onmouseenter' in document.documentElement;
  4438. this.hasFocusIn = 'onfocusin' in document.documentElement;
  4439. this.count = 1;
  4440. }
  4441. EventUtils.prototype.bind = function (target, names, callback, scope) {
  4442. var self = this;
  4443. var id, callbackList, i, name, fakeName, nativeHandler, capture;
  4444. var win = window;
  4445. var defaultNativeHandler = function (evt) {
  4446. self.executeHandlers(fix(evt || win.event), id);
  4447. };
  4448. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4449. return;
  4450. }
  4451. if (!target[self.expando]) {
  4452. id = self.count++;
  4453. target[self.expando] = id;
  4454. self.events[id] = {};
  4455. } else {
  4456. id = target[self.expando];
  4457. }
  4458. scope = scope || target;
  4459. var namesList = names.split(' ');
  4460. i = namesList.length;
  4461. while (i--) {
  4462. name = namesList[i];
  4463. nativeHandler = defaultNativeHandler;
  4464. fakeName = capture = false;
  4465. if (name === 'DOMContentLoaded') {
  4466. name = 'ready';
  4467. }
  4468. if (self.domLoaded && name === 'ready' && target.readyState === 'complete') {
  4469. callback.call(scope, fix({ type: name }));
  4470. continue;
  4471. }
  4472. if (!self.hasMouseEnterLeave) {
  4473. fakeName = self.mouseEnterLeave[name];
  4474. if (fakeName) {
  4475. nativeHandler = function (evt) {
  4476. var current = evt.currentTarget;
  4477. var related = evt.relatedTarget;
  4478. if (related && current.contains) {
  4479. related = current.contains(related);
  4480. } else {
  4481. while (related && related !== current) {
  4482. related = related.parentNode;
  4483. }
  4484. }
  4485. if (!related) {
  4486. evt = fix(evt || win.event);
  4487. evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
  4488. evt.target = current;
  4489. self.executeHandlers(evt, id);
  4490. }
  4491. };
  4492. }
  4493. }
  4494. if (!self.hasFocusIn && (name === 'focusin' || name === 'focusout')) {
  4495. capture = true;
  4496. fakeName = name === 'focusin' ? 'focus' : 'blur';
  4497. nativeHandler = function (evt) {
  4498. evt = fix(evt || win.event);
  4499. evt.type = evt.type === 'focus' ? 'focusin' : 'focusout';
  4500. self.executeHandlers(evt, id);
  4501. };
  4502. }
  4503. callbackList = self.events[id][name];
  4504. if (!callbackList) {
  4505. self.events[id][name] = callbackList = [{
  4506. func: callback,
  4507. scope: scope
  4508. }];
  4509. callbackList.fakeName = fakeName;
  4510. callbackList.capture = capture;
  4511. callbackList.nativeHandler = nativeHandler;
  4512. if (name === 'ready') {
  4513. bindOnReady(target, nativeHandler, self);
  4514. } else {
  4515. addEvent(target, fakeName || name, nativeHandler, capture);
  4516. }
  4517. } else {
  4518. if (name === 'ready' && self.domLoaded) {
  4519. callback(fix({ type: name }));
  4520. } else {
  4521. callbackList.push({
  4522. func: callback,
  4523. scope: scope
  4524. });
  4525. }
  4526. }
  4527. }
  4528. target = callbackList = null;
  4529. return callback;
  4530. };
  4531. EventUtils.prototype.unbind = function (target, names, callback) {
  4532. var callbackList, i, ci, name, eventMap;
  4533. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4534. return this;
  4535. }
  4536. var id = target[this.expando];
  4537. if (id) {
  4538. eventMap = this.events[id];
  4539. if (names) {
  4540. var namesList = names.split(' ');
  4541. i = namesList.length;
  4542. while (i--) {
  4543. name = namesList[i];
  4544. callbackList = eventMap[name];
  4545. if (callbackList) {
  4546. if (callback) {
  4547. ci = callbackList.length;
  4548. while (ci--) {
  4549. if (callbackList[ci].func === callback) {
  4550. var nativeHandler = callbackList.nativeHandler;
  4551. var fakeName = callbackList.fakeName, capture = callbackList.capture;
  4552. callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
  4553. callbackList.nativeHandler = nativeHandler;
  4554. callbackList.fakeName = fakeName;
  4555. callbackList.capture = capture;
  4556. eventMap[name] = callbackList;
  4557. }
  4558. }
  4559. }
  4560. if (!callback || callbackList.length === 0) {
  4561. delete eventMap[name];
  4562. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  4563. }
  4564. }
  4565. }
  4566. } else {
  4567. each$j(eventMap, function (callbackList, name) {
  4568. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  4569. });
  4570. eventMap = {};
  4571. }
  4572. for (name in eventMap) {
  4573. if (has$2(eventMap, name)) {
  4574. return this;
  4575. }
  4576. }
  4577. delete this.events[id];
  4578. try {
  4579. delete target[this.expando];
  4580. } catch (ex) {
  4581. target[this.expando] = null;
  4582. }
  4583. }
  4584. return this;
  4585. };
  4586. EventUtils.prototype.fire = function (target, name, args) {
  4587. var id;
  4588. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4589. return this;
  4590. }
  4591. var event = fix({
  4592. type: name,
  4593. target: target
  4594. }, args);
  4595. do {
  4596. id = target[this.expando];
  4597. if (id) {
  4598. this.executeHandlers(event, id);
  4599. }
  4600. target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
  4601. } while (target && !event.isPropagationStopped());
  4602. return this;
  4603. };
  4604. EventUtils.prototype.clean = function (target) {
  4605. var i, children;
  4606. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4607. return this;
  4608. }
  4609. if (target[this.expando]) {
  4610. this.unbind(target);
  4611. }
  4612. if (!target.getElementsByTagName) {
  4613. target = target.document;
  4614. }
  4615. if (target && target.getElementsByTagName) {
  4616. this.unbind(target);
  4617. children = target.getElementsByTagName('*');
  4618. i = children.length;
  4619. while (i--) {
  4620. target = children[i];
  4621. if (target[this.expando]) {
  4622. this.unbind(target);
  4623. }
  4624. }
  4625. }
  4626. return this;
  4627. };
  4628. EventUtils.prototype.destroy = function () {
  4629. this.events = {};
  4630. };
  4631. EventUtils.prototype.cancel = function (e) {
  4632. if (e) {
  4633. e.preventDefault();
  4634. e.stopImmediatePropagation();
  4635. }
  4636. return false;
  4637. };
  4638. EventUtils.prototype.executeHandlers = function (evt, id) {
  4639. var container = this.events[id];
  4640. var callbackList = container && container[evt.type];
  4641. if (callbackList) {
  4642. for (var i = 0, l = callbackList.length; i < l; i++) {
  4643. var callback = callbackList[i];
  4644. if (callback && callback.func.call(callback.scope, evt) === false) {
  4645. evt.preventDefault();
  4646. }
  4647. if (evt.isImmediatePropagationStopped()) {
  4648. return;
  4649. }
  4650. }
  4651. }
  4652. };
  4653. EventUtils.Event = new EventUtils();
  4654. return EventUtils;
  4655. }();
  4656. var support, Expr, getText, isXML, tokenize, compile, select$1, outermostContext, sortInput, hasDuplicate, setDocument, document$1, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, expando = 'sizzle' + -new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function (a, b) {
  4657. if (a === b) {
  4658. hasDuplicate = true;
  4659. }
  4660. return 0;
  4661. }, strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, hasOwn = {}.hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push$1 = arr.push, slice$1 = arr.slice, indexOf = arr.indexOf || function (elem) {
  4662. var i = 0, len = this.length;
  4663. for (; i < len; i++) {
  4664. if (this[i] === elem) {
  4665. return i;
  4666. }
  4667. }
  4668. return -1;
  4669. }, booleans = 'checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped', whitespace = '[\\x20\\t\\r\\n\\f]', identifier = '(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+', attributes = '\\[' + whitespace + '*(' + identifier + ')(?:' + whitespace + '*([*^$|!~]?=)' + whitespace + '*(?:\'((?:\\\\.|[^\\\\\'])*)\'|"((?:\\\\.|[^\\\\"])*)"|(' + identifier + '))|)' + whitespace + '*\\]', pseudos = ':(' + identifier + ')(?:\\((' + '(\'((?:\\\\.|[^\\\\\'])*)\'|"((?:\\\\.|[^\\\\"])*)")|' + '((?:\\\\.|[^\\\\()[\\]]|' + attributes + ')*)|' + '.*' + ')\\)|)', rtrim = new RegExp('^' + whitespace + '+|((?:^|[^\\\\])(?:\\\\.)*)' + whitespace + '+$', 'g'), rcomma = new RegExp('^' + whitespace + '*,' + whitespace + '*'), rcombinators = new RegExp('^' + whitespace + '*([>+~]|' + whitespace + ')' + whitespace + '*'), rattributeQuotes = new RegExp('=' + whitespace + '*([^\\]\'"]*?)' + whitespace + '*\\]', 'g'), rpseudo = new RegExp(pseudos), ridentifier = new RegExp('^' + identifier + '$'), matchExpr = {
  4670. ID: new RegExp('^#(' + identifier + ')'),
  4671. CLASS: new RegExp('^\\.(' + identifier + ')'),
  4672. TAG: new RegExp('^(' + identifier + '|[*])'),
  4673. ATTR: new RegExp('^' + attributes),
  4674. PSEUDO: new RegExp('^' + pseudos),
  4675. CHILD: new RegExp('^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(' + whitespace + '*(even|odd|(([+-]|)(\\d*)n|)' + whitespace + '*(?:([+-]|)' + whitespace + '*(\\d+)|))' + whitespace + '*\\)|)', 'i'),
  4676. bool: new RegExp('^(?:' + booleans + ')$', 'i'),
  4677. needsContext: new RegExp('^' + whitespace + '*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(' + whitespace + '*((?:-\\d)?\\d*)' + whitespace + '*\\)|)(?=[^-]|$)', 'i')
  4678. }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, rquickExpr$1 = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, runescape = new RegExp('\\\\([\\da-f]{1,6}' + whitespace + '?|(' + whitespace + ')|.)', 'ig'), funescape = function (_, escaped, escapedWhitespace) {
  4679. var high = '0x' + escaped - 65536;
  4680. return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320);
  4681. };
  4682. try {
  4683. push$1.apply(arr = slice$1.call(preferredDoc.childNodes), preferredDoc.childNodes);
  4684. arr[preferredDoc.childNodes.length].nodeType;
  4685. } catch (e) {
  4686. push$1 = {
  4687. apply: arr.length ? function (target, els) {
  4688. push_native.apply(target, slice$1.call(els));
  4689. } : function (target, els) {
  4690. var j = target.length, i = 0;
  4691. while (target[j++] = els[i++]) {
  4692. }
  4693. target.length = j - 1;
  4694. }
  4695. };
  4696. }
  4697. var Sizzle = function (selector, context, results, seed) {
  4698. var match, elem, m, nodeType, i, groups, old, nid, newContext, newSelector;
  4699. if ((context ? context.ownerDocument || context : preferredDoc) !== document$1) {
  4700. setDocument(context);
  4701. }
  4702. context = context || document$1;
  4703. results = results || [];
  4704. if (!selector || typeof selector !== 'string') {
  4705. return results;
  4706. }
  4707. if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) {
  4708. return [];
  4709. }
  4710. if (documentIsHTML && !seed) {
  4711. if (match = rquickExpr$1.exec(selector)) {
  4712. if (m = match[1]) {
  4713. if (nodeType === 9) {
  4714. elem = context.getElementById(m);
  4715. if (elem && elem.parentNode) {
  4716. if (elem.id === m) {
  4717. results.push(elem);
  4718. return results;
  4719. }
  4720. } else {
  4721. return results;
  4722. }
  4723. } else {
  4724. if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains(context, elem) && elem.id === m) {
  4725. results.push(elem);
  4726. return results;
  4727. }
  4728. }
  4729. } else if (match[2]) {
  4730. push$1.apply(results, context.getElementsByTagName(selector));
  4731. return results;
  4732. } else if ((m = match[3]) && support.getElementsByClassName) {
  4733. push$1.apply(results, context.getElementsByClassName(m));
  4734. return results;
  4735. }
  4736. }
  4737. if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
  4738. nid = old = expando;
  4739. newContext = context;
  4740. newSelector = nodeType === 9 && selector;
  4741. if (nodeType === 1 && context.nodeName.toLowerCase() !== 'object') {
  4742. groups = tokenize(selector);
  4743. if (old = context.getAttribute('id')) {
  4744. nid = old.replace(rescape, '\\$&');
  4745. } else {
  4746. context.setAttribute('id', nid);
  4747. }
  4748. nid = '[id=\'' + nid + '\'] ';
  4749. i = groups.length;
  4750. while (i--) {
  4751. groups[i] = nid + toSelector(groups[i]);
  4752. }
  4753. newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
  4754. newSelector = groups.join(',');
  4755. }
  4756. if (newSelector) {
  4757. try {
  4758. push$1.apply(results, newContext.querySelectorAll(newSelector));
  4759. return results;
  4760. } catch (qsaError) {
  4761. } finally {
  4762. if (!old) {
  4763. context.removeAttribute('id');
  4764. }
  4765. }
  4766. }
  4767. }
  4768. }
  4769. return select$1(selector.replace(rtrim, '$1'), context, results, seed);
  4770. };
  4771. function createCache() {
  4772. var keys = [];
  4773. function cache(key, value) {
  4774. if (keys.push(key + ' ') > Expr.cacheLength) {
  4775. delete cache[keys.shift()];
  4776. }
  4777. return cache[key + ' '] = value;
  4778. }
  4779. return cache;
  4780. }
  4781. function markFunction(fn) {
  4782. fn[expando] = true;
  4783. return fn;
  4784. }
  4785. function siblingCheck(a, b) {
  4786. var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && (~b.sourceIndex || MAX_NEGATIVE) - (~a.sourceIndex || MAX_NEGATIVE);
  4787. if (diff) {
  4788. return diff;
  4789. }
  4790. if (cur) {
  4791. while (cur = cur.nextSibling) {
  4792. if (cur === b) {
  4793. return -1;
  4794. }
  4795. }
  4796. }
  4797. return a ? 1 : -1;
  4798. }
  4799. function createInputPseudo(type) {
  4800. return function (elem) {
  4801. var name = elem.nodeName.toLowerCase();
  4802. return name === 'input' && elem.type === type;
  4803. };
  4804. }
  4805. function createButtonPseudo(type) {
  4806. return function (elem) {
  4807. var name = elem.nodeName.toLowerCase();
  4808. return (name === 'input' || name === 'button') && elem.type === type;
  4809. };
  4810. }
  4811. function createPositionalPseudo(fn) {
  4812. return markFunction(function (argument) {
  4813. argument = +argument;
  4814. return markFunction(function (seed, matches) {
  4815. var j, matchIndexes = fn([], seed.length, argument), i = matchIndexes.length;
  4816. while (i--) {
  4817. if (seed[j = matchIndexes[i]]) {
  4818. seed[j] = !(matches[j] = seed[j]);
  4819. }
  4820. }
  4821. });
  4822. });
  4823. }
  4824. function testContext(context) {
  4825. return context && typeof context.getElementsByTagName !== strundefined && context;
  4826. }
  4827. support = Sizzle.support = {};
  4828. isXML = Sizzle.isXML = function (elem) {
  4829. var documentElement = elem && (elem.ownerDocument || elem).documentElement;
  4830. return documentElement ? documentElement.nodeName !== 'HTML' : false;
  4831. };
  4832. setDocument = Sizzle.setDocument = function (node) {
  4833. var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView;
  4834. function getTop(win) {
  4835. try {
  4836. return win.top;
  4837. } catch (ex) {
  4838. }
  4839. return null;
  4840. }
  4841. if (doc === document$1 || doc.nodeType !== 9 || !doc.documentElement) {
  4842. return document$1;
  4843. }
  4844. document$1 = doc;
  4845. docElem = doc.documentElement;
  4846. documentIsHTML = !isXML(doc);
  4847. if (parent && parent !== getTop(parent)) {
  4848. if (parent.addEventListener) {
  4849. parent.addEventListener('unload', function () {
  4850. setDocument();
  4851. }, false);
  4852. } else if (parent.attachEvent) {
  4853. parent.attachEvent('onunload', function () {
  4854. setDocument();
  4855. });
  4856. }
  4857. }
  4858. support.attributes = true;
  4859. support.getElementsByTagName = true;
  4860. support.getElementsByClassName = rnative.test(doc.getElementsByClassName);
  4861. support.getById = true;
  4862. Expr.find.ID = function (id, context) {
  4863. if (typeof context.getElementById !== strundefined && documentIsHTML) {
  4864. var m = context.getElementById(id);
  4865. return m && m.parentNode ? [m] : [];
  4866. }
  4867. };
  4868. Expr.filter.ID = function (id) {
  4869. var attrId = id.replace(runescape, funescape);
  4870. return function (elem) {
  4871. return elem.getAttribute('id') === attrId;
  4872. };
  4873. };
  4874. Expr.find.TAG = support.getElementsByTagName ? function (tag, context) {
  4875. if (typeof context.getElementsByTagName !== strundefined) {
  4876. return context.getElementsByTagName(tag);
  4877. }
  4878. } : function (tag, context) {
  4879. var elem, tmp = [], i = 0, results = context.getElementsByTagName(tag);
  4880. if (tag === '*') {
  4881. while (elem = results[i++]) {
  4882. if (elem.nodeType === 1) {
  4883. tmp.push(elem);
  4884. }
  4885. }
  4886. return tmp;
  4887. }
  4888. return results;
  4889. };
  4890. Expr.find.CLASS = support.getElementsByClassName && function (className, context) {
  4891. if (documentIsHTML) {
  4892. return context.getElementsByClassName(className);
  4893. }
  4894. };
  4895. rbuggyMatches = [];
  4896. rbuggyQSA = [];
  4897. support.disconnectedMatch = true;
  4898. rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join('|'));
  4899. rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join('|'));
  4900. hasCompare = rnative.test(docElem.compareDocumentPosition);
  4901. contains = hasCompare || rnative.test(docElem.contains) ? function (a, b) {
  4902. var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode;
  4903. return a === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
  4904. } : function (a, b) {
  4905. if (b) {
  4906. while (b = b.parentNode) {
  4907. if (b === a) {
  4908. return true;
  4909. }
  4910. }
  4911. }
  4912. return false;
  4913. };
  4914. sortOrder = hasCompare ? function (a, b) {
  4915. if (a === b) {
  4916. hasDuplicate = true;
  4917. return 0;
  4918. }
  4919. var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
  4920. if (compare) {
  4921. return compare;
  4922. }
  4923. compare = (a.ownerDocument || a) === (b.ownerDocument || b) ? a.compareDocumentPosition(b) : 1;
  4924. if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {
  4925. if (a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a)) {
  4926. return -1;
  4927. }
  4928. if (b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b)) {
  4929. return 1;
  4930. }
  4931. return sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
  4932. }
  4933. return compare & 4 ? -1 : 1;
  4934. } : function (a, b) {
  4935. if (a === b) {
  4936. hasDuplicate = true;
  4937. return 0;
  4938. }
  4939. var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [a], bp = [b];
  4940. if (!aup || !bup) {
  4941. return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
  4942. } else if (aup === bup) {
  4943. return siblingCheck(a, b);
  4944. }
  4945. cur = a;
  4946. while (cur = cur.parentNode) {
  4947. ap.unshift(cur);
  4948. }
  4949. cur = b;
  4950. while (cur = cur.parentNode) {
  4951. bp.unshift(cur);
  4952. }
  4953. while (ap[i] === bp[i]) {
  4954. i++;
  4955. }
  4956. return i ? siblingCheck(ap[i], bp[i]) : ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0;
  4957. };
  4958. return doc;
  4959. };
  4960. Sizzle.matches = function (expr, elements) {
  4961. return Sizzle(expr, null, null, elements);
  4962. };
  4963. Sizzle.matchesSelector = function (elem, expr) {
  4964. if ((elem.ownerDocument || elem) !== document$1) {
  4965. setDocument(elem);
  4966. }
  4967. expr = expr.replace(rattributeQuotes, '=\'$1\']');
  4968. if (support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
  4969. try {
  4970. var ret = matches.call(elem, expr);
  4971. if (ret || support.disconnectedMatch || elem.document && elem.document.nodeType !== 11) {
  4972. return ret;
  4973. }
  4974. } catch (e) {
  4975. }
  4976. }
  4977. return Sizzle(expr, document$1, null, [elem]).length > 0;
  4978. };
  4979. Sizzle.contains = function (context, elem) {
  4980. if ((context.ownerDocument || context) !== document$1) {
  4981. setDocument(context);
  4982. }
  4983. return contains(context, elem);
  4984. };
  4985. Sizzle.attr = function (elem, name) {
  4986. if ((elem.ownerDocument || elem) !== document$1) {
  4987. setDocument(elem);
  4988. }
  4989. var fn = Expr.attrHandle[name.toLowerCase()], val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;
  4990. return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
  4991. };
  4992. Sizzle.error = function (msg) {
  4993. throw new Error('Syntax error, unrecognized expression: ' + msg);
  4994. };
  4995. Sizzle.uniqueSort = function (results) {
  4996. var elem, duplicates = [], j = 0, i = 0;
  4997. hasDuplicate = !support.detectDuplicates;
  4998. sortInput = !support.sortStable && results.slice(0);
  4999. results.sort(sortOrder);
  5000. if (hasDuplicate) {
  5001. while (elem = results[i++]) {
  5002. if (elem === results[i]) {
  5003. j = duplicates.push(i);
  5004. }
  5005. }
  5006. while (j--) {
  5007. results.splice(duplicates[j], 1);
  5008. }
  5009. }
  5010. sortInput = null;
  5011. return results;
  5012. };
  5013. getText = Sizzle.getText = function (elem) {
  5014. var node, ret = '', i = 0, nodeType = elem.nodeType;
  5015. if (!nodeType) {
  5016. while (node = elem[i++]) {
  5017. ret += getText(node);
  5018. }
  5019. } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
  5020. if (typeof elem.textContent === 'string') {
  5021. return elem.textContent;
  5022. } else {
  5023. for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5024. ret += getText(elem);
  5025. }
  5026. }
  5027. } else if (nodeType === 3 || nodeType === 4) {
  5028. return elem.nodeValue;
  5029. }
  5030. return ret;
  5031. };
  5032. Expr = Sizzle.selectors = {
  5033. cacheLength: 50,
  5034. createPseudo: markFunction,
  5035. match: matchExpr,
  5036. attrHandle: {},
  5037. find: {},
  5038. relative: {
  5039. '>': {
  5040. dir: 'parentNode',
  5041. first: true
  5042. },
  5043. ' ': { dir: 'parentNode' },
  5044. '+': {
  5045. dir: 'previousSibling',
  5046. first: true
  5047. },
  5048. '~': { dir: 'previousSibling' }
  5049. },
  5050. preFilter: {
  5051. ATTR: function (match) {
  5052. match[1] = match[1].replace(runescape, funescape);
  5053. match[3] = (match[3] || match[4] || match[5] || '').replace(runescape, funescape);
  5054. if (match[2] === '~=') {
  5055. match[3] = ' ' + match[3] + ' ';
  5056. }
  5057. return match.slice(0, 4);
  5058. },
  5059. CHILD: function (match) {
  5060. match[1] = match[1].toLowerCase();
  5061. if (match[1].slice(0, 3) === 'nth') {
  5062. if (!match[3]) {
  5063. Sizzle.error(match[0]);
  5064. }
  5065. match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === 'even' || match[3] === 'odd'));
  5066. match[5] = +(match[7] + match[8] || match[3] === 'odd');
  5067. } else if (match[3]) {
  5068. Sizzle.error(match[0]);
  5069. }
  5070. return match;
  5071. },
  5072. PSEUDO: function (match) {
  5073. var excess, unquoted = !match[6] && match[2];
  5074. if (matchExpr.CHILD.test(match[0])) {
  5075. return null;
  5076. }
  5077. if (match[3]) {
  5078. match[2] = match[4] || match[5] || '';
  5079. } else if (unquoted && rpseudo.test(unquoted) && (excess = tokenize(unquoted, true)) && (excess = unquoted.indexOf(')', unquoted.length - excess) - unquoted.length)) {
  5080. match[0] = match[0].slice(0, excess);
  5081. match[2] = unquoted.slice(0, excess);
  5082. }
  5083. return match.slice(0, 3);
  5084. }
  5085. },
  5086. filter: {
  5087. TAG: function (nodeNameSelector) {
  5088. var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
  5089. return nodeNameSelector === '*' ? function () {
  5090. return true;
  5091. } : function (elem) {
  5092. return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
  5093. };
  5094. },
  5095. CLASS: function (className) {
  5096. var pattern = classCache[className + ' '];
  5097. return pattern || (pattern = new RegExp('(^|' + whitespace + ')' + className + '(' + whitespace + '|$)')) && classCache(className, function (elem) {
  5098. return pattern.test(typeof elem.className === 'string' && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute('class') || '');
  5099. });
  5100. },
  5101. ATTR: function (name, operator, check) {
  5102. return function (elem) {
  5103. var result = Sizzle.attr(elem, name);
  5104. if (result == null) {
  5105. return operator === '!=';
  5106. }
  5107. if (!operator) {
  5108. return true;
  5109. }
  5110. result += '';
  5111. return operator === '=' ? result === check : operator === '!=' ? result !== check : operator === '^=' ? check && result.indexOf(check) === 0 : operator === '*=' ? check && result.indexOf(check) > -1 : operator === '$=' ? check && result.slice(-check.length) === check : operator === '~=' ? (' ' + result + ' ').indexOf(check) > -1 : operator === '|=' ? result === check || result.slice(0, check.length + 1) === check + '-' : false;
  5112. };
  5113. },
  5114. CHILD: function (type, what, argument, first, last) {
  5115. var simple = type.slice(0, 3) !== 'nth', forward = type.slice(-4) !== 'last', ofType = what === 'of-type';
  5116. return first === 1 && last === 0 ? function (elem) {
  5117. return !!elem.parentNode;
  5118. } : function (elem, context, xml) {
  5119. var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? 'nextSibling' : 'previousSibling', parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType;
  5120. if (parent) {
  5121. if (simple) {
  5122. while (dir) {
  5123. node = elem;
  5124. while (node = node[dir]) {
  5125. if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
  5126. return false;
  5127. }
  5128. }
  5129. start = dir = type === 'only' && !start && 'nextSibling';
  5130. }
  5131. return true;
  5132. }
  5133. start = [forward ? parent.firstChild : parent.lastChild];
  5134. if (forward && useCache) {
  5135. outerCache = parent[expando] || (parent[expando] = {});
  5136. cache = outerCache[type] || [];
  5137. nodeIndex = cache[0] === dirruns && cache[1];
  5138. diff = cache[0] === dirruns && cache[2];
  5139. node = nodeIndex && parent.childNodes[nodeIndex];
  5140. while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5141. if (node.nodeType === 1 && ++diff && node === elem) {
  5142. outerCache[type] = [
  5143. dirruns,
  5144. nodeIndex,
  5145. diff
  5146. ];
  5147. break;
  5148. }
  5149. }
  5150. } else if (useCache && (cache = (elem[expando] || (elem[expando] = {}))[type]) && cache[0] === dirruns) {
  5151. diff = cache[1];
  5152. } else {
  5153. while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5154. if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) {
  5155. if (useCache) {
  5156. (node[expando] || (node[expando] = {}))[type] = [
  5157. dirruns,
  5158. diff
  5159. ];
  5160. }
  5161. if (node === elem) {
  5162. break;
  5163. }
  5164. }
  5165. }
  5166. }
  5167. diff -= last;
  5168. return diff === first || diff % first === 0 && diff / first >= 0;
  5169. }
  5170. };
  5171. },
  5172. PSEUDO: function (pseudo, argument) {
  5173. var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error('unsupported pseudo: ' + pseudo);
  5174. if (fn[expando]) {
  5175. return fn(argument);
  5176. }
  5177. if (fn.length > 1) {
  5178. args = [
  5179. pseudo,
  5180. pseudo,
  5181. '',
  5182. argument
  5183. ];
  5184. return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) {
  5185. var idx, matched = fn(seed, argument), i = matched.length;
  5186. while (i--) {
  5187. idx = indexOf.call(seed, matched[i]);
  5188. seed[idx] = !(matches[idx] = matched[i]);
  5189. }
  5190. }) : function (elem) {
  5191. return fn(elem, 0, args);
  5192. };
  5193. }
  5194. return fn;
  5195. }
  5196. },
  5197. pseudos: {
  5198. not: markFunction(function (selector) {
  5199. var input = [], results = [], matcher = compile(selector.replace(rtrim, '$1'));
  5200. return matcher[expando] ? markFunction(function (seed, matches, context, xml) {
  5201. var elem, unmatched = matcher(seed, null, xml, []), i = seed.length;
  5202. while (i--) {
  5203. if (elem = unmatched[i]) {
  5204. seed[i] = !(matches[i] = elem);
  5205. }
  5206. }
  5207. }) : function (elem, context, xml) {
  5208. input[0] = elem;
  5209. matcher(input, null, xml, results);
  5210. input[0] = null;
  5211. return !results.pop();
  5212. };
  5213. }),
  5214. has: markFunction(function (selector) {
  5215. return function (elem) {
  5216. return Sizzle(selector, elem).length > 0;
  5217. };
  5218. }),
  5219. contains: markFunction(function (text) {
  5220. text = text.replace(runescape, funescape);
  5221. return function (elem) {
  5222. return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1;
  5223. };
  5224. }),
  5225. lang: markFunction(function (lang) {
  5226. if (!ridentifier.test(lang || '')) {
  5227. Sizzle.error('unsupported lang: ' + lang);
  5228. }
  5229. lang = lang.replace(runescape, funescape).toLowerCase();
  5230. return function (elem) {
  5231. var elemLang;
  5232. do {
  5233. if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute('xml:lang') || elem.getAttribute('lang')) {
  5234. elemLang = elemLang.toLowerCase();
  5235. return elemLang === lang || elemLang.indexOf(lang + '-') === 0;
  5236. }
  5237. } while ((elem = elem.parentNode) && elem.nodeType === 1);
  5238. return false;
  5239. };
  5240. }),
  5241. target: function (elem) {
  5242. var hash = window.location && window.location.hash;
  5243. return hash && hash.slice(1) === elem.id;
  5244. },
  5245. root: function (elem) {
  5246. return elem === docElem;
  5247. },
  5248. focus: function (elem) {
  5249. return elem === document$1.activeElement && (!document$1.hasFocus || document$1.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
  5250. },
  5251. enabled: function (elem) {
  5252. return elem.disabled === false;
  5253. },
  5254. disabled: function (elem) {
  5255. return elem.disabled === true;
  5256. },
  5257. checked: function (elem) {
  5258. var nodeName = elem.nodeName.toLowerCase();
  5259. return nodeName === 'input' && !!elem.checked || nodeName === 'option' && !!elem.selected;
  5260. },
  5261. selected: function (elem) {
  5262. if (elem.parentNode) {
  5263. elem.parentNode.selectedIndex;
  5264. }
  5265. return elem.selected === true;
  5266. },
  5267. empty: function (elem) {
  5268. for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5269. if (elem.nodeType < 6) {
  5270. return false;
  5271. }
  5272. }
  5273. return true;
  5274. },
  5275. parent: function (elem) {
  5276. return !Expr.pseudos.empty(elem);
  5277. },
  5278. header: function (elem) {
  5279. return rheader.test(elem.nodeName);
  5280. },
  5281. input: function (elem) {
  5282. return rinputs.test(elem.nodeName);
  5283. },
  5284. button: function (elem) {
  5285. var name = elem.nodeName.toLowerCase();
  5286. return name === 'input' && elem.type === 'button' || name === 'button';
  5287. },
  5288. text: function (elem) {
  5289. var attr;
  5290. return elem.nodeName.toLowerCase() === 'input' && elem.type === 'text' && ((attr = elem.getAttribute('type')) == null || attr.toLowerCase() === 'text');
  5291. },
  5292. first: createPositionalPseudo(function () {
  5293. return [0];
  5294. }),
  5295. last: createPositionalPseudo(function (matchIndexes, length) {
  5296. return [length - 1];
  5297. }),
  5298. eq: createPositionalPseudo(function (matchIndexes, length, argument) {
  5299. return [argument < 0 ? argument + length : argument];
  5300. }),
  5301. even: createPositionalPseudo(function (matchIndexes, length) {
  5302. var i = 0;
  5303. for (; i < length; i += 2) {
  5304. matchIndexes.push(i);
  5305. }
  5306. return matchIndexes;
  5307. }),
  5308. odd: createPositionalPseudo(function (matchIndexes, length) {
  5309. var i = 1;
  5310. for (; i < length; i += 2) {
  5311. matchIndexes.push(i);
  5312. }
  5313. return matchIndexes;
  5314. }),
  5315. lt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5316. var i = argument < 0 ? argument + length : argument;
  5317. for (; --i >= 0;) {
  5318. matchIndexes.push(i);
  5319. }
  5320. return matchIndexes;
  5321. }),
  5322. gt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5323. var i = argument < 0 ? argument + length : argument;
  5324. for (; ++i < length;) {
  5325. matchIndexes.push(i);
  5326. }
  5327. return matchIndexes;
  5328. })
  5329. }
  5330. };
  5331. Expr.pseudos.nth = Expr.pseudos.eq;
  5332. each$k([
  5333. 'radio',
  5334. 'checkbox',
  5335. 'file',
  5336. 'password',
  5337. 'image'
  5338. ], function (i) {
  5339. Expr.pseudos[i] = createInputPseudo(i);
  5340. });
  5341. each$k([
  5342. 'submit',
  5343. 'reset'
  5344. ], function (i) {
  5345. Expr.pseudos[i] = createButtonPseudo(i);
  5346. });
  5347. function setFilters() {
  5348. }
  5349. setFilters.prototype = Expr.filters = Expr.pseudos;
  5350. Expr.setFilters = new setFilters();
  5351. tokenize = Sizzle.tokenize = function (selector, parseOnly) {
  5352. var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + ' '];
  5353. if (cached) {
  5354. return parseOnly ? 0 : cached.slice(0);
  5355. }
  5356. soFar = selector;
  5357. groups = [];
  5358. preFilters = Expr.preFilter;
  5359. while (soFar) {
  5360. if (!matched || (match = rcomma.exec(soFar))) {
  5361. if (match) {
  5362. soFar = soFar.slice(match[0].length) || soFar;
  5363. }
  5364. groups.push(tokens = []);
  5365. }
  5366. matched = false;
  5367. if (match = rcombinators.exec(soFar)) {
  5368. matched = match.shift();
  5369. tokens.push({
  5370. value: matched,
  5371. type: match[0].replace(rtrim, ' ')
  5372. });
  5373. soFar = soFar.slice(matched.length);
  5374. }
  5375. for (type in Expr.filter) {
  5376. if (!Expr.filter.hasOwnProperty(type)) {
  5377. continue;
  5378. }
  5379. if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) {
  5380. matched = match.shift();
  5381. tokens.push({
  5382. value: matched,
  5383. type: type,
  5384. matches: match
  5385. });
  5386. soFar = soFar.slice(matched.length);
  5387. }
  5388. }
  5389. if (!matched) {
  5390. break;
  5391. }
  5392. }
  5393. return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : tokenCache(selector, groups).slice(0);
  5394. };
  5395. function toSelector(tokens) {
  5396. var i = 0, len = tokens.length, selector = '';
  5397. for (; i < len; i++) {
  5398. selector += tokens[i].value;
  5399. }
  5400. return selector;
  5401. }
  5402. function addCombinator(matcher, combinator, base) {
  5403. var dir = combinator.dir, checkNonElements = base && dir === 'parentNode', doneName = done++;
  5404. return combinator.first ? function (elem, context, xml) {
  5405. while (elem = elem[dir]) {
  5406. if (elem.nodeType === 1 || checkNonElements) {
  5407. return matcher(elem, context, xml);
  5408. }
  5409. }
  5410. } : function (elem, context, xml) {
  5411. var oldCache, outerCache, newCache = [
  5412. dirruns,
  5413. doneName
  5414. ];
  5415. if (xml) {
  5416. while (elem = elem[dir]) {
  5417. if (elem.nodeType === 1 || checkNonElements) {
  5418. if (matcher(elem, context, xml)) {
  5419. return true;
  5420. }
  5421. }
  5422. }
  5423. } else {
  5424. while (elem = elem[dir]) {
  5425. if (elem.nodeType === 1 || checkNonElements) {
  5426. outerCache = elem[expando] || (elem[expando] = {});
  5427. if ((oldCache = outerCache[dir]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
  5428. return newCache[2] = oldCache[2];
  5429. } else {
  5430. outerCache[dir] = newCache;
  5431. if (newCache[2] = matcher(elem, context, xml)) {
  5432. return true;
  5433. }
  5434. }
  5435. }
  5436. }
  5437. }
  5438. };
  5439. }
  5440. function elementMatcher(matchers) {
  5441. return matchers.length > 1 ? function (elem, context, xml) {
  5442. var i = matchers.length;
  5443. while (i--) {
  5444. if (!matchers[i](elem, context, xml)) {
  5445. return false;
  5446. }
  5447. }
  5448. return true;
  5449. } : matchers[0];
  5450. }
  5451. function multipleContexts(selector, contexts, results) {
  5452. var i = 0, len = contexts.length;
  5453. for (; i < len; i++) {
  5454. Sizzle(selector, contexts[i], results);
  5455. }
  5456. return results;
  5457. }
  5458. function condense(unmatched, map, filter, context, xml) {
  5459. var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null;
  5460. for (; i < len; i++) {
  5461. if (elem = unmatched[i]) {
  5462. if (!filter || filter(elem, context, xml)) {
  5463. newUnmatched.push(elem);
  5464. if (mapped) {
  5465. map.push(i);
  5466. }
  5467. }
  5468. }
  5469. }
  5470. return newUnmatched;
  5471. }
  5472. function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
  5473. if (postFilter && !postFilter[expando]) {
  5474. postFilter = setMatcher(postFilter);
  5475. }
  5476. if (postFinder && !postFinder[expando]) {
  5477. postFinder = setMatcher(postFinder, postSelector);
  5478. }
  5479. return markFunction(function (seed, results, context, xml) {
  5480. var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, elems = seed || multipleContexts(selector || '*', context.nodeType ? [context] : context, []), matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems, matcherOut = matcher ? postFinder || (seed ? preFilter : preexisting || postFilter) ? [] : results : matcherIn;
  5481. if (matcher) {
  5482. matcher(matcherIn, matcherOut, context, xml);
  5483. }
  5484. if (postFilter) {
  5485. temp = condense(matcherOut, postMap);
  5486. postFilter(temp, [], context, xml);
  5487. i = temp.length;
  5488. while (i--) {
  5489. if (elem = temp[i]) {
  5490. matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
  5491. }
  5492. }
  5493. }
  5494. if (seed) {
  5495. if (postFinder || preFilter) {
  5496. if (postFinder) {
  5497. temp = [];
  5498. i = matcherOut.length;
  5499. while (i--) {
  5500. if (elem = matcherOut[i]) {
  5501. temp.push(matcherIn[i] = elem);
  5502. }
  5503. }
  5504. postFinder(null, matcherOut = [], temp, xml);
  5505. }
  5506. i = matcherOut.length;
  5507. while (i--) {
  5508. if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf.call(seed, elem) : preMap[i]) > -1) {
  5509. seed[temp] = !(results[temp] = elem);
  5510. }
  5511. }
  5512. }
  5513. } else {
  5514. matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
  5515. if (postFinder) {
  5516. postFinder(null, results, matcherOut, xml);
  5517. } else {
  5518. push$1.apply(results, matcherOut);
  5519. }
  5520. }
  5521. });
  5522. }
  5523. function matcherFromTokens(tokens) {
  5524. var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[tokens[0].type], implicitRelative = leadingRelative || Expr.relative[' '], i = leadingRelative ? 1 : 0, matchContext = addCombinator(function (elem) {
  5525. return elem === checkContext;
  5526. }, implicitRelative, true), matchAnyContext = addCombinator(function (elem) {
  5527. return indexOf.call(checkContext, elem) > -1;
  5528. }, implicitRelative, true), matchers = [function (elem, context, xml) {
  5529. var ret = !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
  5530. checkContext = null;
  5531. return ret;
  5532. }];
  5533. for (; i < len; i++) {
  5534. if (matcher = Expr.relative[tokens[i].type]) {
  5535. matchers = [addCombinator(elementMatcher(matchers), matcher)];
  5536. } else {
  5537. matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);
  5538. if (matcher[expando]) {
  5539. j = ++i;
  5540. for (; j < len; j++) {
  5541. if (Expr.relative[tokens[j].type]) {
  5542. break;
  5543. }
  5544. }
  5545. return setMatcher(i > 1 && elementMatcher(matchers), i > 1 && toSelector(tokens.slice(0, i - 1).concat({ value: tokens[i - 2].type === ' ' ? '*' : '' })).replace(rtrim, '$1'), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens(tokens = tokens.slice(j)), j < len && toSelector(tokens));
  5546. }
  5547. matchers.push(matcher);
  5548. }
  5549. }
  5550. return elementMatcher(matchers);
  5551. }
  5552. function matcherFromGroupMatchers(elementMatchers, setMatchers) {
  5553. var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function (seed, context, xml, results, outermost) {
  5554. var elem, j, matcher, matchedCount = 0, i = '0', unmatched = seed && [], setMatched = [], contextBackup = outermostContext, elems = seed || byElement && Expr.find.TAG('*', outermost), dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1, len = elems.length;
  5555. if (outermost) {
  5556. outermostContext = context !== document$1 && context;
  5557. }
  5558. for (; i !== len && (elem = elems[i]) != null; i++) {
  5559. if (byElement && elem) {
  5560. j = 0;
  5561. while (matcher = elementMatchers[j++]) {
  5562. if (matcher(elem, context, xml)) {
  5563. results.push(elem);
  5564. break;
  5565. }
  5566. }
  5567. if (outermost) {
  5568. dirruns = dirrunsUnique;
  5569. }
  5570. }
  5571. if (bySet) {
  5572. if (elem = !matcher && elem) {
  5573. matchedCount--;
  5574. }
  5575. if (seed) {
  5576. unmatched.push(elem);
  5577. }
  5578. }
  5579. }
  5580. matchedCount += i;
  5581. if (bySet && i !== matchedCount) {
  5582. j = 0;
  5583. while (matcher = setMatchers[j++]) {
  5584. matcher(unmatched, setMatched, context, xml);
  5585. }
  5586. if (seed) {
  5587. if (matchedCount > 0) {
  5588. while (i--) {
  5589. if (!(unmatched[i] || setMatched[i])) {
  5590. setMatched[i] = pop.call(results);
  5591. }
  5592. }
  5593. }
  5594. setMatched = condense(setMatched);
  5595. }
  5596. push$1.apply(results, setMatched);
  5597. if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
  5598. Sizzle.uniqueSort(results);
  5599. }
  5600. }
  5601. if (outermost) {
  5602. dirruns = dirrunsUnique;
  5603. outermostContext = contextBackup;
  5604. }
  5605. return unmatched;
  5606. };
  5607. return bySet ? markFunction(superMatcher) : superMatcher;
  5608. }
  5609. compile = Sizzle.compile = function (selector, match) {
  5610. var i, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + ' '];
  5611. if (!cached) {
  5612. if (!match) {
  5613. match = tokenize(selector);
  5614. }
  5615. i = match.length;
  5616. while (i--) {
  5617. cached = matcherFromTokens(match[i]);
  5618. if (cached[expando]) {
  5619. setMatchers.push(cached);
  5620. } else {
  5621. elementMatchers.push(cached);
  5622. }
  5623. }
  5624. cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
  5625. cached.selector = selector;
  5626. }
  5627. return cached;
  5628. };
  5629. select$1 = Sizzle.select = function (selector, context, results, seed) {
  5630. var i, tokens, token, type, find, compiled = typeof selector === 'function' && selector, match = !seed && tokenize(selector = compiled.selector || selector);
  5631. results = results || [];
  5632. if (match.length === 1) {
  5633. tokens = match[0] = match[0].slice(0);
  5634. if (tokens.length > 2 && (token = tokens[0]).type === 'ID' && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
  5635. context = (Expr.find.ID(token.matches[0].replace(runescape, funescape), context) || [])[0];
  5636. if (!context) {
  5637. return results;
  5638. } else if (compiled) {
  5639. context = context.parentNode;
  5640. }
  5641. selector = selector.slice(tokens.shift().value.length);
  5642. }
  5643. i = matchExpr.needsContext.test(selector) ? 0 : tokens.length;
  5644. while (i--) {
  5645. token = tokens[i];
  5646. if (Expr.relative[type = token.type]) {
  5647. break;
  5648. }
  5649. if (find = Expr.find[type]) {
  5650. if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {
  5651. tokens.splice(i, 1);
  5652. selector = seed.length && toSelector(tokens);
  5653. if (!selector) {
  5654. push$1.apply(results, seed);
  5655. return results;
  5656. }
  5657. break;
  5658. }
  5659. }
  5660. }
  5661. }
  5662. (compiled || compile(selector, match))(seed, context, !documentIsHTML, results, rsibling.test(selector) && testContext(context.parentNode) || context);
  5663. return results;
  5664. };
  5665. support.sortStable = expando.split('').sort(sortOrder).join('') === expando;
  5666. support.detectDuplicates = !!hasDuplicate;
  5667. setDocument();
  5668. support.sortDetached = true;
  5669. var doc = document;
  5670. var push = Array.prototype.push;
  5671. var slice = Array.prototype.slice;
  5672. var rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
  5673. var Event$1 = EventUtils.Event;
  5674. var skipUniques = Tools.makeMap('children,contents,next,prev');
  5675. var isDefined = function (obj) {
  5676. return typeof obj !== 'undefined';
  5677. };
  5678. var isString = function (obj) {
  5679. return typeof obj === 'string';
  5680. };
  5681. var isWindow = function (obj) {
  5682. return obj && obj === obj.window;
  5683. };
  5684. var createFragment$1 = function (html, fragDoc) {
  5685. fragDoc = fragDoc || doc;
  5686. var container = fragDoc.createElement('div');
  5687. var frag = fragDoc.createDocumentFragment();
  5688. container.innerHTML = html;
  5689. var node;
  5690. while (node = container.firstChild) {
  5691. frag.appendChild(node);
  5692. }
  5693. return frag;
  5694. };
  5695. var domManipulate = function (targetNodes, sourceItem, callback, reverse) {
  5696. var i;
  5697. if (isString(sourceItem)) {
  5698. sourceItem = createFragment$1(sourceItem, getElementDocument(targetNodes[0]));
  5699. } else if (sourceItem.length && !sourceItem.nodeType) {
  5700. sourceItem = DomQuery.makeArray(sourceItem);
  5701. if (reverse) {
  5702. for (i = sourceItem.length - 1; i >= 0; i--) {
  5703. domManipulate(targetNodes, sourceItem[i], callback, reverse);
  5704. }
  5705. } else {
  5706. for (i = 0; i < sourceItem.length; i++) {
  5707. domManipulate(targetNodes, sourceItem[i], callback, reverse);
  5708. }
  5709. }
  5710. return targetNodes;
  5711. }
  5712. if (sourceItem.nodeType) {
  5713. i = targetNodes.length;
  5714. while (i--) {
  5715. callback.call(targetNodes[i], sourceItem);
  5716. }
  5717. }
  5718. return targetNodes;
  5719. };
  5720. var hasClass = function (node, className) {
  5721. return node && className && (' ' + node.className + ' ').indexOf(' ' + className + ' ') !== -1;
  5722. };
  5723. var wrap$2 = function (elements, wrapper, all) {
  5724. var lastParent, newWrapper;
  5725. wrapper = DomQuery(wrapper)[0];
  5726. elements.each(function () {
  5727. var self = this;
  5728. if (!all || lastParent !== self.parentNode) {
  5729. lastParent = self.parentNode;
  5730. newWrapper = wrapper.cloneNode(false);
  5731. self.parentNode.insertBefore(newWrapper, self);
  5732. newWrapper.appendChild(self);
  5733. } else {
  5734. newWrapper.appendChild(self);
  5735. }
  5736. });
  5737. return elements;
  5738. };
  5739. var numericCssMap = Tools.makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom', ' ');
  5740. var booleanMap = Tools.makeMap('checked compact declare defer disabled ismap multiple nohref noshade nowrap readonly selected', ' ');
  5741. var propFix = {
  5742. for: 'htmlFor',
  5743. class: 'className',
  5744. readonly: 'readOnly'
  5745. };
  5746. var cssFix = { float: 'cssFloat' };
  5747. var attrHooks = {}, cssHooks = {};
  5748. var DomQueryConstructor = function (selector, context) {
  5749. return new DomQuery.fn.init(selector, context);
  5750. };
  5751. var inArray$1 = function (item, array) {
  5752. var i;
  5753. if (array.indexOf) {
  5754. return array.indexOf(item);
  5755. }
  5756. i = array.length;
  5757. while (i--) {
  5758. if (array[i] === item) {
  5759. return i;
  5760. }
  5761. }
  5762. return -1;
  5763. };
  5764. var whiteSpaceRegExp = /^\s*|\s*$/g;
  5765. var trim$1 = function (str) {
  5766. return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp, '');
  5767. };
  5768. var each$g = function (obj, callback) {
  5769. var length, key, i, value;
  5770. if (obj) {
  5771. length = obj.length;
  5772. if (length === undefined) {
  5773. for (key in obj) {
  5774. if (obj.hasOwnProperty(key)) {
  5775. value = obj[key];
  5776. if (callback.call(value, key, value) === false) {
  5777. break;
  5778. }
  5779. }
  5780. }
  5781. } else {
  5782. for (i = 0; i < length; i++) {
  5783. value = obj[i];
  5784. if (callback.call(value, i, value) === false) {
  5785. break;
  5786. }
  5787. }
  5788. }
  5789. }
  5790. return obj;
  5791. };
  5792. var grep$2 = function (array, callback) {
  5793. var out = [];
  5794. each$g(array, function (i, item) {
  5795. if (callback(item, i)) {
  5796. out.push(item);
  5797. }
  5798. });
  5799. return out;
  5800. };
  5801. var getElementDocument = function (element) {
  5802. if (!element) {
  5803. return doc;
  5804. }
  5805. if (element.nodeType === 9) {
  5806. return element;
  5807. }
  5808. return element.ownerDocument;
  5809. };
  5810. DomQueryConstructor.fn = DomQueryConstructor.prototype = {
  5811. constructor: DomQueryConstructor,
  5812. selector: '',
  5813. context: null,
  5814. length: 0,
  5815. init: function (selector, context) {
  5816. var self = this;
  5817. var match, node;
  5818. if (!selector) {
  5819. return self;
  5820. }
  5821. if (selector.nodeType) {
  5822. self.context = self[0] = selector;
  5823. self.length = 1;
  5824. return self;
  5825. }
  5826. if (context && context.nodeType) {
  5827. self.context = context;
  5828. } else {
  5829. if (context) {
  5830. return DomQuery(selector).attr(context);
  5831. }
  5832. self.context = context = document;
  5833. }
  5834. if (isString(selector)) {
  5835. self.selector = selector;
  5836. if (selector.charAt(0) === '<' && selector.charAt(selector.length - 1) === '>' && selector.length >= 3) {
  5837. match = [
  5838. null,
  5839. selector,
  5840. null
  5841. ];
  5842. } else {
  5843. match = rquickExpr.exec(selector);
  5844. }
  5845. if (match) {
  5846. if (match[1]) {
  5847. node = createFragment$1(selector, getElementDocument(context)).firstChild;
  5848. while (node) {
  5849. push.call(self, node);
  5850. node = node.nextSibling;
  5851. }
  5852. } else {
  5853. node = getElementDocument(context).getElementById(match[2]);
  5854. if (!node) {
  5855. return self;
  5856. }
  5857. if (node.id !== match[2]) {
  5858. return self.find(selector);
  5859. }
  5860. self.length = 1;
  5861. self[0] = node;
  5862. }
  5863. } else {
  5864. return DomQuery(context).find(selector);
  5865. }
  5866. } else {
  5867. this.add(selector, false);
  5868. }
  5869. return self;
  5870. },
  5871. toArray: function () {
  5872. return Tools.toArray(this);
  5873. },
  5874. add: function (items, sort) {
  5875. var self = this;
  5876. var nodes, i;
  5877. if (isString(items)) {
  5878. return self.add(DomQuery(items));
  5879. }
  5880. if (sort !== false) {
  5881. nodes = DomQuery.unique(self.toArray().concat(DomQuery.makeArray(items)));
  5882. self.length = nodes.length;
  5883. for (i = 0; i < nodes.length; i++) {
  5884. self[i] = nodes[i];
  5885. }
  5886. } else {
  5887. push.apply(self, DomQuery.makeArray(items));
  5888. }
  5889. return self;
  5890. },
  5891. attr: function (name, value) {
  5892. var self = this;
  5893. var hook;
  5894. if (typeof name === 'object') {
  5895. each$g(name, function (name, value) {
  5896. self.attr(name, value);
  5897. });
  5898. } else if (isDefined(value)) {
  5899. this.each(function () {
  5900. var hook;
  5901. if (this.nodeType === 1) {
  5902. hook = attrHooks[name];
  5903. if (hook && hook.set) {
  5904. hook.set(this, value);
  5905. return;
  5906. }
  5907. if (value === null) {
  5908. this.removeAttribute(name, 2);
  5909. } else {
  5910. this.setAttribute(name, value, 2);
  5911. }
  5912. }
  5913. });
  5914. } else {
  5915. if (self[0] && self[0].nodeType === 1) {
  5916. hook = attrHooks[name];
  5917. if (hook && hook.get) {
  5918. return hook.get(self[0], name);
  5919. }
  5920. if (booleanMap[name]) {
  5921. return self.prop(name) ? name : undefined;
  5922. }
  5923. value = self[0].getAttribute(name, 2);
  5924. if (value === null) {
  5925. value = undefined;
  5926. }
  5927. }
  5928. return value;
  5929. }
  5930. return self;
  5931. },
  5932. removeAttr: function (name) {
  5933. return this.attr(name, null);
  5934. },
  5935. prop: function (name, value) {
  5936. var self = this;
  5937. name = propFix[name] || name;
  5938. if (typeof name === 'object') {
  5939. each$g(name, function (name, value) {
  5940. self.prop(name, value);
  5941. });
  5942. } else if (isDefined(value)) {
  5943. this.each(function () {
  5944. if (this.nodeType === 1) {
  5945. this[name] = value;
  5946. }
  5947. });
  5948. } else {
  5949. if (self[0] && self[0].nodeType && name in self[0]) {
  5950. return self[0][name];
  5951. }
  5952. return value;
  5953. }
  5954. return self;
  5955. },
  5956. css: function (name, value) {
  5957. var self = this;
  5958. var elm, hook;
  5959. var camel = function (name) {
  5960. return name.replace(/-(\D)/g, function (a, b) {
  5961. return b.toUpperCase();
  5962. });
  5963. };
  5964. var dashed = function (name) {
  5965. return name.replace(/[A-Z]/g, function (a) {
  5966. return '-' + a;
  5967. });
  5968. };
  5969. if (typeof name === 'object') {
  5970. each$g(name, function (name, value) {
  5971. self.css(name, value);
  5972. });
  5973. } else {
  5974. if (isDefined(value)) {
  5975. name = camel(name);
  5976. if (typeof value === 'number' && !numericCssMap[name]) {
  5977. value = value.toString() + 'px';
  5978. }
  5979. self.each(function () {
  5980. var style = this.style;
  5981. hook = cssHooks[name];
  5982. if (hook && hook.set) {
  5983. hook.set(this, value);
  5984. return;
  5985. }
  5986. try {
  5987. this.style[cssFix[name] || name] = value;
  5988. } catch (ex) {
  5989. }
  5990. if (value === null || value === '') {
  5991. if (style.removeProperty) {
  5992. style.removeProperty(dashed(name));
  5993. } else {
  5994. style.removeAttribute(name);
  5995. }
  5996. }
  5997. });
  5998. } else {
  5999. elm = self[0];
  6000. hook = cssHooks[name];
  6001. if (hook && hook.get) {
  6002. return hook.get(elm);
  6003. }
  6004. if (elm.ownerDocument.defaultView) {
  6005. try {
  6006. return elm.ownerDocument.defaultView.getComputedStyle(elm, null).getPropertyValue(dashed(name));
  6007. } catch (ex) {
  6008. return undefined;
  6009. }
  6010. } else if (elm.currentStyle) {
  6011. return elm.currentStyle[camel(name)];
  6012. } else {
  6013. return '';
  6014. }
  6015. }
  6016. }
  6017. return self;
  6018. },
  6019. remove: function () {
  6020. var self = this;
  6021. var node, i = this.length;
  6022. while (i--) {
  6023. node = self[i];
  6024. Event$1.clean(node);
  6025. if (node.parentNode) {
  6026. node.parentNode.removeChild(node);
  6027. }
  6028. }
  6029. return this;
  6030. },
  6031. empty: function () {
  6032. var self = this;
  6033. var node, i = this.length;
  6034. while (i--) {
  6035. node = self[i];
  6036. while (node.firstChild) {
  6037. node.removeChild(node.firstChild);
  6038. }
  6039. }
  6040. return this;
  6041. },
  6042. html: function (value) {
  6043. var self = this;
  6044. var i;
  6045. if (isDefined(value)) {
  6046. i = self.length;
  6047. try {
  6048. while (i--) {
  6049. self[i].innerHTML = value;
  6050. }
  6051. } catch (ex) {
  6052. DomQuery(self[i]).empty().append(value);
  6053. }
  6054. return self;
  6055. }
  6056. return self[0] ? self[0].innerHTML : '';
  6057. },
  6058. text: function (value) {
  6059. var self = this;
  6060. var i;
  6061. if (isDefined(value)) {
  6062. i = self.length;
  6063. while (i--) {
  6064. if ('innerText' in self[i]) {
  6065. self[i].innerText = value;
  6066. } else {
  6067. self[0].textContent = value;
  6068. }
  6069. }
  6070. return self;
  6071. }
  6072. return self[0] ? self[0].innerText || self[0].textContent : '';
  6073. },
  6074. append: function () {
  6075. return domManipulate(this, arguments, function (node) {
  6076. if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6077. this.appendChild(node);
  6078. }
  6079. });
  6080. },
  6081. prepend: function () {
  6082. return domManipulate(this, arguments, function (node) {
  6083. if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6084. this.insertBefore(node, this.firstChild);
  6085. }
  6086. }, true);
  6087. },
  6088. before: function () {
  6089. var self = this;
  6090. if (self[0] && self[0].parentNode) {
  6091. return domManipulate(self, arguments, function (node) {
  6092. this.parentNode.insertBefore(node, this);
  6093. });
  6094. }
  6095. return self;
  6096. },
  6097. after: function () {
  6098. var self = this;
  6099. if (self[0] && self[0].parentNode) {
  6100. return domManipulate(self, arguments, function (node) {
  6101. this.parentNode.insertBefore(node, this.nextSibling);
  6102. }, true);
  6103. }
  6104. return self;
  6105. },
  6106. appendTo: function (val) {
  6107. DomQuery(val).append(this);
  6108. return this;
  6109. },
  6110. prependTo: function (val) {
  6111. DomQuery(val).prepend(this);
  6112. return this;
  6113. },
  6114. replaceWith: function (content) {
  6115. return this.before(content).remove();
  6116. },
  6117. wrap: function (content) {
  6118. return wrap$2(this, content);
  6119. },
  6120. wrapAll: function (content) {
  6121. return wrap$2(this, content, true);
  6122. },
  6123. wrapInner: function (content) {
  6124. this.each(function () {
  6125. DomQuery(this).contents().wrapAll(content);
  6126. });
  6127. return this;
  6128. },
  6129. unwrap: function () {
  6130. return this.parent().each(function () {
  6131. DomQuery(this).replaceWith(this.childNodes);
  6132. });
  6133. },
  6134. clone: function () {
  6135. var result = [];
  6136. this.each(function () {
  6137. result.push(this.cloneNode(true));
  6138. });
  6139. return DomQuery(result);
  6140. },
  6141. addClass: function (className) {
  6142. return this.toggleClass(className, true);
  6143. },
  6144. removeClass: function (className) {
  6145. return this.toggleClass(className, false);
  6146. },
  6147. toggleClass: function (className, state) {
  6148. var self = this;
  6149. if (typeof className !== 'string') {
  6150. return self;
  6151. }
  6152. if (className.indexOf(' ') !== -1) {
  6153. each$g(className.split(' '), function () {
  6154. self.toggleClass(this, state);
  6155. });
  6156. } else {
  6157. self.each(function (index, node) {
  6158. var classState = hasClass(node, className);
  6159. if (classState !== state) {
  6160. var existingClassName = node.className;
  6161. if (classState) {
  6162. node.className = trim$1((' ' + existingClassName + ' ').replace(' ' + className + ' ', ' '));
  6163. } else {
  6164. node.className += existingClassName ? ' ' + className : className;
  6165. }
  6166. }
  6167. });
  6168. }
  6169. return self;
  6170. },
  6171. hasClass: function (className) {
  6172. return hasClass(this[0], className);
  6173. },
  6174. each: function (callback) {
  6175. return each$g(this, callback);
  6176. },
  6177. on: function (name, callback) {
  6178. return this.each(function () {
  6179. Event$1.bind(this, name, callback);
  6180. });
  6181. },
  6182. off: function (name, callback) {
  6183. return this.each(function () {
  6184. Event$1.unbind(this, name, callback);
  6185. });
  6186. },
  6187. trigger: function (name) {
  6188. return this.each(function () {
  6189. if (typeof name === 'object') {
  6190. Event$1.fire(this, name.type, name);
  6191. } else {
  6192. Event$1.fire(this, name);
  6193. }
  6194. });
  6195. },
  6196. show: function () {
  6197. return this.css('display', '');
  6198. },
  6199. hide: function () {
  6200. return this.css('display', 'none');
  6201. },
  6202. slice: function () {
  6203. return DomQuery(slice.apply(this, arguments));
  6204. },
  6205. eq: function (index) {
  6206. return index === -1 ? this.slice(index) : this.slice(index, +index + 1);
  6207. },
  6208. first: function () {
  6209. return this.eq(0);
  6210. },
  6211. last: function () {
  6212. return this.eq(-1);
  6213. },
  6214. find: function (selector) {
  6215. var i, l;
  6216. var ret = [];
  6217. for (i = 0, l = this.length; i < l; i++) {
  6218. DomQuery.find(selector, this[i], ret);
  6219. }
  6220. return DomQuery(ret);
  6221. },
  6222. filter: function (selector) {
  6223. if (typeof selector === 'function') {
  6224. return DomQuery(grep$2(this.toArray(), function (item, i) {
  6225. return selector(i, item);
  6226. }));
  6227. }
  6228. return DomQuery(DomQuery.filter(selector, this.toArray()));
  6229. },
  6230. closest: function (selector) {
  6231. var result = [];
  6232. if (selector instanceof DomQuery) {
  6233. selector = selector[0];
  6234. }
  6235. this.each(function (i, node) {
  6236. while (node) {
  6237. if (typeof selector === 'string' && DomQuery(node).is(selector)) {
  6238. result.push(node);
  6239. break;
  6240. } else if (node === selector) {
  6241. result.push(node);
  6242. break;
  6243. }
  6244. node = node.parentNode;
  6245. }
  6246. });
  6247. return DomQuery(result);
  6248. },
  6249. offset: function (offset) {
  6250. var elm, doc, docElm;
  6251. var x = 0, y = 0, pos;
  6252. if (!offset) {
  6253. elm = this[0];
  6254. if (elm) {
  6255. doc = elm.ownerDocument;
  6256. docElm = doc.documentElement;
  6257. if (elm.getBoundingClientRect) {
  6258. pos = elm.getBoundingClientRect();
  6259. x = pos.left + (docElm.scrollLeft || doc.body.scrollLeft) - docElm.clientLeft;
  6260. y = pos.top + (docElm.scrollTop || doc.body.scrollTop) - docElm.clientTop;
  6261. }
  6262. }
  6263. return {
  6264. left: x,
  6265. top: y
  6266. };
  6267. }
  6268. return this.css(offset);
  6269. },
  6270. push: push,
  6271. sort: Array.prototype.sort,
  6272. splice: Array.prototype.splice
  6273. };
  6274. Tools.extend(DomQueryConstructor, {
  6275. extend: Tools.extend,
  6276. makeArray: function (object) {
  6277. if (isWindow(object) || object.nodeType) {
  6278. return [object];
  6279. }
  6280. return Tools.toArray(object);
  6281. },
  6282. inArray: inArray$1,
  6283. isArray: Tools.isArray,
  6284. each: each$g,
  6285. trim: trim$1,
  6286. grep: grep$2,
  6287. find: Sizzle,
  6288. expr: Sizzle.selectors,
  6289. unique: Sizzle.uniqueSort,
  6290. text: Sizzle.getText,
  6291. contains: Sizzle.contains,
  6292. filter: function (expr, elems, not) {
  6293. var i = elems.length;
  6294. if (not) {
  6295. expr = ':not(' + expr + ')';
  6296. }
  6297. while (i--) {
  6298. if (elems[i].nodeType !== 1) {
  6299. elems.splice(i, 1);
  6300. }
  6301. }
  6302. if (elems.length === 1) {
  6303. elems = DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [];
  6304. } else {
  6305. elems = DomQuery.find.matches(expr, elems);
  6306. }
  6307. return elems;
  6308. }
  6309. });
  6310. var dir = function (el, prop, until) {
  6311. var matched = [];
  6312. var cur = el[prop];
  6313. if (typeof until !== 'string' && until instanceof DomQuery) {
  6314. until = until[0];
  6315. }
  6316. while (cur && cur.nodeType !== 9) {
  6317. if (until !== undefined) {
  6318. if (cur === until) {
  6319. break;
  6320. }
  6321. if (typeof until === 'string' && DomQuery(cur).is(until)) {
  6322. break;
  6323. }
  6324. }
  6325. if (cur.nodeType === 1) {
  6326. matched.push(cur);
  6327. }
  6328. cur = cur[prop];
  6329. }
  6330. return matched;
  6331. };
  6332. var sibling$1 = function (node, siblingName, nodeType, until) {
  6333. var result = [];
  6334. if (until instanceof DomQuery) {
  6335. until = until[0];
  6336. }
  6337. for (; node; node = node[siblingName]) {
  6338. if (nodeType && node.nodeType !== nodeType) {
  6339. continue;
  6340. }
  6341. if (until !== undefined) {
  6342. if (node === until) {
  6343. break;
  6344. }
  6345. if (typeof until === 'string' && DomQuery(node).is(until)) {
  6346. break;
  6347. }
  6348. }
  6349. result.push(node);
  6350. }
  6351. return result;
  6352. };
  6353. var firstSibling = function (node, siblingName, nodeType) {
  6354. for (node = node[siblingName]; node; node = node[siblingName]) {
  6355. if (node.nodeType === nodeType) {
  6356. return node;
  6357. }
  6358. }
  6359. return null;
  6360. };
  6361. each$g({
  6362. parent: function (node) {
  6363. var parent = node.parentNode;
  6364. return parent && parent.nodeType !== 11 ? parent : null;
  6365. },
  6366. parents: function (node) {
  6367. return dir(node, 'parentNode');
  6368. },
  6369. next: function (node) {
  6370. return firstSibling(node, 'nextSibling', 1);
  6371. },
  6372. prev: function (node) {
  6373. return firstSibling(node, 'previousSibling', 1);
  6374. },
  6375. children: function (node) {
  6376. return sibling$1(node.firstChild, 'nextSibling', 1);
  6377. },
  6378. contents: function (node) {
  6379. return Tools.toArray((node.nodeName === 'iframe' ? node.contentDocument || node.contentWindow.document : node).childNodes);
  6380. }
  6381. }, function (name, fn) {
  6382. DomQueryConstructor.fn[name] = function (selector) {
  6383. var self = this;
  6384. var result = [];
  6385. self.each(function () {
  6386. var nodes = fn.call(result, this, selector, result);
  6387. if (nodes) {
  6388. if (DomQuery.isArray(nodes)) {
  6389. result.push.apply(result, nodes);
  6390. } else {
  6391. result.push(nodes);
  6392. }
  6393. }
  6394. });
  6395. if (this.length > 1) {
  6396. if (!skipUniques[name]) {
  6397. result = DomQuery.unique(result);
  6398. }
  6399. if (name.indexOf('parents') === 0) {
  6400. result = result.reverse();
  6401. }
  6402. }
  6403. var wrappedResult = DomQuery(result);
  6404. if (selector) {
  6405. return wrappedResult.filter(selector);
  6406. }
  6407. return wrappedResult;
  6408. };
  6409. });
  6410. each$g({
  6411. parentsUntil: function (node, until) {
  6412. return dir(node, 'parentNode', until);
  6413. },
  6414. nextUntil: function (node, until) {
  6415. return sibling$1(node, 'nextSibling', 1, until).slice(1);
  6416. },
  6417. prevUntil: function (node, until) {
  6418. return sibling$1(node, 'previousSibling', 1, until).slice(1);
  6419. }
  6420. }, function (name, fn) {
  6421. DomQueryConstructor.fn[name] = function (selector, filter) {
  6422. var self = this;
  6423. var result = [];
  6424. self.each(function () {
  6425. var nodes = fn.call(result, this, selector, result);
  6426. if (nodes) {
  6427. if (DomQuery.isArray(nodes)) {
  6428. result.push.apply(result, nodes);
  6429. } else {
  6430. result.push(nodes);
  6431. }
  6432. }
  6433. });
  6434. if (this.length > 1) {
  6435. result = DomQuery.unique(result);
  6436. if (name.indexOf('parents') === 0 || name === 'prevUntil') {
  6437. result = result.reverse();
  6438. }
  6439. }
  6440. var wrappedResult = DomQuery(result);
  6441. if (filter) {
  6442. return wrappedResult.filter(filter);
  6443. }
  6444. return wrappedResult;
  6445. };
  6446. });
  6447. DomQueryConstructor.fn.is = function (selector) {
  6448. return !!selector && this.filter(selector).length > 0;
  6449. };
  6450. DomQueryConstructor.fn.init.prototype = DomQueryConstructor.fn;
  6451. DomQueryConstructor.overrideDefaults = function (callback) {
  6452. var defaults;
  6453. var sub = function (selector, context) {
  6454. defaults = defaults || callback();
  6455. if (arguments.length === 0) {
  6456. selector = defaults.element;
  6457. }
  6458. if (!context) {
  6459. context = defaults.context;
  6460. }
  6461. return new sub.fn.init(selector, context);
  6462. };
  6463. DomQuery.extend(sub, this);
  6464. return sub;
  6465. };
  6466. DomQueryConstructor.attrHooks = attrHooks;
  6467. DomQueryConstructor.cssHooks = cssHooks;
  6468. var DomQuery = DomQueryConstructor;
  6469. var each$f = Tools.each;
  6470. var grep$1 = Tools.grep;
  6471. var isIE = Env.ie;
  6472. var simpleSelectorRe = /^([a-z0-9],?)+$/i;
  6473. var setupAttrHooks = function (styles, settings, getContext) {
  6474. var keepValues = settings.keep_values;
  6475. var keepUrlHook = {
  6476. set: function ($elm, value, name) {
  6477. if (settings.url_converter && value !== null) {
  6478. value = settings.url_converter.call(settings.url_converter_scope || getContext(), value, name, $elm[0]);
  6479. }
  6480. $elm.attr('data-mce-' + name, value).attr(name, value);
  6481. },
  6482. get: function ($elm, name) {
  6483. return $elm.attr('data-mce-' + name) || $elm.attr(name);
  6484. }
  6485. };
  6486. var attrHooks = {
  6487. style: {
  6488. set: function ($elm, value) {
  6489. if (value !== null && typeof value === 'object') {
  6490. $elm.css(value);
  6491. return;
  6492. }
  6493. if (keepValues) {
  6494. $elm.attr('data-mce-style', value);
  6495. }
  6496. if (value !== null && typeof value === 'string') {
  6497. $elm.removeAttr('style');
  6498. $elm.css(styles.parse(value));
  6499. } else {
  6500. $elm.attr('style', value);
  6501. }
  6502. },
  6503. get: function ($elm) {
  6504. var value = $elm.attr('data-mce-style') || $elm.attr('style');
  6505. value = styles.serialize(styles.parse(value), $elm[0].nodeName);
  6506. return value;
  6507. }
  6508. }
  6509. };
  6510. if (keepValues) {
  6511. attrHooks.href = attrHooks.src = keepUrlHook;
  6512. }
  6513. return attrHooks;
  6514. };
  6515. var updateInternalStyleAttr = function (styles, $elm) {
  6516. var rawValue = $elm.attr('style');
  6517. var value = styles.serialize(styles.parse(rawValue), $elm[0].nodeName);
  6518. if (!value) {
  6519. value = null;
  6520. }
  6521. $elm.attr('data-mce-style', value);
  6522. };
  6523. var findNodeIndex = function (node, normalized) {
  6524. var idx = 0, lastNodeType, nodeType;
  6525. if (node) {
  6526. for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
  6527. nodeType = node.nodeType;
  6528. if (normalized && nodeType === 3) {
  6529. if (nodeType === lastNodeType || !node.nodeValue.length) {
  6530. continue;
  6531. }
  6532. }
  6533. idx++;
  6534. lastNodeType = nodeType;
  6535. }
  6536. }
  6537. return idx;
  6538. };
  6539. var DOMUtils = function (doc, settings) {
  6540. if (settings === void 0) {
  6541. settings = {};
  6542. }
  6543. var addedStyles = {};
  6544. var win = window;
  6545. var files = {};
  6546. var counter = 0;
  6547. var stdMode = true;
  6548. var boxModel = true;
  6549. var styleSheetLoader = instance.forElement(SugarElement.fromDom(doc), {
  6550. contentCssCors: settings.contentCssCors,
  6551. referrerPolicy: settings.referrerPolicy
  6552. });
  6553. var boundEvents = [];
  6554. var schema = settings.schema ? settings.schema : Schema({});
  6555. var styles = Styles({
  6556. url_converter: settings.url_converter,
  6557. url_converter_scope: settings.url_converter_scope
  6558. }, settings.schema);
  6559. var events = settings.ownEvents ? new EventUtils() : EventUtils.Event;
  6560. var blockElementsMap = schema.getBlockElements();
  6561. var $ = DomQuery.overrideDefaults(function () {
  6562. return {
  6563. context: doc,
  6564. element: self.getRoot()
  6565. };
  6566. });
  6567. var isBlock = function (node) {
  6568. if (typeof node === 'string') {
  6569. return !!blockElementsMap[node];
  6570. } else if (node) {
  6571. var type = node.nodeType;
  6572. if (type) {
  6573. return !!(type === 1 && blockElementsMap[node.nodeName]);
  6574. }
  6575. }
  6576. return false;
  6577. };
  6578. var get = function (elm) {
  6579. return elm && doc && isString$1(elm) ? doc.getElementById(elm) : elm;
  6580. };
  6581. var $$ = function (elm) {
  6582. return $(typeof elm === 'string' ? get(elm) : elm);
  6583. };
  6584. var getAttrib = function (elm, name, defaultVal) {
  6585. var hook, value;
  6586. var $elm = $$(elm);
  6587. if ($elm.length) {
  6588. hook = attrHooks[name];
  6589. if (hook && hook.get) {
  6590. value = hook.get($elm, name);
  6591. } else {
  6592. value = $elm.attr(name);
  6593. }
  6594. }
  6595. if (typeof value === 'undefined') {
  6596. value = defaultVal || '';
  6597. }
  6598. return value;
  6599. };
  6600. var getAttribs = function (elm) {
  6601. var node = get(elm);
  6602. if (!node) {
  6603. return [];
  6604. }
  6605. return node.attributes;
  6606. };
  6607. var setAttrib = function (elm, name, value) {
  6608. if (value === '') {
  6609. value = null;
  6610. }
  6611. var $elm = $$(elm);
  6612. var originalValue = $elm.attr(name);
  6613. if (!$elm.length) {
  6614. return;
  6615. }
  6616. var hook = attrHooks[name];
  6617. if (hook && hook.set) {
  6618. hook.set($elm, value, name);
  6619. } else {
  6620. $elm.attr(name, value);
  6621. }
  6622. if (originalValue !== value && settings.onSetAttrib) {
  6623. settings.onSetAttrib({
  6624. attrElm: $elm,
  6625. attrName: name,
  6626. attrValue: value
  6627. });
  6628. }
  6629. };
  6630. var clone = function (node, deep) {
  6631. if (!isIE || node.nodeType !== 1 || deep) {
  6632. return node.cloneNode(deep);
  6633. } else {
  6634. var clone_1 = doc.createElement(node.nodeName);
  6635. each$f(getAttribs(node), function (attr) {
  6636. setAttrib(clone_1, attr.nodeName, getAttrib(node, attr.nodeName));
  6637. });
  6638. return clone_1;
  6639. }
  6640. };
  6641. var getRoot = function () {
  6642. return settings.root_element || doc.body;
  6643. };
  6644. var getViewPort = function (argWin) {
  6645. var vp = getBounds(argWin);
  6646. return {
  6647. x: vp.x,
  6648. y: vp.y,
  6649. w: vp.width,
  6650. h: vp.height
  6651. };
  6652. };
  6653. var getPos$1 = function (elm, rootElm) {
  6654. return getPos(doc.body, get(elm), rootElm);
  6655. };
  6656. var setStyle = function (elm, name, value) {
  6657. var $elm = isString$1(name) ? $$(elm).css(name, value) : $$(elm).css(name);
  6658. if (settings.update_styles) {
  6659. updateInternalStyleAttr(styles, $elm);
  6660. }
  6661. };
  6662. var setStyles = function (elm, stylesArg) {
  6663. var $elm = $$(elm).css(stylesArg);
  6664. if (settings.update_styles) {
  6665. updateInternalStyleAttr(styles, $elm);
  6666. }
  6667. };
  6668. var getStyle = function (elm, name, computed) {
  6669. var $elm = $$(elm);
  6670. if (computed) {
  6671. return $elm.css(name);
  6672. }
  6673. name = name.replace(/-(\D)/g, function (a, b) {
  6674. return b.toUpperCase();
  6675. });
  6676. if (name === 'float') {
  6677. name = Env.browser.isIE() ? 'styleFloat' : 'cssFloat';
  6678. }
  6679. return $elm[0] && $elm[0].style ? $elm[0].style[name] : undefined;
  6680. };
  6681. var getSize = function (elm) {
  6682. var w, h;
  6683. elm = get(elm);
  6684. w = getStyle(elm, 'width');
  6685. h = getStyle(elm, 'height');
  6686. if (w.indexOf('px') === -1) {
  6687. w = 0;
  6688. }
  6689. if (h.indexOf('px') === -1) {
  6690. h = 0;
  6691. }
  6692. return {
  6693. w: parseInt(w, 10) || elm.offsetWidth || elm.clientWidth,
  6694. h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight
  6695. };
  6696. };
  6697. var getRect = function (elm) {
  6698. elm = get(elm);
  6699. var pos = getPos$1(elm);
  6700. var size = getSize(elm);
  6701. return {
  6702. x: pos.x,
  6703. y: pos.y,
  6704. w: size.w,
  6705. h: size.h
  6706. };
  6707. };
  6708. var is = function (elm, selector) {
  6709. var i;
  6710. if (!elm) {
  6711. return false;
  6712. }
  6713. if (!Array.isArray(elm)) {
  6714. if (selector === '*') {
  6715. return elm.nodeType === 1;
  6716. }
  6717. if (simpleSelectorRe.test(selector)) {
  6718. var selectors = selector.toLowerCase().split(/,/);
  6719. var elmName = elm.nodeName.toLowerCase();
  6720. for (i = selectors.length - 1; i >= 0; i--) {
  6721. if (selectors[i] === elmName) {
  6722. return true;
  6723. }
  6724. }
  6725. return false;
  6726. }
  6727. if (elm.nodeType && elm.nodeType !== 1) {
  6728. return false;
  6729. }
  6730. }
  6731. var elms = !Array.isArray(elm) ? [elm] : elm;
  6732. return Sizzle(selector, elms[0].ownerDocument || elms[0], null, elms).length > 0;
  6733. };
  6734. var getParents = function (elm, selector, root, collect) {
  6735. var result = [];
  6736. var selectorVal;
  6737. var node = get(elm);
  6738. collect = collect === undefined;
  6739. root = root || (getRoot().nodeName !== 'BODY' ? getRoot().parentNode : null);
  6740. if (Tools.is(selector, 'string')) {
  6741. selectorVal = selector;
  6742. if (selector === '*') {
  6743. selector = function (node) {
  6744. return node.nodeType === 1;
  6745. };
  6746. } else {
  6747. selector = function (node) {
  6748. return is(node, selectorVal);
  6749. };
  6750. }
  6751. }
  6752. while (node) {
  6753. if (node === root || isNullable(node.nodeType) || isDocument$1(node) || isDocumentFragment(node)) {
  6754. break;
  6755. }
  6756. if (!selector || typeof selector === 'function' && selector(node)) {
  6757. if (collect) {
  6758. result.push(node);
  6759. } else {
  6760. return [node];
  6761. }
  6762. }
  6763. node = node.parentNode;
  6764. }
  6765. return collect ? result : null;
  6766. };
  6767. var getParent = function (node, selector, root) {
  6768. var parents = getParents(node, selector, root, false);
  6769. return parents && parents.length > 0 ? parents[0] : null;
  6770. };
  6771. var _findSib = function (node, selector, name) {
  6772. var func = selector;
  6773. if (node) {
  6774. if (typeof selector === 'string') {
  6775. func = function (node) {
  6776. return is(node, selector);
  6777. };
  6778. }
  6779. for (node = node[name]; node; node = node[name]) {
  6780. if (typeof func === 'function' && func(node)) {
  6781. return node;
  6782. }
  6783. }
  6784. }
  6785. return null;
  6786. };
  6787. var getNext = function (node, selector) {
  6788. return _findSib(node, selector, 'nextSibling');
  6789. };
  6790. var getPrev = function (node, selector) {
  6791. return _findSib(node, selector, 'previousSibling');
  6792. };
  6793. var select = function (selector, scope) {
  6794. return Sizzle(selector, get(scope) || settings.root_element || doc, []);
  6795. };
  6796. var run = function (elm, func, scope) {
  6797. var result;
  6798. var node = typeof elm === 'string' ? get(elm) : elm;
  6799. if (!node) {
  6800. return false;
  6801. }
  6802. if (Tools.isArray(node) && (node.length || node.length === 0)) {
  6803. result = [];
  6804. each$f(node, function (elm, i) {
  6805. if (elm) {
  6806. result.push(func.call(scope, typeof elm === 'string' ? get(elm) : elm, i));
  6807. }
  6808. });
  6809. return result;
  6810. }
  6811. var context = scope ? scope : this;
  6812. return func.call(context, node);
  6813. };
  6814. var setAttribs = function (elm, attrs) {
  6815. $$(elm).each(function (i, node) {
  6816. each$f(attrs, function (value, name) {
  6817. setAttrib(node, name, value);
  6818. });
  6819. });
  6820. };
  6821. var setHTML = function (elm, html) {
  6822. var $elm = $$(elm);
  6823. if (isIE) {
  6824. $elm.each(function (i, target) {
  6825. if (target.canHaveHTML === false) {
  6826. return;
  6827. }
  6828. while (target.firstChild) {
  6829. target.removeChild(target.firstChild);
  6830. }
  6831. try {
  6832. target.innerHTML = '<br>' + html;
  6833. target.removeChild(target.firstChild);
  6834. } catch (ex) {
  6835. DomQuery('<div></div>').html('<br>' + html).contents().slice(1).appendTo(target);
  6836. }
  6837. return html;
  6838. });
  6839. } else {
  6840. $elm.html(html);
  6841. }
  6842. };
  6843. var add = function (parentElm, name, attrs, html, create) {
  6844. return run(parentElm, function (parentElm) {
  6845. var newElm = typeof name === 'string' ? doc.createElement(name) : name;
  6846. setAttribs(newElm, attrs);
  6847. if (html) {
  6848. if (typeof html !== 'string' && html.nodeType) {
  6849. newElm.appendChild(html);
  6850. } else if (typeof html === 'string') {
  6851. setHTML(newElm, html);
  6852. }
  6853. }
  6854. return !create ? parentElm.appendChild(newElm) : newElm;
  6855. });
  6856. };
  6857. var create = function (name, attrs, html) {
  6858. return add(doc.createElement(name), name, attrs, html, true);
  6859. };
  6860. var decode = Entities.decode;
  6861. var encode = Entities.encodeAllRaw;
  6862. var createHTML = function (name, attrs, html) {
  6863. var outHtml = '', key;
  6864. outHtml += '<' + name;
  6865. for (key in attrs) {
  6866. if (hasNonNullableKey(attrs, key)) {
  6867. outHtml += ' ' + key + '="' + encode(attrs[key]) + '"';
  6868. }
  6869. }
  6870. if (typeof html !== 'undefined') {
  6871. return outHtml + '>' + html + '</' + name + '>';
  6872. }
  6873. return outHtml + ' />';
  6874. };
  6875. var createFragment = function (html) {
  6876. var node;
  6877. var container = doc.createElement('div');
  6878. var frag = doc.createDocumentFragment();
  6879. frag.appendChild(container);
  6880. if (html) {
  6881. container.innerHTML = html;
  6882. }
  6883. while (node = container.firstChild) {
  6884. frag.appendChild(node);
  6885. }
  6886. frag.removeChild(container);
  6887. return frag;
  6888. };
  6889. var remove = function (node, keepChildren) {
  6890. var $node = $$(node);
  6891. if (keepChildren) {
  6892. $node.each(function () {
  6893. var child;
  6894. while (child = this.firstChild) {
  6895. if (child.nodeType === 3 && child.data.length === 0) {
  6896. this.removeChild(child);
  6897. } else {
  6898. this.parentNode.insertBefore(child, this);
  6899. }
  6900. }
  6901. }).remove();
  6902. } else {
  6903. $node.remove();
  6904. }
  6905. return $node.length > 1 ? $node.toArray() : $node[0];
  6906. };
  6907. var removeAllAttribs = function (e) {
  6908. return run(e, function (e) {
  6909. var i;
  6910. var attrs = e.attributes;
  6911. for (i = attrs.length - 1; i >= 0; i--) {
  6912. e.removeAttributeNode(attrs.item(i));
  6913. }
  6914. });
  6915. };
  6916. var parseStyle = function (cssText) {
  6917. return styles.parse(cssText);
  6918. };
  6919. var serializeStyle = function (stylesArg, name) {
  6920. return styles.serialize(stylesArg, name);
  6921. };
  6922. var addStyle = function (cssText) {
  6923. var head, styleElm;
  6924. if (self !== DOMUtils.DOM && doc === document) {
  6925. if (addedStyles[cssText]) {
  6926. return;
  6927. }
  6928. addedStyles[cssText] = true;
  6929. }
  6930. styleElm = doc.getElementById('mceDefaultStyles');
  6931. if (!styleElm) {
  6932. styleElm = doc.createElement('style');
  6933. styleElm.id = 'mceDefaultStyles';
  6934. styleElm.type = 'text/css';
  6935. head = doc.getElementsByTagName('head')[0];
  6936. if (head.firstChild) {
  6937. head.insertBefore(styleElm, head.firstChild);
  6938. } else {
  6939. head.appendChild(styleElm);
  6940. }
  6941. }
  6942. if (styleElm.styleSheet) {
  6943. styleElm.styleSheet.cssText += cssText;
  6944. } else {
  6945. styleElm.appendChild(doc.createTextNode(cssText));
  6946. }
  6947. };
  6948. var loadCSS = function (urls) {
  6949. if (!urls) {
  6950. urls = '';
  6951. }
  6952. each$k(urls.split(','), function (url) {
  6953. files[url] = true;
  6954. styleSheetLoader.load(url, noop);
  6955. });
  6956. };
  6957. var toggleClass = function (elm, cls, state) {
  6958. $$(elm).toggleClass(cls, state).each(function () {
  6959. if (this.className === '') {
  6960. DomQuery(this).attr('class', null);
  6961. }
  6962. });
  6963. };
  6964. var addClass = function (elm, cls) {
  6965. $$(elm).addClass(cls);
  6966. };
  6967. var removeClass = function (elm, cls) {
  6968. toggleClass(elm, cls, false);
  6969. };
  6970. var hasClass = function (elm, cls) {
  6971. return $$(elm).hasClass(cls);
  6972. };
  6973. var show = function (elm) {
  6974. $$(elm).show();
  6975. };
  6976. var hide = function (elm) {
  6977. $$(elm).hide();
  6978. };
  6979. var isHidden = function (elm) {
  6980. return $$(elm).css('display') === 'none';
  6981. };
  6982. var uniqueId = function (prefix) {
  6983. return (!prefix ? 'mce_' : prefix) + counter++;
  6984. };
  6985. var getOuterHTML = function (elm) {
  6986. var node = typeof elm === 'string' ? get(elm) : elm;
  6987. return isElement$5(node) ? node.outerHTML : DomQuery('<div></div>').append(DomQuery(node).clone()).html();
  6988. };
  6989. var setOuterHTML = function (elm, html) {
  6990. $$(elm).each(function () {
  6991. try {
  6992. if ('outerHTML' in this) {
  6993. this.outerHTML = html;
  6994. return;
  6995. }
  6996. } catch (ex) {
  6997. }
  6998. remove(DomQuery(this).html(html), true);
  6999. });
  7000. };
  7001. var insertAfter = function (node, reference) {
  7002. var referenceNode = get(reference);
  7003. return run(node, function (node) {
  7004. var parent = referenceNode.parentNode;
  7005. var nextSibling = referenceNode.nextSibling;
  7006. if (nextSibling) {
  7007. parent.insertBefore(node, nextSibling);
  7008. } else {
  7009. parent.appendChild(node);
  7010. }
  7011. return node;
  7012. });
  7013. };
  7014. var replace = function (newElm, oldElm, keepChildren) {
  7015. return run(oldElm, function (oldElm) {
  7016. if (Tools.is(oldElm, 'array')) {
  7017. newElm = newElm.cloneNode(true);
  7018. }
  7019. if (keepChildren) {
  7020. each$f(grep$1(oldElm.childNodes), function (node) {
  7021. newElm.appendChild(node);
  7022. });
  7023. }
  7024. return oldElm.parentNode.replaceChild(newElm, oldElm);
  7025. });
  7026. };
  7027. var rename = function (elm, name) {
  7028. var newElm;
  7029. if (elm.nodeName !== name.toUpperCase()) {
  7030. newElm = create(name);
  7031. each$f(getAttribs(elm), function (attrNode) {
  7032. setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
  7033. });
  7034. replace(newElm, elm, true);
  7035. }
  7036. return newElm || elm;
  7037. };
  7038. var findCommonAncestor = function (a, b) {
  7039. var ps = a, pe;
  7040. while (ps) {
  7041. pe = b;
  7042. while (pe && ps !== pe) {
  7043. pe = pe.parentNode;
  7044. }
  7045. if (ps === pe) {
  7046. break;
  7047. }
  7048. ps = ps.parentNode;
  7049. }
  7050. if (!ps && a.ownerDocument) {
  7051. return a.ownerDocument.documentElement;
  7052. }
  7053. return ps;
  7054. };
  7055. var toHex = function (rgbVal) {
  7056. return styles.toHex(Tools.trim(rgbVal));
  7057. };
  7058. var isNonEmptyElement = function (node) {
  7059. if (isElement$5(node)) {
  7060. var isNamedAnchor = node.nodeName.toLowerCase() === 'a' && !getAttrib(node, 'href') && getAttrib(node, 'id');
  7061. if (getAttrib(node, 'name') || getAttrib(node, 'data-mce-bookmark') || isNamedAnchor) {
  7062. return true;
  7063. }
  7064. }
  7065. return false;
  7066. };
  7067. var isEmpty = function (node, elements) {
  7068. var type, name, brCount = 0;
  7069. if (isNonEmptyElement(node)) {
  7070. return false;
  7071. }
  7072. node = node.firstChild;
  7073. if (node) {
  7074. var walker = new DomTreeWalker(node, node.parentNode);
  7075. var whitespace = schema ? schema.getWhiteSpaceElements() : {};
  7076. elements = elements || (schema ? schema.getNonEmptyElements() : null);
  7077. do {
  7078. type = node.nodeType;
  7079. if (isElement$5(node)) {
  7080. var bogusVal = node.getAttribute('data-mce-bogus');
  7081. if (bogusVal) {
  7082. node = walker.next(bogusVal === 'all');
  7083. continue;
  7084. }
  7085. name = node.nodeName.toLowerCase();
  7086. if (elements && elements[name]) {
  7087. if (name === 'br') {
  7088. brCount++;
  7089. node = walker.next();
  7090. continue;
  7091. }
  7092. return false;
  7093. }
  7094. if (isNonEmptyElement(node)) {
  7095. return false;
  7096. }
  7097. }
  7098. if (type === 8) {
  7099. return false;
  7100. }
  7101. if (type === 3 && !isWhitespaceText(node.nodeValue)) {
  7102. return false;
  7103. }
  7104. if (type === 3 && node.parentNode && whitespace[node.parentNode.nodeName] && isWhitespaceText(node.nodeValue)) {
  7105. return false;
  7106. }
  7107. node = walker.next();
  7108. } while (node);
  7109. }
  7110. return brCount <= 1;
  7111. };
  7112. var createRng = function () {
  7113. return doc.createRange();
  7114. };
  7115. var split = function (parentElm, splitElm, replacementElm) {
  7116. var range = createRng();
  7117. var beforeFragment;
  7118. var afterFragment;
  7119. var parentNode;
  7120. if (parentElm && splitElm) {
  7121. range.setStart(parentElm.parentNode, findNodeIndex(parentElm));
  7122. range.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
  7123. beforeFragment = range.extractContents();
  7124. range = createRng();
  7125. range.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
  7126. range.setEnd(parentElm.parentNode, findNodeIndex(parentElm) + 1);
  7127. afterFragment = range.extractContents();
  7128. parentNode = parentElm.parentNode;
  7129. parentNode.insertBefore(trimNode(self, beforeFragment), parentElm);
  7130. if (replacementElm) {
  7131. parentNode.insertBefore(replacementElm, parentElm);
  7132. } else {
  7133. parentNode.insertBefore(splitElm, parentElm);
  7134. }
  7135. parentNode.insertBefore(trimNode(self, afterFragment), parentElm);
  7136. remove(parentElm);
  7137. return replacementElm || splitElm;
  7138. }
  7139. };
  7140. var bind = function (target, name, func, scope) {
  7141. if (Tools.isArray(target)) {
  7142. var i = target.length;
  7143. var rv = [];
  7144. while (i--) {
  7145. rv[i] = bind(target[i], name, func, scope);
  7146. }
  7147. return rv;
  7148. }
  7149. if (settings.collect && (target === doc || target === win)) {
  7150. boundEvents.push([
  7151. target,
  7152. name,
  7153. func,
  7154. scope
  7155. ]);
  7156. }
  7157. var output = events.bind(target, name, func, scope || self);
  7158. return output;
  7159. };
  7160. var unbind = function (target, name, func) {
  7161. if (Tools.isArray(target)) {
  7162. var i = target.length;
  7163. var rv = [];
  7164. while (i--) {
  7165. rv[i] = unbind(target[i], name, func);
  7166. }
  7167. return rv;
  7168. } else {
  7169. if (boundEvents.length > 0 && (target === doc || target === win)) {
  7170. var i = boundEvents.length;
  7171. while (i--) {
  7172. var item = boundEvents[i];
  7173. if (target === item[0] && (!name || name === item[1]) && (!func || func === item[2])) {
  7174. events.unbind(item[0], item[1], item[2]);
  7175. }
  7176. }
  7177. }
  7178. return events.unbind(target, name, func);
  7179. }
  7180. };
  7181. var fire = function (target, name, evt) {
  7182. return events.fire(target, name, evt);
  7183. };
  7184. var getContentEditable = function (node) {
  7185. if (node && isElement$5(node)) {
  7186. var contentEditable = node.getAttribute('data-mce-contenteditable');
  7187. if (contentEditable && contentEditable !== 'inherit') {
  7188. return contentEditable;
  7189. }
  7190. return node.contentEditable !== 'inherit' ? node.contentEditable : null;
  7191. } else {
  7192. return null;
  7193. }
  7194. };
  7195. var getContentEditableParent = function (node) {
  7196. var root = getRoot();
  7197. var state = null;
  7198. for (; node && node !== root; node = node.parentNode) {
  7199. state = getContentEditable(node);
  7200. if (state !== null) {
  7201. break;
  7202. }
  7203. }
  7204. return state;
  7205. };
  7206. var destroy = function () {
  7207. if (boundEvents.length > 0) {
  7208. var i = boundEvents.length;
  7209. while (i--) {
  7210. var item = boundEvents[i];
  7211. events.unbind(item[0], item[1], item[2]);
  7212. }
  7213. }
  7214. each$j(files, function (_, url) {
  7215. styleSheetLoader.unload(url);
  7216. delete files[url];
  7217. });
  7218. if (Sizzle.setDocument) {
  7219. Sizzle.setDocument();
  7220. }
  7221. };
  7222. var isChildOf = function (node, parent) {
  7223. if (!isIE) {
  7224. return node === parent || parent.contains(node);
  7225. } else {
  7226. while (node) {
  7227. if (parent === node) {
  7228. return true;
  7229. }
  7230. node = node.parentNode;
  7231. }
  7232. return false;
  7233. }
  7234. };
  7235. var dumpRng = function (r) {
  7236. return 'startContainer: ' + r.startContainer.nodeName + ', startOffset: ' + r.startOffset + ', endContainer: ' + r.endContainer.nodeName + ', endOffset: ' + r.endOffset;
  7237. };
  7238. var self = {
  7239. doc: doc,
  7240. settings: settings,
  7241. win: win,
  7242. files: files,
  7243. stdMode: stdMode,
  7244. boxModel: boxModel,
  7245. styleSheetLoader: styleSheetLoader,
  7246. boundEvents: boundEvents,
  7247. styles: styles,
  7248. schema: schema,
  7249. events: events,
  7250. isBlock: isBlock,
  7251. $: $,
  7252. $$: $$,
  7253. root: null,
  7254. clone: clone,
  7255. getRoot: getRoot,
  7256. getViewPort: getViewPort,
  7257. getRect: getRect,
  7258. getSize: getSize,
  7259. getParent: getParent,
  7260. getParents: getParents,
  7261. get: get,
  7262. getNext: getNext,
  7263. getPrev: getPrev,
  7264. select: select,
  7265. is: is,
  7266. add: add,
  7267. create: create,
  7268. createHTML: createHTML,
  7269. createFragment: createFragment,
  7270. remove: remove,
  7271. setStyle: setStyle,
  7272. getStyle: getStyle,
  7273. setStyles: setStyles,
  7274. removeAllAttribs: removeAllAttribs,
  7275. setAttrib: setAttrib,
  7276. setAttribs: setAttribs,
  7277. getAttrib: getAttrib,
  7278. getPos: getPos$1,
  7279. parseStyle: parseStyle,
  7280. serializeStyle: serializeStyle,
  7281. addStyle: addStyle,
  7282. loadCSS: loadCSS,
  7283. addClass: addClass,
  7284. removeClass: removeClass,
  7285. hasClass: hasClass,
  7286. toggleClass: toggleClass,
  7287. show: show,
  7288. hide: hide,
  7289. isHidden: isHidden,
  7290. uniqueId: uniqueId,
  7291. setHTML: setHTML,
  7292. getOuterHTML: getOuterHTML,
  7293. setOuterHTML: setOuterHTML,
  7294. decode: decode,
  7295. encode: encode,
  7296. insertAfter: insertAfter,
  7297. replace: replace,
  7298. rename: rename,
  7299. findCommonAncestor: findCommonAncestor,
  7300. toHex: toHex,
  7301. run: run,
  7302. getAttribs: getAttribs,
  7303. isEmpty: isEmpty,
  7304. createRng: createRng,
  7305. nodeIndex: findNodeIndex,
  7306. split: split,
  7307. bind: bind,
  7308. unbind: unbind,
  7309. fire: fire,
  7310. getContentEditable: getContentEditable,
  7311. getContentEditableParent: getContentEditableParent,
  7312. destroy: destroy,
  7313. isChildOf: isChildOf,
  7314. dumpRng: dumpRng
  7315. };
  7316. var attrHooks = setupAttrHooks(styles, settings, constant(self));
  7317. return self;
  7318. };
  7319. DOMUtils.DOM = DOMUtils(document);
  7320. DOMUtils.nodeIndex = findNodeIndex;
  7321. var DOM$a = DOMUtils.DOM;
  7322. var each$e = Tools.each, grep = Tools.grep;
  7323. var QUEUED = 0;
  7324. var LOADING = 1;
  7325. var LOADED = 2;
  7326. var FAILED = 3;
  7327. var ScriptLoader = function () {
  7328. function ScriptLoader(settings) {
  7329. if (settings === void 0) {
  7330. settings = {};
  7331. }
  7332. this.states = {};
  7333. this.queue = [];
  7334. this.scriptLoadedCallbacks = {};
  7335. this.queueLoadedCallbacks = [];
  7336. this.loading = 0;
  7337. this.settings = settings;
  7338. }
  7339. ScriptLoader.prototype._setReferrerPolicy = function (referrerPolicy) {
  7340. this.settings.referrerPolicy = referrerPolicy;
  7341. };
  7342. ScriptLoader.prototype.loadScript = function (url, success, failure) {
  7343. var dom = DOM$a;
  7344. var elm;
  7345. var cleanup = function () {
  7346. dom.remove(id);
  7347. if (elm) {
  7348. elm.onerror = elm.onload = elm = null;
  7349. }
  7350. };
  7351. var done = function () {
  7352. cleanup();
  7353. success();
  7354. };
  7355. var error = function () {
  7356. cleanup();
  7357. if (isFunction(failure)) {
  7358. failure();
  7359. } else {
  7360. if (typeof console !== 'undefined' && console.log) {
  7361. console.log('Failed to load script: ' + url);
  7362. }
  7363. }
  7364. };
  7365. var id = dom.uniqueId();
  7366. elm = document.createElement('script');
  7367. elm.id = id;
  7368. elm.type = 'text/javascript';
  7369. elm.src = Tools._addCacheSuffix(url);
  7370. if (this.settings.referrerPolicy) {
  7371. dom.setAttrib(elm, 'referrerpolicy', this.settings.referrerPolicy);
  7372. }
  7373. elm.onload = done;
  7374. elm.onerror = error;
  7375. (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
  7376. };
  7377. ScriptLoader.prototype.isDone = function (url) {
  7378. return this.states[url] === LOADED;
  7379. };
  7380. ScriptLoader.prototype.markDone = function (url) {
  7381. this.states[url] = LOADED;
  7382. };
  7383. ScriptLoader.prototype.add = function (url, success, scope, failure) {
  7384. var state = this.states[url];
  7385. this.queue.push(url);
  7386. if (state === undefined) {
  7387. this.states[url] = QUEUED;
  7388. }
  7389. if (success) {
  7390. if (!this.scriptLoadedCallbacks[url]) {
  7391. this.scriptLoadedCallbacks[url] = [];
  7392. }
  7393. this.scriptLoadedCallbacks[url].push({
  7394. success: success,
  7395. failure: failure,
  7396. scope: scope || this
  7397. });
  7398. }
  7399. };
  7400. ScriptLoader.prototype.load = function (url, success, scope, failure) {
  7401. return this.add(url, success, scope, failure);
  7402. };
  7403. ScriptLoader.prototype.remove = function (url) {
  7404. delete this.states[url];
  7405. delete this.scriptLoadedCallbacks[url];
  7406. };
  7407. ScriptLoader.prototype.loadQueue = function (success, scope, failure) {
  7408. this.loadScripts(this.queue, success, scope, failure);
  7409. };
  7410. ScriptLoader.prototype.loadScripts = function (scripts, success, scope, failure) {
  7411. var self = this;
  7412. var failures = [];
  7413. var execCallbacks = function (name, url) {
  7414. each$e(self.scriptLoadedCallbacks[url], function (callback) {
  7415. if (isFunction(callback[name])) {
  7416. callback[name].call(callback.scope);
  7417. }
  7418. });
  7419. self.scriptLoadedCallbacks[url] = undefined;
  7420. };
  7421. self.queueLoadedCallbacks.push({
  7422. success: success,
  7423. failure: failure,
  7424. scope: scope || this
  7425. });
  7426. var loadScripts = function () {
  7427. var loadingScripts = grep(scripts);
  7428. scripts.length = 0;
  7429. each$e(loadingScripts, function (url) {
  7430. if (self.states[url] === LOADED) {
  7431. execCallbacks('success', url);
  7432. return;
  7433. }
  7434. if (self.states[url] === FAILED) {
  7435. execCallbacks('failure', url);
  7436. return;
  7437. }
  7438. if (self.states[url] !== LOADING) {
  7439. self.states[url] = LOADING;
  7440. self.loading++;
  7441. self.loadScript(url, function () {
  7442. self.states[url] = LOADED;
  7443. self.loading--;
  7444. execCallbacks('success', url);
  7445. loadScripts();
  7446. }, function () {
  7447. self.states[url] = FAILED;
  7448. self.loading--;
  7449. failures.push(url);
  7450. execCallbacks('failure', url);
  7451. loadScripts();
  7452. });
  7453. }
  7454. });
  7455. if (!self.loading) {
  7456. var notifyCallbacks = self.queueLoadedCallbacks.slice(0);
  7457. self.queueLoadedCallbacks.length = 0;
  7458. each$e(notifyCallbacks, function (callback) {
  7459. if (failures.length === 0) {
  7460. if (isFunction(callback.success)) {
  7461. callback.success.call(callback.scope);
  7462. }
  7463. } else {
  7464. if (isFunction(callback.failure)) {
  7465. callback.failure.call(callback.scope, failures);
  7466. }
  7467. }
  7468. });
  7469. }
  7470. };
  7471. loadScripts();
  7472. };
  7473. ScriptLoader.ScriptLoader = new ScriptLoader();
  7474. return ScriptLoader;
  7475. }();
  7476. var Cell = function (initial) {
  7477. var value = initial;
  7478. var get = function () {
  7479. return value;
  7480. };
  7481. var set = function (v) {
  7482. value = v;
  7483. };
  7484. return {
  7485. get: get,
  7486. set: set
  7487. };
  7488. };
  7489. var isRaw = function (str) {
  7490. return isObject(str) && has$2(str, 'raw');
  7491. };
  7492. var isTokenised = function (str) {
  7493. return isArray$1(str) && str.length > 1;
  7494. };
  7495. var data = {};
  7496. var currentCode = Cell('en');
  7497. var getLanguageData = function () {
  7498. return get$9(data, currentCode.get());
  7499. };
  7500. var getData = function () {
  7501. return map$2(data, function (value) {
  7502. return __assign({}, value);
  7503. });
  7504. };
  7505. var setCode = function (newCode) {
  7506. if (newCode) {
  7507. currentCode.set(newCode);
  7508. }
  7509. };
  7510. var getCode = function () {
  7511. return currentCode.get();
  7512. };
  7513. var add$4 = function (code, items) {
  7514. var langData = data[code];
  7515. if (!langData) {
  7516. data[code] = langData = {};
  7517. }
  7518. each$j(items, function (translation, name) {
  7519. langData[name.toLowerCase()] = translation;
  7520. });
  7521. };
  7522. var translate = function (text) {
  7523. var langData = getLanguageData().getOr({});
  7524. var toString = function (obj) {
  7525. if (isFunction(obj)) {
  7526. return Object.prototype.toString.call(obj);
  7527. }
  7528. return !isEmpty(obj) ? '' + obj : '';
  7529. };
  7530. var isEmpty = function (text) {
  7531. return text === '' || text === null || text === undefined;
  7532. };
  7533. var getLangData = function (text) {
  7534. var textstr = toString(text);
  7535. return get$9(langData, textstr.toLowerCase()).map(toString).getOr(textstr);
  7536. };
  7537. var removeContext = function (str) {
  7538. return str.replace(/{context:\w+}$/, '');
  7539. };
  7540. if (isEmpty(text)) {
  7541. return '';
  7542. }
  7543. if (isRaw(text)) {
  7544. return toString(text.raw);
  7545. }
  7546. if (isTokenised(text)) {
  7547. var values_1 = text.slice(1);
  7548. var substitued = getLangData(text[0]).replace(/\{([0-9]+)\}/g, function ($1, $2) {
  7549. return has$2(values_1, $2) ? toString(values_1[$2]) : $1;
  7550. });
  7551. return removeContext(substitued);
  7552. }
  7553. return removeContext(getLangData(text));
  7554. };
  7555. var isRtl$1 = function () {
  7556. return getLanguageData().bind(function (items) {
  7557. return get$9(items, '_dir');
  7558. }).exists(function (dir) {
  7559. return dir === 'rtl';
  7560. });
  7561. };
  7562. var hasCode = function (code) {
  7563. return has$2(data, code);
  7564. };
  7565. var I18n = {
  7566. getData: getData,
  7567. setCode: setCode,
  7568. getCode: getCode,
  7569. add: add$4,
  7570. translate: translate,
  7571. isRtl: isRtl$1,
  7572. hasCode: hasCode
  7573. };
  7574. var AddOnManager = function () {
  7575. var items = [];
  7576. var urls = {};
  7577. var lookup = {};
  7578. var _listeners = [];
  7579. var runListeners = function (name, state) {
  7580. var matchedListeners = filter$4(_listeners, function (listener) {
  7581. return listener.name === name && listener.state === state;
  7582. });
  7583. each$k(matchedListeners, function (listener) {
  7584. return listener.callback();
  7585. });
  7586. };
  7587. var get = function (name) {
  7588. if (lookup[name]) {
  7589. return lookup[name].instance;
  7590. }
  7591. return undefined;
  7592. };
  7593. var dependencies = function (name) {
  7594. var result;
  7595. if (lookup[name]) {
  7596. result = lookup[name].dependencies;
  7597. }
  7598. return result || [];
  7599. };
  7600. var requireLangPack = function (name, languages) {
  7601. if (AddOnManager.languageLoad !== false) {
  7602. waitFor(name, function () {
  7603. var language = I18n.getCode();
  7604. var wrappedLanguages = ',' + (languages || '') + ',';
  7605. if (!language || languages && wrappedLanguages.indexOf(',' + language + ',') === -1) {
  7606. return;
  7607. }
  7608. ScriptLoader.ScriptLoader.add(urls[name] + '/langs/' + language + '.js');
  7609. }, 'loaded');
  7610. }
  7611. };
  7612. var add = function (id, addOn, dependencies) {
  7613. var addOnConstructor = addOn;
  7614. items.push(addOnConstructor);
  7615. lookup[id] = {
  7616. instance: addOnConstructor,
  7617. dependencies: dependencies
  7618. };
  7619. runListeners(id, 'added');
  7620. return addOnConstructor;
  7621. };
  7622. var remove = function (name) {
  7623. delete urls[name];
  7624. delete lookup[name];
  7625. };
  7626. var createUrl = function (baseUrl, dep) {
  7627. if (typeof dep === 'object') {
  7628. return dep;
  7629. }
  7630. return typeof baseUrl === 'string' ? {
  7631. prefix: '',
  7632. resource: dep,
  7633. suffix: ''
  7634. } : {
  7635. prefix: baseUrl.prefix,
  7636. resource: dep,
  7637. suffix: baseUrl.suffix
  7638. };
  7639. };
  7640. var addComponents = function (pluginName, scripts) {
  7641. var pluginUrl = urls[pluginName];
  7642. each$k(scripts, function (script) {
  7643. ScriptLoader.ScriptLoader.add(pluginUrl + '/' + script);
  7644. });
  7645. };
  7646. var loadDependencies = function (name, addOnUrl, success, scope) {
  7647. var deps = dependencies(name);
  7648. each$k(deps, function (dep) {
  7649. var newUrl = createUrl(addOnUrl, dep);
  7650. load(newUrl.resource, newUrl, undefined, undefined);
  7651. });
  7652. if (success) {
  7653. if (scope) {
  7654. success.call(scope);
  7655. } else {
  7656. success.call(ScriptLoader);
  7657. }
  7658. }
  7659. };
  7660. var load = function (name, addOnUrl, success, scope, failure) {
  7661. if (urls[name]) {
  7662. return;
  7663. }
  7664. var urlString = typeof addOnUrl === 'string' ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
  7665. if (urlString.indexOf('/') !== 0 && urlString.indexOf('://') === -1) {
  7666. urlString = AddOnManager.baseURL + '/' + urlString;
  7667. }
  7668. urls[name] = urlString.substring(0, urlString.lastIndexOf('/'));
  7669. var done = function () {
  7670. runListeners(name, 'loaded');
  7671. loadDependencies(name, addOnUrl, success, scope);
  7672. };
  7673. if (lookup[name]) {
  7674. done();
  7675. } else {
  7676. ScriptLoader.ScriptLoader.add(urlString, done, scope, failure);
  7677. }
  7678. };
  7679. var waitFor = function (name, callback, state) {
  7680. if (state === void 0) {
  7681. state = 'added';
  7682. }
  7683. if (has$2(lookup, name) && state === 'added') {
  7684. callback();
  7685. } else if (has$2(urls, name) && state === 'loaded') {
  7686. callback();
  7687. } else {
  7688. _listeners.push({
  7689. name: name,
  7690. state: state,
  7691. callback: callback
  7692. });
  7693. }
  7694. };
  7695. return {
  7696. items: items,
  7697. urls: urls,
  7698. lookup: lookup,
  7699. _listeners: _listeners,
  7700. get: get,
  7701. dependencies: dependencies,
  7702. requireLangPack: requireLangPack,
  7703. add: add,
  7704. remove: remove,
  7705. createUrl: createUrl,
  7706. addComponents: addComponents,
  7707. load: load,
  7708. waitFor: waitFor
  7709. };
  7710. };
  7711. AddOnManager.languageLoad = true;
  7712. AddOnManager.baseURL = '';
  7713. AddOnManager.PluginManager = AddOnManager();
  7714. AddOnManager.ThemeManager = AddOnManager();
  7715. var singleton = function (doRevoke) {
  7716. var subject = Cell(Optional.none());
  7717. var revoke = function () {
  7718. return subject.get().each(doRevoke);
  7719. };
  7720. var clear = function () {
  7721. revoke();
  7722. subject.set(Optional.none());
  7723. };
  7724. var isSet = function () {
  7725. return subject.get().isSome();
  7726. };
  7727. var get = function () {
  7728. return subject.get();
  7729. };
  7730. var set = function (s) {
  7731. revoke();
  7732. subject.set(Optional.some(s));
  7733. };
  7734. return {
  7735. clear: clear,
  7736. isSet: isSet,
  7737. get: get,
  7738. set: set
  7739. };
  7740. };
  7741. var value = function () {
  7742. var subject = singleton(noop);
  7743. var on = function (f) {
  7744. return subject.get().each(f);
  7745. };
  7746. return __assign(__assign({}, subject), { on: on });
  7747. };
  7748. var first = function (fn, rate) {
  7749. var timer = null;
  7750. var cancel = function () {
  7751. if (!isNull(timer)) {
  7752. clearTimeout(timer);
  7753. timer = null;
  7754. }
  7755. };
  7756. var throttle = function () {
  7757. var args = [];
  7758. for (var _i = 0; _i < arguments.length; _i++) {
  7759. args[_i] = arguments[_i];
  7760. }
  7761. if (isNull(timer)) {
  7762. timer = setTimeout(function () {
  7763. timer = null;
  7764. fn.apply(null, args);
  7765. }, rate);
  7766. }
  7767. };
  7768. return {
  7769. cancel: cancel,
  7770. throttle: throttle
  7771. };
  7772. };
  7773. var last = function (fn, rate) {
  7774. var timer = null;
  7775. var cancel = function () {
  7776. if (!isNull(timer)) {
  7777. clearTimeout(timer);
  7778. timer = null;
  7779. }
  7780. };
  7781. var throttle = function () {
  7782. var args = [];
  7783. for (var _i = 0; _i < arguments.length; _i++) {
  7784. args[_i] = arguments[_i];
  7785. }
  7786. cancel();
  7787. timer = setTimeout(function () {
  7788. timer = null;
  7789. fn.apply(null, args);
  7790. }, rate);
  7791. };
  7792. return {
  7793. cancel: cancel,
  7794. throttle: throttle
  7795. };
  7796. };
  7797. var read$4 = function (element, attr) {
  7798. var value = get$6(element, attr);
  7799. return value === undefined || value === '' ? [] : value.split(' ');
  7800. };
  7801. var add$3 = function (element, attr, id) {
  7802. var old = read$4(element, attr);
  7803. var nu = old.concat([id]);
  7804. set$1(element, attr, nu.join(' '));
  7805. return true;
  7806. };
  7807. var remove$5 = function (element, attr, id) {
  7808. var nu = filter$4(read$4(element, attr), function (v) {
  7809. return v !== id;
  7810. });
  7811. if (nu.length > 0) {
  7812. set$1(element, attr, nu.join(' '));
  7813. } else {
  7814. remove$6(element, attr);
  7815. }
  7816. return false;
  7817. };
  7818. var supports = function (element) {
  7819. return element.dom.classList !== undefined;
  7820. };
  7821. var get$4 = function (element) {
  7822. return read$4(element, 'class');
  7823. };
  7824. var add$2 = function (element, clazz) {
  7825. return add$3(element, 'class', clazz);
  7826. };
  7827. var remove$4 = function (element, clazz) {
  7828. return remove$5(element, 'class', clazz);
  7829. };
  7830. var add$1 = function (element, clazz) {
  7831. if (supports(element)) {
  7832. element.dom.classList.add(clazz);
  7833. } else {
  7834. add$2(element, clazz);
  7835. }
  7836. };
  7837. var cleanClass = function (element) {
  7838. var classList = supports(element) ? element.dom.classList : get$4(element);
  7839. if (classList.length === 0) {
  7840. remove$6(element, 'class');
  7841. }
  7842. };
  7843. var remove$3 = function (element, clazz) {
  7844. if (supports(element)) {
  7845. var classList = element.dom.classList;
  7846. classList.remove(clazz);
  7847. } else {
  7848. remove$4(element, clazz);
  7849. }
  7850. cleanClass(element);
  7851. };
  7852. var has = function (element, clazz) {
  7853. return supports(element) && element.dom.classList.contains(clazz);
  7854. };
  7855. var descendants$1 = function (scope, predicate) {
  7856. var result = [];
  7857. each$k(children(scope), function (x) {
  7858. if (predicate(x)) {
  7859. result = result.concat([x]);
  7860. }
  7861. result = result.concat(descendants$1(x, predicate));
  7862. });
  7863. return result;
  7864. };
  7865. var descendants = function (scope, selector) {
  7866. return all(selector, scope);
  7867. };
  7868. var annotation = constant('mce-annotation');
  7869. var dataAnnotation = constant('data-mce-annotation');
  7870. var dataAnnotationId = constant('data-mce-annotation-uid');
  7871. var identify = function (editor, annotationName) {
  7872. var rng = editor.selection.getRng();
  7873. var start = SugarElement.fromDom(rng.startContainer);
  7874. var root = SugarElement.fromDom(editor.getBody());
  7875. var selector = annotationName.fold(function () {
  7876. return '.' + annotation();
  7877. }, function (an) {
  7878. return '[' + dataAnnotation() + '="' + an + '"]';
  7879. });
  7880. var newStart = child$1(start, rng.startOffset).getOr(start);
  7881. var closest = closest$2(newStart, selector, function (n) {
  7882. return eq(n, root);
  7883. });
  7884. var getAttr = function (c, property) {
  7885. if (has$1(c, property)) {
  7886. return Optional.some(get$6(c, property));
  7887. } else {
  7888. return Optional.none();
  7889. }
  7890. };
  7891. return closest.bind(function (c) {
  7892. return getAttr(c, '' + dataAnnotationId()).bind(function (uid) {
  7893. return getAttr(c, '' + dataAnnotation()).map(function (name) {
  7894. var elements = findMarkers(editor, uid);
  7895. return {
  7896. uid: uid,
  7897. name: name,
  7898. elements: elements
  7899. };
  7900. });
  7901. });
  7902. });
  7903. };
  7904. var isAnnotation = function (elem) {
  7905. return isElement$6(elem) && has(elem, annotation());
  7906. };
  7907. var findMarkers = function (editor, uid) {
  7908. var body = SugarElement.fromDom(editor.getBody());
  7909. return descendants(body, '[' + dataAnnotationId() + '="' + uid + '"]');
  7910. };
  7911. var findAll = function (editor, name) {
  7912. var body = SugarElement.fromDom(editor.getBody());
  7913. var markers = descendants(body, '[' + dataAnnotation() + '="' + name + '"]');
  7914. var directory = {};
  7915. each$k(markers, function (m) {
  7916. var uid = get$6(m, dataAnnotationId());
  7917. var nodesAlready = get$9(directory, uid).getOr([]);
  7918. directory[uid] = nodesAlready.concat([m]);
  7919. });
  7920. return directory;
  7921. };
  7922. var setup$n = function (editor, _registry) {
  7923. var changeCallbacks = Cell({});
  7924. var initData = function () {
  7925. return {
  7926. listeners: [],
  7927. previous: value()
  7928. };
  7929. };
  7930. var withCallbacks = function (name, f) {
  7931. updateCallbacks(name, function (data) {
  7932. f(data);
  7933. return data;
  7934. });
  7935. };
  7936. var updateCallbacks = function (name, f) {
  7937. var callbackMap = changeCallbacks.get();
  7938. var data = get$9(callbackMap, name).getOrThunk(initData);
  7939. var outputData = f(data);
  7940. callbackMap[name] = outputData;
  7941. changeCallbacks.set(callbackMap);
  7942. };
  7943. var fireCallbacks = function (name, uid, elements) {
  7944. withCallbacks(name, function (data) {
  7945. each$k(data.listeners, function (f) {
  7946. return f(true, name, {
  7947. uid: uid,
  7948. nodes: map$3(elements, function (elem) {
  7949. return elem.dom;
  7950. })
  7951. });
  7952. });
  7953. });
  7954. };
  7955. var fireNoAnnotation = function (name) {
  7956. withCallbacks(name, function (data) {
  7957. each$k(data.listeners, function (f) {
  7958. return f(false, name);
  7959. });
  7960. });
  7961. };
  7962. var onNodeChange = last(function () {
  7963. var callbackMap = changeCallbacks.get();
  7964. var annotations = sort(keys(callbackMap));
  7965. each$k(annotations, function (name) {
  7966. updateCallbacks(name, function (data) {
  7967. var prev = data.previous.get();
  7968. identify(editor, Optional.some(name)).fold(function () {
  7969. if (prev.isSome()) {
  7970. fireNoAnnotation(name);
  7971. data.previous.clear();
  7972. }
  7973. }, function (_a) {
  7974. var uid = _a.uid, name = _a.name, elements = _a.elements;
  7975. if (!is$1(prev, uid)) {
  7976. fireCallbacks(name, uid, elements);
  7977. data.previous.set(uid);
  7978. }
  7979. });
  7980. return {
  7981. previous: data.previous,
  7982. listeners: data.listeners
  7983. };
  7984. });
  7985. });
  7986. }, 30);
  7987. editor.on('remove', function () {
  7988. onNodeChange.cancel();
  7989. });
  7990. editor.on('NodeChange', function () {
  7991. onNodeChange.throttle();
  7992. });
  7993. var addListener = function (name, f) {
  7994. updateCallbacks(name, function (data) {
  7995. return {
  7996. previous: data.previous,
  7997. listeners: data.listeners.concat([f])
  7998. };
  7999. });
  8000. };
  8001. return { addListener: addListener };
  8002. };
  8003. var setup$m = function (editor, registry) {
  8004. var identifyParserNode = function (span) {
  8005. return Optional.from(span.attr(dataAnnotation())).bind(registry.lookup);
  8006. };
  8007. editor.on('init', function () {
  8008. editor.serializer.addNodeFilter('span', function (spans) {
  8009. each$k(spans, function (span) {
  8010. identifyParserNode(span).each(function (settings) {
  8011. if (settings.persistent === false) {
  8012. span.unwrap();
  8013. }
  8014. });
  8015. });
  8016. });
  8017. });
  8018. };
  8019. var create$7 = function () {
  8020. var annotations = {};
  8021. var register = function (name, settings) {
  8022. annotations[name] = {
  8023. name: name,
  8024. settings: settings
  8025. };
  8026. };
  8027. var lookup = function (name) {
  8028. return get$9(annotations, name).map(function (a) {
  8029. return a.settings;
  8030. });
  8031. };
  8032. return {
  8033. register: register,
  8034. lookup: lookup
  8035. };
  8036. };
  8037. var unique = 0;
  8038. var generate = function (prefix) {
  8039. var date = new Date();
  8040. var time = date.getTime();
  8041. var random = Math.floor(Math.random() * 1000000000);
  8042. unique++;
  8043. return prefix + '_' + random + unique + String(time);
  8044. };
  8045. var add = function (element, classes) {
  8046. each$k(classes, function (x) {
  8047. add$1(element, x);
  8048. });
  8049. };
  8050. var fromHtml = function (html, scope) {
  8051. var doc = scope || document;
  8052. var div = doc.createElement('div');
  8053. div.innerHTML = html;
  8054. return children(SugarElement.fromDom(div));
  8055. };
  8056. var fromDom$1 = function (nodes) {
  8057. return map$3(nodes, SugarElement.fromDom);
  8058. };
  8059. var get$3 = function (element) {
  8060. return element.dom.innerHTML;
  8061. };
  8062. var set = function (element, content) {
  8063. var owner = owner$1(element);
  8064. var docDom = owner.dom;
  8065. var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  8066. var contentElements = fromHtml(content, docDom);
  8067. append(fragment, contentElements);
  8068. empty(element);
  8069. append$1(element, fragment);
  8070. };
  8071. var clone$1 = function (original, isDeep) {
  8072. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  8073. };
  8074. var shallow = function (original) {
  8075. return clone$1(original, false);
  8076. };
  8077. var deep$1 = function (original) {
  8078. return clone$1(original, true);
  8079. };
  8080. var TextWalker = function (startNode, rootNode, isBoundary) {
  8081. if (isBoundary === void 0) {
  8082. isBoundary = never;
  8083. }
  8084. var walker = new DomTreeWalker(startNode, rootNode);
  8085. var walk = function (direction) {
  8086. var next;
  8087. do {
  8088. next = walker[direction]();
  8089. } while (next && !isText$7(next) && !isBoundary(next));
  8090. return Optional.from(next).filter(isText$7);
  8091. };
  8092. return {
  8093. current: function () {
  8094. return Optional.from(walker.current()).filter(isText$7);
  8095. },
  8096. next: function () {
  8097. return walk('next');
  8098. },
  8099. prev: function () {
  8100. return walk('prev');
  8101. },
  8102. prev2: function () {
  8103. return walk('prev2');
  8104. }
  8105. };
  8106. };
  8107. var TextSeeker = function (dom, isBoundary) {
  8108. var isBlockBoundary = isBoundary ? isBoundary : function (node) {
  8109. return dom.isBlock(node) || isBr$5(node) || isContentEditableFalse$b(node);
  8110. };
  8111. var walk = function (node, offset, walker, process) {
  8112. if (isText$7(node)) {
  8113. var newOffset = process(node, offset, node.data);
  8114. if (newOffset !== -1) {
  8115. return Optional.some({
  8116. container: node,
  8117. offset: newOffset
  8118. });
  8119. }
  8120. }
  8121. return walker().bind(function (next) {
  8122. return walk(next.container, next.offset, walker, process);
  8123. });
  8124. };
  8125. var backwards = function (node, offset, process, root) {
  8126. var walker = TextWalker(node, root, isBlockBoundary);
  8127. return walk(node, offset, function () {
  8128. return walker.prev().map(function (prev) {
  8129. return {
  8130. container: prev,
  8131. offset: prev.length
  8132. };
  8133. });
  8134. }, process).getOrNull();
  8135. };
  8136. var forwards = function (node, offset, process, root) {
  8137. var walker = TextWalker(node, root, isBlockBoundary);
  8138. return walk(node, offset, function () {
  8139. return walker.next().map(function (next) {
  8140. return {
  8141. container: next,
  8142. offset: 0
  8143. };
  8144. });
  8145. }, process).getOrNull();
  8146. };
  8147. return {
  8148. backwards: backwards,
  8149. forwards: forwards
  8150. };
  8151. };
  8152. var round$2 = Math.round;
  8153. var clone = function (rect) {
  8154. if (!rect) {
  8155. return {
  8156. left: 0,
  8157. top: 0,
  8158. bottom: 0,
  8159. right: 0,
  8160. width: 0,
  8161. height: 0
  8162. };
  8163. }
  8164. return {
  8165. left: round$2(rect.left),
  8166. top: round$2(rect.top),
  8167. bottom: round$2(rect.bottom),
  8168. right: round$2(rect.right),
  8169. width: round$2(rect.width),
  8170. height: round$2(rect.height)
  8171. };
  8172. };
  8173. var collapse = function (rect, toStart) {
  8174. rect = clone(rect);
  8175. if (toStart) {
  8176. rect.right = rect.left;
  8177. } else {
  8178. rect.left = rect.left + rect.width;
  8179. rect.right = rect.left;
  8180. }
  8181. rect.width = 0;
  8182. return rect;
  8183. };
  8184. var isEqual = function (rect1, rect2) {
  8185. return rect1.left === rect2.left && rect1.top === rect2.top && rect1.bottom === rect2.bottom && rect1.right === rect2.right;
  8186. };
  8187. var isValidOverflow = function (overflowY, rect1, rect2) {
  8188. return overflowY >= 0 && overflowY <= Math.min(rect1.height, rect2.height) / 2;
  8189. };
  8190. var isAbove$1 = function (rect1, rect2) {
  8191. var halfHeight = Math.min(rect2.height / 2, rect1.height / 2);
  8192. if (rect1.bottom - halfHeight < rect2.top) {
  8193. return true;
  8194. }
  8195. if (rect1.top > rect2.bottom) {
  8196. return false;
  8197. }
  8198. return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
  8199. };
  8200. var isBelow$1 = function (rect1, rect2) {
  8201. if (rect1.top > rect2.bottom) {
  8202. return true;
  8203. }
  8204. if (rect1.bottom < rect2.top) {
  8205. return false;
  8206. }
  8207. return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
  8208. };
  8209. var containsXY = function (rect, clientX, clientY) {
  8210. return clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
  8211. };
  8212. var clamp$2 = function (value, min, max) {
  8213. return Math.min(Math.max(value, min), max);
  8214. };
  8215. var getSelectedNode = function (range) {
  8216. var startContainer = range.startContainer, startOffset = range.startOffset;
  8217. if (startContainer.hasChildNodes() && range.endOffset === startOffset + 1) {
  8218. return startContainer.childNodes[startOffset];
  8219. }
  8220. return null;
  8221. };
  8222. var getNode$1 = function (container, offset) {
  8223. if (isElement$5(container) && container.hasChildNodes()) {
  8224. var childNodes = container.childNodes;
  8225. var safeOffset = clamp$2(offset, 0, childNodes.length - 1);
  8226. return childNodes[safeOffset];
  8227. } else {
  8228. return container;
  8229. }
  8230. };
  8231. var getNodeUnsafe = function (container, offset) {
  8232. if (offset < 0 && isElement$5(container) && container.hasChildNodes()) {
  8233. return undefined;
  8234. } else {
  8235. return getNode$1(container, offset);
  8236. }
  8237. };
  8238. var extendingChars = new RegExp('[\u0300-\u036f\u0483-\u0487\u0488-\u0489\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u0610-\u061a' + '\u064b-\u065f\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0' + '\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e3-\u0902\u093a\u093c' + '\u0941-\u0948\u094d\u0951-\u0957\u0962-\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2-\u09e3' + '\u0a01-\u0a02\u0a3c\u0a41-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a51\u0a70-\u0a71\u0a75\u0a81-\u0a82\u0abc' + '\u0ac1-\u0ac5\u0ac7-\u0ac8\u0acd\u0ae2-\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57' + '\u0b62-\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c00\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56' + '\u0c62-\u0c63\u0c81\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc-\u0ccd\u0cd5-\u0cd6\u0ce2-\u0ce3\u0d01\u0d3e\u0d41-\u0d44' + '\u0d4d\u0d57\u0d62-\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9' + '\u0ebb-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86-\u0f87\u0f8d-\u0f97' + '\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039-\u103a\u103d-\u103e\u1058-\u1059\u105e-\u1060\u1071-\u1074' + '\u1082\u1085-\u1086\u108d\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752-\u1753\u1772-\u1773\u17b4-\u17b5' + '\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927-\u1928\u1932\u1939-\u193b\u1a17-\u1a18' + '\u1a1b\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1ab0-\u1abd\u1ABE\u1b00-\u1b03\u1b34' + '\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80-\u1b81\u1ba2-\u1ba5\u1ba8-\u1ba9\u1bab-\u1bad\u1be6\u1be8-\u1be9' + '\u1bed\u1bef-\u1bf1\u1c2c-\u1c33\u1c36-\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1cf4\u1cf8-\u1cf9' + '\u1dc0-\u1df5\u1dfc-\u1dff\u200c-\u200d\u20d0-\u20dc\u20DD-\u20E0\u20e1\u20E2-\u20E4\u20e5-\u20f0\u2cef-\u2cf1' + '\u2d7f\u2de0-\u2dff\u302a-\u302d\u302e-\u302f\u3099-\u309a\ua66f\uA670-\uA672\ua674-\ua67d\ua69e-\ua69f\ua6f0-\ua6f1' + '\ua802\ua806\ua80b\ua825-\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc' + '\ua9e5\uaa29-\uaa2e\uaa31-\uaa32\uaa35-\uaa36\uaa43\uaa4c\uaa7c\uaab0\uaab2-\uaab4\uaab7-\uaab8\uaabe-\uaabf\uaac1' + '\uaaec-\uaaed\uaaf6\uabe5\uabe8\uabed\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\uff9e-\uff9f]');
  8239. var isExtendingChar = function (ch) {
  8240. return typeof ch === 'string' && ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
  8241. };
  8242. var or = function () {
  8243. var args = [];
  8244. for (var _i = 0; _i < arguments.length; _i++) {
  8245. args[_i] = arguments[_i];
  8246. }
  8247. return function (x) {
  8248. for (var i = 0; i < args.length; i++) {
  8249. if (args[i](x)) {
  8250. return true;
  8251. }
  8252. }
  8253. return false;
  8254. };
  8255. };
  8256. var and = function () {
  8257. var args = [];
  8258. for (var _i = 0; _i < arguments.length; _i++) {
  8259. args[_i] = arguments[_i];
  8260. }
  8261. return function (x) {
  8262. for (var i = 0; i < args.length; i++) {
  8263. if (!args[i](x)) {
  8264. return false;
  8265. }
  8266. }
  8267. return true;
  8268. };
  8269. };
  8270. var isElement$3 = isElement$5;
  8271. var isCaretCandidate$2 = isCaretCandidate$3;
  8272. var isBlock$1 = matchStyleValues('display', 'block table');
  8273. var isFloated = matchStyleValues('float', 'left right');
  8274. var isValidElementCaretCandidate = and(isElement$3, isCaretCandidate$2, not(isFloated));
  8275. var isNotPre = not(matchStyleValues('white-space', 'pre pre-line pre-wrap'));
  8276. var isText$4 = isText$7;
  8277. var isBr$2 = isBr$5;
  8278. var nodeIndex$1 = DOMUtils.nodeIndex;
  8279. var resolveIndex$1 = getNodeUnsafe;
  8280. var createRange$1 = function (doc) {
  8281. return 'createRange' in doc ? doc.createRange() : DOMUtils.DOM.createRng();
  8282. };
  8283. var isWhiteSpace$1 = function (chr) {
  8284. return chr && /[\r\n\t ]/.test(chr);
  8285. };
  8286. var isRange = function (rng) {
  8287. return !!rng.setStart && !!rng.setEnd;
  8288. };
  8289. var isHiddenWhiteSpaceRange = function (range) {
  8290. var container = range.startContainer;
  8291. var offset = range.startOffset;
  8292. if (isWhiteSpace$1(range.toString()) && isNotPre(container.parentNode) && isText$7(container)) {
  8293. var text = container.data;
  8294. if (isWhiteSpace$1(text[offset - 1]) || isWhiteSpace$1(text[offset + 1])) {
  8295. return true;
  8296. }
  8297. }
  8298. return false;
  8299. };
  8300. var getBrClientRect = function (brNode) {
  8301. var doc = brNode.ownerDocument;
  8302. var rng = createRange$1(doc);
  8303. var nbsp$1 = doc.createTextNode(nbsp);
  8304. var parentNode = brNode.parentNode;
  8305. parentNode.insertBefore(nbsp$1, brNode);
  8306. rng.setStart(nbsp$1, 0);
  8307. rng.setEnd(nbsp$1, 1);
  8308. var clientRect = clone(rng.getBoundingClientRect());
  8309. parentNode.removeChild(nbsp$1);
  8310. return clientRect;
  8311. };
  8312. var getBoundingClientRectWebKitText = function (rng) {
  8313. var sc = rng.startContainer;
  8314. var ec = rng.endContainer;
  8315. var so = rng.startOffset;
  8316. var eo = rng.endOffset;
  8317. if (sc === ec && isText$7(ec) && so === 0 && eo === 1) {
  8318. var newRng = rng.cloneRange();
  8319. newRng.setEndAfter(ec);
  8320. return getBoundingClientRect$1(newRng);
  8321. } else {
  8322. return null;
  8323. }
  8324. };
  8325. var isZeroRect = function (r) {
  8326. return r.left === 0 && r.right === 0 && r.top === 0 && r.bottom === 0;
  8327. };
  8328. var getBoundingClientRect$1 = function (item) {
  8329. var clientRect;
  8330. var clientRects = item.getClientRects();
  8331. if (clientRects.length > 0) {
  8332. clientRect = clone(clientRects[0]);
  8333. } else {
  8334. clientRect = clone(item.getBoundingClientRect());
  8335. }
  8336. if (!isRange(item) && isBr$2(item) && isZeroRect(clientRect)) {
  8337. return getBrClientRect(item);
  8338. }
  8339. if (isZeroRect(clientRect) && isRange(item)) {
  8340. return getBoundingClientRectWebKitText(item);
  8341. }
  8342. return clientRect;
  8343. };
  8344. var collapseAndInflateWidth = function (clientRect, toStart) {
  8345. var newClientRect = collapse(clientRect, toStart);
  8346. newClientRect.width = 1;
  8347. newClientRect.right = newClientRect.left + 1;
  8348. return newClientRect;
  8349. };
  8350. var getCaretPositionClientRects = function (caretPosition) {
  8351. var clientRects = [];
  8352. var addUniqueAndValidRect = function (clientRect) {
  8353. if (clientRect.height === 0) {
  8354. return;
  8355. }
  8356. if (clientRects.length > 0) {
  8357. if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
  8358. return;
  8359. }
  8360. }
  8361. clientRects.push(clientRect);
  8362. };
  8363. var addCharacterOffset = function (container, offset) {
  8364. var range = createRange$1(container.ownerDocument);
  8365. if (offset < container.data.length) {
  8366. if (isExtendingChar(container.data[offset])) {
  8367. return clientRects;
  8368. }
  8369. if (isExtendingChar(container.data[offset - 1])) {
  8370. range.setStart(container, offset);
  8371. range.setEnd(container, offset + 1);
  8372. if (!isHiddenWhiteSpaceRange(range)) {
  8373. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  8374. return clientRects;
  8375. }
  8376. }
  8377. }
  8378. if (offset > 0) {
  8379. range.setStart(container, offset - 1);
  8380. range.setEnd(container, offset);
  8381. if (!isHiddenWhiteSpaceRange(range)) {
  8382. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  8383. }
  8384. }
  8385. if (offset < container.data.length) {
  8386. range.setStart(container, offset);
  8387. range.setEnd(container, offset + 1);
  8388. if (!isHiddenWhiteSpaceRange(range)) {
  8389. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), true));
  8390. }
  8391. }
  8392. };
  8393. var container = caretPosition.container();
  8394. var offset = caretPosition.offset();
  8395. if (isText$4(container)) {
  8396. addCharacterOffset(container, offset);
  8397. return clientRects;
  8398. }
  8399. if (isElement$3(container)) {
  8400. if (caretPosition.isAtEnd()) {
  8401. var node = resolveIndex$1(container, offset);
  8402. if (isText$4(node)) {
  8403. addCharacterOffset(node, node.data.length);
  8404. }
  8405. if (isValidElementCaretCandidate(node) && !isBr$2(node)) {
  8406. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  8407. }
  8408. } else {
  8409. var node = resolveIndex$1(container, offset);
  8410. if (isText$4(node)) {
  8411. addCharacterOffset(node, 0);
  8412. }
  8413. if (isValidElementCaretCandidate(node) && caretPosition.isAtEnd()) {
  8414. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  8415. return clientRects;
  8416. }
  8417. var beforeNode = resolveIndex$1(caretPosition.container(), caretPosition.offset() - 1);
  8418. if (isValidElementCaretCandidate(beforeNode) && !isBr$2(beforeNode)) {
  8419. if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
  8420. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(beforeNode), false));
  8421. }
  8422. }
  8423. if (isValidElementCaretCandidate(node)) {
  8424. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), true));
  8425. }
  8426. }
  8427. }
  8428. return clientRects;
  8429. };
  8430. var CaretPosition = function (container, offset, clientRects) {
  8431. var isAtStart = function () {
  8432. if (isText$4(container)) {
  8433. return offset === 0;
  8434. }
  8435. return offset === 0;
  8436. };
  8437. var isAtEnd = function () {
  8438. if (isText$4(container)) {
  8439. return offset >= container.data.length;
  8440. }
  8441. return offset >= container.childNodes.length;
  8442. };
  8443. var toRange = function () {
  8444. var range = createRange$1(container.ownerDocument);
  8445. range.setStart(container, offset);
  8446. range.setEnd(container, offset);
  8447. return range;
  8448. };
  8449. var getClientRects = function () {
  8450. if (!clientRects) {
  8451. clientRects = getCaretPositionClientRects(CaretPosition(container, offset));
  8452. }
  8453. return clientRects;
  8454. };
  8455. var isVisible = function () {
  8456. return getClientRects().length > 0;
  8457. };
  8458. var isEqual = function (caretPosition) {
  8459. return caretPosition && container === caretPosition.container() && offset === caretPosition.offset();
  8460. };
  8461. var getNode = function (before) {
  8462. return resolveIndex$1(container, before ? offset - 1 : offset);
  8463. };
  8464. return {
  8465. container: constant(container),
  8466. offset: constant(offset),
  8467. toRange: toRange,
  8468. getClientRects: getClientRects,
  8469. isVisible: isVisible,
  8470. isAtStart: isAtStart,
  8471. isAtEnd: isAtEnd,
  8472. isEqual: isEqual,
  8473. getNode: getNode
  8474. };
  8475. };
  8476. CaretPosition.fromRangeStart = function (range) {
  8477. return CaretPosition(range.startContainer, range.startOffset);
  8478. };
  8479. CaretPosition.fromRangeEnd = function (range) {
  8480. return CaretPosition(range.endContainer, range.endOffset);
  8481. };
  8482. CaretPosition.after = function (node) {
  8483. return CaretPosition(node.parentNode, nodeIndex$1(node) + 1);
  8484. };
  8485. CaretPosition.before = function (node) {
  8486. return CaretPosition(node.parentNode, nodeIndex$1(node));
  8487. };
  8488. CaretPosition.isAbove = function (pos1, pos2) {
  8489. return lift2(head(pos2.getClientRects()), last$2(pos1.getClientRects()), isAbove$1).getOr(false);
  8490. };
  8491. CaretPosition.isBelow = function (pos1, pos2) {
  8492. return lift2(last$2(pos2.getClientRects()), head(pos1.getClientRects()), isBelow$1).getOr(false);
  8493. };
  8494. CaretPosition.isAtStart = function (pos) {
  8495. return pos ? pos.isAtStart() : false;
  8496. };
  8497. CaretPosition.isAtEnd = function (pos) {
  8498. return pos ? pos.isAtEnd() : false;
  8499. };
  8500. CaretPosition.isTextPosition = function (pos) {
  8501. return pos ? isText$7(pos.container()) : false;
  8502. };
  8503. CaretPosition.isElementPosition = function (pos) {
  8504. return CaretPosition.isTextPosition(pos) === false;
  8505. };
  8506. var trimEmptyTextNode$1 = function (dom, node) {
  8507. if (isText$7(node) && node.data.length === 0) {
  8508. dom.remove(node);
  8509. }
  8510. };
  8511. var insertNode = function (dom, rng, node) {
  8512. rng.insertNode(node);
  8513. trimEmptyTextNode$1(dom, node.previousSibling);
  8514. trimEmptyTextNode$1(dom, node.nextSibling);
  8515. };
  8516. var insertFragment = function (dom, rng, frag) {
  8517. var firstChild = Optional.from(frag.firstChild);
  8518. var lastChild = Optional.from(frag.lastChild);
  8519. rng.insertNode(frag);
  8520. firstChild.each(function (child) {
  8521. return trimEmptyTextNode$1(dom, child.previousSibling);
  8522. });
  8523. lastChild.each(function (child) {
  8524. return trimEmptyTextNode$1(dom, child.nextSibling);
  8525. });
  8526. };
  8527. var rangeInsertNode = function (dom, rng, node) {
  8528. if (isDocumentFragment(node)) {
  8529. insertFragment(dom, rng, node);
  8530. } else {
  8531. insertNode(dom, rng, node);
  8532. }
  8533. };
  8534. var isText$3 = isText$7;
  8535. var isBogus = isBogus$2;
  8536. var nodeIndex = DOMUtils.nodeIndex;
  8537. var normalizedParent = function (node) {
  8538. var parentNode = node.parentNode;
  8539. if (isBogus(parentNode)) {
  8540. return normalizedParent(parentNode);
  8541. }
  8542. return parentNode;
  8543. };
  8544. var getChildNodes = function (node) {
  8545. if (!node) {
  8546. return [];
  8547. }
  8548. return reduce(node.childNodes, function (result, node) {
  8549. if (isBogus(node) && node.nodeName !== 'BR') {
  8550. result = result.concat(getChildNodes(node));
  8551. } else {
  8552. result.push(node);
  8553. }
  8554. return result;
  8555. }, []);
  8556. };
  8557. var normalizedTextOffset = function (node, offset) {
  8558. while (node = node.previousSibling) {
  8559. if (!isText$3(node)) {
  8560. break;
  8561. }
  8562. offset += node.data.length;
  8563. }
  8564. return offset;
  8565. };
  8566. var equal = function (a) {
  8567. return function (b) {
  8568. return a === b;
  8569. };
  8570. };
  8571. var normalizedNodeIndex = function (node) {
  8572. var nodes, index;
  8573. nodes = getChildNodes(normalizedParent(node));
  8574. index = findIndex$1(nodes, equal(node), node);
  8575. nodes = nodes.slice(0, index + 1);
  8576. var numTextFragments = reduce(nodes, function (result, node, i) {
  8577. if (isText$3(node) && isText$3(nodes[i - 1])) {
  8578. result++;
  8579. }
  8580. return result;
  8581. }, 0);
  8582. nodes = filter$2(nodes, matchNodeNames([node.nodeName]));
  8583. index = findIndex$1(nodes, equal(node), node);
  8584. return index - numTextFragments;
  8585. };
  8586. var createPathItem = function (node) {
  8587. var name;
  8588. if (isText$3(node)) {
  8589. name = 'text()';
  8590. } else {
  8591. name = node.nodeName.toLowerCase();
  8592. }
  8593. return name + '[' + normalizedNodeIndex(node) + ']';
  8594. };
  8595. var parentsUntil$1 = function (root, node, predicate) {
  8596. var parents = [];
  8597. for (node = node.parentNode; node !== root; node = node.parentNode) {
  8598. if (predicate && predicate(node)) {
  8599. break;
  8600. }
  8601. parents.push(node);
  8602. }
  8603. return parents;
  8604. };
  8605. var create$6 = function (root, caretPosition) {
  8606. var container, offset, path = [], outputOffset, childNodes, parents;
  8607. container = caretPosition.container();
  8608. offset = caretPosition.offset();
  8609. if (isText$3(container)) {
  8610. outputOffset = normalizedTextOffset(container, offset);
  8611. } else {
  8612. childNodes = container.childNodes;
  8613. if (offset >= childNodes.length) {
  8614. outputOffset = 'after';
  8615. offset = childNodes.length - 1;
  8616. } else {
  8617. outputOffset = 'before';
  8618. }
  8619. container = childNodes[offset];
  8620. }
  8621. path.push(createPathItem(container));
  8622. parents = parentsUntil$1(root, container);
  8623. parents = filter$2(parents, not(isBogus$2));
  8624. path = path.concat(map$1(parents, function (node) {
  8625. return createPathItem(node);
  8626. }));
  8627. return path.reverse().join('/') + ',' + outputOffset;
  8628. };
  8629. var resolvePathItem = function (node, name, index) {
  8630. var nodes = getChildNodes(node);
  8631. nodes = filter$2(nodes, function (node, index) {
  8632. return !isText$3(node) || !isText$3(nodes[index - 1]);
  8633. });
  8634. nodes = filter$2(nodes, matchNodeNames([name]));
  8635. return nodes[index];
  8636. };
  8637. var findTextPosition = function (container, offset) {
  8638. var node = container, targetOffset = 0, dataLen;
  8639. while (isText$3(node)) {
  8640. dataLen = node.data.length;
  8641. if (offset >= targetOffset && offset <= targetOffset + dataLen) {
  8642. container = node;
  8643. offset = offset - targetOffset;
  8644. break;
  8645. }
  8646. if (!isText$3(node.nextSibling)) {
  8647. container = node;
  8648. offset = dataLen;
  8649. break;
  8650. }
  8651. targetOffset += dataLen;
  8652. node = node.nextSibling;
  8653. }
  8654. if (isText$3(container) && offset > container.data.length) {
  8655. offset = container.data.length;
  8656. }
  8657. return CaretPosition(container, offset);
  8658. };
  8659. var resolve$2 = function (root, path) {
  8660. var offset;
  8661. if (!path) {
  8662. return null;
  8663. }
  8664. var parts = path.split(',');
  8665. var paths = parts[0].split('/');
  8666. offset = parts.length > 1 ? parts[1] : 'before';
  8667. var container = reduce(paths, function (result, value) {
  8668. var match = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value);
  8669. if (!match) {
  8670. return null;
  8671. }
  8672. if (match[1] === 'text()') {
  8673. match[1] = '#text';
  8674. }
  8675. return resolvePathItem(result, match[1], parseInt(match[2], 10));
  8676. }, root);
  8677. if (!container) {
  8678. return null;
  8679. }
  8680. if (!isText$3(container)) {
  8681. if (offset === 'after') {
  8682. offset = nodeIndex(container) + 1;
  8683. } else {
  8684. offset = nodeIndex(container);
  8685. }
  8686. return CaretPosition(container.parentNode, offset);
  8687. }
  8688. return findTextPosition(container, parseInt(offset, 10));
  8689. };
  8690. var isContentEditableFalse$9 = isContentEditableFalse$b;
  8691. var getNormalizedTextOffset = function (trim, container, offset) {
  8692. var node, trimmedOffset;
  8693. trimmedOffset = trim(container.data.slice(0, offset)).length;
  8694. for (node = container.previousSibling; node && isText$7(node); node = node.previousSibling) {
  8695. trimmedOffset += trim(node.data).length;
  8696. }
  8697. return trimmedOffset;
  8698. };
  8699. var getPoint = function (dom, trim, normalized, rng, start) {
  8700. var container = rng[start ? 'startContainer' : 'endContainer'];
  8701. var offset = rng[start ? 'startOffset' : 'endOffset'];
  8702. var point = [];
  8703. var childNodes, after = 0;
  8704. var root = dom.getRoot();
  8705. if (isText$7(container)) {
  8706. point.push(normalized ? getNormalizedTextOffset(trim, container, offset) : offset);
  8707. } else {
  8708. childNodes = container.childNodes;
  8709. if (offset >= childNodes.length && childNodes.length) {
  8710. after = 1;
  8711. offset = Math.max(0, childNodes.length - 1);
  8712. }
  8713. point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
  8714. }
  8715. for (; container && container !== root; container = container.parentNode) {
  8716. point.push(dom.nodeIndex(container, normalized));
  8717. }
  8718. return point;
  8719. };
  8720. var getLocation = function (trim, selection, normalized, rng) {
  8721. var dom = selection.dom, bookmark = {};
  8722. bookmark.start = getPoint(dom, trim, normalized, rng, true);
  8723. if (!selection.isCollapsed()) {
  8724. bookmark.end = getPoint(dom, trim, normalized, rng, false);
  8725. }
  8726. if (isRangeInCaretContainerBlock(rng)) {
  8727. bookmark.isFakeCaret = true;
  8728. }
  8729. return bookmark;
  8730. };
  8731. var findIndex = function (dom, name, element) {
  8732. var count = 0;
  8733. Tools.each(dom.select(name), function (node) {
  8734. if (node.getAttribute('data-mce-bogus') === 'all') {
  8735. return;
  8736. }
  8737. if (node === element) {
  8738. return false;
  8739. }
  8740. count++;
  8741. });
  8742. return count;
  8743. };
  8744. var moveEndPoint$1 = function (rng, start) {
  8745. var container, offset, childNodes;
  8746. var prefix = start ? 'start' : 'end';
  8747. container = rng[prefix + 'Container'];
  8748. offset = rng[prefix + 'Offset'];
  8749. if (isElement$5(container) && container.nodeName === 'TR') {
  8750. childNodes = container.childNodes;
  8751. container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
  8752. if (container) {
  8753. offset = start ? 0 : container.childNodes.length;
  8754. rng['set' + (start ? 'Start' : 'End')](container, offset);
  8755. }
  8756. }
  8757. };
  8758. var normalizeTableCellSelection = function (rng) {
  8759. moveEndPoint$1(rng, true);
  8760. moveEndPoint$1(rng, false);
  8761. return rng;
  8762. };
  8763. var findSibling = function (node, offset) {
  8764. var sibling;
  8765. if (isElement$5(node)) {
  8766. node = getNode$1(node, offset);
  8767. if (isContentEditableFalse$9(node)) {
  8768. return node;
  8769. }
  8770. }
  8771. if (isCaretContainer$2(node)) {
  8772. if (isText$7(node) && isCaretContainerBlock$1(node)) {
  8773. node = node.parentNode;
  8774. }
  8775. sibling = node.previousSibling;
  8776. if (isContentEditableFalse$9(sibling)) {
  8777. return sibling;
  8778. }
  8779. sibling = node.nextSibling;
  8780. if (isContentEditableFalse$9(sibling)) {
  8781. return sibling;
  8782. }
  8783. }
  8784. };
  8785. var findAdjacentContentEditableFalseElm = function (rng) {
  8786. return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
  8787. };
  8788. var getOffsetBookmark = function (trim, normalized, selection) {
  8789. var element = selection.getNode();
  8790. var name = element ? element.nodeName : null;
  8791. var rng = selection.getRng();
  8792. if (isContentEditableFalse$9(element) || name === 'IMG') {
  8793. return {
  8794. name: name,
  8795. index: findIndex(selection.dom, name, element)
  8796. };
  8797. }
  8798. var sibling = findAdjacentContentEditableFalseElm(rng);
  8799. if (sibling) {
  8800. name = sibling.tagName;
  8801. return {
  8802. name: name,
  8803. index: findIndex(selection.dom, name, sibling)
  8804. };
  8805. }
  8806. return getLocation(trim, selection, normalized, rng);
  8807. };
  8808. var getCaretBookmark = function (selection) {
  8809. var rng = selection.getRng();
  8810. return {
  8811. start: create$6(selection.dom.getRoot(), CaretPosition.fromRangeStart(rng)),
  8812. end: create$6(selection.dom.getRoot(), CaretPosition.fromRangeEnd(rng))
  8813. };
  8814. };
  8815. var getRangeBookmark = function (selection) {
  8816. return { rng: selection.getRng() };
  8817. };
  8818. var createBookmarkSpan = function (dom, id, filled) {
  8819. var args = {
  8820. 'data-mce-type': 'bookmark',
  8821. id: id,
  8822. 'style': 'overflow:hidden;line-height:0px'
  8823. };
  8824. return filled ? dom.create('span', args, '&#xFEFF;') : dom.create('span', args);
  8825. };
  8826. var getPersistentBookmark = function (selection, filled) {
  8827. var dom = selection.dom;
  8828. var rng = selection.getRng();
  8829. var id = dom.uniqueId();
  8830. var collapsed = selection.isCollapsed();
  8831. var element = selection.getNode();
  8832. var name = element.nodeName;
  8833. if (name === 'IMG') {
  8834. return {
  8835. name: name,
  8836. index: findIndex(dom, name, element)
  8837. };
  8838. }
  8839. var rng2 = normalizeTableCellSelection(rng.cloneRange());
  8840. if (!collapsed) {
  8841. rng2.collapse(false);
  8842. var endBookmarkNode = createBookmarkSpan(dom, id + '_end', filled);
  8843. rangeInsertNode(dom, rng2, endBookmarkNode);
  8844. }
  8845. rng = normalizeTableCellSelection(rng);
  8846. rng.collapse(true);
  8847. var startBookmarkNode = createBookmarkSpan(dom, id + '_start', filled);
  8848. rangeInsertNode(dom, rng, startBookmarkNode);
  8849. selection.moveToBookmark({
  8850. id: id,
  8851. keep: true
  8852. });
  8853. return { id: id };
  8854. };
  8855. var getBookmark$2 = function (selection, type, normalized) {
  8856. if (type === 2) {
  8857. return getOffsetBookmark(trim$2, normalized, selection);
  8858. } else if (type === 3) {
  8859. return getCaretBookmark(selection);
  8860. } else if (type) {
  8861. return getRangeBookmark(selection);
  8862. } else {
  8863. return getPersistentBookmark(selection, false);
  8864. }
  8865. };
  8866. var getUndoBookmark = curry(getOffsetBookmark, identity, true);
  8867. var DOM$9 = DOMUtils.DOM;
  8868. var defaultPreviewStyles = 'font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow';
  8869. var getBodySetting = function (editor, name, defaultValue) {
  8870. var value = editor.getParam(name, defaultValue);
  8871. if (value.indexOf('=') !== -1) {
  8872. var bodyObj = editor.getParam(name, '', 'hash');
  8873. return get$9(bodyObj, editor.id).getOr(defaultValue);
  8874. } else {
  8875. return value;
  8876. }
  8877. };
  8878. var getIframeAttrs = function (editor) {
  8879. return editor.getParam('iframe_attrs', {});
  8880. };
  8881. var getDocType = function (editor) {
  8882. return editor.getParam('doctype', '<!DOCTYPE html>');
  8883. };
  8884. var getDocumentBaseUrl = function (editor) {
  8885. return editor.getParam('document_base_url', '');
  8886. };
  8887. var getBodyId = function (editor) {
  8888. return getBodySetting(editor, 'body_id', 'tinymce');
  8889. };
  8890. var getBodyClass = function (editor) {
  8891. return getBodySetting(editor, 'body_class', '');
  8892. };
  8893. var getContentSecurityPolicy = function (editor) {
  8894. return editor.getParam('content_security_policy', '');
  8895. };
  8896. var shouldPutBrInPre$1 = function (editor) {
  8897. return editor.getParam('br_in_pre', true);
  8898. };
  8899. var getForcedRootBlock = function (editor) {
  8900. if (editor.getParam('force_p_newlines', false)) {
  8901. return 'p';
  8902. }
  8903. var block = editor.getParam('forced_root_block', 'p');
  8904. if (block === false) {
  8905. return '';
  8906. } else if (block === true) {
  8907. return 'p';
  8908. } else {
  8909. return block;
  8910. }
  8911. };
  8912. var getForcedRootBlockAttrs = function (editor) {
  8913. return editor.getParam('forced_root_block_attrs', {});
  8914. };
  8915. var getBrNewLineSelector = function (editor) {
  8916. return editor.getParam('br_newline_selector', '.mce-toc h2,figcaption,caption');
  8917. };
  8918. var getNoNewLineSelector = function (editor) {
  8919. return editor.getParam('no_newline_selector', '');
  8920. };
  8921. var shouldKeepStyles = function (editor) {
  8922. return editor.getParam('keep_styles', true);
  8923. };
  8924. var shouldEndContainerOnEmptyBlock = function (editor) {
  8925. return editor.getParam('end_container_on_empty_block', false);
  8926. };
  8927. var getFontStyleValues = function (editor) {
  8928. return Tools.explode(editor.getParam('font_size_style_values', 'xx-small,x-small,small,medium,large,x-large,xx-large'));
  8929. };
  8930. var getFontSizeClasses = function (editor) {
  8931. return Tools.explode(editor.getParam('font_size_classes', ''));
  8932. };
  8933. var getImagesDataImgFilter = function (editor) {
  8934. return editor.getParam('images_dataimg_filter', always, 'function');
  8935. };
  8936. var isAutomaticUploadsEnabled = function (editor) {
  8937. return editor.getParam('automatic_uploads', true, 'boolean');
  8938. };
  8939. var shouldReuseFileName = function (editor) {
  8940. return editor.getParam('images_reuse_filename', false, 'boolean');
  8941. };
  8942. var shouldReplaceBlobUris = function (editor) {
  8943. return editor.getParam('images_replace_blob_uris', true, 'boolean');
  8944. };
  8945. var getIconPackName = function (editor) {
  8946. return editor.getParam('icons', '', 'string');
  8947. };
  8948. var getIconsUrl = function (editor) {
  8949. return editor.getParam('icons_url', '', 'string');
  8950. };
  8951. var getImageUploadUrl = function (editor) {
  8952. return editor.getParam('images_upload_url', '', 'string');
  8953. };
  8954. var getImageUploadBasePath = function (editor) {
  8955. return editor.getParam('images_upload_base_path', '', 'string');
  8956. };
  8957. var getImagesUploadCredentials = function (editor) {
  8958. return editor.getParam('images_upload_credentials', false, 'boolean');
  8959. };
  8960. var getImagesUploadHandler = function (editor) {
  8961. return editor.getParam('images_upload_handler', null, 'function');
  8962. };
  8963. var shouldUseContentCssCors = function (editor) {
  8964. return editor.getParam('content_css_cors', false, 'boolean');
  8965. };
  8966. var getReferrerPolicy = function (editor) {
  8967. return editor.getParam('referrer_policy', '', 'string');
  8968. };
  8969. var getLanguageCode = function (editor) {
  8970. return editor.getParam('language', 'en', 'string');
  8971. };
  8972. var getLanguageUrl = function (editor) {
  8973. return editor.getParam('language_url', '', 'string');
  8974. };
  8975. var shouldIndentUseMargin = function (editor) {
  8976. return editor.getParam('indent_use_margin', false);
  8977. };
  8978. var getIndentation = function (editor) {
  8979. return editor.getParam('indentation', '40px', 'string');
  8980. };
  8981. var getContentCss = function (editor) {
  8982. var contentCss = editor.getParam('content_css');
  8983. if (isString$1(contentCss)) {
  8984. return map$3(contentCss.split(','), trim$4);
  8985. } else if (isArray$1(contentCss)) {
  8986. return contentCss;
  8987. } else if (contentCss === false || editor.inline) {
  8988. return [];
  8989. } else {
  8990. return ['default'];
  8991. }
  8992. };
  8993. var getFontCss = function (editor) {
  8994. var fontCss = editor.getParam('font_css', []);
  8995. return isArray$1(fontCss) ? fontCss : map$3(fontCss.split(','), trim$4);
  8996. };
  8997. var getDirectionality = function (editor) {
  8998. return editor.getParam('directionality', I18n.isRtl() ? 'rtl' : undefined);
  8999. };
  9000. var getInlineBoundarySelector = function (editor) {
  9001. return editor.getParam('inline_boundaries_selector', 'a[href],code,.mce-annotation', 'string');
  9002. };
  9003. var getObjectResizing = function (editor) {
  9004. var selector = editor.getParam('object_resizing');
  9005. if (selector === false || Env.iOS) {
  9006. return false;
  9007. } else {
  9008. return isString$1(selector) ? selector : 'table,img,figure.image,div,video,iframe';
  9009. }
  9010. };
  9011. var getResizeImgProportional = function (editor) {
  9012. return editor.getParam('resize_img_proportional', true, 'boolean');
  9013. };
  9014. var getPlaceholder = function (editor) {
  9015. return editor.getParam('placeholder', DOM$9.getAttrib(editor.getElement(), 'placeholder'), 'string');
  9016. };
  9017. var getEventRoot = function (editor) {
  9018. return editor.getParam('event_root');
  9019. };
  9020. var getServiceMessage = function (editor) {
  9021. return editor.getParam('service_message');
  9022. };
  9023. var getTheme = function (editor) {
  9024. return editor.getParam('theme');
  9025. };
  9026. var shouldValidate = function (editor) {
  9027. return editor.getParam('validate');
  9028. };
  9029. var isInlineBoundariesEnabled = function (editor) {
  9030. return editor.getParam('inline_boundaries') !== false;
  9031. };
  9032. var getFormats = function (editor) {
  9033. return editor.getParam('formats');
  9034. };
  9035. var getPreviewStyles = function (editor) {
  9036. var style = editor.getParam('preview_styles', defaultPreviewStyles);
  9037. if (isString$1(style)) {
  9038. return style;
  9039. } else {
  9040. return '';
  9041. }
  9042. };
  9043. var canFormatEmptyLines = function (editor) {
  9044. return editor.getParam('format_empty_lines', false, 'boolean');
  9045. };
  9046. var getCustomUiSelector = function (editor) {
  9047. return editor.getParam('custom_ui_selector', '', 'string');
  9048. };
  9049. var getThemeUrl = function (editor) {
  9050. return editor.getParam('theme_url');
  9051. };
  9052. var isInline = function (editor) {
  9053. return editor.getParam('inline');
  9054. };
  9055. var hasHiddenInput = function (editor) {
  9056. return editor.getParam('hidden_input');
  9057. };
  9058. var shouldPatchSubmit = function (editor) {
  9059. return editor.getParam('submit_patch');
  9060. };
  9061. var isEncodingXml = function (editor) {
  9062. return editor.getParam('encoding') === 'xml';
  9063. };
  9064. var shouldAddFormSubmitTrigger = function (editor) {
  9065. return editor.getParam('add_form_submit_trigger');
  9066. };
  9067. var shouldAddUnloadTrigger = function (editor) {
  9068. return editor.getParam('add_unload_trigger');
  9069. };
  9070. var hasForcedRootBlock = function (editor) {
  9071. return getForcedRootBlock(editor) !== '';
  9072. };
  9073. var getCustomUndoRedoLevels = function (editor) {
  9074. return editor.getParam('custom_undo_redo_levels', 0, 'number');
  9075. };
  9076. var shouldDisableNodeChange = function (editor) {
  9077. return editor.getParam('disable_nodechange');
  9078. };
  9079. var isReadOnly$1 = function (editor) {
  9080. return editor.getParam('readonly');
  9081. };
  9082. var hasContentCssCors = function (editor) {
  9083. return editor.getParam('content_css_cors');
  9084. };
  9085. var getPlugins = function (editor) {
  9086. return editor.getParam('plugins', '', 'string');
  9087. };
  9088. var getExternalPlugins$1 = function (editor) {
  9089. return editor.getParam('external_plugins');
  9090. };
  9091. var shouldBlockUnsupportedDrop = function (editor) {
  9092. return editor.getParam('block_unsupported_drop', true, 'boolean');
  9093. };
  9094. var isVisualAidsEnabled = function (editor) {
  9095. return editor.getParam('visual', true, 'boolean');
  9096. };
  9097. var getVisualAidsTableClass = function (editor) {
  9098. return editor.getParam('visual_table_class', 'mce-item-table', 'string');
  9099. };
  9100. var getVisualAidsAnchorClass = function (editor) {
  9101. return editor.getParam('visual_anchor_class', 'mce-item-anchor', 'string');
  9102. };
  9103. var getIframeTitle = function (editor) {
  9104. return editor.getParam('iframe_aria_text', 'Rich Text Area. Press ALT-0 for help.', 'string');
  9105. };
  9106. var isElement$2 = isElement$5;
  9107. var isText$2 = isText$7;
  9108. var removeNode$1 = function (node) {
  9109. var parentNode = node.parentNode;
  9110. if (parentNode) {
  9111. parentNode.removeChild(node);
  9112. }
  9113. };
  9114. var trimCount = function (text) {
  9115. var trimmedText = trim$2(text);
  9116. return {
  9117. count: text.length - trimmedText.length,
  9118. text: trimmedText
  9119. };
  9120. };
  9121. var deleteZwspChars = function (caretContainer) {
  9122. var idx;
  9123. while ((idx = caretContainer.data.lastIndexOf(ZWSP$1)) !== -1) {
  9124. caretContainer.deleteData(idx, 1);
  9125. }
  9126. };
  9127. var removeUnchanged = function (caretContainer, pos) {
  9128. remove$2(caretContainer);
  9129. return pos;
  9130. };
  9131. var removeTextAndReposition = function (caretContainer, pos) {
  9132. var before = trimCount(caretContainer.data.substr(0, pos.offset()));
  9133. var after = trimCount(caretContainer.data.substr(pos.offset()));
  9134. var text = before.text + after.text;
  9135. if (text.length > 0) {
  9136. deleteZwspChars(caretContainer);
  9137. return CaretPosition(caretContainer, pos.offset() - before.count);
  9138. } else {
  9139. return pos;
  9140. }
  9141. };
  9142. var removeElementAndReposition = function (caretContainer, pos) {
  9143. var parentNode = pos.container();
  9144. var newPosition = indexOf$2(from(parentNode.childNodes), caretContainer).map(function (index) {
  9145. return index < pos.offset() ? CaretPosition(parentNode, pos.offset() - 1) : pos;
  9146. }).getOr(pos);
  9147. remove$2(caretContainer);
  9148. return newPosition;
  9149. };
  9150. var removeTextCaretContainer = function (caretContainer, pos) {
  9151. return isText$2(caretContainer) && pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9152. };
  9153. var removeElementCaretContainer = function (caretContainer, pos) {
  9154. return pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9155. };
  9156. var removeAndReposition = function (container, pos) {
  9157. return CaretPosition.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
  9158. };
  9159. var remove$2 = function (caretContainerNode) {
  9160. if (isElement$2(caretContainerNode) && isCaretContainer$2(caretContainerNode)) {
  9161. if (hasContent(caretContainerNode)) {
  9162. caretContainerNode.removeAttribute('data-mce-caret');
  9163. } else {
  9164. removeNode$1(caretContainerNode);
  9165. }
  9166. }
  9167. if (isText$2(caretContainerNode)) {
  9168. deleteZwspChars(caretContainerNode);
  9169. if (caretContainerNode.data.length === 0) {
  9170. removeNode$1(caretContainerNode);
  9171. }
  9172. }
  9173. };
  9174. var browser$2 = detect().browser;
  9175. var isContentEditableFalse$8 = isContentEditableFalse$b;
  9176. var isMedia$1 = isMedia$2;
  9177. var isTableCell$3 = isTableCell$5;
  9178. var inlineFakeCaretSelector = '*[contentEditable=false],video,audio,embed,object';
  9179. var getAbsoluteClientRect = function (root, element, before) {
  9180. var clientRect = collapse(element.getBoundingClientRect(), before);
  9181. var scrollX;
  9182. var scrollY;
  9183. if (root.tagName === 'BODY') {
  9184. var docElm = root.ownerDocument.documentElement;
  9185. scrollX = root.scrollLeft || docElm.scrollLeft;
  9186. scrollY = root.scrollTop || docElm.scrollTop;
  9187. } else {
  9188. var rootRect = root.getBoundingClientRect();
  9189. scrollX = root.scrollLeft - rootRect.left;
  9190. scrollY = root.scrollTop - rootRect.top;
  9191. }
  9192. clientRect.left += scrollX;
  9193. clientRect.right += scrollX;
  9194. clientRect.top += scrollY;
  9195. clientRect.bottom += scrollY;
  9196. clientRect.width = 1;
  9197. var margin = element.offsetWidth - element.clientWidth;
  9198. if (margin > 0) {
  9199. if (before) {
  9200. margin *= -1;
  9201. }
  9202. clientRect.left += margin;
  9203. clientRect.right += margin;
  9204. }
  9205. return clientRect;
  9206. };
  9207. var trimInlineCaretContainers = function (root) {
  9208. var fakeCaretTargetNodes = descendants(SugarElement.fromDom(root), inlineFakeCaretSelector);
  9209. for (var i = 0; i < fakeCaretTargetNodes.length; i++) {
  9210. var node = fakeCaretTargetNodes[i].dom;
  9211. var sibling = node.previousSibling;
  9212. if (endsWithCaretContainer$1(sibling)) {
  9213. var data = sibling.data;
  9214. if (data.length === 1) {
  9215. sibling.parentNode.removeChild(sibling);
  9216. } else {
  9217. sibling.deleteData(data.length - 1, 1);
  9218. }
  9219. }
  9220. sibling = node.nextSibling;
  9221. if (startsWithCaretContainer$1(sibling)) {
  9222. var data = sibling.data;
  9223. if (data.length === 1) {
  9224. sibling.parentNode.removeChild(sibling);
  9225. } else {
  9226. sibling.deleteData(0, 1);
  9227. }
  9228. }
  9229. }
  9230. };
  9231. var FakeCaret = function (editor, root, isBlock, hasFocus) {
  9232. var lastVisualCaret = value();
  9233. var cursorInterval;
  9234. var caretContainerNode;
  9235. var rootBlock = getForcedRootBlock(editor);
  9236. var caretBlock = rootBlock.length > 0 ? rootBlock : 'p';
  9237. var show = function (before, element) {
  9238. var rng;
  9239. hide();
  9240. if (isTableCell$3(element)) {
  9241. return null;
  9242. }
  9243. if (isBlock(element)) {
  9244. caretContainerNode = insertBlock$1(caretBlock, element, before);
  9245. var clientRect = getAbsoluteClientRect(root, element, before);
  9246. DomQuery(caretContainerNode).css('top', clientRect.top);
  9247. var caret = DomQuery('<div class="mce-visual-caret" data-mce-bogus="all"></div>').css(__assign({}, clientRect)).appendTo(root)[0];
  9248. lastVisualCaret.set({
  9249. caret: caret,
  9250. element: element,
  9251. before: before
  9252. });
  9253. if (before) {
  9254. DomQuery(caret).addClass('mce-visual-caret-before');
  9255. }
  9256. startBlink();
  9257. rng = element.ownerDocument.createRange();
  9258. rng.setStart(caretContainerNode, 0);
  9259. rng.setEnd(caretContainerNode, 0);
  9260. } else {
  9261. caretContainerNode = insertInline$1(element, before);
  9262. rng = element.ownerDocument.createRange();
  9263. if (isInlineFakeCaretTarget(caretContainerNode.nextSibling)) {
  9264. rng.setStart(caretContainerNode, 0);
  9265. rng.setEnd(caretContainerNode, 0);
  9266. } else {
  9267. rng.setStart(caretContainerNode, 1);
  9268. rng.setEnd(caretContainerNode, 1);
  9269. }
  9270. return rng;
  9271. }
  9272. return rng;
  9273. };
  9274. var hide = function () {
  9275. trimInlineCaretContainers(root);
  9276. if (caretContainerNode) {
  9277. remove$2(caretContainerNode);
  9278. caretContainerNode = null;
  9279. }
  9280. lastVisualCaret.on(function (caretState) {
  9281. DomQuery(caretState.caret).remove();
  9282. lastVisualCaret.clear();
  9283. });
  9284. if (cursorInterval) {
  9285. Delay.clearInterval(cursorInterval);
  9286. cursorInterval = undefined;
  9287. }
  9288. };
  9289. var startBlink = function () {
  9290. cursorInterval = Delay.setInterval(function () {
  9291. if (hasFocus()) {
  9292. DomQuery('div.mce-visual-caret', root).toggleClass('mce-visual-caret-hidden');
  9293. } else {
  9294. DomQuery('div.mce-visual-caret', root).addClass('mce-visual-caret-hidden');
  9295. }
  9296. }, 500);
  9297. };
  9298. var reposition = function () {
  9299. lastVisualCaret.on(function (caretState) {
  9300. var clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
  9301. DomQuery(caretState.caret).css(__assign({}, clientRect));
  9302. });
  9303. };
  9304. var destroy = function () {
  9305. return Delay.clearInterval(cursorInterval);
  9306. };
  9307. var getCss = function () {
  9308. return '.mce-visual-caret {' + 'position: absolute;' + 'background-color: black;' + 'background-color: currentcolor;' + '}' + '.mce-visual-caret-hidden {' + 'display: none;' + '}' + '*[data-mce-caret] {' + 'position: absolute;' + 'left: -1000px;' + 'right: auto;' + 'top: 0;' + 'margin: 0;' + 'padding: 0;' + '}';
  9309. };
  9310. return {
  9311. show: show,
  9312. hide: hide,
  9313. getCss: getCss,
  9314. reposition: reposition,
  9315. destroy: destroy
  9316. };
  9317. };
  9318. var isFakeCaretTableBrowser = function () {
  9319. return browser$2.isIE() || browser$2.isEdge() || browser$2.isFirefox();
  9320. };
  9321. var isInlineFakeCaretTarget = function (node) {
  9322. return isContentEditableFalse$8(node) || isMedia$1(node);
  9323. };
  9324. var isFakeCaretTarget = function (node) {
  9325. return isInlineFakeCaretTarget(node) || isTable$3(node) && isFakeCaretTableBrowser();
  9326. };
  9327. var isContentEditableFalse$7 = isContentEditableFalse$b;
  9328. var isMedia = isMedia$2;
  9329. var isBlockLike = matchStyleValues('display', 'block table table-cell table-caption list-item');
  9330. var isCaretContainer = isCaretContainer$2;
  9331. var isCaretContainerBlock = isCaretContainerBlock$1;
  9332. var isElement$1 = isElement$5;
  9333. var isCaretCandidate$1 = isCaretCandidate$3;
  9334. var isForwards = function (direction) {
  9335. return direction > 0;
  9336. };
  9337. var isBackwards = function (direction) {
  9338. return direction < 0;
  9339. };
  9340. var skipCaretContainers = function (walk, shallow) {
  9341. var node;
  9342. while (node = walk(shallow)) {
  9343. if (!isCaretContainerBlock(node)) {
  9344. return node;
  9345. }
  9346. }
  9347. return null;
  9348. };
  9349. var findNode$1 = function (node, direction, predicateFn, rootNode, shallow) {
  9350. var walker = new DomTreeWalker(node, rootNode);
  9351. var isCefOrCaretContainer = isContentEditableFalse$7(node) || isCaretContainerBlock(node);
  9352. if (isBackwards(direction)) {
  9353. if (isCefOrCaretContainer) {
  9354. node = skipCaretContainers(walker.prev.bind(walker), true);
  9355. if (predicateFn(node)) {
  9356. return node;
  9357. }
  9358. }
  9359. while (node = skipCaretContainers(walker.prev.bind(walker), shallow)) {
  9360. if (predicateFn(node)) {
  9361. return node;
  9362. }
  9363. }
  9364. }
  9365. if (isForwards(direction)) {
  9366. if (isCefOrCaretContainer) {
  9367. node = skipCaretContainers(walker.next.bind(walker), true);
  9368. if (predicateFn(node)) {
  9369. return node;
  9370. }
  9371. }
  9372. while (node = skipCaretContainers(walker.next.bind(walker), shallow)) {
  9373. if (predicateFn(node)) {
  9374. return node;
  9375. }
  9376. }
  9377. }
  9378. return null;
  9379. };
  9380. var getParentBlock$2 = function (node, rootNode) {
  9381. while (node && node !== rootNode) {
  9382. if (isBlockLike(node)) {
  9383. return node;
  9384. }
  9385. node = node.parentNode;
  9386. }
  9387. return null;
  9388. };
  9389. var isInSameBlock = function (caretPosition1, caretPosition2, rootNode) {
  9390. return getParentBlock$2(caretPosition1.container(), rootNode) === getParentBlock$2(caretPosition2.container(), rootNode);
  9391. };
  9392. var getChildNodeAtRelativeOffset = function (relativeOffset, caretPosition) {
  9393. if (!caretPosition) {
  9394. return null;
  9395. }
  9396. var container = caretPosition.container();
  9397. var offset = caretPosition.offset();
  9398. if (!isElement$1(container)) {
  9399. return null;
  9400. }
  9401. return container.childNodes[offset + relativeOffset];
  9402. };
  9403. var beforeAfter = function (before, node) {
  9404. var range = node.ownerDocument.createRange();
  9405. if (before) {
  9406. range.setStartBefore(node);
  9407. range.setEndBefore(node);
  9408. } else {
  9409. range.setStartAfter(node);
  9410. range.setEndAfter(node);
  9411. }
  9412. return range;
  9413. };
  9414. var isNodesInSameBlock = function (root, node1, node2) {
  9415. return getParentBlock$2(node1, root) === getParentBlock$2(node2, root);
  9416. };
  9417. var lean = function (left, root, node) {
  9418. var siblingName = left ? 'previousSibling' : 'nextSibling';
  9419. while (node && node !== root) {
  9420. var sibling = node[siblingName];
  9421. if (isCaretContainer(sibling)) {
  9422. sibling = sibling[siblingName];
  9423. }
  9424. if (isContentEditableFalse$7(sibling) || isMedia(sibling)) {
  9425. if (isNodesInSameBlock(root, sibling, node)) {
  9426. return sibling;
  9427. }
  9428. break;
  9429. }
  9430. if (isCaretCandidate$1(sibling)) {
  9431. break;
  9432. }
  9433. node = node.parentNode;
  9434. }
  9435. return null;
  9436. };
  9437. var before$2 = curry(beforeAfter, true);
  9438. var after$2 = curry(beforeAfter, false);
  9439. var normalizeRange = function (direction, root, range) {
  9440. var node;
  9441. var leanLeft = curry(lean, true, root);
  9442. var leanRight = curry(lean, false, root);
  9443. var container = range.startContainer;
  9444. var offset = range.startOffset;
  9445. if (isCaretContainerBlock$1(container)) {
  9446. if (!isElement$1(container)) {
  9447. container = container.parentNode;
  9448. }
  9449. var location_1 = container.getAttribute('data-mce-caret');
  9450. if (location_1 === 'before') {
  9451. node = container.nextSibling;
  9452. if (isFakeCaretTarget(node)) {
  9453. return before$2(node);
  9454. }
  9455. }
  9456. if (location_1 === 'after') {
  9457. node = container.previousSibling;
  9458. if (isFakeCaretTarget(node)) {
  9459. return after$2(node);
  9460. }
  9461. }
  9462. }
  9463. if (!range.collapsed) {
  9464. return range;
  9465. }
  9466. if (isText$7(container)) {
  9467. if (isCaretContainer(container)) {
  9468. if (direction === 1) {
  9469. node = leanRight(container);
  9470. if (node) {
  9471. return before$2(node);
  9472. }
  9473. node = leanLeft(container);
  9474. if (node) {
  9475. return after$2(node);
  9476. }
  9477. }
  9478. if (direction === -1) {
  9479. node = leanLeft(container);
  9480. if (node) {
  9481. return after$2(node);
  9482. }
  9483. node = leanRight(container);
  9484. if (node) {
  9485. return before$2(node);
  9486. }
  9487. }
  9488. return range;
  9489. }
  9490. if (endsWithCaretContainer$1(container) && offset >= container.data.length - 1) {
  9491. if (direction === 1) {
  9492. node = leanRight(container);
  9493. if (node) {
  9494. return before$2(node);
  9495. }
  9496. }
  9497. return range;
  9498. }
  9499. if (startsWithCaretContainer$1(container) && offset <= 1) {
  9500. if (direction === -1) {
  9501. node = leanLeft(container);
  9502. if (node) {
  9503. return after$2(node);
  9504. }
  9505. }
  9506. return range;
  9507. }
  9508. if (offset === container.data.length) {
  9509. node = leanRight(container);
  9510. if (node) {
  9511. return before$2(node);
  9512. }
  9513. return range;
  9514. }
  9515. if (offset === 0) {
  9516. node = leanLeft(container);
  9517. if (node) {
  9518. return after$2(node);
  9519. }
  9520. return range;
  9521. }
  9522. }
  9523. return range;
  9524. };
  9525. var getRelativeCefElm = function (forward, caretPosition) {
  9526. return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition)).filter(isContentEditableFalse$7);
  9527. };
  9528. var getNormalizedRangeEndPoint = function (direction, root, range) {
  9529. var normalizedRange = normalizeRange(direction, root, range);
  9530. if (direction === -1) {
  9531. return CaretPosition.fromRangeStart(normalizedRange);
  9532. }
  9533. return CaretPosition.fromRangeEnd(normalizedRange);
  9534. };
  9535. var getElementFromPosition = function (pos) {
  9536. return Optional.from(pos.getNode()).map(SugarElement.fromDom);
  9537. };
  9538. var getElementFromPrevPosition = function (pos) {
  9539. return Optional.from(pos.getNode(true)).map(SugarElement.fromDom);
  9540. };
  9541. var getVisualCaretPosition = function (walkFn, caretPosition) {
  9542. while (caretPosition = walkFn(caretPosition)) {
  9543. if (caretPosition.isVisible()) {
  9544. return caretPosition;
  9545. }
  9546. }
  9547. return caretPosition;
  9548. };
  9549. var isMoveInsideSameBlock = function (from, to) {
  9550. var inSameBlock = isInSameBlock(from, to);
  9551. if (!inSameBlock && isBr$5(from.getNode())) {
  9552. return true;
  9553. }
  9554. return inSameBlock;
  9555. };
  9556. var HDirection;
  9557. (function (HDirection) {
  9558. HDirection[HDirection['Backwards'] = -1] = 'Backwards';
  9559. HDirection[HDirection['Forwards'] = 1] = 'Forwards';
  9560. }(HDirection || (HDirection = {})));
  9561. var isContentEditableFalse$6 = isContentEditableFalse$b;
  9562. var isText$1 = isText$7;
  9563. var isElement = isElement$5;
  9564. var isBr$1 = isBr$5;
  9565. var isCaretCandidate = isCaretCandidate$3;
  9566. var isAtomic = isAtomic$1;
  9567. var isEditableCaretCandidate = isEditableCaretCandidate$1;
  9568. var getParents$3 = function (node, root) {
  9569. var parents = [];
  9570. while (node && node !== root) {
  9571. parents.push(node);
  9572. node = node.parentNode;
  9573. }
  9574. return parents;
  9575. };
  9576. var nodeAtIndex = function (container, offset) {
  9577. if (container.hasChildNodes() && offset < container.childNodes.length) {
  9578. return container.childNodes[offset];
  9579. }
  9580. return null;
  9581. };
  9582. var getCaretCandidatePosition = function (direction, node) {
  9583. if (isForwards(direction)) {
  9584. if (isCaretCandidate(node.previousSibling) && !isText$1(node.previousSibling)) {
  9585. return CaretPosition.before(node);
  9586. }
  9587. if (isText$1(node)) {
  9588. return CaretPosition(node, 0);
  9589. }
  9590. }
  9591. if (isBackwards(direction)) {
  9592. if (isCaretCandidate(node.nextSibling) && !isText$1(node.nextSibling)) {
  9593. return CaretPosition.after(node);
  9594. }
  9595. if (isText$1(node)) {
  9596. return CaretPosition(node, node.data.length);
  9597. }
  9598. }
  9599. if (isBackwards(direction)) {
  9600. if (isBr$1(node)) {
  9601. return CaretPosition.before(node);
  9602. }
  9603. return CaretPosition.after(node);
  9604. }
  9605. return CaretPosition.before(node);
  9606. };
  9607. var moveForwardFromBr = function (root, nextNode) {
  9608. var nextSibling = nextNode.nextSibling;
  9609. if (nextSibling && isCaretCandidate(nextSibling)) {
  9610. if (isText$1(nextSibling)) {
  9611. return CaretPosition(nextSibling, 0);
  9612. } else {
  9613. return CaretPosition.before(nextSibling);
  9614. }
  9615. } else {
  9616. return findCaretPosition$1(HDirection.Forwards, CaretPosition.after(nextNode), root);
  9617. }
  9618. };
  9619. var findCaretPosition$1 = function (direction, startPos, root) {
  9620. var node;
  9621. var nextNode;
  9622. var innerNode;
  9623. var caretPosition;
  9624. if (!isElement(root) || !startPos) {
  9625. return null;
  9626. }
  9627. if (startPos.isEqual(CaretPosition.after(root)) && root.lastChild) {
  9628. caretPosition = CaretPosition.after(root.lastChild);
  9629. if (isBackwards(direction) && isCaretCandidate(root.lastChild) && isElement(root.lastChild)) {
  9630. return isBr$1(root.lastChild) ? CaretPosition.before(root.lastChild) : caretPosition;
  9631. }
  9632. } else {
  9633. caretPosition = startPos;
  9634. }
  9635. var container = caretPosition.container();
  9636. var offset = caretPosition.offset();
  9637. if (isText$1(container)) {
  9638. if (isBackwards(direction) && offset > 0) {
  9639. return CaretPosition(container, --offset);
  9640. }
  9641. if (isForwards(direction) && offset < container.length) {
  9642. return CaretPosition(container, ++offset);
  9643. }
  9644. node = container;
  9645. } else {
  9646. if (isBackwards(direction) && offset > 0) {
  9647. nextNode = nodeAtIndex(container, offset - 1);
  9648. if (isCaretCandidate(nextNode)) {
  9649. if (!isAtomic(nextNode)) {
  9650. innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
  9651. if (innerNode) {
  9652. if (isText$1(innerNode)) {
  9653. return CaretPosition(innerNode, innerNode.data.length);
  9654. }
  9655. return CaretPosition.after(innerNode);
  9656. }
  9657. }
  9658. if (isText$1(nextNode)) {
  9659. return CaretPosition(nextNode, nextNode.data.length);
  9660. }
  9661. return CaretPosition.before(nextNode);
  9662. }
  9663. }
  9664. if (isForwards(direction) && offset < container.childNodes.length) {
  9665. nextNode = nodeAtIndex(container, offset);
  9666. if (isCaretCandidate(nextNode)) {
  9667. if (isBr$1(nextNode)) {
  9668. return moveForwardFromBr(root, nextNode);
  9669. }
  9670. if (!isAtomic(nextNode)) {
  9671. innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
  9672. if (innerNode) {
  9673. if (isText$1(innerNode)) {
  9674. return CaretPosition(innerNode, 0);
  9675. }
  9676. return CaretPosition.before(innerNode);
  9677. }
  9678. }
  9679. if (isText$1(nextNode)) {
  9680. return CaretPosition(nextNode, 0);
  9681. }
  9682. return CaretPosition.after(nextNode);
  9683. }
  9684. }
  9685. node = nextNode ? nextNode : caretPosition.getNode();
  9686. }
  9687. if (isForwards(direction) && caretPosition.isAtEnd() || isBackwards(direction) && caretPosition.isAtStart()) {
  9688. node = findNode$1(node, direction, always, root, true);
  9689. if (isEditableCaretCandidate(node, root)) {
  9690. return getCaretCandidatePosition(direction, node);
  9691. }
  9692. }
  9693. nextNode = findNode$1(node, direction, isEditableCaretCandidate, root);
  9694. var rootContentEditableFalseElm = last$1(filter$4(getParents$3(container, root), isContentEditableFalse$6));
  9695. if (rootContentEditableFalseElm && (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
  9696. if (isForwards(direction)) {
  9697. caretPosition = CaretPosition.after(rootContentEditableFalseElm);
  9698. } else {
  9699. caretPosition = CaretPosition.before(rootContentEditableFalseElm);
  9700. }
  9701. return caretPosition;
  9702. }
  9703. if (nextNode) {
  9704. return getCaretCandidatePosition(direction, nextNode);
  9705. }
  9706. return null;
  9707. };
  9708. var CaretWalker = function (root) {
  9709. return {
  9710. next: function (caretPosition) {
  9711. return findCaretPosition$1(HDirection.Forwards, caretPosition, root);
  9712. },
  9713. prev: function (caretPosition) {
  9714. return findCaretPosition$1(HDirection.Backwards, caretPosition, root);
  9715. }
  9716. };
  9717. };
  9718. var walkToPositionIn = function (forward, root, start) {
  9719. var position = forward ? CaretPosition.before(start) : CaretPosition.after(start);
  9720. return fromPosition(forward, root, position);
  9721. };
  9722. var afterElement = function (node) {
  9723. return isBr$5(node) ? CaretPosition.before(node) : CaretPosition.after(node);
  9724. };
  9725. var isBeforeOrStart = function (position) {
  9726. if (CaretPosition.isTextPosition(position)) {
  9727. return position.offset() === 0;
  9728. } else {
  9729. return isCaretCandidate$3(position.getNode());
  9730. }
  9731. };
  9732. var isAfterOrEnd = function (position) {
  9733. if (CaretPosition.isTextPosition(position)) {
  9734. var container = position.container();
  9735. return position.offset() === container.data.length;
  9736. } else {
  9737. return isCaretCandidate$3(position.getNode(true));
  9738. }
  9739. };
  9740. var isBeforeAfterSameElement = function (from, to) {
  9741. return !CaretPosition.isTextPosition(from) && !CaretPosition.isTextPosition(to) && from.getNode() === to.getNode(true);
  9742. };
  9743. var isAtBr = function (position) {
  9744. return !CaretPosition.isTextPosition(position) && isBr$5(position.getNode());
  9745. };
  9746. var shouldSkipPosition = function (forward, from, to) {
  9747. if (forward) {
  9748. return !isBeforeAfterSameElement(from, to) && !isAtBr(from) && isAfterOrEnd(from) && isBeforeOrStart(to);
  9749. } else {
  9750. return !isBeforeAfterSameElement(to, from) && isBeforeOrStart(from) && isAfterOrEnd(to);
  9751. }
  9752. };
  9753. var fromPosition = function (forward, root, pos) {
  9754. var walker = CaretWalker(root);
  9755. return Optional.from(forward ? walker.next(pos) : walker.prev(pos));
  9756. };
  9757. var navigate = function (forward, root, from) {
  9758. return fromPosition(forward, root, from).bind(function (to) {
  9759. if (isInSameBlock(from, to, root) && shouldSkipPosition(forward, from, to)) {
  9760. return fromPosition(forward, root, to);
  9761. } else {
  9762. return Optional.some(to);
  9763. }
  9764. });
  9765. };
  9766. var navigateIgnore = function (forward, root, from, ignoreFilter) {
  9767. return navigate(forward, root, from).bind(function (pos) {
  9768. return ignoreFilter(pos) ? navigateIgnore(forward, root, pos, ignoreFilter) : Optional.some(pos);
  9769. });
  9770. };
  9771. var positionIn = function (forward, element) {
  9772. var startNode = forward ? element.firstChild : element.lastChild;
  9773. if (isText$7(startNode)) {
  9774. return Optional.some(CaretPosition(startNode, forward ? 0 : startNode.data.length));
  9775. } else if (startNode) {
  9776. if (isCaretCandidate$3(startNode)) {
  9777. return Optional.some(forward ? CaretPosition.before(startNode) : afterElement(startNode));
  9778. } else {
  9779. return walkToPositionIn(forward, element, startNode);
  9780. }
  9781. } else {
  9782. return Optional.none();
  9783. }
  9784. };
  9785. var nextPosition = curry(fromPosition, true);
  9786. var prevPosition = curry(fromPosition, false);
  9787. var firstPositionIn = curry(positionIn, true);
  9788. var lastPositionIn = curry(positionIn, false);
  9789. var CARET_ID$1 = '_mce_caret';
  9790. var isCaretNode = function (node) {
  9791. return isElement$5(node) && node.id === CARET_ID$1;
  9792. };
  9793. var getParentCaretContainer = function (body, node) {
  9794. while (node && node !== body) {
  9795. if (node.id === CARET_ID$1) {
  9796. return node;
  9797. }
  9798. node = node.parentNode;
  9799. }
  9800. return null;
  9801. };
  9802. var isStringPathBookmark = function (bookmark) {
  9803. return isString$1(bookmark.start);
  9804. };
  9805. var isRangeBookmark = function (bookmark) {
  9806. return has$2(bookmark, 'rng');
  9807. };
  9808. var isIdBookmark = function (bookmark) {
  9809. return has$2(bookmark, 'id');
  9810. };
  9811. var isIndexBookmark = function (bookmark) {
  9812. return has$2(bookmark, 'name');
  9813. };
  9814. var isPathBookmark = function (bookmark) {
  9815. return Tools.isArray(bookmark.start);
  9816. };
  9817. var addBogus = function (dom, node) {
  9818. if (isElement$5(node) && dom.isBlock(node) && !node.innerHTML && !Env.ie) {
  9819. node.innerHTML = '<br data-mce-bogus="1" />';
  9820. }
  9821. return node;
  9822. };
  9823. var resolveCaretPositionBookmark = function (dom, bookmark) {
  9824. var pos;
  9825. var rng = dom.createRng();
  9826. pos = resolve$2(dom.getRoot(), bookmark.start);
  9827. rng.setStart(pos.container(), pos.offset());
  9828. pos = resolve$2(dom.getRoot(), bookmark.end);
  9829. rng.setEnd(pos.container(), pos.offset());
  9830. return rng;
  9831. };
  9832. var insertZwsp = function (node, rng) {
  9833. var textNode = node.ownerDocument.createTextNode(ZWSP$1);
  9834. node.appendChild(textNode);
  9835. rng.setStart(textNode, 0);
  9836. rng.setEnd(textNode, 0);
  9837. };
  9838. var isEmpty$1 = function (node) {
  9839. return node.hasChildNodes() === false;
  9840. };
  9841. var tryFindRangePosition = function (node, rng) {
  9842. return lastPositionIn(node).fold(never, function (pos) {
  9843. rng.setStart(pos.container(), pos.offset());
  9844. rng.setEnd(pos.container(), pos.offset());
  9845. return true;
  9846. });
  9847. };
  9848. var padEmptyCaretContainer = function (root, node, rng) {
  9849. if (isEmpty$1(node) && getParentCaretContainer(root, node)) {
  9850. insertZwsp(node, rng);
  9851. return true;
  9852. } else {
  9853. return false;
  9854. }
  9855. };
  9856. var setEndPoint = function (dom, start, bookmark, rng) {
  9857. var point = bookmark[start ? 'start' : 'end'];
  9858. var i, node, offset, children;
  9859. var root = dom.getRoot();
  9860. if (point) {
  9861. offset = point[0];
  9862. for (node = root, i = point.length - 1; i >= 1; i--) {
  9863. children = node.childNodes;
  9864. if (padEmptyCaretContainer(root, node, rng)) {
  9865. return true;
  9866. }
  9867. if (point[i] > children.length - 1) {
  9868. if (padEmptyCaretContainer(root, node, rng)) {
  9869. return true;
  9870. }
  9871. return tryFindRangePosition(node, rng);
  9872. }
  9873. node = children[point[i]];
  9874. }
  9875. if (node.nodeType === 3) {
  9876. offset = Math.min(point[0], node.nodeValue.length);
  9877. }
  9878. if (node.nodeType === 1) {
  9879. offset = Math.min(point[0], node.childNodes.length);
  9880. }
  9881. if (start) {
  9882. rng.setStart(node, offset);
  9883. } else {
  9884. rng.setEnd(node, offset);
  9885. }
  9886. }
  9887. return true;
  9888. };
  9889. var isValidTextNode = function (node) {
  9890. return isText$7(node) && node.data.length > 0;
  9891. };
  9892. var restoreEndPoint = function (dom, suffix, bookmark) {
  9893. var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev;
  9894. var keep = bookmark.keep;
  9895. var container, offset;
  9896. if (marker) {
  9897. node = marker.parentNode;
  9898. if (suffix === 'start') {
  9899. if (!keep) {
  9900. idx = dom.nodeIndex(marker);
  9901. } else {
  9902. if (marker.hasChildNodes()) {
  9903. node = marker.firstChild;
  9904. idx = 1;
  9905. } else if (isValidTextNode(marker.nextSibling)) {
  9906. node = marker.nextSibling;
  9907. idx = 0;
  9908. } else if (isValidTextNode(marker.previousSibling)) {
  9909. node = marker.previousSibling;
  9910. idx = marker.previousSibling.data.length;
  9911. } else {
  9912. node = marker.parentNode;
  9913. idx = dom.nodeIndex(marker) + 1;
  9914. }
  9915. }
  9916. container = node;
  9917. offset = idx;
  9918. } else {
  9919. if (!keep) {
  9920. idx = dom.nodeIndex(marker);
  9921. } else {
  9922. if (marker.hasChildNodes()) {
  9923. node = marker.firstChild;
  9924. idx = 1;
  9925. } else if (isValidTextNode(marker.previousSibling)) {
  9926. node = marker.previousSibling;
  9927. idx = marker.previousSibling.data.length;
  9928. } else {
  9929. node = marker.parentNode;
  9930. idx = dom.nodeIndex(marker);
  9931. }
  9932. }
  9933. container = node;
  9934. offset = idx;
  9935. }
  9936. if (!keep) {
  9937. prev = marker.previousSibling;
  9938. next = marker.nextSibling;
  9939. Tools.each(Tools.grep(marker.childNodes), function (node) {
  9940. if (isText$7(node)) {
  9941. node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
  9942. }
  9943. });
  9944. while (marker = dom.get(bookmark.id + '_' + suffix)) {
  9945. dom.remove(marker, true);
  9946. }
  9947. if (prev && next && prev.nodeType === next.nodeType && isText$7(prev) && !Env.opera) {
  9948. idx = prev.nodeValue.length;
  9949. prev.appendData(next.nodeValue);
  9950. dom.remove(next);
  9951. container = prev;
  9952. offset = idx;
  9953. }
  9954. }
  9955. return Optional.some(CaretPosition(container, offset));
  9956. } else {
  9957. return Optional.none();
  9958. }
  9959. };
  9960. var resolvePaths = function (dom, bookmark) {
  9961. var rng = dom.createRng();
  9962. if (setEndPoint(dom, true, bookmark, rng) && setEndPoint(dom, false, bookmark, rng)) {
  9963. return Optional.some(rng);
  9964. } else {
  9965. return Optional.none();
  9966. }
  9967. };
  9968. var resolveId = function (dom, bookmark) {
  9969. var startPos = restoreEndPoint(dom, 'start', bookmark);
  9970. var endPos = restoreEndPoint(dom, 'end', bookmark);
  9971. return lift2(startPos, endPos.or(startPos), function (spos, epos) {
  9972. var rng = dom.createRng();
  9973. rng.setStart(addBogus(dom, spos.container()), spos.offset());
  9974. rng.setEnd(addBogus(dom, epos.container()), epos.offset());
  9975. return rng;
  9976. });
  9977. };
  9978. var resolveIndex = function (dom, bookmark) {
  9979. return Optional.from(dom.select(bookmark.name)[bookmark.index]).map(function (elm) {
  9980. var rng = dom.createRng();
  9981. rng.selectNode(elm);
  9982. return rng;
  9983. });
  9984. };
  9985. var resolve$1 = function (selection, bookmark) {
  9986. var dom = selection.dom;
  9987. if (bookmark) {
  9988. if (isPathBookmark(bookmark)) {
  9989. return resolvePaths(dom, bookmark);
  9990. } else if (isStringPathBookmark(bookmark)) {
  9991. return Optional.some(resolveCaretPositionBookmark(dom, bookmark));
  9992. } else if (isIdBookmark(bookmark)) {
  9993. return resolveId(dom, bookmark);
  9994. } else if (isIndexBookmark(bookmark)) {
  9995. return resolveIndex(dom, bookmark);
  9996. } else if (isRangeBookmark(bookmark)) {
  9997. return Optional.some(bookmark.rng);
  9998. }
  9999. }
  10000. return Optional.none();
  10001. };
  10002. var getBookmark$1 = function (selection, type, normalized) {
  10003. return getBookmark$2(selection, type, normalized);
  10004. };
  10005. var moveToBookmark = function (selection, bookmark) {
  10006. resolve$1(selection, bookmark).each(function (rng) {
  10007. selection.setRng(rng);
  10008. });
  10009. };
  10010. var isBookmarkNode$1 = function (node) {
  10011. return isElement$5(node) && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
  10012. };
  10013. var is = function (expected) {
  10014. return function (actual) {
  10015. return expected === actual;
  10016. };
  10017. };
  10018. var isNbsp = is(nbsp);
  10019. var isWhiteSpace = function (chr) {
  10020. return chr !== '' && ' \f\n\r\t\x0B'.indexOf(chr) !== -1;
  10021. };
  10022. var isContent = function (chr) {
  10023. return !isWhiteSpace(chr) && !isNbsp(chr);
  10024. };
  10025. var isNode = function (node) {
  10026. return !!node.nodeType;
  10027. };
  10028. var isInlineBlock = function (node) {
  10029. return node && /^(IMG)$/.test(node.nodeName);
  10030. };
  10031. var moveStart = function (dom, selection, rng) {
  10032. var offset = rng.startOffset;
  10033. var container = rng.startContainer;
  10034. if (container === rng.endContainer) {
  10035. if (isInlineBlock(container.childNodes[offset])) {
  10036. return;
  10037. }
  10038. }
  10039. if (isElement$5(container)) {
  10040. var nodes = container.childNodes;
  10041. var walker = void 0;
  10042. if (offset < nodes.length) {
  10043. container = nodes[offset];
  10044. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10045. } else {
  10046. container = nodes[nodes.length - 1];
  10047. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10048. walker.next(true);
  10049. }
  10050. for (var node = walker.current(); node; node = walker.next()) {
  10051. if (isText$7(node) && !isWhiteSpaceNode$1(node)) {
  10052. rng.setStart(node, 0);
  10053. selection.setRng(rng);
  10054. return;
  10055. }
  10056. }
  10057. }
  10058. };
  10059. var getNonWhiteSpaceSibling = function (node, next, inc) {
  10060. if (node) {
  10061. var nextName = next ? 'nextSibling' : 'previousSibling';
  10062. for (node = inc ? node : node[nextName]; node; node = node[nextName]) {
  10063. if (isElement$5(node) || !isWhiteSpaceNode$1(node)) {
  10064. return node;
  10065. }
  10066. }
  10067. }
  10068. };
  10069. var isTextBlock$1 = function (editor, name) {
  10070. if (isNode(name)) {
  10071. name = name.nodeName;
  10072. }
  10073. return !!editor.schema.getTextBlockElements()[name.toLowerCase()];
  10074. };
  10075. var isValid = function (ed, parent, child) {
  10076. return ed.schema.isValidChild(parent, child);
  10077. };
  10078. var isWhiteSpaceNode$1 = function (node, allowSpaces) {
  10079. if (allowSpaces === void 0) {
  10080. allowSpaces = false;
  10081. }
  10082. if (isNonNullable(node) && isText$7(node)) {
  10083. var data = allowSpaces ? node.data.replace(/ /g, '\xA0') : node.data;
  10084. return isWhitespaceText(data);
  10085. } else {
  10086. return false;
  10087. }
  10088. };
  10089. var isEmptyTextNode$1 = function (node) {
  10090. return isNonNullable(node) && isText$7(node) && node.length === 0;
  10091. };
  10092. var replaceVars = function (value, vars) {
  10093. if (isFunction(value)) {
  10094. value = value(vars);
  10095. } else if (isNonNullable(vars)) {
  10096. value = value.replace(/%(\w+)/g, function (str, name) {
  10097. return vars[name] || str;
  10098. });
  10099. }
  10100. return value;
  10101. };
  10102. var isEq$5 = function (str1, str2) {
  10103. str1 = str1 || '';
  10104. str2 = str2 || '';
  10105. str1 = '' + (str1.nodeName || str1);
  10106. str2 = '' + (str2.nodeName || str2);
  10107. return str1.toLowerCase() === str2.toLowerCase();
  10108. };
  10109. var normalizeStyleValue = function (dom, value, name) {
  10110. if (name === 'color' || name === 'backgroundColor') {
  10111. value = dom.toHex(value);
  10112. }
  10113. if (name === 'fontWeight' && value === 700) {
  10114. value = 'bold';
  10115. }
  10116. if (name === 'fontFamily') {
  10117. value = value.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
  10118. }
  10119. return '' + value;
  10120. };
  10121. var getStyle = function (dom, node, name) {
  10122. return normalizeStyleValue(dom, dom.getStyle(node, name), name);
  10123. };
  10124. var getTextDecoration = function (dom, node) {
  10125. var decoration;
  10126. dom.getParent(node, function (n) {
  10127. decoration = dom.getStyle(n, 'text-decoration');
  10128. return decoration && decoration !== 'none';
  10129. });
  10130. return decoration;
  10131. };
  10132. var getParents$2 = function (dom, node, selector) {
  10133. return dom.getParents(node, selector, dom.getRoot());
  10134. };
  10135. var isVariableFormatName = function (editor, formatName) {
  10136. var hasVariableValues = function (format) {
  10137. var isVariableValue = function (val) {
  10138. return val.length > 1 && val.charAt(0) === '%';
  10139. };
  10140. return exists([
  10141. 'styles',
  10142. 'attributes'
  10143. ], function (key) {
  10144. return get$9(format, key).exists(function (field) {
  10145. var fieldValues = isArray$1(field) ? field : values(field);
  10146. return exists(fieldValues, isVariableValue);
  10147. });
  10148. });
  10149. };
  10150. return exists(editor.formatter.get(formatName), hasVariableValues);
  10151. };
  10152. var areSimilarFormats = function (editor, formatName, otherFormatName) {
  10153. var validKeys = [
  10154. 'inline',
  10155. 'block',
  10156. 'selector',
  10157. 'attributes',
  10158. 'styles',
  10159. 'classes'
  10160. ];
  10161. var filterObj = function (format) {
  10162. return filter$3(format, function (_, key) {
  10163. return exists(validKeys, function (validKey) {
  10164. return validKey === key;
  10165. });
  10166. });
  10167. };
  10168. return exists(editor.formatter.get(formatName), function (fmt1) {
  10169. var filteredFmt1 = filterObj(fmt1);
  10170. return exists(editor.formatter.get(otherFormatName), function (fmt2) {
  10171. var filteredFmt2 = filterObj(fmt2);
  10172. return equal$1(filteredFmt1, filteredFmt2);
  10173. });
  10174. });
  10175. };
  10176. var isBlockFormat = function (format) {
  10177. return hasNonNullableKey(format, 'block');
  10178. };
  10179. var isSelectorFormat = function (format) {
  10180. return hasNonNullableKey(format, 'selector');
  10181. };
  10182. var isInlineFormat = function (format) {
  10183. return hasNonNullableKey(format, 'inline');
  10184. };
  10185. var isMixedFormat = function (format) {
  10186. return isSelectorFormat(format) && isInlineFormat(format) && is$1(get$9(format, 'mixed'), true);
  10187. };
  10188. var shouldExpandToSelector = function (format) {
  10189. return isSelectorFormat(format) && format.expand !== false && !isInlineFormat(format);
  10190. };
  10191. var isBookmarkNode = isBookmarkNode$1;
  10192. var getParents$1 = getParents$2;
  10193. var isWhiteSpaceNode = isWhiteSpaceNode$1;
  10194. var isTextBlock = isTextBlock$1;
  10195. var isBogusBr = function (node) {
  10196. return isBr$5(node) && node.getAttribute('data-mce-bogus') && !node.nextSibling;
  10197. };
  10198. var findParentContentEditable = function (dom, node) {
  10199. var parent = node;
  10200. while (parent) {
  10201. if (isElement$5(parent) && dom.getContentEditable(parent)) {
  10202. return dom.getContentEditable(parent) === 'false' ? parent : node;
  10203. }
  10204. parent = parent.parentNode;
  10205. }
  10206. return node;
  10207. };
  10208. var walkText = function (start, node, offset, predicate) {
  10209. var str = node.data;
  10210. for (var i = offset; start ? i >= 0 : i < str.length; start ? i-- : i++) {
  10211. if (predicate(str.charAt(i))) {
  10212. return start ? i + 1 : i;
  10213. }
  10214. }
  10215. return -1;
  10216. };
  10217. var findSpace = function (start, node, offset) {
  10218. return walkText(start, node, offset, function (c) {
  10219. return isNbsp(c) || isWhiteSpace(c);
  10220. });
  10221. };
  10222. var findContent = function (start, node, offset) {
  10223. return walkText(start, node, offset, isContent);
  10224. };
  10225. var findWordEndPoint = function (dom, body, container, offset, start, includeTrailingSpaces) {
  10226. var lastTextNode;
  10227. var rootNode = dom.getParent(container, dom.isBlock) || body;
  10228. var walk = function (container, offset, pred) {
  10229. var textSeeker = TextSeeker(dom);
  10230. var walker = start ? textSeeker.backwards : textSeeker.forwards;
  10231. return Optional.from(walker(container, offset, function (text, textOffset) {
  10232. if (isBookmarkNode(text.parentNode)) {
  10233. return -1;
  10234. } else {
  10235. lastTextNode = text;
  10236. return pred(start, text, textOffset);
  10237. }
  10238. }, rootNode));
  10239. };
  10240. var spaceResult = walk(container, offset, findSpace);
  10241. return spaceResult.bind(function (result) {
  10242. return includeTrailingSpaces ? walk(result.container, result.offset + (start ? -1 : 0), findContent) : Optional.some(result);
  10243. }).orThunk(function () {
  10244. return lastTextNode ? Optional.some({
  10245. container: lastTextNode,
  10246. offset: start ? 0 : lastTextNode.length
  10247. }) : Optional.none();
  10248. });
  10249. };
  10250. var findSelectorEndPoint = function (dom, formatList, rng, container, siblingName) {
  10251. if (isText$7(container) && isEmpty$3(container.data) && container[siblingName]) {
  10252. container = container[siblingName];
  10253. }
  10254. var parents = getParents$1(dom, container);
  10255. for (var i = 0; i < parents.length; i++) {
  10256. for (var y = 0; y < formatList.length; y++) {
  10257. var curFormat = formatList[y];
  10258. if (isNonNullable(curFormat.collapsed) && curFormat.collapsed !== rng.collapsed) {
  10259. continue;
  10260. }
  10261. if (isSelectorFormat(curFormat) && dom.is(parents[i], curFormat.selector)) {
  10262. return parents[i];
  10263. }
  10264. }
  10265. }
  10266. return container;
  10267. };
  10268. var findBlockEndPoint = function (editor, formatList, container, siblingName) {
  10269. var node = container;
  10270. var dom = editor.dom;
  10271. var root = dom.getRoot();
  10272. var format = formatList[0];
  10273. if (isBlockFormat(format)) {
  10274. node = format.wrapper ? null : dom.getParent(container, format.block, root);
  10275. }
  10276. if (!node) {
  10277. var scopeRoot = dom.getParent(container, 'LI,TD,TH');
  10278. node = dom.getParent(isText$7(container) ? container.parentNode : container, function (node) {
  10279. return node !== root && isTextBlock(editor, node);
  10280. }, scopeRoot);
  10281. }
  10282. if (node && isBlockFormat(format) && format.wrapper) {
  10283. node = getParents$1(dom, node, 'ul,ol').reverse()[0] || node;
  10284. }
  10285. if (!node) {
  10286. node = container;
  10287. while (node[siblingName] && !dom.isBlock(node[siblingName])) {
  10288. node = node[siblingName];
  10289. if (isEq$5(node, 'br')) {
  10290. break;
  10291. }
  10292. }
  10293. }
  10294. return node || container;
  10295. };
  10296. var isAtBlockBoundary$1 = function (dom, root, container, siblingName) {
  10297. var parent = container.parentNode;
  10298. if (isNonNullable(container[siblingName])) {
  10299. return false;
  10300. } else if (parent === root || isNullable(parent) || dom.isBlock(parent)) {
  10301. return true;
  10302. } else {
  10303. return isAtBlockBoundary$1(dom, root, parent, siblingName);
  10304. }
  10305. };
  10306. var findParentContainer = function (dom, formatList, container, offset, start) {
  10307. var parent = container;
  10308. var siblingName = start ? 'previousSibling' : 'nextSibling';
  10309. var root = dom.getRoot();
  10310. if (isText$7(container) && !isWhiteSpaceNode(container)) {
  10311. if (start ? offset > 0 : offset < container.data.length) {
  10312. return container;
  10313. }
  10314. }
  10315. while (true) {
  10316. if (!formatList[0].block_expand && dom.isBlock(parent)) {
  10317. return parent;
  10318. }
  10319. for (var sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
  10320. var allowSpaces = isText$7(sibling) && !isAtBlockBoundary$1(dom, root, sibling, siblingName);
  10321. if (!isBookmarkNode(sibling) && !isBogusBr(sibling) && !isWhiteSpaceNode(sibling, allowSpaces)) {
  10322. return parent;
  10323. }
  10324. }
  10325. if (parent === root || parent.parentNode === root) {
  10326. container = parent;
  10327. break;
  10328. }
  10329. parent = parent.parentNode;
  10330. }
  10331. return container;
  10332. };
  10333. var isSelfOrParentBookmark = function (container) {
  10334. return isBookmarkNode(container.parentNode) || isBookmarkNode(container);
  10335. };
  10336. var expandRng = function (editor, rng, formatList, includeTrailingSpace) {
  10337. if (includeTrailingSpace === void 0) {
  10338. includeTrailingSpace = false;
  10339. }
  10340. var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  10341. var dom = editor.dom;
  10342. var format = formatList[0];
  10343. if (isElement$5(startContainer) && startContainer.hasChildNodes()) {
  10344. startContainer = getNode$1(startContainer, startOffset);
  10345. if (isText$7(startContainer)) {
  10346. startOffset = 0;
  10347. }
  10348. }
  10349. if (isElement$5(endContainer) && endContainer.hasChildNodes()) {
  10350. endContainer = getNode$1(endContainer, rng.collapsed ? endOffset : endOffset - 1);
  10351. if (isText$7(endContainer)) {
  10352. endOffset = endContainer.nodeValue.length;
  10353. }
  10354. }
  10355. startContainer = findParentContentEditable(dom, startContainer);
  10356. endContainer = findParentContentEditable(dom, endContainer);
  10357. if (isSelfOrParentBookmark(startContainer)) {
  10358. startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
  10359. if (rng.collapsed) {
  10360. startContainer = startContainer.previousSibling || startContainer;
  10361. } else {
  10362. startContainer = startContainer.nextSibling || startContainer;
  10363. }
  10364. if (isText$7(startContainer)) {
  10365. startOffset = rng.collapsed ? startContainer.length : 0;
  10366. }
  10367. }
  10368. if (isSelfOrParentBookmark(endContainer)) {
  10369. endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
  10370. if (rng.collapsed) {
  10371. endContainer = endContainer.nextSibling || endContainer;
  10372. } else {
  10373. endContainer = endContainer.previousSibling || endContainer;
  10374. }
  10375. if (isText$7(endContainer)) {
  10376. endOffset = rng.collapsed ? 0 : endContainer.length;
  10377. }
  10378. }
  10379. if (rng.collapsed) {
  10380. var startPoint = findWordEndPoint(dom, editor.getBody(), startContainer, startOffset, true, includeTrailingSpace);
  10381. startPoint.each(function (_a) {
  10382. var container = _a.container, offset = _a.offset;
  10383. startContainer = container;
  10384. startOffset = offset;
  10385. });
  10386. var endPoint = findWordEndPoint(dom, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
  10387. endPoint.each(function (_a) {
  10388. var container = _a.container, offset = _a.offset;
  10389. endContainer = container;
  10390. endOffset = offset;
  10391. });
  10392. }
  10393. if (isInlineFormat(format) || format.block_expand) {
  10394. if (!isInlineFormat(format) || (!isText$7(startContainer) || startOffset === 0)) {
  10395. startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  10396. }
  10397. if (!isInlineFormat(format) || (!isText$7(endContainer) || endOffset === endContainer.nodeValue.length)) {
  10398. endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  10399. }
  10400. }
  10401. if (shouldExpandToSelector(format)) {
  10402. startContainer = findSelectorEndPoint(dom, formatList, rng, startContainer, 'previousSibling');
  10403. endContainer = findSelectorEndPoint(dom, formatList, rng, endContainer, 'nextSibling');
  10404. }
  10405. if (isBlockFormat(format) || isSelectorFormat(format)) {
  10406. startContainer = findBlockEndPoint(editor, formatList, startContainer, 'previousSibling');
  10407. endContainer = findBlockEndPoint(editor, formatList, endContainer, 'nextSibling');
  10408. if (isBlockFormat(format)) {
  10409. if (!dom.isBlock(startContainer)) {
  10410. startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  10411. }
  10412. if (!dom.isBlock(endContainer)) {
  10413. endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  10414. }
  10415. }
  10416. }
  10417. if (isElement$5(startContainer)) {
  10418. startOffset = dom.nodeIndex(startContainer);
  10419. startContainer = startContainer.parentNode;
  10420. }
  10421. if (isElement$5(endContainer)) {
  10422. endOffset = dom.nodeIndex(endContainer) + 1;
  10423. endContainer = endContainer.parentNode;
  10424. }
  10425. return {
  10426. startContainer: startContainer,
  10427. startOffset: startOffset,
  10428. endContainer: endContainer,
  10429. endOffset: endOffset
  10430. };
  10431. };
  10432. var walk$2 = function (dom, rng, callback) {
  10433. var startOffset = rng.startOffset;
  10434. var startContainer = getNode$1(rng.startContainer, startOffset);
  10435. var endOffset = rng.endOffset;
  10436. var endContainer = getNode$1(rng.endContainer, endOffset - 1);
  10437. var exclude = function (nodes) {
  10438. var firstNode = nodes[0];
  10439. if (isText$7(firstNode) && firstNode === startContainer && startOffset >= firstNode.data.length) {
  10440. nodes.splice(0, 1);
  10441. }
  10442. var lastNode = nodes[nodes.length - 1];
  10443. if (endOffset === 0 && nodes.length > 0 && lastNode === endContainer && isText$7(lastNode)) {
  10444. nodes.splice(nodes.length - 1, 1);
  10445. }
  10446. return nodes;
  10447. };
  10448. var collectSiblings = function (node, name, endNode) {
  10449. var siblings = [];
  10450. for (; node && node !== endNode; node = node[name]) {
  10451. siblings.push(node);
  10452. }
  10453. return siblings;
  10454. };
  10455. var findEndPoint = function (node, root) {
  10456. return dom.getParent(node, function (node) {
  10457. return node.parentNode === root;
  10458. }, root);
  10459. };
  10460. var walkBoundary = function (startNode, endNode, next) {
  10461. var siblingName = next ? 'nextSibling' : 'previousSibling';
  10462. for (var node = startNode, parent_1 = node.parentNode; node && node !== endNode; node = parent_1) {
  10463. parent_1 = node.parentNode;
  10464. var siblings_1 = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
  10465. if (siblings_1.length) {
  10466. if (!next) {
  10467. siblings_1.reverse();
  10468. }
  10469. callback(exclude(siblings_1));
  10470. }
  10471. }
  10472. };
  10473. if (startContainer === endContainer) {
  10474. return callback(exclude([startContainer]));
  10475. }
  10476. var ancestor = dom.findCommonAncestor(startContainer, endContainer);
  10477. if (dom.isChildOf(startContainer, endContainer)) {
  10478. return walkBoundary(startContainer, ancestor, true);
  10479. }
  10480. if (dom.isChildOf(endContainer, startContainer)) {
  10481. return walkBoundary(endContainer, ancestor);
  10482. }
  10483. var startPoint = findEndPoint(startContainer, ancestor) || startContainer;
  10484. var endPoint = findEndPoint(endContainer, ancestor) || endContainer;
  10485. walkBoundary(startContainer, startPoint, true);
  10486. var siblings = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint === endContainer ? endPoint.nextSibling : endPoint);
  10487. if (siblings.length) {
  10488. callback(exclude(siblings));
  10489. }
  10490. walkBoundary(endContainer, endPoint);
  10491. };
  10492. var getRanges = function (selection) {
  10493. var ranges = [];
  10494. if (selection) {
  10495. for (var i = 0; i < selection.rangeCount; i++) {
  10496. ranges.push(selection.getRangeAt(i));
  10497. }
  10498. }
  10499. return ranges;
  10500. };
  10501. var getSelectedNodes = function (ranges) {
  10502. return bind(ranges, function (range) {
  10503. var node = getSelectedNode(range);
  10504. return node ? [SugarElement.fromDom(node)] : [];
  10505. });
  10506. };
  10507. var hasMultipleRanges = function (selection) {
  10508. return getRanges(selection).length > 1;
  10509. };
  10510. var getCellsFromRanges = function (ranges) {
  10511. return filter$4(getSelectedNodes(ranges), isTableCell$4);
  10512. };
  10513. var getCellsFromElement = function (elm) {
  10514. return descendants(elm, 'td[data-mce-selected],th[data-mce-selected]');
  10515. };
  10516. var getCellsFromElementOrRanges = function (ranges, element) {
  10517. var selectedCells = getCellsFromElement(element);
  10518. return selectedCells.length > 0 ? selectedCells : getCellsFromRanges(ranges);
  10519. };
  10520. var getCellsFromEditor = function (editor) {
  10521. return getCellsFromElementOrRanges(getRanges(editor.selection.getSel()), SugarElement.fromDom(editor.getBody()));
  10522. };
  10523. var getClosestTable = function (cell, isRoot) {
  10524. return ancestor$2(cell, 'table', isRoot);
  10525. };
  10526. var getStartNode = function (rng) {
  10527. var sc = rng.startContainer, so = rng.startOffset;
  10528. if (isText$7(sc)) {
  10529. return so === 0 ? Optional.some(SugarElement.fromDom(sc)) : Optional.none();
  10530. } else {
  10531. return Optional.from(sc.childNodes[so]).map(SugarElement.fromDom);
  10532. }
  10533. };
  10534. var getEndNode = function (rng) {
  10535. var ec = rng.endContainer, eo = rng.endOffset;
  10536. if (isText$7(ec)) {
  10537. return eo === ec.data.length ? Optional.some(SugarElement.fromDom(ec)) : Optional.none();
  10538. } else {
  10539. return Optional.from(ec.childNodes[eo - 1]).map(SugarElement.fromDom);
  10540. }
  10541. };
  10542. var getFirstChildren = function (node) {
  10543. return firstChild(node).fold(constant([node]), function (child) {
  10544. return [node].concat(getFirstChildren(child));
  10545. });
  10546. };
  10547. var getLastChildren$1 = function (node) {
  10548. return lastChild(node).fold(constant([node]), function (child) {
  10549. if (name(child) === 'br') {
  10550. return prevSibling(child).map(function (sibling) {
  10551. return [node].concat(getLastChildren$1(sibling));
  10552. }).getOr([]);
  10553. } else {
  10554. return [node].concat(getLastChildren$1(child));
  10555. }
  10556. });
  10557. };
  10558. var hasAllContentsSelected = function (elm, rng) {
  10559. return lift2(getStartNode(rng), getEndNode(rng), function (startNode, endNode) {
  10560. var start = find$3(getFirstChildren(elm), curry(eq, startNode));
  10561. var end = find$3(getLastChildren$1(elm), curry(eq, endNode));
  10562. return start.isSome() && end.isSome();
  10563. }).getOr(false);
  10564. };
  10565. var moveEndPoint = function (dom, rng, node, start) {
  10566. var root = node, walker = new DomTreeWalker(node, root);
  10567. var moveCaretBeforeOnEnterElementsMap = filter$3(dom.schema.getMoveCaretBeforeOnEnterElements(), function (_, name) {
  10568. return !contains$3([
  10569. 'td',
  10570. 'th',
  10571. 'table'
  10572. ], name.toLowerCase());
  10573. });
  10574. do {
  10575. if (isText$7(node) && Tools.trim(node.nodeValue).length !== 0) {
  10576. if (start) {
  10577. rng.setStart(node, 0);
  10578. } else {
  10579. rng.setEnd(node, node.nodeValue.length);
  10580. }
  10581. return;
  10582. }
  10583. if (moveCaretBeforeOnEnterElementsMap[node.nodeName]) {
  10584. if (start) {
  10585. rng.setStartBefore(node);
  10586. } else {
  10587. if (node.nodeName === 'BR') {
  10588. rng.setEndBefore(node);
  10589. } else {
  10590. rng.setEndAfter(node);
  10591. }
  10592. }
  10593. return;
  10594. }
  10595. } while (node = start ? walker.next() : walker.prev());
  10596. if (root.nodeName === 'BODY') {
  10597. if (start) {
  10598. rng.setStart(root, 0);
  10599. } else {
  10600. rng.setEnd(root, root.childNodes.length);
  10601. }
  10602. }
  10603. };
  10604. var hasAnyRanges = function (editor) {
  10605. var sel = editor.selection.getSel();
  10606. return sel && sel.rangeCount > 0;
  10607. };
  10608. var runOnRanges = function (editor, executor) {
  10609. var fakeSelectionNodes = getCellsFromEditor(editor);
  10610. if (fakeSelectionNodes.length > 0) {
  10611. each$k(fakeSelectionNodes, function (elem) {
  10612. var node = elem.dom;
  10613. var fakeNodeRng = editor.dom.createRng();
  10614. fakeNodeRng.setStartBefore(node);
  10615. fakeNodeRng.setEndAfter(node);
  10616. executor(fakeNodeRng, true);
  10617. });
  10618. } else {
  10619. executor(editor.selection.getRng(), false);
  10620. }
  10621. };
  10622. var preserve = function (selection, fillBookmark, executor) {
  10623. var bookmark = getPersistentBookmark(selection, fillBookmark);
  10624. executor(bookmark);
  10625. selection.moveToBookmark(bookmark);
  10626. };
  10627. var NodeValue = function (is, name) {
  10628. var get = function (element) {
  10629. if (!is(element)) {
  10630. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  10631. }
  10632. return getOption(element).getOr('');
  10633. };
  10634. var getOption = function (element) {
  10635. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  10636. };
  10637. var set = function (element, value) {
  10638. if (!is(element)) {
  10639. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  10640. }
  10641. element.dom.nodeValue = value;
  10642. };
  10643. return {
  10644. get: get,
  10645. getOption: getOption,
  10646. set: set
  10647. };
  10648. };
  10649. var api$1 = NodeValue(isText$8, 'text');
  10650. var get$2 = function (element) {
  10651. return api$1.get(element);
  10652. };
  10653. var isZeroWidth = function (elem) {
  10654. return isText$8(elem) && get$2(elem) === ZWSP$1;
  10655. };
  10656. var context = function (editor, elem, wrapName, nodeName) {
  10657. return parent(elem).fold(function () {
  10658. return 'skipping';
  10659. }, function (parent) {
  10660. if (nodeName === 'br' || isZeroWidth(elem)) {
  10661. return 'valid';
  10662. } else if (isAnnotation(elem)) {
  10663. return 'existing';
  10664. } else if (isCaretNode(elem.dom)) {
  10665. return 'caret';
  10666. } else if (!isValid(editor, wrapName, nodeName) || !isValid(editor, name(parent), wrapName)) {
  10667. return 'invalid-child';
  10668. } else {
  10669. return 'valid';
  10670. }
  10671. });
  10672. };
  10673. var applyWordGrab = function (editor, rng) {
  10674. var r = expandRng(editor, rng, [{ inline: 'span' }]);
  10675. rng.setStart(r.startContainer, r.startOffset);
  10676. rng.setEnd(r.endContainer, r.endOffset);
  10677. editor.selection.setRng(rng);
  10678. };
  10679. var makeAnnotation = function (eDoc, _a, annotationName, decorate) {
  10680. var _b = _a.uid, uid = _b === void 0 ? generate('mce-annotation') : _b, data = __rest(_a, ['uid']);
  10681. var master = SugarElement.fromTag('span', eDoc);
  10682. add$1(master, annotation());
  10683. set$1(master, '' + dataAnnotationId(), uid);
  10684. set$1(master, '' + dataAnnotation(), annotationName);
  10685. var _c = decorate(uid, data), _d = _c.attributes, attributes = _d === void 0 ? {} : _d, _e = _c.classes, classes = _e === void 0 ? [] : _e;
  10686. setAll$1(master, attributes);
  10687. add(master, classes);
  10688. return master;
  10689. };
  10690. var annotate = function (editor, rng, annotationName, decorate, data) {
  10691. var newWrappers = [];
  10692. var master = makeAnnotation(editor.getDoc(), data, annotationName, decorate);
  10693. var wrapper = value();
  10694. var finishWrapper = function () {
  10695. wrapper.clear();
  10696. };
  10697. var getOrOpenWrapper = function () {
  10698. return wrapper.get().getOrThunk(function () {
  10699. var nu = shallow(master);
  10700. newWrappers.push(nu);
  10701. wrapper.set(nu);
  10702. return nu;
  10703. });
  10704. };
  10705. var processElements = function (elems) {
  10706. each$k(elems, processElement);
  10707. };
  10708. var processElement = function (elem) {
  10709. var ctx = context(editor, elem, 'span', name(elem));
  10710. switch (ctx) {
  10711. case 'invalid-child': {
  10712. finishWrapper();
  10713. var children$1 = children(elem);
  10714. processElements(children$1);
  10715. finishWrapper();
  10716. break;
  10717. }
  10718. case 'valid': {
  10719. var w = getOrOpenWrapper();
  10720. wrap$3(elem, w);
  10721. break;
  10722. }
  10723. }
  10724. };
  10725. var processNodes = function (nodes) {
  10726. var elems = map$3(nodes, SugarElement.fromDom);
  10727. processElements(elems);
  10728. };
  10729. walk$2(editor.dom, rng, function (nodes) {
  10730. finishWrapper();
  10731. processNodes(nodes);
  10732. });
  10733. return newWrappers;
  10734. };
  10735. var annotateWithBookmark = function (editor, name, settings, data) {
  10736. editor.undoManager.transact(function () {
  10737. var selection = editor.selection;
  10738. var initialRng = selection.getRng();
  10739. var hasFakeSelection = getCellsFromEditor(editor).length > 0;
  10740. if (initialRng.collapsed && !hasFakeSelection) {
  10741. applyWordGrab(editor, initialRng);
  10742. }
  10743. if (selection.getRng().collapsed && !hasFakeSelection) {
  10744. var wrapper = makeAnnotation(editor.getDoc(), data, name, settings.decorate);
  10745. set(wrapper, nbsp);
  10746. selection.getRng().insertNode(wrapper.dom);
  10747. selection.select(wrapper.dom);
  10748. } else {
  10749. preserve(selection, false, function () {
  10750. runOnRanges(editor, function (selectionRng) {
  10751. annotate(editor, selectionRng, name, settings.decorate, data);
  10752. });
  10753. });
  10754. }
  10755. });
  10756. };
  10757. var Annotator = function (editor) {
  10758. var registry = create$7();
  10759. setup$m(editor, registry);
  10760. var changes = setup$n(editor);
  10761. return {
  10762. register: function (name, settings) {
  10763. registry.register(name, settings);
  10764. },
  10765. annotate: function (name, data) {
  10766. registry.lookup(name).each(function (settings) {
  10767. annotateWithBookmark(editor, name, settings, data);
  10768. });
  10769. },
  10770. annotationChanged: function (name, callback) {
  10771. changes.addListener(name, callback);
  10772. },
  10773. remove: function (name) {
  10774. identify(editor, Optional.some(name)).each(function (_a) {
  10775. var elements = _a.elements;
  10776. each$k(elements, unwrap);
  10777. });
  10778. },
  10779. getAll: function (name) {
  10780. var directory = findAll(editor, name);
  10781. return map$2(directory, function (elems) {
  10782. return map$3(elems, function (elem) {
  10783. return elem.dom;
  10784. });
  10785. });
  10786. }
  10787. };
  10788. };
  10789. var BookmarkManager = function (selection) {
  10790. return {
  10791. getBookmark: curry(getBookmark$1, selection),
  10792. moveToBookmark: curry(moveToBookmark, selection)
  10793. };
  10794. };
  10795. BookmarkManager.isBookmarkNode = isBookmarkNode$1;
  10796. var getContentEditableRoot$1 = function (root, node) {
  10797. while (node && node !== root) {
  10798. if (isContentEditableTrue$4(node) || isContentEditableFalse$b(node)) {
  10799. return node;
  10800. }
  10801. node = node.parentNode;
  10802. }
  10803. return null;
  10804. };
  10805. var isXYWithinRange = function (clientX, clientY, range) {
  10806. if (range.collapsed) {
  10807. return false;
  10808. }
  10809. if (Env.browser.isIE() && range.startOffset === range.endOffset - 1 && range.startContainer === range.endContainer) {
  10810. var elm = range.startContainer.childNodes[range.startOffset];
  10811. if (isElement$5(elm)) {
  10812. return exists(elm.getClientRects(), function (rect) {
  10813. return containsXY(rect, clientX, clientY);
  10814. });
  10815. }
  10816. }
  10817. return exists(range.getClientRects(), function (rect) {
  10818. return containsXY(rect, clientX, clientY);
  10819. });
  10820. };
  10821. var firePreProcess = function (editor, args) {
  10822. return editor.fire('PreProcess', args);
  10823. };
  10824. var firePostProcess = function (editor, args) {
  10825. return editor.fire('PostProcess', args);
  10826. };
  10827. var fireRemove = function (editor) {
  10828. return editor.fire('remove');
  10829. };
  10830. var fireDetach = function (editor) {
  10831. return editor.fire('detach');
  10832. };
  10833. var fireSwitchMode = function (editor, mode) {
  10834. return editor.fire('SwitchMode', { mode: mode });
  10835. };
  10836. var fireObjectResizeStart = function (editor, target, width, height, origin) {
  10837. editor.fire('ObjectResizeStart', {
  10838. target: target,
  10839. width: width,
  10840. height: height,
  10841. origin: origin
  10842. });
  10843. };
  10844. var fireObjectResized = function (editor, target, width, height, origin) {
  10845. editor.fire('ObjectResized', {
  10846. target: target,
  10847. width: width,
  10848. height: height,
  10849. origin: origin
  10850. });
  10851. };
  10852. var firePreInit = function (editor) {
  10853. return editor.fire('PreInit');
  10854. };
  10855. var firePostRender = function (editor) {
  10856. return editor.fire('PostRender');
  10857. };
  10858. var fireInit = function (editor) {
  10859. return editor.fire('Init');
  10860. };
  10861. var firePlaceholderToggle = function (editor, state) {
  10862. return editor.fire('PlaceholderToggle', { state: state });
  10863. };
  10864. var fireError = function (editor, errorType, error) {
  10865. return editor.fire(errorType, error);
  10866. };
  10867. var fireFormatApply = function (editor, format, node, vars) {
  10868. return editor.fire('FormatApply', {
  10869. format: format,
  10870. node: node,
  10871. vars: vars
  10872. });
  10873. };
  10874. var fireFormatRemove = function (editor, format, node, vars) {
  10875. return editor.fire('FormatRemove', {
  10876. format: format,
  10877. node: node,
  10878. vars: vars
  10879. });
  10880. };
  10881. var VK = {
  10882. BACKSPACE: 8,
  10883. DELETE: 46,
  10884. DOWN: 40,
  10885. ENTER: 13,
  10886. ESC: 27,
  10887. LEFT: 37,
  10888. RIGHT: 39,
  10889. SPACEBAR: 32,
  10890. TAB: 9,
  10891. UP: 38,
  10892. PAGE_UP: 33,
  10893. PAGE_DOWN: 34,
  10894. END: 35,
  10895. HOME: 36,
  10896. modifierPressed: function (e) {
  10897. return e.shiftKey || e.ctrlKey || e.altKey || VK.metaKeyPressed(e);
  10898. },
  10899. metaKeyPressed: function (e) {
  10900. return Env.mac ? e.metaKey : e.ctrlKey && !e.altKey;
  10901. }
  10902. };
  10903. var isContentEditableFalse$5 = isContentEditableFalse$b;
  10904. var ControlSelection = function (selection, editor) {
  10905. var elementSelectionAttr = 'data-mce-selected';
  10906. var dom = editor.dom, each = Tools.each;
  10907. var selectedElm, selectedElmGhost, resizeHelper, selectedHandle, resizeBackdrop;
  10908. var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
  10909. var width, height;
  10910. var editableDoc = editor.getDoc(), rootDocument = document;
  10911. var abs = Math.abs, round = Math.round, rootElement = editor.getBody();
  10912. var startScrollWidth, startScrollHeight;
  10913. var resizeHandles = {
  10914. nw: [
  10915. 0,
  10916. 0,
  10917. -1,
  10918. -1
  10919. ],
  10920. ne: [
  10921. 1,
  10922. 0,
  10923. 1,
  10924. -1
  10925. ],
  10926. se: [
  10927. 1,
  10928. 1,
  10929. 1,
  10930. 1
  10931. ],
  10932. sw: [
  10933. 0,
  10934. 1,
  10935. -1,
  10936. 1
  10937. ]
  10938. };
  10939. var isImage = function (elm) {
  10940. return elm && (elm.nodeName === 'IMG' || editor.dom.is(elm, 'figure.image'));
  10941. };
  10942. var isMedia = function (elm) {
  10943. return isMedia$2(elm) || dom.hasClass(elm, 'mce-preview-object');
  10944. };
  10945. var isEventOnImageOutsideRange = function (evt, range) {
  10946. if (evt.type === 'longpress' || evt.type.indexOf('touch') === 0) {
  10947. var touch = evt.touches[0];
  10948. return isImage(evt.target) && !isXYWithinRange(touch.clientX, touch.clientY, range);
  10949. } else {
  10950. return isImage(evt.target) && !isXYWithinRange(evt.clientX, evt.clientY, range);
  10951. }
  10952. };
  10953. var contextMenuSelectImage = function (evt) {
  10954. var target = evt.target;
  10955. if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) && !evt.isDefaultPrevented()) {
  10956. editor.selection.select(target);
  10957. }
  10958. };
  10959. var getResizeTargets = function (elm) {
  10960. if (dom.is(elm, 'figure.image')) {
  10961. return [elm.querySelector('img')];
  10962. } else if (dom.hasClass(elm, 'mce-preview-object') && isNonNullable(elm.firstElementChild)) {
  10963. return [
  10964. elm,
  10965. elm.firstElementChild
  10966. ];
  10967. } else {
  10968. return [elm];
  10969. }
  10970. };
  10971. var isResizable = function (elm) {
  10972. var selector = getObjectResizing(editor);
  10973. if (!selector) {
  10974. return false;
  10975. }
  10976. if (elm.getAttribute('data-mce-resize') === 'false') {
  10977. return false;
  10978. }
  10979. if (elm === editor.getBody()) {
  10980. return false;
  10981. }
  10982. if (dom.hasClass(elm, 'mce-preview-object')) {
  10983. return is$2(SugarElement.fromDom(elm.firstElementChild), selector);
  10984. } else {
  10985. return is$2(SugarElement.fromDom(elm), selector);
  10986. }
  10987. };
  10988. var createGhostElement = function (elm) {
  10989. if (isMedia(elm)) {
  10990. return dom.create('img', { src: Env.transparentSrc });
  10991. } else {
  10992. return elm.cloneNode(true);
  10993. }
  10994. };
  10995. var setSizeProp = function (element, name, value) {
  10996. if (isNonNullable(value)) {
  10997. var targets = getResizeTargets(element);
  10998. each$k(targets, function (target) {
  10999. if (target.style[name] || !editor.schema.isValid(target.nodeName.toLowerCase(), name)) {
  11000. dom.setStyle(target, name, value);
  11001. } else {
  11002. dom.setAttrib(target, name, '' + value);
  11003. }
  11004. });
  11005. }
  11006. };
  11007. var setGhostElmSize = function (ghostElm, width, height) {
  11008. setSizeProp(ghostElm, 'width', width);
  11009. setSizeProp(ghostElm, 'height', height);
  11010. };
  11011. var resizeGhostElement = function (e) {
  11012. var deltaX, deltaY, proportional;
  11013. var resizeHelperX, resizeHelperY;
  11014. deltaX = e.screenX - startX;
  11015. deltaY = e.screenY - startY;
  11016. width = deltaX * selectedHandle[2] + startW;
  11017. height = deltaY * selectedHandle[3] + startH;
  11018. width = width < 5 ? 5 : width;
  11019. height = height < 5 ? 5 : height;
  11020. if ((isImage(selectedElm) || isMedia(selectedElm)) && getResizeImgProportional(editor) !== false) {
  11021. proportional = !VK.modifierPressed(e);
  11022. } else {
  11023. proportional = VK.modifierPressed(e);
  11024. }
  11025. if (proportional) {
  11026. if (abs(deltaX) > abs(deltaY)) {
  11027. height = round(width * ratio);
  11028. width = round(height / ratio);
  11029. } else {
  11030. width = round(height / ratio);
  11031. height = round(width * ratio);
  11032. }
  11033. }
  11034. setGhostElmSize(selectedElmGhost, width, height);
  11035. resizeHelperX = selectedHandle.startPos.x + deltaX;
  11036. resizeHelperY = selectedHandle.startPos.y + deltaY;
  11037. resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
  11038. resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
  11039. dom.setStyles(resizeHelper, {
  11040. left: resizeHelperX,
  11041. top: resizeHelperY,
  11042. display: 'block'
  11043. });
  11044. resizeHelper.innerHTML = width + ' &times; ' + height;
  11045. if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
  11046. dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
  11047. }
  11048. if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
  11049. dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
  11050. }
  11051. deltaX = rootElement.scrollWidth - startScrollWidth;
  11052. deltaY = rootElement.scrollHeight - startScrollHeight;
  11053. if (deltaX + deltaY !== 0) {
  11054. dom.setStyles(resizeHelper, {
  11055. left: resizeHelperX - deltaX,
  11056. top: resizeHelperY - deltaY
  11057. });
  11058. }
  11059. if (!resizeStarted) {
  11060. fireObjectResizeStart(editor, selectedElm, startW, startH, 'corner-' + selectedHandle.name);
  11061. resizeStarted = true;
  11062. }
  11063. };
  11064. var endGhostResize = function () {
  11065. var wasResizeStarted = resizeStarted;
  11066. resizeStarted = false;
  11067. if (wasResizeStarted) {
  11068. setSizeProp(selectedElm, 'width', width);
  11069. setSizeProp(selectedElm, 'height', height);
  11070. }
  11071. dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
  11072. dom.unbind(editableDoc, 'mouseup', endGhostResize);
  11073. if (rootDocument !== editableDoc) {
  11074. dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
  11075. dom.unbind(rootDocument, 'mouseup', endGhostResize);
  11076. }
  11077. dom.remove(selectedElmGhost);
  11078. dom.remove(resizeHelper);
  11079. dom.remove(resizeBackdrop);
  11080. showResizeRect(selectedElm);
  11081. if (wasResizeStarted) {
  11082. fireObjectResized(editor, selectedElm, width, height, 'corner-' + selectedHandle.name);
  11083. dom.setAttrib(selectedElm, 'style', dom.getAttrib(selectedElm, 'style'));
  11084. }
  11085. editor.nodeChanged();
  11086. };
  11087. var showResizeRect = function (targetElm) {
  11088. unbindResizeHandleEvents();
  11089. var position = dom.getPos(targetElm, rootElement);
  11090. var selectedElmX = position.x;
  11091. var selectedElmY = position.y;
  11092. var rect = targetElm.getBoundingClientRect();
  11093. var targetWidth = rect.width || rect.right - rect.left;
  11094. var targetHeight = rect.height || rect.bottom - rect.top;
  11095. if (selectedElm !== targetElm) {
  11096. hideResizeRect();
  11097. selectedElm = targetElm;
  11098. width = height = 0;
  11099. }
  11100. var e = editor.fire('ObjectSelected', { target: targetElm });
  11101. var selectedValue = dom.getAttrib(selectedElm, elementSelectionAttr, '1');
  11102. if (isResizable(targetElm) && !e.isDefaultPrevented()) {
  11103. each(resizeHandles, function (handle, name) {
  11104. var handleElm;
  11105. var startDrag = function (e) {
  11106. var target = getResizeTargets(selectedElm)[0];
  11107. startX = e.screenX;
  11108. startY = e.screenY;
  11109. startW = target.clientWidth;
  11110. startH = target.clientHeight;
  11111. ratio = startH / startW;
  11112. selectedHandle = handle;
  11113. selectedHandle.name = name;
  11114. selectedHandle.startPos = {
  11115. x: targetWidth * handle[0] + selectedElmX,
  11116. y: targetHeight * handle[1] + selectedElmY
  11117. };
  11118. startScrollWidth = rootElement.scrollWidth;
  11119. startScrollHeight = rootElement.scrollHeight;
  11120. resizeBackdrop = dom.add(rootElement, 'div', {
  11121. 'class': 'mce-resize-backdrop',
  11122. 'data-mce-bogus': 'all'
  11123. });
  11124. dom.setStyles(resizeBackdrop, {
  11125. position: 'fixed',
  11126. left: '0',
  11127. top: '0',
  11128. width: '100%',
  11129. height: '100%'
  11130. });
  11131. selectedElmGhost = createGhostElement(selectedElm);
  11132. dom.addClass(selectedElmGhost, 'mce-clonedresizable');
  11133. dom.setAttrib(selectedElmGhost, 'data-mce-bogus', 'all');
  11134. selectedElmGhost.contentEditable = 'false';
  11135. dom.setStyles(selectedElmGhost, {
  11136. left: selectedElmX,
  11137. top: selectedElmY,
  11138. margin: 0
  11139. });
  11140. setGhostElmSize(selectedElmGhost, targetWidth, targetHeight);
  11141. selectedElmGhost.removeAttribute(elementSelectionAttr);
  11142. rootElement.appendChild(selectedElmGhost);
  11143. dom.bind(editableDoc, 'mousemove', resizeGhostElement);
  11144. dom.bind(editableDoc, 'mouseup', endGhostResize);
  11145. if (rootDocument !== editableDoc) {
  11146. dom.bind(rootDocument, 'mousemove', resizeGhostElement);
  11147. dom.bind(rootDocument, 'mouseup', endGhostResize);
  11148. }
  11149. resizeHelper = dom.add(rootElement, 'div', {
  11150. 'class': 'mce-resize-helper',
  11151. 'data-mce-bogus': 'all'
  11152. }, startW + ' &times; ' + startH);
  11153. };
  11154. handleElm = dom.get('mceResizeHandle' + name);
  11155. if (handleElm) {
  11156. dom.remove(handleElm);
  11157. }
  11158. handleElm = dom.add(rootElement, 'div', {
  11159. 'id': 'mceResizeHandle' + name,
  11160. 'data-mce-bogus': 'all',
  11161. 'class': 'mce-resizehandle',
  11162. 'unselectable': true,
  11163. 'style': 'cursor:' + name + '-resize; margin:0; padding:0'
  11164. });
  11165. if (Env.ie === 11) {
  11166. handleElm.contentEditable = false;
  11167. }
  11168. dom.bind(handleElm, 'mousedown', function (e) {
  11169. e.stopImmediatePropagation();
  11170. e.preventDefault();
  11171. startDrag(e);
  11172. });
  11173. handle.elm = handleElm;
  11174. dom.setStyles(handleElm, {
  11175. left: targetWidth * handle[0] + selectedElmX - handleElm.offsetWidth / 2,
  11176. top: targetHeight * handle[1] + selectedElmY - handleElm.offsetHeight / 2
  11177. });
  11178. });
  11179. } else {
  11180. hideResizeRect();
  11181. }
  11182. if (!dom.getAttrib(selectedElm, elementSelectionAttr)) {
  11183. selectedElm.setAttribute(elementSelectionAttr, selectedValue);
  11184. }
  11185. };
  11186. var hideResizeRect = function () {
  11187. unbindResizeHandleEvents();
  11188. if (selectedElm) {
  11189. selectedElm.removeAttribute(elementSelectionAttr);
  11190. }
  11191. each$j(resizeHandles, function (value, name) {
  11192. var handleElm = dom.get('mceResizeHandle' + name);
  11193. if (handleElm) {
  11194. dom.unbind(handleElm);
  11195. dom.remove(handleElm);
  11196. }
  11197. });
  11198. };
  11199. var updateResizeRect = function (e) {
  11200. var startElm, controlElm;
  11201. var isChildOrEqual = function (node, parent) {
  11202. if (node) {
  11203. do {
  11204. if (node === parent) {
  11205. return true;
  11206. }
  11207. } while (node = node.parentNode);
  11208. }
  11209. };
  11210. if (resizeStarted || editor.removed) {
  11211. return;
  11212. }
  11213. each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function (img) {
  11214. img.removeAttribute(elementSelectionAttr);
  11215. });
  11216. controlElm = e.type === 'mousedown' ? e.target : selection.getNode();
  11217. controlElm = dom.$(controlElm).closest('table,img,figure.image,hr,video,span.mce-preview-object')[0];
  11218. if (isChildOrEqual(controlElm, rootElement)) {
  11219. disableGeckoResize();
  11220. startElm = selection.getStart(true);
  11221. if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
  11222. showResizeRect(controlElm);
  11223. return;
  11224. }
  11225. }
  11226. hideResizeRect();
  11227. };
  11228. var isWithinContentEditableFalse = function (elm) {
  11229. return isContentEditableFalse$5(getContentEditableRoot$1(editor.getBody(), elm));
  11230. };
  11231. var unbindResizeHandleEvents = function () {
  11232. each$j(resizeHandles, function (handle) {
  11233. if (handle.elm) {
  11234. dom.unbind(handle.elm);
  11235. delete handle.elm;
  11236. }
  11237. });
  11238. };
  11239. var disableGeckoResize = function () {
  11240. try {
  11241. editor.getDoc().execCommand('enableObjectResizing', false, 'false');
  11242. } catch (ex) {
  11243. }
  11244. };
  11245. editor.on('init', function () {
  11246. disableGeckoResize();
  11247. if (Env.browser.isIE() || Env.browser.isEdge()) {
  11248. editor.on('mousedown click', function (e) {
  11249. var target = e.target, nodeName = target.nodeName;
  11250. if (!resizeStarted && /^(TABLE|IMG|HR)$/.test(nodeName) && !isWithinContentEditableFalse(target)) {
  11251. if (e.button !== 2) {
  11252. editor.selection.select(target, nodeName === 'TABLE');
  11253. }
  11254. if (e.type === 'mousedown') {
  11255. editor.nodeChanged();
  11256. }
  11257. }
  11258. });
  11259. var handleMSControlSelect_1 = function (e) {
  11260. var delayedSelect = function (node) {
  11261. Delay.setEditorTimeout(editor, function () {
  11262. return editor.selection.select(node);
  11263. });
  11264. };
  11265. if (isWithinContentEditableFalse(e.target) || isMedia$2(e.target)) {
  11266. e.preventDefault();
  11267. delayedSelect(e.target);
  11268. return;
  11269. }
  11270. if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) {
  11271. e.preventDefault();
  11272. if (e.target.tagName === 'IMG') {
  11273. delayedSelect(e.target);
  11274. }
  11275. }
  11276. };
  11277. dom.bind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11278. editor.on('remove', function () {
  11279. return dom.unbind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11280. });
  11281. }
  11282. var throttledUpdateResizeRect = Delay.throttle(function (e) {
  11283. if (!editor.composing) {
  11284. updateResizeRect(e);
  11285. }
  11286. });
  11287. editor.on('nodechange ResizeEditor ResizeWindow ResizeContent drop FullscreenStateChanged', throttledUpdateResizeRect);
  11288. editor.on('keyup compositionend', function (e) {
  11289. if (selectedElm && selectedElm.nodeName === 'TABLE') {
  11290. throttledUpdateResizeRect(e);
  11291. }
  11292. });
  11293. editor.on('hide blur', hideResizeRect);
  11294. editor.on('contextmenu longpress', contextMenuSelectImage, true);
  11295. });
  11296. editor.on('remove', unbindResizeHandleEvents);
  11297. var destroy = function () {
  11298. selectedElm = selectedElmGhost = resizeBackdrop = null;
  11299. };
  11300. return {
  11301. isResizable: isResizable,
  11302. showResizeRect: showResizeRect,
  11303. hideResizeRect: hideResizeRect,
  11304. updateResizeRect: updateResizeRect,
  11305. destroy: destroy
  11306. };
  11307. };
  11308. var hasCeProperty = function (node) {
  11309. return isContentEditableTrue$4(node) || isContentEditableFalse$b(node);
  11310. };
  11311. var findParent$1 = function (node, rootNode, predicate) {
  11312. while (node && node !== rootNode) {
  11313. if (predicate(node)) {
  11314. return node;
  11315. }
  11316. node = node.parentNode;
  11317. }
  11318. return null;
  11319. };
  11320. var findClosestIeRange = function (clientX, clientY, doc) {
  11321. var rects;
  11322. var element = doc.elementFromPoint(clientX, clientY);
  11323. var rng = doc.body.createTextRange();
  11324. if (!element || element.tagName === 'HTML') {
  11325. element = doc.body;
  11326. }
  11327. rng.moveToElementText(element);
  11328. rects = Tools.toArray(rng.getClientRects());
  11329. rects = rects.sort(function (a, b) {
  11330. a = Math.abs(Math.max(a.top - clientY, a.bottom - clientY));
  11331. b = Math.abs(Math.max(b.top - clientY, b.bottom - clientY));
  11332. return a - b;
  11333. });
  11334. if (rects.length > 0) {
  11335. clientY = (rects[0].bottom + rects[0].top) / 2;
  11336. try {
  11337. rng.moveToPoint(clientX, clientY);
  11338. rng.collapse(true);
  11339. return rng;
  11340. } catch (ex) {
  11341. }
  11342. }
  11343. return null;
  11344. };
  11345. var moveOutOfContentEditableFalse = function (rng, rootNode) {
  11346. var parentElement = rng && rng.parentElement ? rng.parentElement() : null;
  11347. return isContentEditableFalse$b(findParent$1(parentElement, rootNode, hasCeProperty)) ? null : rng;
  11348. };
  11349. var fromPoint = function (clientX, clientY, doc) {
  11350. var rng, point;
  11351. var pointDoc = doc;
  11352. if (pointDoc.caretPositionFromPoint) {
  11353. point = pointDoc.caretPositionFromPoint(clientX, clientY);
  11354. if (point) {
  11355. rng = doc.createRange();
  11356. rng.setStart(point.offsetNode, point.offset);
  11357. rng.collapse(true);
  11358. }
  11359. } else if (pointDoc.caretRangeFromPoint) {
  11360. rng = pointDoc.caretRangeFromPoint(clientX, clientY);
  11361. } else if (pointDoc.body.createTextRange) {
  11362. rng = pointDoc.body.createTextRange();
  11363. try {
  11364. rng.moveToPoint(clientX, clientY);
  11365. rng.collapse(true);
  11366. } catch (ex) {
  11367. rng = findClosestIeRange(clientX, clientY, doc);
  11368. }
  11369. return moveOutOfContentEditableFalse(rng, doc.body);
  11370. }
  11371. return rng;
  11372. };
  11373. var isEq$4 = function (rng1, rng2) {
  11374. return rng1 && rng2 && (rng1.startContainer === rng2.startContainer && rng1.startOffset === rng2.startOffset) && (rng1.endContainer === rng2.endContainer && rng1.endOffset === rng2.endOffset);
  11375. };
  11376. var findParent = function (node, rootNode, predicate) {
  11377. while (node && node !== rootNode) {
  11378. if (predicate(node)) {
  11379. return node;
  11380. }
  11381. node = node.parentNode;
  11382. }
  11383. return null;
  11384. };
  11385. var hasParent$1 = function (node, rootNode, predicate) {
  11386. return findParent(node, rootNode, predicate) !== null;
  11387. };
  11388. var hasParentWithName = function (node, rootNode, name) {
  11389. return hasParent$1(node, rootNode, function (node) {
  11390. return node.nodeName === name;
  11391. });
  11392. };
  11393. var isTable = function (node) {
  11394. return node && node.nodeName === 'TABLE';
  11395. };
  11396. var isTableCell$2 = function (node) {
  11397. return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  11398. };
  11399. var isCeFalseCaretContainer = function (node, rootNode) {
  11400. return isCaretContainer$2(node) && hasParent$1(node, rootNode, isCaretNode) === false;
  11401. };
  11402. var hasBrBeforeAfter = function (dom, node, left) {
  11403. var walker = new DomTreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || dom.getRoot());
  11404. while (node = walker[left ? 'prev' : 'next']()) {
  11405. if (isBr$5(node)) {
  11406. return true;
  11407. }
  11408. }
  11409. };
  11410. var isPrevNode = function (node, name) {
  11411. return node.previousSibling && node.previousSibling.nodeName === name;
  11412. };
  11413. var hasContentEditableFalseParent = function (body, node) {
  11414. while (node && node !== body) {
  11415. if (isContentEditableFalse$b(node)) {
  11416. return true;
  11417. }
  11418. node = node.parentNode;
  11419. }
  11420. return false;
  11421. };
  11422. var findTextNodeRelative = function (dom, isAfterNode, collapsed, left, startNode) {
  11423. var lastInlineElement;
  11424. var body = dom.getRoot();
  11425. var node;
  11426. var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11427. var parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body;
  11428. if (left && isBr$5(startNode) && isAfterNode && dom.isEmpty(parentBlockContainer)) {
  11429. return Optional.some(CaretPosition(startNode.parentNode, dom.nodeIndex(startNode)));
  11430. }
  11431. var walker = new DomTreeWalker(startNode, parentBlockContainer);
  11432. while (node = walker[left ? 'prev' : 'next']()) {
  11433. if (dom.getContentEditableParent(node) === 'false' || isCeFalseCaretContainer(node, body)) {
  11434. return Optional.none();
  11435. }
  11436. if (isText$7(node) && node.nodeValue.length > 0) {
  11437. if (hasParentWithName(node, body, 'A') === false) {
  11438. return Optional.some(CaretPosition(node, left ? node.nodeValue.length : 0));
  11439. }
  11440. return Optional.none();
  11441. }
  11442. if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  11443. return Optional.none();
  11444. }
  11445. lastInlineElement = node;
  11446. }
  11447. if (collapsed && lastInlineElement) {
  11448. return Optional.some(CaretPosition(lastInlineElement, 0));
  11449. }
  11450. return Optional.none();
  11451. };
  11452. var normalizeEndPoint = function (dom, collapsed, start, rng) {
  11453. var container, offset;
  11454. var body = dom.getRoot();
  11455. var node;
  11456. var directionLeft, normalized = false;
  11457. container = rng[(start ? 'start' : 'end') + 'Container'];
  11458. offset = rng[(start ? 'start' : 'end') + 'Offset'];
  11459. var isAfterNode = isElement$5(container) && offset === container.childNodes.length;
  11460. var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11461. directionLeft = start;
  11462. if (isCaretContainer$2(container)) {
  11463. return Optional.none();
  11464. }
  11465. if (isElement$5(container) && offset > container.childNodes.length - 1) {
  11466. directionLeft = false;
  11467. }
  11468. if (isDocument$1(container)) {
  11469. container = body;
  11470. offset = 0;
  11471. }
  11472. if (container === body) {
  11473. if (directionLeft) {
  11474. node = container.childNodes[offset > 0 ? offset - 1 : 0];
  11475. if (node) {
  11476. if (isCaretContainer$2(node)) {
  11477. return Optional.none();
  11478. }
  11479. if (nonEmptyElementsMap[node.nodeName] || isTable(node)) {
  11480. return Optional.none();
  11481. }
  11482. }
  11483. }
  11484. if (container.hasChildNodes()) {
  11485. offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
  11486. container = container.childNodes[offset];
  11487. offset = isText$7(container) && isAfterNode ? container.data.length : 0;
  11488. if (!collapsed && container === body.lastChild && isTable(container)) {
  11489. return Optional.none();
  11490. }
  11491. if (hasContentEditableFalseParent(body, container) || isCaretContainer$2(container)) {
  11492. return Optional.none();
  11493. }
  11494. if (container.hasChildNodes() && isTable(container) === false) {
  11495. node = container;
  11496. var walker = new DomTreeWalker(container, body);
  11497. do {
  11498. if (isContentEditableFalse$b(node) || isCaretContainer$2(node)) {
  11499. normalized = false;
  11500. break;
  11501. }
  11502. if (isText$7(node) && node.nodeValue.length > 0) {
  11503. offset = directionLeft ? 0 : node.nodeValue.length;
  11504. container = node;
  11505. normalized = true;
  11506. break;
  11507. }
  11508. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCell$2(node)) {
  11509. offset = dom.nodeIndex(node);
  11510. container = node.parentNode;
  11511. if (!directionLeft) {
  11512. offset++;
  11513. }
  11514. normalized = true;
  11515. break;
  11516. }
  11517. } while (node = directionLeft ? walker.next() : walker.prev());
  11518. }
  11519. }
  11520. }
  11521. if (collapsed) {
  11522. if (isText$7(container) && offset === 0) {
  11523. findTextNodeRelative(dom, isAfterNode, collapsed, true, container).each(function (pos) {
  11524. container = pos.container();
  11525. offset = pos.offset();
  11526. normalized = true;
  11527. });
  11528. }
  11529. if (isElement$5(container)) {
  11530. node = container.childNodes[offset];
  11531. if (!node) {
  11532. node = container.childNodes[offset - 1];
  11533. }
  11534. if (node && isBr$5(node) && !isPrevNode(node, 'A') && !hasBrBeforeAfter(dom, node, false) && !hasBrBeforeAfter(dom, node, true)) {
  11535. findTextNodeRelative(dom, isAfterNode, collapsed, true, node).each(function (pos) {
  11536. container = pos.container();
  11537. offset = pos.offset();
  11538. normalized = true;
  11539. });
  11540. }
  11541. }
  11542. }
  11543. if (directionLeft && !collapsed && isText$7(container) && offset === container.nodeValue.length) {
  11544. findTextNodeRelative(dom, isAfterNode, collapsed, false, container).each(function (pos) {
  11545. container = pos.container();
  11546. offset = pos.offset();
  11547. normalized = true;
  11548. });
  11549. }
  11550. return normalized ? Optional.some(CaretPosition(container, offset)) : Optional.none();
  11551. };
  11552. var normalize$2 = function (dom, rng) {
  11553. var collapsed = rng.collapsed, normRng = rng.cloneRange();
  11554. var startPos = CaretPosition.fromRangeStart(rng);
  11555. normalizeEndPoint(dom, collapsed, true, normRng).each(function (pos) {
  11556. if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
  11557. normRng.setStart(pos.container(), pos.offset());
  11558. }
  11559. });
  11560. if (!collapsed) {
  11561. normalizeEndPoint(dom, collapsed, false, normRng).each(function (pos) {
  11562. normRng.setEnd(pos.container(), pos.offset());
  11563. });
  11564. }
  11565. if (collapsed) {
  11566. normRng.collapse(true);
  11567. }
  11568. return isEq$4(rng, normRng) ? Optional.none() : Optional.some(normRng);
  11569. };
  11570. var splitText = function (node, offset) {
  11571. return node.splitText(offset);
  11572. };
  11573. var split = function (rng) {
  11574. var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  11575. if (startContainer === endContainer && isText$7(startContainer)) {
  11576. if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  11577. endContainer = splitText(startContainer, startOffset);
  11578. startContainer = endContainer.previousSibling;
  11579. if (endOffset > startOffset) {
  11580. endOffset = endOffset - startOffset;
  11581. startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
  11582. endOffset = endContainer.nodeValue.length;
  11583. startOffset = 0;
  11584. } else {
  11585. endOffset = 0;
  11586. }
  11587. }
  11588. } else {
  11589. if (isText$7(startContainer) && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  11590. startContainer = splitText(startContainer, startOffset);
  11591. startOffset = 0;
  11592. }
  11593. if (isText$7(endContainer) && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
  11594. endContainer = splitText(endContainer, endOffset).previousSibling;
  11595. endOffset = endContainer.nodeValue.length;
  11596. }
  11597. }
  11598. return {
  11599. startContainer: startContainer,
  11600. startOffset: startOffset,
  11601. endContainer: endContainer,
  11602. endOffset: endOffset
  11603. };
  11604. };
  11605. var RangeUtils = function (dom) {
  11606. var walk = function (rng, callback) {
  11607. return walk$2(dom, rng, callback);
  11608. };
  11609. var split$1 = split;
  11610. var normalize = function (rng) {
  11611. return normalize$2(dom, rng).fold(never, function (normalizedRng) {
  11612. rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
  11613. rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
  11614. return true;
  11615. });
  11616. };
  11617. return {
  11618. walk: walk,
  11619. split: split$1,
  11620. normalize: normalize
  11621. };
  11622. };
  11623. RangeUtils.compareRanges = isEq$4;
  11624. RangeUtils.getCaretRangeFromPoint = fromPoint;
  11625. RangeUtils.getSelectedNode = getSelectedNode;
  11626. RangeUtils.getNode = getNode$1;
  11627. var Dimension = function (name, getOffset) {
  11628. var set = function (element, h) {
  11629. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  11630. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  11631. }
  11632. var dom = element.dom;
  11633. if (isSupported(dom)) {
  11634. dom.style[name] = h + 'px';
  11635. }
  11636. };
  11637. var get = function (element) {
  11638. var r = getOffset(element);
  11639. if (r <= 0 || r === null) {
  11640. var css = get$5(element, name);
  11641. return parseFloat(css) || 0;
  11642. }
  11643. return r;
  11644. };
  11645. var getOuter = get;
  11646. var aggregate = function (element, properties) {
  11647. return foldl(properties, function (acc, property) {
  11648. var val = get$5(element, property);
  11649. var value = val === undefined ? 0 : parseInt(val, 10);
  11650. return isNaN(value) ? acc : acc + value;
  11651. }, 0);
  11652. };
  11653. var max = function (element, value, properties) {
  11654. var cumulativeInclusions = aggregate(element, properties);
  11655. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  11656. return absoluteMax;
  11657. };
  11658. return {
  11659. set: set,
  11660. get: get,
  11661. getOuter: getOuter,
  11662. aggregate: aggregate,
  11663. max: max
  11664. };
  11665. };
  11666. var api = Dimension('height', function (element) {
  11667. var dom = element.dom;
  11668. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  11669. });
  11670. var get$1 = function (element) {
  11671. return api.get(element);
  11672. };
  11673. var walkUp = function (navigation, doc) {
  11674. var frame = navigation.view(doc);
  11675. return frame.fold(constant([]), function (f) {
  11676. var parent = navigation.owner(f);
  11677. var rest = walkUp(navigation, parent);
  11678. return [f].concat(rest);
  11679. });
  11680. };
  11681. var pathTo = function (element, navigation) {
  11682. var d = navigation.owner(element);
  11683. return walkUp(navigation, d);
  11684. };
  11685. var view = function (doc) {
  11686. var _a;
  11687. var element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  11688. return element.map(SugarElement.fromDom);
  11689. };
  11690. var owner = function (element) {
  11691. return documentOrOwner(element);
  11692. };
  11693. var Navigation = /*#__PURE__*/Object.freeze({
  11694. __proto__: null,
  11695. view: view,
  11696. owner: owner
  11697. });
  11698. var find$1 = function (element) {
  11699. var doc = SugarElement.fromDom(document);
  11700. var scroll = get$8(doc);
  11701. var frames = pathTo(element, Navigation);
  11702. var offset = viewport(element);
  11703. var r = foldr(frames, function (b, a) {
  11704. var loc = viewport(a);
  11705. return {
  11706. left: b.left + loc.left,
  11707. top: b.top + loc.top
  11708. };
  11709. }, {
  11710. left: 0,
  11711. top: 0
  11712. });
  11713. return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  11714. };
  11715. var excludeFromDescend = function (element) {
  11716. return name(element) === 'textarea';
  11717. };
  11718. var fireScrollIntoViewEvent = function (editor, data) {
  11719. var scrollEvent = editor.fire('ScrollIntoView', data);
  11720. return scrollEvent.isDefaultPrevented();
  11721. };
  11722. var fireAfterScrollIntoViewEvent = function (editor, data) {
  11723. editor.fire('AfterScrollIntoView', data);
  11724. };
  11725. var descend = function (element, offset) {
  11726. var children$1 = children(element);
  11727. if (children$1.length === 0 || excludeFromDescend(element)) {
  11728. return {
  11729. element: element,
  11730. offset: offset
  11731. };
  11732. } else if (offset < children$1.length && !excludeFromDescend(children$1[offset])) {
  11733. return {
  11734. element: children$1[offset],
  11735. offset: 0
  11736. };
  11737. } else {
  11738. var last = children$1[children$1.length - 1];
  11739. if (excludeFromDescend(last)) {
  11740. return {
  11741. element: element,
  11742. offset: offset
  11743. };
  11744. } else {
  11745. if (name(last) === 'img') {
  11746. return {
  11747. element: last,
  11748. offset: 1
  11749. };
  11750. } else if (isText$8(last)) {
  11751. return {
  11752. element: last,
  11753. offset: get$2(last).length
  11754. };
  11755. } else {
  11756. return {
  11757. element: last,
  11758. offset: children(last).length
  11759. };
  11760. }
  11761. }
  11762. }
  11763. };
  11764. var markerInfo = function (element, cleanupFun) {
  11765. var pos = absolute(element);
  11766. var height = get$1(element);
  11767. return {
  11768. element: element,
  11769. bottom: pos.top + height,
  11770. height: height,
  11771. pos: pos,
  11772. cleanup: cleanupFun
  11773. };
  11774. };
  11775. var createMarker = function (element, offset) {
  11776. var startPoint = descend(element, offset);
  11777. var span = SugarElement.fromHtml('<span data-mce-bogus="all" style="display: inline-block;">' + ZWSP$1 + '</span>');
  11778. before$4(startPoint.element, span);
  11779. return markerInfo(span, function () {
  11780. return remove$7(span);
  11781. });
  11782. };
  11783. var elementMarker = function (element) {
  11784. return markerInfo(SugarElement.fromDom(element), noop);
  11785. };
  11786. var withMarker = function (editor, f, rng, alignToTop) {
  11787. preserveWith(editor, function (_s, _e) {
  11788. return applyWithMarker(editor, f, rng, alignToTop);
  11789. }, rng);
  11790. };
  11791. var withScrollEvents = function (editor, doc, f, marker, alignToTop) {
  11792. var data = {
  11793. elm: marker.element.dom,
  11794. alignToTop: alignToTop
  11795. };
  11796. if (fireScrollIntoViewEvent(editor, data)) {
  11797. return;
  11798. }
  11799. var scrollTop = get$8(doc).top;
  11800. f(doc, scrollTop, marker, alignToTop);
  11801. fireAfterScrollIntoViewEvent(editor, data);
  11802. };
  11803. var applyWithMarker = function (editor, f, rng, alignToTop) {
  11804. var body = SugarElement.fromDom(editor.getBody());
  11805. var doc = SugarElement.fromDom(editor.getDoc());
  11806. reflow(body);
  11807. var marker = createMarker(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  11808. withScrollEvents(editor, doc, f, marker, alignToTop);
  11809. marker.cleanup();
  11810. };
  11811. var withElement = function (editor, element, f, alignToTop) {
  11812. var doc = SugarElement.fromDom(editor.getDoc());
  11813. withScrollEvents(editor, doc, f, elementMarker(element), alignToTop);
  11814. };
  11815. var preserveWith = function (editor, f, rng) {
  11816. var startElement = rng.startContainer;
  11817. var startOffset = rng.startOffset;
  11818. var endElement = rng.endContainer;
  11819. var endOffset = rng.endOffset;
  11820. f(SugarElement.fromDom(startElement), SugarElement.fromDom(endElement));
  11821. var newRng = editor.dom.createRng();
  11822. newRng.setStart(startElement, startOffset);
  11823. newRng.setEnd(endElement, endOffset);
  11824. editor.selection.setRng(rng);
  11825. };
  11826. var scrollToMarker = function (marker, viewHeight, alignToTop, doc) {
  11827. var pos = marker.pos;
  11828. if (alignToTop) {
  11829. to(pos.left, pos.top, doc);
  11830. } else {
  11831. var y = pos.top - viewHeight + marker.height;
  11832. to(pos.left, y, doc);
  11833. }
  11834. };
  11835. var intoWindowIfNeeded = function (doc, scrollTop, viewHeight, marker, alignToTop) {
  11836. var viewportBottom = viewHeight + scrollTop;
  11837. var markerTop = marker.pos.top;
  11838. var markerBottom = marker.bottom;
  11839. var largerThanViewport = markerBottom - markerTop >= viewHeight;
  11840. if (markerTop < scrollTop) {
  11841. scrollToMarker(marker, viewHeight, alignToTop !== false, doc);
  11842. } else if (markerTop > viewportBottom) {
  11843. var align = largerThanViewport ? alignToTop !== false : alignToTop === true;
  11844. scrollToMarker(marker, viewHeight, align, doc);
  11845. } else if (markerBottom > viewportBottom && !largerThanViewport) {
  11846. scrollToMarker(marker, viewHeight, alignToTop === true, doc);
  11847. }
  11848. };
  11849. var intoWindow = function (doc, scrollTop, marker, alignToTop) {
  11850. var viewHeight = doc.dom.defaultView.innerHeight;
  11851. intoWindowIfNeeded(doc, scrollTop, viewHeight, marker, alignToTop);
  11852. };
  11853. var intoFrame = function (doc, scrollTop, marker, alignToTop) {
  11854. var frameViewHeight = doc.dom.defaultView.innerHeight;
  11855. intoWindowIfNeeded(doc, scrollTop, frameViewHeight, marker, alignToTop);
  11856. var op = find$1(marker.element);
  11857. var viewportBounds = getBounds(window);
  11858. if (op.top < viewportBounds.y) {
  11859. intoView(marker.element, alignToTop !== false);
  11860. } else if (op.top > viewportBounds.bottom) {
  11861. intoView(marker.element, alignToTop === true);
  11862. }
  11863. };
  11864. var rangeIntoWindow = function (editor, rng, alignToTop) {
  11865. return withMarker(editor, intoWindow, rng, alignToTop);
  11866. };
  11867. var elementIntoWindow = function (editor, element, alignToTop) {
  11868. return withElement(editor, element, intoWindow, alignToTop);
  11869. };
  11870. var rangeIntoFrame = function (editor, rng, alignToTop) {
  11871. return withMarker(editor, intoFrame, rng, alignToTop);
  11872. };
  11873. var elementIntoFrame = function (editor, element, alignToTop) {
  11874. return withElement(editor, element, intoFrame, alignToTop);
  11875. };
  11876. var scrollElementIntoView = function (editor, element, alignToTop) {
  11877. var scroller = editor.inline ? elementIntoWindow : elementIntoFrame;
  11878. scroller(editor, element, alignToTop);
  11879. };
  11880. var scrollRangeIntoView = function (editor, rng, alignToTop) {
  11881. var scroller = editor.inline ? rangeIntoWindow : rangeIntoFrame;
  11882. scroller(editor, rng, alignToTop);
  11883. };
  11884. var getDocument = function () {
  11885. return SugarElement.fromDom(document);
  11886. };
  11887. var focus$1 = function (element) {
  11888. return element.dom.focus();
  11889. };
  11890. var hasFocus$1 = function (element) {
  11891. var root = getRootNode(element).dom;
  11892. return element.dom === root.activeElement;
  11893. };
  11894. var active = function (root) {
  11895. if (root === void 0) {
  11896. root = getDocument();
  11897. }
  11898. return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  11899. };
  11900. var search = function (element) {
  11901. return active(getRootNode(element)).filter(function (e) {
  11902. return element.dom.contains(e.dom);
  11903. });
  11904. };
  11905. var create$5 = function (start, soffset, finish, foffset) {
  11906. return {
  11907. start: start,
  11908. soffset: soffset,
  11909. finish: finish,
  11910. foffset: foffset
  11911. };
  11912. };
  11913. var SimRange = { create: create$5 };
  11914. var adt$1 = Adt.generate([
  11915. { before: ['element'] },
  11916. {
  11917. on: [
  11918. 'element',
  11919. 'offset'
  11920. ]
  11921. },
  11922. { after: ['element'] }
  11923. ]);
  11924. var cata = function (subject, onBefore, onOn, onAfter) {
  11925. return subject.fold(onBefore, onOn, onAfter);
  11926. };
  11927. var getStart$2 = function (situ) {
  11928. return situ.fold(identity, identity, identity);
  11929. };
  11930. var before$1 = adt$1.before;
  11931. var on = adt$1.on;
  11932. var after$1 = adt$1.after;
  11933. var Situ = {
  11934. before: before$1,
  11935. on: on,
  11936. after: after$1,
  11937. cata: cata,
  11938. getStart: getStart$2
  11939. };
  11940. var adt = Adt.generate([
  11941. { domRange: ['rng'] },
  11942. {
  11943. relative: [
  11944. 'startSitu',
  11945. 'finishSitu'
  11946. ]
  11947. },
  11948. {
  11949. exact: [
  11950. 'start',
  11951. 'soffset',
  11952. 'finish',
  11953. 'foffset'
  11954. ]
  11955. }
  11956. ]);
  11957. var exactFromRange = function (simRange) {
  11958. return adt.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  11959. };
  11960. var getStart$1 = function (selection) {
  11961. return selection.match({
  11962. domRange: function (rng) {
  11963. return SugarElement.fromDom(rng.startContainer);
  11964. },
  11965. relative: function (startSitu, _finishSitu) {
  11966. return Situ.getStart(startSitu);
  11967. },
  11968. exact: function (start, _soffset, _finish, _foffset) {
  11969. return start;
  11970. }
  11971. });
  11972. };
  11973. var domRange = adt.domRange;
  11974. var relative = adt.relative;
  11975. var exact = adt.exact;
  11976. var getWin = function (selection) {
  11977. var start = getStart$1(selection);
  11978. return defaultView(start);
  11979. };
  11980. var range = SimRange.create;
  11981. var SimSelection = {
  11982. domRange: domRange,
  11983. relative: relative,
  11984. exact: exact,
  11985. exactFromRange: exactFromRange,
  11986. getWin: getWin,
  11987. range: range
  11988. };
  11989. var browser$1 = detect().browser;
  11990. var clamp$1 = function (offset, element) {
  11991. var max = isText$8(element) ? get$2(element).length : children(element).length + 1;
  11992. if (offset > max) {
  11993. return max;
  11994. } else if (offset < 0) {
  11995. return 0;
  11996. }
  11997. return offset;
  11998. };
  11999. var normalizeRng = function (rng) {
  12000. return SimSelection.range(rng.start, clamp$1(rng.soffset, rng.start), rng.finish, clamp$1(rng.foffset, rng.finish));
  12001. };
  12002. var isOrContains = function (root, elm) {
  12003. return !isRestrictedNode(elm.dom) && (contains$1(root, elm) || eq(root, elm));
  12004. };
  12005. var isRngInRoot = function (root) {
  12006. return function (rng) {
  12007. return isOrContains(root, rng.start) && isOrContains(root, rng.finish);
  12008. };
  12009. };
  12010. var shouldStore = function (editor) {
  12011. return editor.inline === true || browser$1.isIE();
  12012. };
  12013. var nativeRangeToSelectionRange = function (r) {
  12014. return SimSelection.range(SugarElement.fromDom(r.startContainer), r.startOffset, SugarElement.fromDom(r.endContainer), r.endOffset);
  12015. };
  12016. var readRange = function (win) {
  12017. var selection = win.getSelection();
  12018. var rng = !selection || selection.rangeCount === 0 ? Optional.none() : Optional.from(selection.getRangeAt(0));
  12019. return rng.map(nativeRangeToSelectionRange);
  12020. };
  12021. var getBookmark = function (root) {
  12022. var win = defaultView(root);
  12023. return readRange(win.dom).filter(isRngInRoot(root));
  12024. };
  12025. var validate = function (root, bookmark) {
  12026. return Optional.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
  12027. };
  12028. var bookmarkToNativeRng = function (bookmark) {
  12029. var rng = document.createRange();
  12030. try {
  12031. rng.setStart(bookmark.start.dom, bookmark.soffset);
  12032. rng.setEnd(bookmark.finish.dom, bookmark.foffset);
  12033. return Optional.some(rng);
  12034. } catch (_) {
  12035. return Optional.none();
  12036. }
  12037. };
  12038. var store = function (editor) {
  12039. var newBookmark = shouldStore(editor) ? getBookmark(SugarElement.fromDom(editor.getBody())) : Optional.none();
  12040. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12041. };
  12042. var storeNative = function (editor, rng) {
  12043. var root = SugarElement.fromDom(editor.getBody());
  12044. var range = shouldStore(editor) ? Optional.from(rng) : Optional.none();
  12045. var newBookmark = range.map(nativeRangeToSelectionRange).filter(isRngInRoot(root));
  12046. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12047. };
  12048. var getRng = function (editor) {
  12049. var bookmark = editor.bookmark ? editor.bookmark : Optional.none();
  12050. return bookmark.bind(function (x) {
  12051. return validate(SugarElement.fromDom(editor.getBody()), x);
  12052. }).bind(bookmarkToNativeRng);
  12053. };
  12054. var restore = function (editor) {
  12055. getRng(editor).each(function (rng) {
  12056. return editor.selection.setRng(rng);
  12057. });
  12058. };
  12059. var isEditorUIElement$1 = function (elm) {
  12060. var className = elm.className.toString();
  12061. return className.indexOf('tox-') !== -1 || className.indexOf('mce-') !== -1;
  12062. };
  12063. var FocusManager = { isEditorUIElement: isEditorUIElement$1 };
  12064. var isManualNodeChange = function (e) {
  12065. return e.type === 'nodechange' && e.selectionChange;
  12066. };
  12067. var registerPageMouseUp = function (editor, throttledStore) {
  12068. var mouseUpPage = function () {
  12069. throttledStore.throttle();
  12070. };
  12071. DOMUtils.DOM.bind(document, 'mouseup', mouseUpPage);
  12072. editor.on('remove', function () {
  12073. DOMUtils.DOM.unbind(document, 'mouseup', mouseUpPage);
  12074. });
  12075. };
  12076. var registerFocusOut = function (editor) {
  12077. editor.on('focusout', function () {
  12078. store(editor);
  12079. });
  12080. };
  12081. var registerMouseUp = function (editor, throttledStore) {
  12082. editor.on('mouseup touchend', function (_e) {
  12083. throttledStore.throttle();
  12084. });
  12085. };
  12086. var registerEditorEvents = function (editor, throttledStore) {
  12087. var browser = detect().browser;
  12088. if (browser.isIE()) {
  12089. registerFocusOut(editor);
  12090. } else {
  12091. registerMouseUp(editor, throttledStore);
  12092. }
  12093. editor.on('keyup NodeChange', function (e) {
  12094. if (!isManualNodeChange(e)) {
  12095. store(editor);
  12096. }
  12097. });
  12098. };
  12099. var register$3 = function (editor) {
  12100. var throttledStore = first(function () {
  12101. store(editor);
  12102. }, 0);
  12103. editor.on('init', function () {
  12104. if (editor.inline) {
  12105. registerPageMouseUp(editor, throttledStore);
  12106. }
  12107. registerEditorEvents(editor, throttledStore);
  12108. });
  12109. editor.on('remove', function () {
  12110. throttledStore.cancel();
  12111. });
  12112. };
  12113. var documentFocusInHandler;
  12114. var DOM$8 = DOMUtils.DOM;
  12115. var isEditorUIElement = function (elm) {
  12116. return FocusManager.isEditorUIElement(elm);
  12117. };
  12118. var isEditorContentAreaElement = function (elm) {
  12119. var classList = elm.classList;
  12120. if (classList !== undefined) {
  12121. return classList.contains('tox-edit-area') || classList.contains('tox-edit-area__iframe') || classList.contains('mce-content-body');
  12122. } else {
  12123. return false;
  12124. }
  12125. };
  12126. var isUIElement = function (editor, elm) {
  12127. var customSelector = getCustomUiSelector(editor);
  12128. var parent = DOM$8.getParent(elm, function (elm) {
  12129. return isEditorUIElement(elm) || (customSelector ? editor.dom.is(elm, customSelector) : false);
  12130. });
  12131. return parent !== null;
  12132. };
  12133. var getActiveElement = function (editor) {
  12134. try {
  12135. var root = getRootNode(SugarElement.fromDom(editor.getElement()));
  12136. return active(root).fold(function () {
  12137. return document.body;
  12138. }, function (x) {
  12139. return x.dom;
  12140. });
  12141. } catch (ex) {
  12142. return document.body;
  12143. }
  12144. };
  12145. var registerEvents$1 = function (editorManager, e) {
  12146. var editor = e.editor;
  12147. register$3(editor);
  12148. editor.on('focusin', function () {
  12149. var focusedEditor = editorManager.focusedEditor;
  12150. if (focusedEditor !== editor) {
  12151. if (focusedEditor) {
  12152. focusedEditor.fire('blur', { focusedEditor: editor });
  12153. }
  12154. editorManager.setActive(editor);
  12155. editorManager.focusedEditor = editor;
  12156. editor.fire('focus', { blurredEditor: focusedEditor });
  12157. editor.focus(true);
  12158. }
  12159. });
  12160. editor.on('focusout', function () {
  12161. Delay.setEditorTimeout(editor, function () {
  12162. var focusedEditor = editorManager.focusedEditor;
  12163. if (!isUIElement(editor, getActiveElement(editor)) && focusedEditor === editor) {
  12164. editor.fire('blur', { focusedEditor: null });
  12165. editorManager.focusedEditor = null;
  12166. }
  12167. });
  12168. });
  12169. if (!documentFocusInHandler) {
  12170. documentFocusInHandler = function (e) {
  12171. var activeEditor = editorManager.activeEditor;
  12172. if (activeEditor) {
  12173. getOriginalEventTarget(e).each(function (target) {
  12174. if (target.ownerDocument === document) {
  12175. if (target !== document.body && !isUIElement(activeEditor, target) && editorManager.focusedEditor === activeEditor) {
  12176. activeEditor.fire('blur', { focusedEditor: null });
  12177. editorManager.focusedEditor = null;
  12178. }
  12179. }
  12180. });
  12181. }
  12182. };
  12183. DOM$8.bind(document, 'focusin', documentFocusInHandler);
  12184. }
  12185. };
  12186. var unregisterDocumentEvents = function (editorManager, e) {
  12187. if (editorManager.focusedEditor === e.editor) {
  12188. editorManager.focusedEditor = null;
  12189. }
  12190. if (!editorManager.activeEditor) {
  12191. DOM$8.unbind(document, 'focusin', documentFocusInHandler);
  12192. documentFocusInHandler = null;
  12193. }
  12194. };
  12195. var setup$l = function (editorManager) {
  12196. editorManager.on('AddEditor', curry(registerEvents$1, editorManager));
  12197. editorManager.on('RemoveEditor', curry(unregisterDocumentEvents, editorManager));
  12198. };
  12199. var getContentEditableHost = function (editor, node) {
  12200. return editor.dom.getParent(node, function (node) {
  12201. return editor.dom.getContentEditable(node) === 'true';
  12202. });
  12203. };
  12204. var getCollapsedNode = function (rng) {
  12205. return rng.collapsed ? Optional.from(getNode$1(rng.startContainer, rng.startOffset)).map(SugarElement.fromDom) : Optional.none();
  12206. };
  12207. var getFocusInElement = function (root, rng) {
  12208. return getCollapsedNode(rng).bind(function (node) {
  12209. if (isTableSection(node)) {
  12210. return Optional.some(node);
  12211. } else if (contains$1(root, node) === false) {
  12212. return Optional.some(root);
  12213. } else {
  12214. return Optional.none();
  12215. }
  12216. });
  12217. };
  12218. var normalizeSelection$1 = function (editor, rng) {
  12219. getFocusInElement(SugarElement.fromDom(editor.getBody()), rng).bind(function (elm) {
  12220. return firstPositionIn(elm.dom);
  12221. }).fold(function () {
  12222. editor.selection.normalize();
  12223. return;
  12224. }, function (caretPos) {
  12225. return editor.selection.setRng(caretPos.toRange());
  12226. });
  12227. };
  12228. var focusBody = function (body) {
  12229. if (body.setActive) {
  12230. try {
  12231. body.setActive();
  12232. } catch (ex) {
  12233. body.focus();
  12234. }
  12235. } else {
  12236. body.focus();
  12237. }
  12238. };
  12239. var hasElementFocus = function (elm) {
  12240. return hasFocus$1(elm) || search(elm).isSome();
  12241. };
  12242. var hasIframeFocus = function (editor) {
  12243. return editor.iframeElement && hasFocus$1(SugarElement.fromDom(editor.iframeElement));
  12244. };
  12245. var hasInlineFocus = function (editor) {
  12246. var rawBody = editor.getBody();
  12247. return rawBody && hasElementFocus(SugarElement.fromDom(rawBody));
  12248. };
  12249. var hasUiFocus = function (editor) {
  12250. var dos = getRootNode(SugarElement.fromDom(editor.getElement()));
  12251. return active(dos).filter(function (elem) {
  12252. return !isEditorContentAreaElement(elem.dom) && isUIElement(editor, elem.dom);
  12253. }).isSome();
  12254. };
  12255. var hasFocus = function (editor) {
  12256. return editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
  12257. };
  12258. var hasEditorOrUiFocus = function (editor) {
  12259. return hasFocus(editor) || hasUiFocus(editor);
  12260. };
  12261. var focusEditor = function (editor) {
  12262. var selection = editor.selection;
  12263. var body = editor.getBody();
  12264. var rng = selection.getRng();
  12265. editor.quirks.refreshContentEditable();
  12266. if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  12267. getRng(editor).each(function (bookmarkRng) {
  12268. editor.selection.setRng(bookmarkRng);
  12269. rng = bookmarkRng;
  12270. });
  12271. }
  12272. var contentEditableHost = getContentEditableHost(editor, selection.getNode());
  12273. if (editor.$.contains(body, contentEditableHost)) {
  12274. focusBody(contentEditableHost);
  12275. normalizeSelection$1(editor, rng);
  12276. activateEditor(editor);
  12277. return;
  12278. }
  12279. if (!editor.inline) {
  12280. if (!Env.opera) {
  12281. focusBody(body);
  12282. }
  12283. editor.getWin().focus();
  12284. }
  12285. if (Env.gecko || editor.inline) {
  12286. focusBody(body);
  12287. normalizeSelection$1(editor, rng);
  12288. }
  12289. activateEditor(editor);
  12290. };
  12291. var activateEditor = function (editor) {
  12292. return editor.editorManager.setActive(editor);
  12293. };
  12294. var focus = function (editor, skipFocus) {
  12295. if (editor.removed) {
  12296. return;
  12297. }
  12298. if (skipFocus) {
  12299. activateEditor(editor);
  12300. } else {
  12301. focusEditor(editor);
  12302. }
  12303. };
  12304. var getEndpointElement = function (root, rng, start, real, resolve) {
  12305. var container = start ? rng.startContainer : rng.endContainer;
  12306. var offset = start ? rng.startOffset : rng.endOffset;
  12307. return Optional.from(container).map(SugarElement.fromDom).map(function (elm) {
  12308. return !real || !rng.collapsed ? child$1(elm, resolve(elm, offset)).getOr(elm) : elm;
  12309. }).bind(function (elm) {
  12310. return isElement$6(elm) ? Optional.some(elm) : parent(elm).filter(isElement$6);
  12311. }).map(function (elm) {
  12312. return elm.dom;
  12313. }).getOr(root);
  12314. };
  12315. var getStart = function (root, rng, real) {
  12316. return getEndpointElement(root, rng, true, real, function (elm, offset) {
  12317. return Math.min(childNodesCount(elm), offset);
  12318. });
  12319. };
  12320. var getEnd = function (root, rng, real) {
  12321. return getEndpointElement(root, rng, false, real, function (elm, offset) {
  12322. return offset > 0 ? offset - 1 : offset;
  12323. });
  12324. };
  12325. var skipEmptyTextNodes = function (node, forwards) {
  12326. var orig = node;
  12327. while (node && isText$7(node) && node.length === 0) {
  12328. node = forwards ? node.nextSibling : node.previousSibling;
  12329. }
  12330. return node || orig;
  12331. };
  12332. var getNode = function (root, rng) {
  12333. var elm, startContainer, endContainer;
  12334. if (!rng) {
  12335. return root;
  12336. }
  12337. startContainer = rng.startContainer;
  12338. endContainer = rng.endContainer;
  12339. var startOffset = rng.startOffset;
  12340. var endOffset = rng.endOffset;
  12341. elm = rng.commonAncestorContainer;
  12342. if (!rng.collapsed) {
  12343. if (startContainer === endContainer) {
  12344. if (endOffset - startOffset < 2) {
  12345. if (startContainer.hasChildNodes()) {
  12346. elm = startContainer.childNodes[startOffset];
  12347. }
  12348. }
  12349. }
  12350. if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
  12351. if (startContainer.length === startOffset) {
  12352. startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
  12353. } else {
  12354. startContainer = startContainer.parentNode;
  12355. }
  12356. if (endOffset === 0) {
  12357. endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
  12358. } else {
  12359. endContainer = endContainer.parentNode;
  12360. }
  12361. if (startContainer && startContainer === endContainer) {
  12362. return startContainer;
  12363. }
  12364. }
  12365. }
  12366. if (elm && elm.nodeType === 3) {
  12367. return elm.parentNode;
  12368. }
  12369. return elm;
  12370. };
  12371. var getSelectedBlocks = function (dom, rng, startElm, endElm) {
  12372. var node;
  12373. var selectedBlocks = [];
  12374. var root = dom.getRoot();
  12375. startElm = dom.getParent(startElm || getStart(root, rng, rng.collapsed), dom.isBlock);
  12376. endElm = dom.getParent(endElm || getEnd(root, rng, rng.collapsed), dom.isBlock);
  12377. if (startElm && startElm !== root) {
  12378. selectedBlocks.push(startElm);
  12379. }
  12380. if (startElm && endElm && startElm !== endElm) {
  12381. node = startElm;
  12382. var walker = new DomTreeWalker(startElm, root);
  12383. while ((node = walker.next()) && node !== endElm) {
  12384. if (dom.isBlock(node)) {
  12385. selectedBlocks.push(node);
  12386. }
  12387. }
  12388. }
  12389. if (endElm && startElm !== endElm && endElm !== root) {
  12390. selectedBlocks.push(endElm);
  12391. }
  12392. return selectedBlocks;
  12393. };
  12394. var select = function (dom, node, content) {
  12395. return Optional.from(node).map(function (node) {
  12396. var idx = dom.nodeIndex(node);
  12397. var rng = dom.createRng();
  12398. rng.setStart(node.parentNode, idx);
  12399. rng.setEnd(node.parentNode, idx + 1);
  12400. if (content) {
  12401. moveEndPoint(dom, rng, node, true);
  12402. moveEndPoint(dom, rng, node, false);
  12403. }
  12404. return rng;
  12405. });
  12406. };
  12407. var processRanges = function (editor, ranges) {
  12408. return map$3(ranges, function (range) {
  12409. var evt = editor.fire('GetSelectionRange', { range: range });
  12410. return evt.range !== range ? evt.range : range;
  12411. });
  12412. };
  12413. var typeLookup = {
  12414. '#text': 3,
  12415. '#comment': 8,
  12416. '#cdata': 4,
  12417. '#pi': 7,
  12418. '#doctype': 10,
  12419. '#document-fragment': 11
  12420. };
  12421. var walk$1 = function (node, root, prev) {
  12422. var startName = prev ? 'lastChild' : 'firstChild';
  12423. var siblingName = prev ? 'prev' : 'next';
  12424. if (node[startName]) {
  12425. return node[startName];
  12426. }
  12427. if (node !== root) {
  12428. var sibling = node[siblingName];
  12429. if (sibling) {
  12430. return sibling;
  12431. }
  12432. for (var parent_1 = node.parent; parent_1 && parent_1 !== root; parent_1 = parent_1.parent) {
  12433. sibling = parent_1[siblingName];
  12434. if (sibling) {
  12435. return sibling;
  12436. }
  12437. }
  12438. }
  12439. };
  12440. var isEmptyTextNode = function (node) {
  12441. if (!isWhitespaceText(node.value)) {
  12442. return false;
  12443. }
  12444. var parentNode = node.parent;
  12445. if (parentNode && (parentNode.name !== 'span' || parentNode.attr('style')) && /^[ ]+$/.test(node.value)) {
  12446. return false;
  12447. }
  12448. return true;
  12449. };
  12450. var isNonEmptyElement = function (node) {
  12451. var isNamedAnchor = node.name === 'a' && !node.attr('href') && node.attr('id');
  12452. return node.attr('name') || node.attr('id') && !node.firstChild || node.attr('data-mce-bookmark') || isNamedAnchor;
  12453. };
  12454. var AstNode = function () {
  12455. function AstNode(name, type) {
  12456. this.name = name;
  12457. this.type = type;
  12458. if (type === 1) {
  12459. this.attributes = [];
  12460. this.attributes.map = {};
  12461. }
  12462. }
  12463. AstNode.create = function (name, attrs) {
  12464. var node = new AstNode(name, typeLookup[name] || 1);
  12465. if (attrs) {
  12466. each$j(attrs, function (value, attrName) {
  12467. node.attr(attrName, value);
  12468. });
  12469. }
  12470. return node;
  12471. };
  12472. AstNode.prototype.replace = function (node) {
  12473. var self = this;
  12474. if (node.parent) {
  12475. node.remove();
  12476. }
  12477. self.insert(node, self);
  12478. self.remove();
  12479. return self;
  12480. };
  12481. AstNode.prototype.attr = function (name, value) {
  12482. var self = this;
  12483. var attrs;
  12484. if (typeof name !== 'string') {
  12485. if (name !== undefined && name !== null) {
  12486. each$j(name, function (value, key) {
  12487. self.attr(key, value);
  12488. });
  12489. }
  12490. return self;
  12491. }
  12492. if (attrs = self.attributes) {
  12493. if (value !== undefined) {
  12494. if (value === null) {
  12495. if (name in attrs.map) {
  12496. delete attrs.map[name];
  12497. var i = attrs.length;
  12498. while (i--) {
  12499. if (attrs[i].name === name) {
  12500. attrs.splice(i, 1);
  12501. return self;
  12502. }
  12503. }
  12504. }
  12505. return self;
  12506. }
  12507. if (name in attrs.map) {
  12508. var i = attrs.length;
  12509. while (i--) {
  12510. if (attrs[i].name === name) {
  12511. attrs[i].value = value;
  12512. break;
  12513. }
  12514. }
  12515. } else {
  12516. attrs.push({
  12517. name: name,
  12518. value: value
  12519. });
  12520. }
  12521. attrs.map[name] = value;
  12522. return self;
  12523. }
  12524. return attrs.map[name];
  12525. }
  12526. };
  12527. AstNode.prototype.clone = function () {
  12528. var self = this;
  12529. var clone = new AstNode(self.name, self.type);
  12530. var selfAttrs;
  12531. if (selfAttrs = self.attributes) {
  12532. var cloneAttrs = [];
  12533. cloneAttrs.map = {};
  12534. for (var i = 0, l = selfAttrs.length; i < l; i++) {
  12535. var selfAttr = selfAttrs[i];
  12536. if (selfAttr.name !== 'id') {
  12537. cloneAttrs[cloneAttrs.length] = {
  12538. name: selfAttr.name,
  12539. value: selfAttr.value
  12540. };
  12541. cloneAttrs.map[selfAttr.name] = selfAttr.value;
  12542. }
  12543. }
  12544. clone.attributes = cloneAttrs;
  12545. }
  12546. clone.value = self.value;
  12547. clone.shortEnded = self.shortEnded;
  12548. return clone;
  12549. };
  12550. AstNode.prototype.wrap = function (wrapper) {
  12551. var self = this;
  12552. self.parent.insert(wrapper, self);
  12553. wrapper.append(self);
  12554. return self;
  12555. };
  12556. AstNode.prototype.unwrap = function () {
  12557. var self = this;
  12558. for (var node = self.firstChild; node;) {
  12559. var next = node.next;
  12560. self.insert(node, self, true);
  12561. node = next;
  12562. }
  12563. self.remove();
  12564. };
  12565. AstNode.prototype.remove = function () {
  12566. var self = this, parent = self.parent, next = self.next, prev = self.prev;
  12567. if (parent) {
  12568. if (parent.firstChild === self) {
  12569. parent.firstChild = next;
  12570. if (next) {
  12571. next.prev = null;
  12572. }
  12573. } else {
  12574. prev.next = next;
  12575. }
  12576. if (parent.lastChild === self) {
  12577. parent.lastChild = prev;
  12578. if (prev) {
  12579. prev.next = null;
  12580. }
  12581. } else {
  12582. next.prev = prev;
  12583. }
  12584. self.parent = self.next = self.prev = null;
  12585. }
  12586. return self;
  12587. };
  12588. AstNode.prototype.append = function (node) {
  12589. var self = this;
  12590. if (node.parent) {
  12591. node.remove();
  12592. }
  12593. var last = self.lastChild;
  12594. if (last) {
  12595. last.next = node;
  12596. node.prev = last;
  12597. self.lastChild = node;
  12598. } else {
  12599. self.lastChild = self.firstChild = node;
  12600. }
  12601. node.parent = self;
  12602. return node;
  12603. };
  12604. AstNode.prototype.insert = function (node, refNode, before) {
  12605. if (node.parent) {
  12606. node.remove();
  12607. }
  12608. var parent = refNode.parent || this;
  12609. if (before) {
  12610. if (refNode === parent.firstChild) {
  12611. parent.firstChild = node;
  12612. } else {
  12613. refNode.prev.next = node;
  12614. }
  12615. node.prev = refNode.prev;
  12616. node.next = refNode;
  12617. refNode.prev = node;
  12618. } else {
  12619. if (refNode === parent.lastChild) {
  12620. parent.lastChild = node;
  12621. } else {
  12622. refNode.next.prev = node;
  12623. }
  12624. node.next = refNode.next;
  12625. node.prev = refNode;
  12626. refNode.next = node;
  12627. }
  12628. node.parent = parent;
  12629. return node;
  12630. };
  12631. AstNode.prototype.getAll = function (name) {
  12632. var self = this;
  12633. var collection = [];
  12634. for (var node = self.firstChild; node; node = walk$1(node, self)) {
  12635. if (node.name === name) {
  12636. collection.push(node);
  12637. }
  12638. }
  12639. return collection;
  12640. };
  12641. AstNode.prototype.children = function () {
  12642. var self = this;
  12643. var collection = [];
  12644. for (var node = self.firstChild; node; node = node.next) {
  12645. collection.push(node);
  12646. }
  12647. return collection;
  12648. };
  12649. AstNode.prototype.empty = function () {
  12650. var self = this;
  12651. if (self.firstChild) {
  12652. var nodes = [];
  12653. for (var node = self.firstChild; node; node = walk$1(node, self)) {
  12654. nodes.push(node);
  12655. }
  12656. var i = nodes.length;
  12657. while (i--) {
  12658. var node = nodes[i];
  12659. node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
  12660. }
  12661. }
  12662. self.firstChild = self.lastChild = null;
  12663. return self;
  12664. };
  12665. AstNode.prototype.isEmpty = function (elements, whitespace, predicate) {
  12666. if (whitespace === void 0) {
  12667. whitespace = {};
  12668. }
  12669. var self = this;
  12670. var node = self.firstChild;
  12671. if (isNonEmptyElement(self)) {
  12672. return false;
  12673. }
  12674. if (node) {
  12675. do {
  12676. if (node.type === 1) {
  12677. if (node.attr('data-mce-bogus')) {
  12678. continue;
  12679. }
  12680. if (elements[node.name]) {
  12681. return false;
  12682. }
  12683. if (isNonEmptyElement(node)) {
  12684. return false;
  12685. }
  12686. }
  12687. if (node.type === 8) {
  12688. return false;
  12689. }
  12690. if (node.type === 3 && !isEmptyTextNode(node)) {
  12691. return false;
  12692. }
  12693. if (node.type === 3 && node.parent && whitespace[node.parent.name] && isWhitespaceText(node.value)) {
  12694. return false;
  12695. }
  12696. if (predicate && predicate(node)) {
  12697. return false;
  12698. }
  12699. } while (node = walk$1(node, self));
  12700. }
  12701. return true;
  12702. };
  12703. AstNode.prototype.walk = function (prev) {
  12704. return walk$1(this, null, prev);
  12705. };
  12706. return AstNode;
  12707. }();
  12708. var extractBase64DataUris = function (html) {
  12709. var dataImageUri = /data:[^;]+;base64,([a-z0-9\+\/=\s]+)/gi;
  12710. var chunks = [];
  12711. var uris = {};
  12712. var prefix = generate('img');
  12713. var matches;
  12714. var index = 0;
  12715. var count = 0;
  12716. while (matches = dataImageUri.exec(html)) {
  12717. var uri = matches[0];
  12718. var imageId = prefix + '_' + count++;
  12719. uris[imageId] = uri;
  12720. if (index < matches.index) {
  12721. chunks.push(html.substr(index, matches.index - index));
  12722. }
  12723. chunks.push(imageId);
  12724. index = matches.index + uri.length;
  12725. }
  12726. var re = new RegExp(prefix + '_[0-9]+', 'g');
  12727. if (index === 0) {
  12728. return {
  12729. prefix: prefix,
  12730. uris: uris,
  12731. html: html,
  12732. re: re
  12733. };
  12734. } else {
  12735. if (index < html.length) {
  12736. chunks.push(html.substr(index));
  12737. }
  12738. return {
  12739. prefix: prefix,
  12740. uris: uris,
  12741. html: chunks.join(''),
  12742. re: re
  12743. };
  12744. }
  12745. };
  12746. var restoreDataUris = function (html, result) {
  12747. return html.replace(result.re, function (imageId) {
  12748. return get$9(result.uris, imageId).getOr(imageId);
  12749. });
  12750. };
  12751. var parseDataUri$1 = function (uri) {
  12752. var matches = /data:([^;]+);base64,([a-z0-9\+\/=\s]+)/i.exec(uri);
  12753. if (matches) {
  12754. return Optional.some({
  12755. type: matches[1],
  12756. data: decodeURIComponent(matches[2])
  12757. });
  12758. } else {
  12759. return Optional.none();
  12760. }
  12761. };
  12762. var each$d = Tools.each, trim = Tools.trim;
  12763. var queryParts = 'source protocol authority userInfo user password host port relative path directory file query anchor'.split(' ');
  12764. var DEFAULT_PORTS = {
  12765. ftp: 21,
  12766. http: 80,
  12767. https: 443,
  12768. mailto: 25
  12769. };
  12770. var safeSvgDataUrlElements = [
  12771. 'img',
  12772. 'video'
  12773. ];
  12774. var blockSvgDataUris = function (allowSvgDataUrls, tagName) {
  12775. if (isNonNullable(allowSvgDataUrls)) {
  12776. return !allowSvgDataUrls;
  12777. } else {
  12778. return isNonNullable(tagName) ? !contains$3(safeSvgDataUrlElements, tagName) : true;
  12779. }
  12780. };
  12781. var isInvalidUri = function (settings, uri, tagName) {
  12782. if (settings.allow_html_data_urls) {
  12783. return false;
  12784. } else if (/^data:image\//i.test(uri)) {
  12785. return blockSvgDataUris(settings.allow_svg_data_urls, tagName) && /^data:image\/svg\+xml/i.test(uri);
  12786. } else {
  12787. return /^data:/i.test(uri);
  12788. }
  12789. };
  12790. var URI = function () {
  12791. function URI(url, settings) {
  12792. url = trim(url);
  12793. this.settings = settings || {};
  12794. var baseUri = this.settings.base_uri;
  12795. var self = this;
  12796. if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
  12797. self.source = url;
  12798. return;
  12799. }
  12800. var isProtocolRelative = url.indexOf('//') === 0;
  12801. if (url.indexOf('/') === 0 && !isProtocolRelative) {
  12802. url = (baseUri ? baseUri.protocol || 'http' : 'http') + '://mce_host' + url;
  12803. }
  12804. if (!/^[\w\-]*:?\/\//.test(url)) {
  12805. var baseUrl = this.settings.base_uri ? this.settings.base_uri.path : new URI(document.location.href).directory;
  12806. if (this.settings.base_uri && this.settings.base_uri.protocol == '') {
  12807. url = '//mce_host' + self.toAbsPath(baseUrl, url);
  12808. } else {
  12809. var match = /([^#?]*)([#?]?.*)/.exec(url);
  12810. url = (baseUri && baseUri.protocol || 'http') + '://mce_host' + self.toAbsPath(baseUrl, match[1]) + match[2];
  12811. }
  12812. }
  12813. url = url.replace(/@@/g, '(mce_at)');
  12814. var urlMatch = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?(\[[a-zA-Z0-9:.%]+\]|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
  12815. each$d(queryParts, function (v, i) {
  12816. var part = urlMatch[i];
  12817. if (part) {
  12818. part = part.replace(/\(mce_at\)/g, '@@');
  12819. }
  12820. self[v] = part;
  12821. });
  12822. if (baseUri) {
  12823. if (!self.protocol) {
  12824. self.protocol = baseUri.protocol;
  12825. }
  12826. if (!self.userInfo) {
  12827. self.userInfo = baseUri.userInfo;
  12828. }
  12829. if (!self.port && self.host === 'mce_host') {
  12830. self.port = baseUri.port;
  12831. }
  12832. if (!self.host || self.host === 'mce_host') {
  12833. self.host = baseUri.host;
  12834. }
  12835. self.source = '';
  12836. }
  12837. if (isProtocolRelative) {
  12838. self.protocol = '';
  12839. }
  12840. }
  12841. URI.parseDataUri = function (uri) {
  12842. var type;
  12843. var uriComponents = decodeURIComponent(uri).split(',');
  12844. var matches = /data:([^;]+)/.exec(uriComponents[0]);
  12845. if (matches) {
  12846. type = matches[1];
  12847. }
  12848. return {
  12849. type: type,
  12850. data: uriComponents[1]
  12851. };
  12852. };
  12853. URI.isDomSafe = function (uri, context, options) {
  12854. if (options === void 0) {
  12855. options = {};
  12856. }
  12857. if (options.allow_script_urls) {
  12858. return true;
  12859. } else {
  12860. var decodedUri = Entities.decode(uri).replace(/[\s\u0000-\u001F]+/g, '');
  12861. try {
  12862. decodedUri = decodeURIComponent(decodedUri);
  12863. } catch (ex) {
  12864. decodedUri = unescape(decodedUri);
  12865. }
  12866. if (/((java|vb)script|mhtml):/i.test(decodedUri)) {
  12867. return false;
  12868. }
  12869. return !isInvalidUri(options, decodedUri, context);
  12870. }
  12871. };
  12872. URI.getDocumentBaseUrl = function (loc) {
  12873. var baseUrl;
  12874. if (loc.protocol.indexOf('http') !== 0 && loc.protocol !== 'file:') {
  12875. baseUrl = loc.href;
  12876. } else {
  12877. baseUrl = loc.protocol + '//' + loc.host + loc.pathname;
  12878. }
  12879. if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
  12880. baseUrl = baseUrl.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  12881. if (!/[\/\\]$/.test(baseUrl)) {
  12882. baseUrl += '/';
  12883. }
  12884. }
  12885. return baseUrl;
  12886. };
  12887. URI.prototype.setPath = function (path) {
  12888. var pathMatch = /^(.*?)\/?(\w+)?$/.exec(path);
  12889. this.path = pathMatch[0];
  12890. this.directory = pathMatch[1];
  12891. this.file = pathMatch[2];
  12892. this.source = '';
  12893. this.getURI();
  12894. };
  12895. URI.prototype.toRelative = function (uri) {
  12896. var output;
  12897. if (uri === './') {
  12898. return uri;
  12899. }
  12900. var relativeUri = new URI(uri, { base_uri: this });
  12901. if (relativeUri.host !== 'mce_host' && this.host !== relativeUri.host && relativeUri.host || this.port !== relativeUri.port || this.protocol !== relativeUri.protocol && relativeUri.protocol !== '') {
  12902. return relativeUri.getURI();
  12903. }
  12904. var tu = this.getURI(), uu = relativeUri.getURI();
  12905. if (tu === uu || tu.charAt(tu.length - 1) === '/' && tu.substr(0, tu.length - 1) === uu) {
  12906. return tu;
  12907. }
  12908. output = this.toRelPath(this.path, relativeUri.path);
  12909. if (relativeUri.query) {
  12910. output += '?' + relativeUri.query;
  12911. }
  12912. if (relativeUri.anchor) {
  12913. output += '#' + relativeUri.anchor;
  12914. }
  12915. return output;
  12916. };
  12917. URI.prototype.toAbsolute = function (uri, noHost) {
  12918. var absoluteUri = new URI(uri, { base_uri: this });
  12919. return absoluteUri.getURI(noHost && this.isSameOrigin(absoluteUri));
  12920. };
  12921. URI.prototype.isSameOrigin = function (uri) {
  12922. if (this.host == uri.host && this.protocol == uri.protocol) {
  12923. if (this.port == uri.port) {
  12924. return true;
  12925. }
  12926. var defaultPort = DEFAULT_PORTS[this.protocol];
  12927. if (defaultPort && (this.port || defaultPort) == (uri.port || defaultPort)) {
  12928. return true;
  12929. }
  12930. }
  12931. return false;
  12932. };
  12933. URI.prototype.toRelPath = function (base, path) {
  12934. var breakPoint = 0, out = '', i, l;
  12935. var normalizedBase = base.substring(0, base.lastIndexOf('/')).split('/');
  12936. var items = path.split('/');
  12937. if (normalizedBase.length >= items.length) {
  12938. for (i = 0, l = normalizedBase.length; i < l; i++) {
  12939. if (i >= items.length || normalizedBase[i] !== items[i]) {
  12940. breakPoint = i + 1;
  12941. break;
  12942. }
  12943. }
  12944. }
  12945. if (normalizedBase.length < items.length) {
  12946. for (i = 0, l = items.length; i < l; i++) {
  12947. if (i >= normalizedBase.length || normalizedBase[i] !== items[i]) {
  12948. breakPoint = i + 1;
  12949. break;
  12950. }
  12951. }
  12952. }
  12953. if (breakPoint === 1) {
  12954. return path;
  12955. }
  12956. for (i = 0, l = normalizedBase.length - (breakPoint - 1); i < l; i++) {
  12957. out += '../';
  12958. }
  12959. for (i = breakPoint - 1, l = items.length; i < l; i++) {
  12960. if (i !== breakPoint - 1) {
  12961. out += '/' + items[i];
  12962. } else {
  12963. out += items[i];
  12964. }
  12965. }
  12966. return out;
  12967. };
  12968. URI.prototype.toAbsPath = function (base, path) {
  12969. var i, nb = 0, o = [], outPath;
  12970. var tr = /\/$/.test(path) ? '/' : '';
  12971. var normalizedBase = base.split('/');
  12972. var normalizedPath = path.split('/');
  12973. each$d(normalizedBase, function (k) {
  12974. if (k) {
  12975. o.push(k);
  12976. }
  12977. });
  12978. normalizedBase = o;
  12979. for (i = normalizedPath.length - 1, o = []; i >= 0; i--) {
  12980. if (normalizedPath[i].length === 0 || normalizedPath[i] === '.') {
  12981. continue;
  12982. }
  12983. if (normalizedPath[i] === '..') {
  12984. nb++;
  12985. continue;
  12986. }
  12987. if (nb > 0) {
  12988. nb--;
  12989. continue;
  12990. }
  12991. o.push(normalizedPath[i]);
  12992. }
  12993. i = normalizedBase.length - nb;
  12994. if (i <= 0) {
  12995. outPath = reverse(o).join('/');
  12996. } else {
  12997. outPath = normalizedBase.slice(0, i).join('/') + '/' + reverse(o).join('/');
  12998. }
  12999. if (outPath.indexOf('/') !== 0) {
  13000. outPath = '/' + outPath;
  13001. }
  13002. if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) {
  13003. outPath += tr;
  13004. }
  13005. return outPath;
  13006. };
  13007. URI.prototype.getURI = function (noProtoHost) {
  13008. if (noProtoHost === void 0) {
  13009. noProtoHost = false;
  13010. }
  13011. var s;
  13012. if (!this.source || noProtoHost) {
  13013. s = '';
  13014. if (!noProtoHost) {
  13015. if (this.protocol) {
  13016. s += this.protocol + '://';
  13017. } else {
  13018. s += '//';
  13019. }
  13020. if (this.userInfo) {
  13021. s += this.userInfo + '@';
  13022. }
  13023. if (this.host) {
  13024. s += this.host;
  13025. }
  13026. if (this.port) {
  13027. s += ':' + this.port;
  13028. }
  13029. }
  13030. if (this.path) {
  13031. s += this.path;
  13032. }
  13033. if (this.query) {
  13034. s += '?' + this.query;
  13035. }
  13036. if (this.anchor) {
  13037. s += '#' + this.anchor;
  13038. }
  13039. this.source = s;
  13040. }
  13041. return this.source;
  13042. };
  13043. return URI;
  13044. }();
  13045. var filteredClobberElements = Tools.makeMap('button,fieldset,form,iframe,img,image,input,object,output,select,textarea');
  13046. var isValidPrefixAttrName = function (name) {
  13047. return name.indexOf('data-') === 0 || name.indexOf('aria-') === 0;
  13048. };
  13049. var findMatchingEndTagIndex = function (schema, html, startIndex) {
  13050. var startTagRegExp = /<([!?\/])?([A-Za-z0-9\-_:.]+)/g;
  13051. var endTagRegExp = /(?:\s(?:[^'">]+(?:"[^"]*"|'[^']*'))*[^"'>]*(?:"[^">]*|'[^'>]*)?|\s*|\/)>/g;
  13052. var shortEndedElements = schema.getShortEndedElements();
  13053. var count = 1, index = startIndex;
  13054. while (count !== 0) {
  13055. startTagRegExp.lastIndex = index;
  13056. while (true) {
  13057. var startMatch = startTagRegExp.exec(html);
  13058. if (startMatch === null) {
  13059. return index;
  13060. } else if (startMatch[1] === '!') {
  13061. if (startsWith(startMatch[2], '--')) {
  13062. index = findCommentEndIndex(html, false, startMatch.index + '!--'.length);
  13063. } else {
  13064. index = findCommentEndIndex(html, true, startMatch.index + 1);
  13065. }
  13066. break;
  13067. } else {
  13068. endTagRegExp.lastIndex = startTagRegExp.lastIndex;
  13069. var endMatch = endTagRegExp.exec(html);
  13070. if (isNull(endMatch) || endMatch.index !== startTagRegExp.lastIndex) {
  13071. continue;
  13072. }
  13073. if (startMatch[1] === '/') {
  13074. count -= 1;
  13075. } else if (!has$2(shortEndedElements, startMatch[2])) {
  13076. count += 1;
  13077. }
  13078. index = startTagRegExp.lastIndex + endMatch[0].length;
  13079. break;
  13080. }
  13081. }
  13082. }
  13083. return index;
  13084. };
  13085. var isConditionalComment = function (html, startIndex) {
  13086. return /^\s*\[if [\w\W]+\]>.*<!\[endif\](--!?)?>/.test(html.substr(startIndex));
  13087. };
  13088. var findCommentEndIndex = function (html, isBogus, startIndex) {
  13089. if (startIndex === void 0) {
  13090. startIndex = 0;
  13091. }
  13092. var lcHtml = html.toLowerCase();
  13093. if (lcHtml.indexOf('[if ', startIndex) !== -1 && isConditionalComment(lcHtml, startIndex)) {
  13094. var endIfIndex = lcHtml.indexOf('[endif]', startIndex);
  13095. return lcHtml.indexOf('>', endIfIndex);
  13096. } else {
  13097. if (isBogus) {
  13098. var endIndex = lcHtml.indexOf('>', startIndex);
  13099. return endIndex !== -1 ? endIndex : lcHtml.length;
  13100. } else {
  13101. var endCommentRegexp = /--!?>/g;
  13102. endCommentRegexp.lastIndex = startIndex;
  13103. var match = endCommentRegexp.exec(html);
  13104. return match ? match.index + match[0].length : lcHtml.length;
  13105. }
  13106. }
  13107. };
  13108. var checkBogusAttribute = function (regExp, attrString) {
  13109. var matches = regExp.exec(attrString);
  13110. if (matches) {
  13111. var name_1 = matches[1];
  13112. var value = matches[2];
  13113. return typeof name_1 === 'string' && name_1.toLowerCase() === 'data-mce-bogus' ? value : null;
  13114. } else {
  13115. return null;
  13116. }
  13117. };
  13118. var SaxParser = function (settings, schema) {
  13119. var _a;
  13120. if (schema === void 0) {
  13121. schema = Schema();
  13122. }
  13123. settings = settings || {};
  13124. var doc = (_a = settings.document) !== null && _a !== void 0 ? _a : document;
  13125. var form = doc.createElement('form');
  13126. if (settings.fix_self_closing !== false) {
  13127. settings.fix_self_closing = true;
  13128. }
  13129. var comment = settings.comment ? settings.comment : noop;
  13130. var cdata = settings.cdata ? settings.cdata : noop;
  13131. var text = settings.text ? settings.text : noop;
  13132. var start = settings.start ? settings.start : noop;
  13133. var end = settings.end ? settings.end : noop;
  13134. var pi = settings.pi ? settings.pi : noop;
  13135. var doctype = settings.doctype ? settings.doctype : noop;
  13136. var parseInternal = function (base64Extract, format) {
  13137. if (format === void 0) {
  13138. format = 'html';
  13139. }
  13140. var html = base64Extract.html;
  13141. var matches, index = 0, value, endRegExp;
  13142. var stack = [];
  13143. var attrList, i, textData, name;
  13144. var isInternalElement, isShortEnded;
  13145. var elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns;
  13146. var attributesRequired, attributesDefault, attributesForced;
  13147. var anyAttributesRequired, attrValue, idCount = 0;
  13148. var decode = Entities.decode;
  13149. var filteredUrlAttrs = Tools.makeMap('src,href,data,background,action,formaction,poster,xlink:href');
  13150. var parsingMode = format === 'html' ? 0 : 1;
  13151. var processEndTag = function (name) {
  13152. var pos, i;
  13153. pos = stack.length;
  13154. while (pos--) {
  13155. if (stack[pos].name === name) {
  13156. break;
  13157. }
  13158. }
  13159. if (pos >= 0) {
  13160. for (i = stack.length - 1; i >= pos; i--) {
  13161. name = stack[i];
  13162. if (name.valid) {
  13163. end(name.name);
  13164. }
  13165. }
  13166. stack.length = pos;
  13167. }
  13168. };
  13169. var processText = function (value, raw) {
  13170. return text(restoreDataUris(value, base64Extract), raw);
  13171. };
  13172. var processComment = function (value) {
  13173. if (value === '') {
  13174. return;
  13175. }
  13176. if (value.charAt(0) === '>') {
  13177. value = ' ' + value;
  13178. }
  13179. if (!settings.allow_conditional_comments && value.substr(0, 3).toLowerCase() === '[if') {
  13180. value = ' ' + value;
  13181. }
  13182. comment(restoreDataUris(value, base64Extract));
  13183. };
  13184. var processAttr = function (value) {
  13185. return restoreDataUris(value, base64Extract);
  13186. };
  13187. var processMalformedComment = function (value, startIndex) {
  13188. var startTag = value || '';
  13189. var isBogus = !startsWith(startTag, '--');
  13190. var endIndex = findCommentEndIndex(html, isBogus, startIndex);
  13191. value = html.substr(startIndex, endIndex - startIndex);
  13192. processComment(isBogus ? startTag + value : value);
  13193. return endIndex + 1;
  13194. };
  13195. var parseAttribute = function (tagName, name, value, val2, val3) {
  13196. name = name.toLowerCase();
  13197. value = processAttr(name in fillAttrsMap ? name : decode(value || val2 || val3 || ''));
  13198. if (validate && !isInternalElement && isValidPrefixAttrName(name) === false) {
  13199. var attrRule = validAttributesMap[name];
  13200. if (!attrRule && validAttributePatterns) {
  13201. var i_1 = validAttributePatterns.length;
  13202. while (i_1--) {
  13203. attrRule = validAttributePatterns[i_1];
  13204. if (attrRule.pattern.test(name)) {
  13205. break;
  13206. }
  13207. }
  13208. if (i_1 === -1) {
  13209. attrRule = null;
  13210. }
  13211. }
  13212. if (!attrRule) {
  13213. return;
  13214. }
  13215. if (attrRule.validValues && !(value in attrRule.validValues)) {
  13216. return;
  13217. }
  13218. }
  13219. var isNameOrId = name === 'name' || name === 'id';
  13220. if (isNameOrId && tagName in filteredClobberElements && (value in doc || value in form)) {
  13221. return;
  13222. }
  13223. if (filteredUrlAttrs[name] && !URI.isDomSafe(value, tagName, settings)) {
  13224. return;
  13225. }
  13226. if (isInternalElement && (name in filteredUrlAttrs || name.indexOf('on') === 0)) {
  13227. return;
  13228. }
  13229. attrList.map[name] = value;
  13230. attrList.push({
  13231. name: name,
  13232. value: value
  13233. });
  13234. };
  13235. var tokenRegExp = new RegExp('<(?:' + '(?:!--([\\w\\W]*?)--!?>)|' + '(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|' + '(?:![Dd][Oo][Cc][Tt][Yy][Pp][Ee]([\\w\\W]*?)>)|' + '(?:!(--)?)|' + '(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|' + '(?:\\/([A-Za-z][A-Za-z0-9\\-_\\:\\.]*)>)|' + '(?:([A-Za-z][A-Za-z0-9\\-_:.]*)(\\s(?:[^\'">]+(?:"[^"]*"|\'[^\']*\'))*[^"\'>]*(?:"[^">]*|\'[^\'>]*)?|\\s*|\\/)>)' + ')', 'g');
  13236. var attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g;
  13237. var shortEndedElements = schema.getShortEndedElements();
  13238. var selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
  13239. var fillAttrsMap = schema.getBoolAttrs();
  13240. var validate = settings.validate;
  13241. var removeInternalElements = settings.remove_internals;
  13242. var fixSelfClosing = settings.fix_self_closing;
  13243. var specialElements = schema.getSpecialElements();
  13244. var processHtml = html + '>';
  13245. while (matches = tokenRegExp.exec(processHtml)) {
  13246. var matchText = matches[0];
  13247. if (index < matches.index) {
  13248. processText(decode(html.substr(index, matches.index - index)));
  13249. }
  13250. if (value = matches[7]) {
  13251. value = value.toLowerCase();
  13252. if (value.charAt(0) === ':') {
  13253. value = value.substr(1);
  13254. }
  13255. processEndTag(value);
  13256. } else if (value = matches[8]) {
  13257. if (matches.index + matchText.length > html.length) {
  13258. processText(decode(html.substr(matches.index)));
  13259. index = matches.index + matchText.length;
  13260. continue;
  13261. }
  13262. value = value.toLowerCase();
  13263. if (value.charAt(0) === ':') {
  13264. value = value.substr(1);
  13265. }
  13266. isShortEnded = value in shortEndedElements;
  13267. if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value) {
  13268. processEndTag(value);
  13269. }
  13270. var bogusValue = checkBogusAttribute(attrRegExp, matches[9]);
  13271. if (bogusValue !== null) {
  13272. if (bogusValue === 'all') {
  13273. index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
  13274. tokenRegExp.lastIndex = index;
  13275. continue;
  13276. }
  13277. isValidElement = false;
  13278. }
  13279. if (!validate || (elementRule = schema.getElementRule(value))) {
  13280. isValidElement = true;
  13281. if (validate) {
  13282. validAttributesMap = elementRule.attributes;
  13283. validAttributePatterns = elementRule.attributePatterns;
  13284. }
  13285. if (attribsValue = matches[9]) {
  13286. isInternalElement = attribsValue.indexOf('data-mce-type') !== -1;
  13287. if (isInternalElement && removeInternalElements) {
  13288. isValidElement = false;
  13289. }
  13290. attrList = [];
  13291. attrList.map = {};
  13292. attribsValue.replace(attrRegExp, function (match, name, val, val2, val3) {
  13293. parseAttribute(value, name, val, val2, val3);
  13294. return '';
  13295. });
  13296. } else {
  13297. attrList = [];
  13298. attrList.map = {};
  13299. }
  13300. if (validate && !isInternalElement) {
  13301. attributesRequired = elementRule.attributesRequired;
  13302. attributesDefault = elementRule.attributesDefault;
  13303. attributesForced = elementRule.attributesForced;
  13304. anyAttributesRequired = elementRule.removeEmptyAttrs;
  13305. if (anyAttributesRequired && !attrList.length) {
  13306. isValidElement = false;
  13307. }
  13308. if (attributesForced) {
  13309. i = attributesForced.length;
  13310. while (i--) {
  13311. attr = attributesForced[i];
  13312. name = attr.name;
  13313. attrValue = attr.value;
  13314. if (attrValue === '{$uid}') {
  13315. attrValue = 'mce_' + idCount++;
  13316. }
  13317. attrList.map[name] = attrValue;
  13318. attrList.push({
  13319. name: name,
  13320. value: attrValue
  13321. });
  13322. }
  13323. }
  13324. if (attributesDefault) {
  13325. i = attributesDefault.length;
  13326. while (i--) {
  13327. attr = attributesDefault[i];
  13328. name = attr.name;
  13329. if (!(name in attrList.map)) {
  13330. attrValue = attr.value;
  13331. if (attrValue === '{$uid}') {
  13332. attrValue = 'mce_' + idCount++;
  13333. }
  13334. attrList.map[name] = attrValue;
  13335. attrList.push({
  13336. name: name,
  13337. value: attrValue
  13338. });
  13339. }
  13340. }
  13341. }
  13342. if (attributesRequired) {
  13343. i = attributesRequired.length;
  13344. while (i--) {
  13345. if (attributesRequired[i] in attrList.map) {
  13346. break;
  13347. }
  13348. }
  13349. if (i === -1) {
  13350. isValidElement = false;
  13351. }
  13352. }
  13353. if (attr = attrList.map['data-mce-bogus']) {
  13354. if (attr === 'all') {
  13355. index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
  13356. tokenRegExp.lastIndex = index;
  13357. continue;
  13358. }
  13359. isValidElement = false;
  13360. }
  13361. }
  13362. if (isValidElement) {
  13363. start(value, attrList, isShortEnded);
  13364. }
  13365. } else {
  13366. isValidElement = false;
  13367. }
  13368. if (endRegExp = specialElements[value]) {
  13369. endRegExp.lastIndex = index = matches.index + matchText.length;
  13370. if (matches = endRegExp.exec(html)) {
  13371. if (isValidElement) {
  13372. textData = html.substr(index, matches.index - index);
  13373. }
  13374. index = matches.index + matches[0].length;
  13375. } else {
  13376. textData = html.substr(index);
  13377. index = html.length;
  13378. }
  13379. if (isValidElement) {
  13380. if (textData.length > 0) {
  13381. processText(textData, true);
  13382. }
  13383. end(value);
  13384. }
  13385. tokenRegExp.lastIndex = index;
  13386. continue;
  13387. }
  13388. if (!isShortEnded) {
  13389. if (!attribsValue || attribsValue.indexOf('/') !== attribsValue.length - 1) {
  13390. stack.push({
  13391. name: value,
  13392. valid: isValidElement
  13393. });
  13394. } else if (isValidElement) {
  13395. end(value);
  13396. }
  13397. }
  13398. } else if (value = matches[1]) {
  13399. processComment(value);
  13400. } else if (value = matches[2]) {
  13401. var isValidCdataSection = parsingMode === 1 || settings.preserve_cdata || stack.length > 0 && schema.isValidChild(stack[stack.length - 1].name, '#cdata');
  13402. if (isValidCdataSection) {
  13403. cdata(value);
  13404. } else {
  13405. index = processMalformedComment('', matches.index + 2);
  13406. tokenRegExp.lastIndex = index;
  13407. continue;
  13408. }
  13409. } else if (value = matches[3]) {
  13410. doctype(value);
  13411. } else if ((value = matches[4]) || matchText === '<!') {
  13412. index = processMalformedComment(value, matches.index + matchText.length);
  13413. tokenRegExp.lastIndex = index;
  13414. continue;
  13415. } else if (value = matches[5]) {
  13416. if (parsingMode === 1) {
  13417. pi(value, matches[6]);
  13418. } else {
  13419. index = processMalformedComment('?', matches.index + 2);
  13420. tokenRegExp.lastIndex = index;
  13421. continue;
  13422. }
  13423. }
  13424. index = matches.index + matchText.length;
  13425. }
  13426. if (index < html.length) {
  13427. processText(decode(html.substr(index)));
  13428. }
  13429. for (i = stack.length - 1; i >= 0; i--) {
  13430. value = stack[i];
  13431. if (value.valid) {
  13432. end(value.name);
  13433. }
  13434. }
  13435. };
  13436. var parse = function (html, format) {
  13437. if (format === void 0) {
  13438. format = 'html';
  13439. }
  13440. parseInternal(extractBase64DataUris(html), format);
  13441. };
  13442. return { parse: parse };
  13443. };
  13444. SaxParser.findEndTag = findMatchingEndTagIndex;
  13445. var trimHtml = function (tempAttrs, html) {
  13446. var trimContentRegExp = new RegExp(['\\s?(' + tempAttrs.join('|') + ')="[^"]+"'].join('|'), 'gi');
  13447. return html.replace(trimContentRegExp, '');
  13448. };
  13449. var trimInternal = function (serializer, html) {
  13450. var bogusAllRegExp = /<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g;
  13451. var schema = serializer.schema;
  13452. var content = trimHtml(serializer.getTempAttrs(), html);
  13453. var shortEndedElements = schema.getShortEndedElements();
  13454. var matches;
  13455. while (matches = bogusAllRegExp.exec(content)) {
  13456. var index = bogusAllRegExp.lastIndex;
  13457. var matchLength = matches[0].length;
  13458. var endTagIndex = void 0;
  13459. if (shortEndedElements[matches[1]]) {
  13460. endTagIndex = index;
  13461. } else {
  13462. endTagIndex = SaxParser.findEndTag(schema, content, index);
  13463. }
  13464. content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
  13465. bogusAllRegExp.lastIndex = index - matchLength;
  13466. }
  13467. return trim$2(content);
  13468. };
  13469. var trimExternal = trimInternal;
  13470. var trimEmptyContents = function (editor, html) {
  13471. var blockName = getForcedRootBlock(editor);
  13472. var emptyRegExp = new RegExp('^(<' + blockName + '[^>]*>(&nbsp;|&#160;|\\s|\xA0|<br \\/>|)<\\/' + blockName + '>[\r\n]*|<br \\/>[\r\n]*)$');
  13473. return html.replace(emptyRegExp, '');
  13474. };
  13475. var setupArgs$3 = function (args, format) {
  13476. return __assign(__assign({}, args), {
  13477. format: format,
  13478. get: true,
  13479. getInner: true
  13480. });
  13481. };
  13482. var getContentFromBody = function (editor, args, format, body) {
  13483. var defaultedArgs = setupArgs$3(args, format);
  13484. var updatedArgs = args.no_events ? defaultedArgs : editor.fire('BeforeGetContent', defaultedArgs);
  13485. var content;
  13486. if (updatedArgs.format === 'raw') {
  13487. content = Tools.trim(trimExternal(editor.serializer, body.innerHTML));
  13488. } else if (updatedArgs.format === 'text') {
  13489. content = editor.dom.isEmpty(body) ? '' : trim$2(body.innerText || body.textContent);
  13490. } else if (updatedArgs.format === 'tree') {
  13491. content = editor.serializer.serialize(body, updatedArgs);
  13492. } else {
  13493. content = trimEmptyContents(editor, editor.serializer.serialize(body, updatedArgs));
  13494. }
  13495. if (!contains$3([
  13496. 'text',
  13497. 'tree'
  13498. ], updatedArgs.format) && !isWsPreserveElement(SugarElement.fromDom(body))) {
  13499. updatedArgs.content = Tools.trim(content);
  13500. } else {
  13501. updatedArgs.content = content;
  13502. }
  13503. if (updatedArgs.no_events) {
  13504. return updatedArgs.content;
  13505. } else {
  13506. return editor.fire('GetContent', updatedArgs).content;
  13507. }
  13508. };
  13509. var getContentInternal = function (editor, args, format) {
  13510. return Optional.from(editor.getBody()).fold(constant(args.format === 'tree' ? new AstNode('body', 11) : ''), function (body) {
  13511. return getContentFromBody(editor, args, format, body);
  13512. });
  13513. };
  13514. var each$c = Tools.each;
  13515. var ElementUtils = function (dom) {
  13516. var compare = function (node1, node2) {
  13517. if (node1.nodeName !== node2.nodeName) {
  13518. return false;
  13519. }
  13520. var getAttribs = function (node) {
  13521. var attribs = {};
  13522. each$c(dom.getAttribs(node), function (attr) {
  13523. var name = attr.nodeName.toLowerCase();
  13524. if (name.indexOf('_') !== 0 && name !== 'style' && name.indexOf('data-') !== 0) {
  13525. attribs[name] = dom.getAttrib(node, name);
  13526. }
  13527. });
  13528. return attribs;
  13529. };
  13530. var compareObjects = function (obj1, obj2) {
  13531. var value, name;
  13532. for (name in obj1) {
  13533. if (has$2(obj1, name)) {
  13534. value = obj2[name];
  13535. if (typeof value === 'undefined') {
  13536. return false;
  13537. }
  13538. if (obj1[name] !== value) {
  13539. return false;
  13540. }
  13541. delete obj2[name];
  13542. }
  13543. }
  13544. for (name in obj2) {
  13545. if (has$2(obj2, name)) {
  13546. return false;
  13547. }
  13548. }
  13549. return true;
  13550. };
  13551. if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
  13552. return false;
  13553. }
  13554. if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
  13555. return false;
  13556. }
  13557. return !isBookmarkNode$1(node1) && !isBookmarkNode$1(node2);
  13558. };
  13559. return { compare: compare };
  13560. };
  13561. var makeMap$1 = Tools.makeMap;
  13562. var Writer = function (settings) {
  13563. var html = [];
  13564. settings = settings || {};
  13565. var indent = settings.indent;
  13566. var indentBefore = makeMap$1(settings.indent_before || '');
  13567. var indentAfter = makeMap$1(settings.indent_after || '');
  13568. var encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
  13569. var htmlOutput = settings.element_format === 'html';
  13570. return {
  13571. start: function (name, attrs, empty) {
  13572. var i, l, attr, value;
  13573. if (indent && indentBefore[name] && html.length > 0) {
  13574. value = html[html.length - 1];
  13575. if (value.length > 0 && value !== '\n') {
  13576. html.push('\n');
  13577. }
  13578. }
  13579. html.push('<', name);
  13580. if (attrs) {
  13581. for (i = 0, l = attrs.length; i < l; i++) {
  13582. attr = attrs[i];
  13583. html.push(' ', attr.name, '="', encode(attr.value, true), '"');
  13584. }
  13585. }
  13586. if (!empty || htmlOutput) {
  13587. html[html.length] = '>';
  13588. } else {
  13589. html[html.length] = ' />';
  13590. }
  13591. if (empty && indent && indentAfter[name] && html.length > 0) {
  13592. value = html[html.length - 1];
  13593. if (value.length > 0 && value !== '\n') {
  13594. html.push('\n');
  13595. }
  13596. }
  13597. },
  13598. end: function (name) {
  13599. var value;
  13600. html.push('</', name, '>');
  13601. if (indent && indentAfter[name] && html.length > 0) {
  13602. value = html[html.length - 1];
  13603. if (value.length > 0 && value !== '\n') {
  13604. html.push('\n');
  13605. }
  13606. }
  13607. },
  13608. text: function (text, raw) {
  13609. if (text.length > 0) {
  13610. html[html.length] = raw ? text : encode(text);
  13611. }
  13612. },
  13613. cdata: function (text) {
  13614. html.push('<![CDATA[', text, ']]>');
  13615. },
  13616. comment: function (text) {
  13617. html.push('<!--', text, '-->');
  13618. },
  13619. pi: function (name, text) {
  13620. if (text) {
  13621. html.push('<?', name, ' ', encode(text), '?>');
  13622. } else {
  13623. html.push('<?', name, '?>');
  13624. }
  13625. if (indent) {
  13626. html.push('\n');
  13627. }
  13628. },
  13629. doctype: function (text) {
  13630. html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
  13631. },
  13632. reset: function () {
  13633. html.length = 0;
  13634. },
  13635. getContent: function () {
  13636. return html.join('').replace(/\n$/, '');
  13637. }
  13638. };
  13639. };
  13640. var HtmlSerializer = function (settings, schema) {
  13641. if (schema === void 0) {
  13642. schema = Schema();
  13643. }
  13644. var writer = Writer(settings);
  13645. settings = settings || {};
  13646. settings.validate = 'validate' in settings ? settings.validate : true;
  13647. var serialize = function (node) {
  13648. var validate = settings.validate;
  13649. var handlers = {
  13650. 3: function (node) {
  13651. writer.text(node.value, node.raw);
  13652. },
  13653. 8: function (node) {
  13654. writer.comment(node.value);
  13655. },
  13656. 7: function (node) {
  13657. writer.pi(node.name, node.value);
  13658. },
  13659. 10: function (node) {
  13660. writer.doctype(node.value);
  13661. },
  13662. 4: function (node) {
  13663. writer.cdata(node.value);
  13664. },
  13665. 11: function (node) {
  13666. if (node = node.firstChild) {
  13667. do {
  13668. walk(node);
  13669. } while (node = node.next);
  13670. }
  13671. }
  13672. };
  13673. writer.reset();
  13674. var walk = function (node) {
  13675. var handler = handlers[node.type];
  13676. if (!handler) {
  13677. var name_1 = node.name;
  13678. var isEmpty = node.shortEnded;
  13679. var attrs = node.attributes;
  13680. if (validate && attrs && attrs.length > 1) {
  13681. var sortedAttrs = [];
  13682. sortedAttrs.map = {};
  13683. var elementRule = schema.getElementRule(node.name);
  13684. if (elementRule) {
  13685. for (var i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
  13686. var attrName = elementRule.attributesOrder[i];
  13687. if (attrName in attrs.map) {
  13688. var attrValue = attrs.map[attrName];
  13689. sortedAttrs.map[attrName] = attrValue;
  13690. sortedAttrs.push({
  13691. name: attrName,
  13692. value: attrValue
  13693. });
  13694. }
  13695. }
  13696. for (var i = 0, l = attrs.length; i < l; i++) {
  13697. var attrName = attrs[i].name;
  13698. if (!(attrName in sortedAttrs.map)) {
  13699. var attrValue = attrs.map[attrName];
  13700. sortedAttrs.map[attrName] = attrValue;
  13701. sortedAttrs.push({
  13702. name: attrName,
  13703. value: attrValue
  13704. });
  13705. }
  13706. }
  13707. attrs = sortedAttrs;
  13708. }
  13709. }
  13710. writer.start(node.name, attrs, isEmpty);
  13711. if (!isEmpty) {
  13712. if (node = node.firstChild) {
  13713. do {
  13714. walk(node);
  13715. } while (node = node.next);
  13716. }
  13717. writer.end(name_1);
  13718. }
  13719. } else {
  13720. handler(node);
  13721. }
  13722. };
  13723. if (node.type === 1 && !settings.inner) {
  13724. walk(node);
  13725. } else {
  13726. handlers[11](node);
  13727. }
  13728. return writer.getContent();
  13729. };
  13730. return { serialize: serialize };
  13731. };
  13732. var nonInheritableStyles = new Set();
  13733. (function () {
  13734. var nonInheritableStylesArr = [
  13735. 'margin',
  13736. 'margin-left',
  13737. 'margin-right',
  13738. 'margin-top',
  13739. 'margin-bottom',
  13740. 'padding',
  13741. 'padding-left',
  13742. 'padding-right',
  13743. 'padding-top',
  13744. 'padding-bottom',
  13745. 'border',
  13746. 'border-width',
  13747. 'border-style',
  13748. 'border-color',
  13749. 'background',
  13750. 'background-attachment',
  13751. 'background-clip',
  13752. 'background-color',
  13753. 'background-image',
  13754. 'background-origin',
  13755. 'background-position',
  13756. 'background-repeat',
  13757. 'background-size',
  13758. 'float',
  13759. 'position',
  13760. 'left',
  13761. 'right',
  13762. 'top',
  13763. 'bottom',
  13764. 'z-index',
  13765. 'display',
  13766. 'transform',
  13767. 'width',
  13768. 'max-width',
  13769. 'min-width',
  13770. 'height',
  13771. 'max-height',
  13772. 'min-height',
  13773. 'overflow',
  13774. 'overflow-x',
  13775. 'overflow-y',
  13776. 'text-overflow',
  13777. 'vertical-align',
  13778. 'transition',
  13779. 'transition-delay',
  13780. 'transition-duration',
  13781. 'transition-property',
  13782. 'transition-timing-function'
  13783. ];
  13784. each$k(nonInheritableStylesArr, function (style) {
  13785. nonInheritableStyles.add(style);
  13786. });
  13787. }());
  13788. var shorthandStyleProps = [
  13789. 'font',
  13790. 'text-decoration',
  13791. 'text-emphasis'
  13792. ];
  13793. var getStyleProps = function (dom, node) {
  13794. return keys(dom.parseStyle(dom.getAttrib(node, 'style')));
  13795. };
  13796. var isNonInheritableStyle = function (style) {
  13797. return nonInheritableStyles.has(style);
  13798. };
  13799. var hasInheritableStyles = function (dom, node) {
  13800. return forall(getStyleProps(dom, node), function (style) {
  13801. return !isNonInheritableStyle(style);
  13802. });
  13803. };
  13804. var getLonghandStyleProps = function (styles) {
  13805. return filter$4(styles, function (style) {
  13806. return exists(shorthandStyleProps, function (prop) {
  13807. return startsWith(style, prop);
  13808. });
  13809. });
  13810. };
  13811. var hasStyleConflict = function (dom, node, parentNode) {
  13812. var nodeStyleProps = getStyleProps(dom, node);
  13813. var parentNodeStyleProps = getStyleProps(dom, parentNode);
  13814. var valueMismatch = function (prop) {
  13815. var nodeValue = dom.getStyle(node, prop);
  13816. var parentValue = dom.getStyle(parentNode, prop);
  13817. return isNotEmpty(nodeValue) && isNotEmpty(parentValue) && nodeValue !== parentValue;
  13818. };
  13819. return exists(nodeStyleProps, function (nodeStyleProp) {
  13820. var propExists = function (props) {
  13821. return exists(props, function (prop) {
  13822. return prop === nodeStyleProp;
  13823. });
  13824. };
  13825. if (!propExists(parentNodeStyleProps) && propExists(shorthandStyleProps)) {
  13826. var longhandProps = getLonghandStyleProps(parentNodeStyleProps);
  13827. return exists(longhandProps, valueMismatch);
  13828. } else {
  13829. return valueMismatch(nodeStyleProp);
  13830. }
  13831. });
  13832. };
  13833. var isChar = function (forward, predicate, pos) {
  13834. return Optional.from(pos.container()).filter(isText$7).exists(function (text) {
  13835. var delta = forward ? 0 : -1;
  13836. return predicate(text.data.charAt(pos.offset() + delta));
  13837. });
  13838. };
  13839. var isBeforeSpace = curry(isChar, true, isWhiteSpace);
  13840. var isAfterSpace = curry(isChar, false, isWhiteSpace);
  13841. var isEmptyText = function (pos) {
  13842. var container = pos.container();
  13843. return isText$7(container) && (container.data.length === 0 || isZwsp(container.data) && BookmarkManager.isBookmarkNode(container.parentNode));
  13844. };
  13845. var matchesElementPosition = function (before, predicate) {
  13846. return function (pos) {
  13847. return Optional.from(getChildNodeAtRelativeOffset(before ? 0 : -1, pos)).filter(predicate).isSome();
  13848. };
  13849. };
  13850. var isImageBlock = function (node) {
  13851. return isImg(node) && get$5(SugarElement.fromDom(node), 'display') === 'block';
  13852. };
  13853. var isCefNode = function (node) {
  13854. return isContentEditableFalse$b(node) && !isBogusAll$1(node);
  13855. };
  13856. var isBeforeImageBlock = matchesElementPosition(true, isImageBlock);
  13857. var isAfterImageBlock = matchesElementPosition(false, isImageBlock);
  13858. var isBeforeMedia = matchesElementPosition(true, isMedia$2);
  13859. var isAfterMedia = matchesElementPosition(false, isMedia$2);
  13860. var isBeforeTable = matchesElementPosition(true, isTable$3);
  13861. var isAfterTable = matchesElementPosition(false, isTable$3);
  13862. var isBeforeContentEditableFalse = matchesElementPosition(true, isCefNode);
  13863. var isAfterContentEditableFalse = matchesElementPosition(false, isCefNode);
  13864. var getLastChildren = function (elm) {
  13865. var children = [];
  13866. var rawNode = elm.dom;
  13867. while (rawNode) {
  13868. children.push(SugarElement.fromDom(rawNode));
  13869. rawNode = rawNode.lastChild;
  13870. }
  13871. return children;
  13872. };
  13873. var removeTrailingBr = function (elm) {
  13874. var allBrs = descendants(elm, 'br');
  13875. var brs = filter$4(getLastChildren(elm).slice(-1), isBr$4);
  13876. if (allBrs.length === brs.length) {
  13877. each$k(brs, remove$7);
  13878. }
  13879. };
  13880. var fillWithPaddingBr = function (elm) {
  13881. empty(elm);
  13882. append$1(elm, SugarElement.fromHtml('<br data-mce-bogus="1">'));
  13883. };
  13884. var trimBlockTrailingBr = function (elm) {
  13885. lastChild(elm).each(function (lastChild) {
  13886. prevSibling(lastChild).each(function (lastChildPrevSibling) {
  13887. if (isBlock$2(elm) && isBr$4(lastChild) && isBlock$2(lastChildPrevSibling)) {
  13888. remove$7(lastChild);
  13889. }
  13890. });
  13891. });
  13892. };
  13893. var dropLast = function (xs) {
  13894. return xs.slice(0, -1);
  13895. };
  13896. var parentsUntil = function (start, root, predicate) {
  13897. if (contains$1(root, start)) {
  13898. return dropLast(parents$1(start, function (elm) {
  13899. return predicate(elm) || eq(elm, root);
  13900. }));
  13901. } else {
  13902. return [];
  13903. }
  13904. };
  13905. var parents = function (start, root) {
  13906. return parentsUntil(start, root, never);
  13907. };
  13908. var parentsAndSelf = function (start, root) {
  13909. return [start].concat(parents(start, root));
  13910. };
  13911. var navigateIgnoreEmptyTextNodes = function (forward, root, from) {
  13912. return navigateIgnore(forward, root, from, isEmptyText);
  13913. };
  13914. var getClosestBlock$1 = function (root, pos) {
  13915. return find$3(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  13916. };
  13917. var isAtBeforeAfterBlockBoundary = function (forward, root, pos) {
  13918. return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  13919. return getClosestBlock$1(root, pos).fold(function () {
  13920. return isInSameBlock(newPos, pos, root.dom) === false;
  13921. }, function (fromBlock) {
  13922. return isInSameBlock(newPos, pos, root.dom) === false && contains$1(fromBlock, SugarElement.fromDom(newPos.container()));
  13923. });
  13924. });
  13925. };
  13926. var isAtBlockBoundary = function (forward, root, pos) {
  13927. return getClosestBlock$1(root, pos).fold(function () {
  13928. return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  13929. return isInSameBlock(newPos, pos, root.dom) === false;
  13930. });
  13931. }, function (parent) {
  13932. return navigateIgnoreEmptyTextNodes(forward, parent.dom, pos).isNone();
  13933. });
  13934. };
  13935. var isAtStartOfBlock = curry(isAtBlockBoundary, false);
  13936. var isAtEndOfBlock = curry(isAtBlockBoundary, true);
  13937. var isBeforeBlock = curry(isAtBeforeAfterBlockBoundary, false);
  13938. var isAfterBlock = curry(isAtBeforeAfterBlockBoundary, true);
  13939. var isBr = function (pos) {
  13940. return getElementFromPosition(pos).exists(isBr$4);
  13941. };
  13942. var findBr = function (forward, root, pos) {
  13943. var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  13944. var scope = head(parentBlocks).getOr(root);
  13945. return fromPosition(forward, scope.dom, pos).filter(isBr);
  13946. };
  13947. var isBeforeBr$1 = function (root, pos) {
  13948. return getElementFromPosition(pos).exists(isBr$4) || findBr(true, root, pos).isSome();
  13949. };
  13950. var isAfterBr = function (root, pos) {
  13951. return getElementFromPrevPosition(pos).exists(isBr$4) || findBr(false, root, pos).isSome();
  13952. };
  13953. var findPreviousBr = curry(findBr, false);
  13954. var findNextBr = curry(findBr, true);
  13955. var isInMiddleOfText = function (pos) {
  13956. return CaretPosition.isTextPosition(pos) && !pos.isAtStart() && !pos.isAtEnd();
  13957. };
  13958. var getClosestBlock = function (root, pos) {
  13959. var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  13960. return head(parentBlocks).getOr(root);
  13961. };
  13962. var hasSpaceBefore = function (root, pos) {
  13963. if (isInMiddleOfText(pos)) {
  13964. return isAfterSpace(pos);
  13965. } else {
  13966. return isAfterSpace(pos) || prevPosition(getClosestBlock(root, pos).dom, pos).exists(isAfterSpace);
  13967. }
  13968. };
  13969. var hasSpaceAfter = function (root, pos) {
  13970. if (isInMiddleOfText(pos)) {
  13971. return isBeforeSpace(pos);
  13972. } else {
  13973. return isBeforeSpace(pos) || nextPosition(getClosestBlock(root, pos).dom, pos).exists(isBeforeSpace);
  13974. }
  13975. };
  13976. var isPreValue = function (value) {
  13977. return contains$3([
  13978. 'pre',
  13979. 'pre-wrap'
  13980. ], value);
  13981. };
  13982. var isInPre = function (pos) {
  13983. return getElementFromPosition(pos).bind(function (elm) {
  13984. return closest$3(elm, isElement$6);
  13985. }).exists(function (elm) {
  13986. return isPreValue(get$5(elm, 'white-space'));
  13987. });
  13988. };
  13989. var isAtBeginningOfBody = function (root, pos) {
  13990. return prevPosition(root.dom, pos).isNone();
  13991. };
  13992. var isAtEndOfBody = function (root, pos) {
  13993. return nextPosition(root.dom, pos).isNone();
  13994. };
  13995. var isAtLineBoundary = function (root, pos) {
  13996. return isAtBeginningOfBody(root, pos) || isAtEndOfBody(root, pos) || isAtStartOfBlock(root, pos) || isAtEndOfBlock(root, pos) || isAfterBr(root, pos) || isBeforeBr$1(root, pos);
  13997. };
  13998. var needsToHaveNbsp = function (root, pos) {
  13999. if (isInPre(pos)) {
  14000. return false;
  14001. } else {
  14002. return isAtLineBoundary(root, pos) || hasSpaceBefore(root, pos) || hasSpaceAfter(root, pos);
  14003. }
  14004. };
  14005. var needsToBeNbspLeft = function (root, pos) {
  14006. if (isInPre(pos)) {
  14007. return false;
  14008. } else {
  14009. return isAtStartOfBlock(root, pos) || isBeforeBlock(root, pos) || isAfterBr(root, pos) || hasSpaceBefore(root, pos);
  14010. }
  14011. };
  14012. var leanRight = function (pos) {
  14013. var container = pos.container();
  14014. var offset = pos.offset();
  14015. if (isText$7(container) && offset < container.data.length) {
  14016. return CaretPosition(container, offset + 1);
  14017. } else {
  14018. return pos;
  14019. }
  14020. };
  14021. var needsToBeNbspRight = function (root, pos) {
  14022. if (isInPre(pos)) {
  14023. return false;
  14024. } else {
  14025. return isAtEndOfBlock(root, pos) || isAfterBlock(root, pos) || isBeforeBr$1(root, pos) || hasSpaceAfter(root, pos);
  14026. }
  14027. };
  14028. var needsToBeNbsp = function (root, pos) {
  14029. return needsToBeNbspLeft(root, pos) || needsToBeNbspRight(root, leanRight(pos));
  14030. };
  14031. var isNbspAt = function (text, offset) {
  14032. return isNbsp(text.charAt(offset));
  14033. };
  14034. var hasNbsp = function (pos) {
  14035. var container = pos.container();
  14036. return isText$7(container) && contains$2(container.data, nbsp);
  14037. };
  14038. var normalizeNbspMiddle = function (text) {
  14039. var chars = text.split('');
  14040. return map$3(chars, function (chr, i) {
  14041. if (isNbsp(chr) && i > 0 && i < chars.length - 1 && isContent(chars[i - 1]) && isContent(chars[i + 1])) {
  14042. return ' ';
  14043. } else {
  14044. return chr;
  14045. }
  14046. }).join('');
  14047. };
  14048. var normalizeNbspAtStart = function (root, node) {
  14049. var text = node.data;
  14050. var firstPos = CaretPosition(node, 0);
  14051. if (isNbspAt(text, 0) && !needsToBeNbsp(root, firstPos)) {
  14052. node.data = ' ' + text.slice(1);
  14053. return true;
  14054. } else {
  14055. return false;
  14056. }
  14057. };
  14058. var normalizeNbspInMiddleOfTextNode = function (node) {
  14059. var text = node.data;
  14060. var newText = normalizeNbspMiddle(text);
  14061. if (newText !== text) {
  14062. node.data = newText;
  14063. return true;
  14064. } else {
  14065. return false;
  14066. }
  14067. };
  14068. var normalizeNbspAtEnd = function (root, node) {
  14069. var text = node.data;
  14070. var lastPos = CaretPosition(node, text.length - 1);
  14071. if (isNbspAt(text, text.length - 1) && !needsToBeNbsp(root, lastPos)) {
  14072. node.data = text.slice(0, -1) + ' ';
  14073. return true;
  14074. } else {
  14075. return false;
  14076. }
  14077. };
  14078. var normalizeNbsps = function (root, pos) {
  14079. return Optional.some(pos).filter(hasNbsp).bind(function (pos) {
  14080. var container = pos.container();
  14081. var normalized = normalizeNbspAtStart(root, container) || normalizeNbspInMiddleOfTextNode(container) || normalizeNbspAtEnd(root, container);
  14082. return normalized ? Optional.some(pos) : Optional.none();
  14083. });
  14084. };
  14085. var normalizeNbspsInEditor = function (editor) {
  14086. var root = SugarElement.fromDom(editor.getBody());
  14087. if (editor.selection.isCollapsed()) {
  14088. normalizeNbsps(root, CaretPosition.fromRangeStart(editor.selection.getRng())).each(function (pos) {
  14089. editor.selection.setRng(pos.toRange());
  14090. });
  14091. }
  14092. };
  14093. var normalizeContent = function (content, isStartOfContent, isEndOfContent) {
  14094. var result = foldl(content, function (acc, c) {
  14095. if (isWhiteSpace(c) || isNbsp(c)) {
  14096. if (acc.previousCharIsSpace || acc.str === '' && isStartOfContent || acc.str.length === content.length - 1 && isEndOfContent) {
  14097. return {
  14098. previousCharIsSpace: false,
  14099. str: acc.str + nbsp
  14100. };
  14101. } else {
  14102. return {
  14103. previousCharIsSpace: true,
  14104. str: acc.str + ' '
  14105. };
  14106. }
  14107. } else {
  14108. return {
  14109. previousCharIsSpace: false,
  14110. str: acc.str + c
  14111. };
  14112. }
  14113. }, {
  14114. previousCharIsSpace: false,
  14115. str: ''
  14116. });
  14117. return result.str;
  14118. };
  14119. var normalize$1 = function (node, offset, count) {
  14120. if (count === 0) {
  14121. return;
  14122. }
  14123. var elm = SugarElement.fromDom(node);
  14124. var root = ancestor$3(elm, isBlock$2).getOr(elm);
  14125. var whitespace = node.data.slice(offset, offset + count);
  14126. var isEndOfContent = offset + count >= node.data.length && needsToBeNbspRight(root, CaretPosition(node, node.data.length));
  14127. var isStartOfContent = offset === 0 && needsToBeNbspLeft(root, CaretPosition(node, 0));
  14128. node.replaceData(offset, count, normalizeContent(whitespace, isStartOfContent, isEndOfContent));
  14129. };
  14130. var normalizeWhitespaceAfter = function (node, offset) {
  14131. var content = node.data.slice(offset);
  14132. var whitespaceCount = content.length - lTrim(content).length;
  14133. normalize$1(node, offset, whitespaceCount);
  14134. };
  14135. var normalizeWhitespaceBefore = function (node, offset) {
  14136. var content = node.data.slice(0, offset);
  14137. var whitespaceCount = content.length - rTrim(content).length;
  14138. normalize$1(node, offset - whitespaceCount, whitespaceCount);
  14139. };
  14140. var mergeTextNodes = function (prevNode, nextNode, normalizeWhitespace, mergeToPrev) {
  14141. if (mergeToPrev === void 0) {
  14142. mergeToPrev = true;
  14143. }
  14144. var whitespaceOffset = rTrim(prevNode.data).length;
  14145. var newNode = mergeToPrev ? prevNode : nextNode;
  14146. var removeNode = mergeToPrev ? nextNode : prevNode;
  14147. if (mergeToPrev) {
  14148. newNode.appendData(removeNode.data);
  14149. } else {
  14150. newNode.insertData(0, removeNode.data);
  14151. }
  14152. remove$7(SugarElement.fromDom(removeNode));
  14153. if (normalizeWhitespace) {
  14154. normalizeWhitespaceAfter(newNode, whitespaceOffset);
  14155. }
  14156. return newNode;
  14157. };
  14158. var needsReposition = function (pos, elm) {
  14159. var container = pos.container();
  14160. var offset = pos.offset();
  14161. return CaretPosition.isTextPosition(pos) === false && container === elm.parentNode && offset > CaretPosition.before(elm).offset();
  14162. };
  14163. var reposition = function (elm, pos) {
  14164. return needsReposition(pos, elm) ? CaretPosition(pos.container(), pos.offset() - 1) : pos;
  14165. };
  14166. var beforeOrStartOf = function (node) {
  14167. return isText$7(node) ? CaretPosition(node, 0) : CaretPosition.before(node);
  14168. };
  14169. var afterOrEndOf = function (node) {
  14170. return isText$7(node) ? CaretPosition(node, node.data.length) : CaretPosition.after(node);
  14171. };
  14172. var getPreviousSiblingCaretPosition = function (elm) {
  14173. if (isCaretCandidate$3(elm.previousSibling)) {
  14174. return Optional.some(afterOrEndOf(elm.previousSibling));
  14175. } else {
  14176. return elm.previousSibling ? lastPositionIn(elm.previousSibling) : Optional.none();
  14177. }
  14178. };
  14179. var getNextSiblingCaretPosition = function (elm) {
  14180. if (isCaretCandidate$3(elm.nextSibling)) {
  14181. return Optional.some(beforeOrStartOf(elm.nextSibling));
  14182. } else {
  14183. return elm.nextSibling ? firstPositionIn(elm.nextSibling) : Optional.none();
  14184. }
  14185. };
  14186. var findCaretPositionBackwardsFromElm = function (rootElement, elm) {
  14187. var startPosition = CaretPosition.before(elm.previousSibling ? elm.previousSibling : elm.parentNode);
  14188. return prevPosition(rootElement, startPosition).fold(function () {
  14189. return nextPosition(rootElement, CaretPosition.after(elm));
  14190. }, Optional.some);
  14191. };
  14192. var findCaretPositionForwardsFromElm = function (rootElement, elm) {
  14193. return nextPosition(rootElement, CaretPosition.after(elm)).fold(function () {
  14194. return prevPosition(rootElement, CaretPosition.before(elm));
  14195. }, Optional.some);
  14196. };
  14197. var findCaretPositionBackwards = function (rootElement, elm) {
  14198. return getPreviousSiblingCaretPosition(elm).orThunk(function () {
  14199. return getNextSiblingCaretPosition(elm);
  14200. }).orThunk(function () {
  14201. return findCaretPositionBackwardsFromElm(rootElement, elm);
  14202. });
  14203. };
  14204. var findCaretPositionForward = function (rootElement, elm) {
  14205. return getNextSiblingCaretPosition(elm).orThunk(function () {
  14206. return getPreviousSiblingCaretPosition(elm);
  14207. }).orThunk(function () {
  14208. return findCaretPositionForwardsFromElm(rootElement, elm);
  14209. });
  14210. };
  14211. var findCaretPosition = function (forward, rootElement, elm) {
  14212. return forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
  14213. };
  14214. var findCaretPosOutsideElmAfterDelete = function (forward, rootElement, elm) {
  14215. return findCaretPosition(forward, rootElement, elm).map(curry(reposition, elm));
  14216. };
  14217. var setSelection$1 = function (editor, forward, pos) {
  14218. pos.fold(function () {
  14219. editor.focus();
  14220. }, function (pos) {
  14221. editor.selection.setRng(pos.toRange(), forward);
  14222. });
  14223. };
  14224. var eqRawNode = function (rawNode) {
  14225. return function (elm) {
  14226. return elm.dom === rawNode;
  14227. };
  14228. };
  14229. var isBlock = function (editor, elm) {
  14230. return elm && has$2(editor.schema.getBlockElements(), name(elm));
  14231. };
  14232. var paddEmptyBlock = function (elm) {
  14233. if (isEmpty$2(elm)) {
  14234. var br = SugarElement.fromHtml('<br data-mce-bogus="1">');
  14235. empty(elm);
  14236. append$1(elm, br);
  14237. return Optional.some(CaretPosition.before(br.dom));
  14238. } else {
  14239. return Optional.none();
  14240. }
  14241. };
  14242. var deleteNormalized = function (elm, afterDeletePosOpt, normalizeWhitespace) {
  14243. var prevTextOpt = prevSibling(elm).filter(isText$8);
  14244. var nextTextOpt = nextSibling(elm).filter(isText$8);
  14245. remove$7(elm);
  14246. return lift3(prevTextOpt, nextTextOpt, afterDeletePosOpt, function (prev, next, pos) {
  14247. var prevNode = prev.dom, nextNode = next.dom;
  14248. var offset = prevNode.data.length;
  14249. mergeTextNodes(prevNode, nextNode, normalizeWhitespace);
  14250. return pos.container() === nextNode ? CaretPosition(prevNode, offset) : pos;
  14251. }).orThunk(function () {
  14252. if (normalizeWhitespace) {
  14253. prevTextOpt.each(function (elm) {
  14254. return normalizeWhitespaceBefore(elm.dom, elm.dom.length);
  14255. });
  14256. nextTextOpt.each(function (elm) {
  14257. return normalizeWhitespaceAfter(elm.dom, 0);
  14258. });
  14259. }
  14260. return afterDeletePosOpt;
  14261. });
  14262. };
  14263. var isInlineElement = function (editor, element) {
  14264. return has$2(editor.schema.getTextInlineElements(), name(element));
  14265. };
  14266. var deleteElement$2 = function (editor, forward, elm, moveCaret) {
  14267. if (moveCaret === void 0) {
  14268. moveCaret = true;
  14269. }
  14270. var afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom);
  14271. var parentBlock = ancestor$3(elm, curry(isBlock, editor), eqRawNode(editor.getBody()));
  14272. var normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos, isInlineElement(editor, elm));
  14273. if (editor.dom.isEmpty(editor.getBody())) {
  14274. editor.setContent('');
  14275. editor.selection.setCursorLocation();
  14276. } else {
  14277. parentBlock.bind(paddEmptyBlock).fold(function () {
  14278. if (moveCaret) {
  14279. setSelection$1(editor, forward, normalizedAfterDeletePos);
  14280. }
  14281. }, function (paddPos) {
  14282. if (moveCaret) {
  14283. setSelection$1(editor, forward, Optional.some(paddPos));
  14284. }
  14285. });
  14286. }
  14287. };
  14288. var isRootFromElement = function (root) {
  14289. return function (cur) {
  14290. return eq(root, cur);
  14291. };
  14292. };
  14293. var getTableCells = function (table) {
  14294. return descendants(table, 'td,th');
  14295. };
  14296. var getTableDetailsFromRange = function (rng, isRoot) {
  14297. var getTable = function (node) {
  14298. return getClosestTable(SugarElement.fromDom(node), isRoot);
  14299. };
  14300. var startTable = getTable(rng.startContainer);
  14301. var endTable = getTable(rng.endContainer);
  14302. var isStartInTable = startTable.isSome();
  14303. var isEndInTable = endTable.isSome();
  14304. var isSameTable = lift2(startTable, endTable, eq).getOr(false);
  14305. var isMultiTable = !isSameTable && isStartInTable && isEndInTable;
  14306. return {
  14307. startTable: startTable,
  14308. endTable: endTable,
  14309. isStartInTable: isStartInTable,
  14310. isEndInTable: isEndInTable,
  14311. isSameTable: isSameTable,
  14312. isMultiTable: isMultiTable
  14313. };
  14314. };
  14315. var tableCellRng = function (start, end) {
  14316. return {
  14317. start: start,
  14318. end: end
  14319. };
  14320. };
  14321. var tableSelection = function (rng, table, cells) {
  14322. return {
  14323. rng: rng,
  14324. table: table,
  14325. cells: cells
  14326. };
  14327. };
  14328. var deleteAction = Adt.generate([
  14329. {
  14330. singleCellTable: [
  14331. 'rng',
  14332. 'cell'
  14333. ]
  14334. },
  14335. { fullTable: ['table'] },
  14336. {
  14337. partialTable: [
  14338. 'cells',
  14339. 'outsideDetails'
  14340. ]
  14341. },
  14342. {
  14343. multiTable: [
  14344. 'startTableCells',
  14345. 'endTableCells',
  14346. 'betweenRng'
  14347. ]
  14348. }
  14349. ]);
  14350. var getClosestCell$1 = function (container, isRoot) {
  14351. return closest$2(SugarElement.fromDom(container), 'td,th', isRoot);
  14352. };
  14353. var isExpandedCellRng = function (cellRng) {
  14354. return !eq(cellRng.start, cellRng.end);
  14355. };
  14356. var getTableFromCellRng = function (cellRng, isRoot) {
  14357. return getClosestTable(cellRng.start, isRoot).bind(function (startParentTable) {
  14358. return getClosestTable(cellRng.end, isRoot).bind(function (endParentTable) {
  14359. return someIf(eq(startParentTable, endParentTable), startParentTable);
  14360. });
  14361. });
  14362. };
  14363. var isSingleCellTable = function (cellRng, isRoot) {
  14364. return !isExpandedCellRng(cellRng) && getTableFromCellRng(cellRng, isRoot).exists(function (table) {
  14365. var rows = table.dom.rows;
  14366. return rows.length === 1 && rows[0].cells.length === 1;
  14367. });
  14368. };
  14369. var getCellRng = function (rng, isRoot) {
  14370. var startCell = getClosestCell$1(rng.startContainer, isRoot);
  14371. var endCell = getClosestCell$1(rng.endContainer, isRoot);
  14372. return lift2(startCell, endCell, tableCellRng);
  14373. };
  14374. var getCellRangeFromStartTable = function (isRoot) {
  14375. return function (startCell) {
  14376. return getClosestTable(startCell, isRoot).bind(function (table) {
  14377. return last$2(getTableCells(table)).map(function (endCell) {
  14378. return tableCellRng(startCell, endCell);
  14379. });
  14380. });
  14381. };
  14382. };
  14383. var getCellRangeFromEndTable = function (isRoot) {
  14384. return function (endCell) {
  14385. return getClosestTable(endCell, isRoot).bind(function (table) {
  14386. return head(getTableCells(table)).map(function (startCell) {
  14387. return tableCellRng(startCell, endCell);
  14388. });
  14389. });
  14390. };
  14391. };
  14392. var getTableSelectionFromCellRng = function (isRoot) {
  14393. return function (cellRng) {
  14394. return getTableFromCellRng(cellRng, isRoot).map(function (table) {
  14395. return tableSelection(cellRng, table, getTableCells(table));
  14396. });
  14397. };
  14398. };
  14399. var getTableSelections = function (cellRng, selectionDetails, rng, isRoot) {
  14400. if (rng.collapsed || !cellRng.forall(isExpandedCellRng)) {
  14401. return Optional.none();
  14402. } else if (selectionDetails.isSameTable) {
  14403. var sameTableSelection = cellRng.bind(getTableSelectionFromCellRng(isRoot));
  14404. return Optional.some({
  14405. start: sameTableSelection,
  14406. end: sameTableSelection
  14407. });
  14408. } else {
  14409. var startCell = getClosestCell$1(rng.startContainer, isRoot);
  14410. var endCell = getClosestCell$1(rng.endContainer, isRoot);
  14411. var startTableSelection = startCell.bind(getCellRangeFromStartTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  14412. var endTableSelection = endCell.bind(getCellRangeFromEndTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  14413. return Optional.some({
  14414. start: startTableSelection,
  14415. end: endTableSelection
  14416. });
  14417. }
  14418. };
  14419. var getCellIndex = function (cells, cell) {
  14420. return findIndex$2(cells, function (x) {
  14421. return eq(x, cell);
  14422. });
  14423. };
  14424. var getSelectedCells = function (tableSelection) {
  14425. return lift2(getCellIndex(tableSelection.cells, tableSelection.rng.start), getCellIndex(tableSelection.cells, tableSelection.rng.end), function (startIndex, endIndex) {
  14426. return tableSelection.cells.slice(startIndex, endIndex + 1);
  14427. });
  14428. };
  14429. var isSingleCellTableContentSelected = function (optCellRng, rng, isRoot) {
  14430. return optCellRng.exists(function (cellRng) {
  14431. return isSingleCellTable(cellRng, isRoot) && hasAllContentsSelected(cellRng.start, rng);
  14432. });
  14433. };
  14434. var unselectCells = function (rng, selectionDetails) {
  14435. var startTable = selectionDetails.startTable, endTable = selectionDetails.endTable;
  14436. var otherContentRng = rng.cloneRange();
  14437. startTable.each(function (table) {
  14438. return otherContentRng.setStartAfter(table.dom);
  14439. });
  14440. endTable.each(function (table) {
  14441. return otherContentRng.setEndBefore(table.dom);
  14442. });
  14443. return otherContentRng;
  14444. };
  14445. var handleSingleTable = function (cellRng, selectionDetails, rng, isRoot) {
  14446. return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function (_a) {
  14447. var start = _a.start, end = _a.end;
  14448. return start.or(end);
  14449. }).bind(function (tableSelection) {
  14450. var isSameTable = selectionDetails.isSameTable;
  14451. var selectedCells = getSelectedCells(tableSelection).getOr([]);
  14452. if (isSameTable && tableSelection.cells.length === selectedCells.length) {
  14453. return Optional.some(deleteAction.fullTable(tableSelection.table));
  14454. } else if (selectedCells.length > 0) {
  14455. if (isSameTable) {
  14456. return Optional.some(deleteAction.partialTable(selectedCells, Optional.none()));
  14457. } else {
  14458. var otherContentRng = unselectCells(rng, selectionDetails);
  14459. return Optional.some(deleteAction.partialTable(selectedCells, Optional.some(__assign(__assign({}, selectionDetails), { rng: otherContentRng }))));
  14460. }
  14461. } else {
  14462. return Optional.none();
  14463. }
  14464. });
  14465. };
  14466. var handleMultiTable = function (cellRng, selectionDetails, rng, isRoot) {
  14467. return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function (_a) {
  14468. var start = _a.start, end = _a.end;
  14469. var startTableSelectedCells = start.bind(getSelectedCells).getOr([]);
  14470. var endTableSelectedCells = end.bind(getSelectedCells).getOr([]);
  14471. if (startTableSelectedCells.length > 0 && endTableSelectedCells.length > 0) {
  14472. var otherContentRng = unselectCells(rng, selectionDetails);
  14473. return Optional.some(deleteAction.multiTable(startTableSelectedCells, endTableSelectedCells, otherContentRng));
  14474. } else {
  14475. return Optional.none();
  14476. }
  14477. });
  14478. };
  14479. var getActionFromRange = function (root, rng) {
  14480. var isRoot = isRootFromElement(root);
  14481. var optCellRng = getCellRng(rng, isRoot);
  14482. var selectionDetails = getTableDetailsFromRange(rng, isRoot);
  14483. if (isSingleCellTableContentSelected(optCellRng, rng, isRoot)) {
  14484. return optCellRng.map(function (cellRng) {
  14485. return deleteAction.singleCellTable(rng, cellRng.start);
  14486. });
  14487. } else if (selectionDetails.isMultiTable) {
  14488. return handleMultiTable(optCellRng, selectionDetails, rng, isRoot);
  14489. } else {
  14490. return handleSingleTable(optCellRng, selectionDetails, rng, isRoot);
  14491. }
  14492. };
  14493. var freefallRtl = function (root) {
  14494. var child = isComment$1(root) ? prevSibling(root) : lastChild(root);
  14495. return child.bind(freefallRtl).orThunk(function () {
  14496. return Optional.some(root);
  14497. });
  14498. };
  14499. var cleanCells = function (cells) {
  14500. return each$k(cells, function (cell) {
  14501. remove$6(cell, 'contenteditable');
  14502. fillWithPaddingBr(cell);
  14503. });
  14504. };
  14505. var getOutsideBlock = function (editor, container) {
  14506. return Optional.from(editor.dom.getParent(container, editor.dom.isBlock)).map(SugarElement.fromDom);
  14507. };
  14508. var handleEmptyBlock = function (editor, startInTable, emptyBlock) {
  14509. emptyBlock.each(function (block) {
  14510. if (startInTable) {
  14511. remove$7(block);
  14512. } else {
  14513. fillWithPaddingBr(block);
  14514. editor.selection.setCursorLocation(block.dom, 0);
  14515. }
  14516. });
  14517. };
  14518. var deleteContentInsideCell = function (editor, cell, rng, isFirstCellInSelection) {
  14519. var insideTableRng = rng.cloneRange();
  14520. if (isFirstCellInSelection) {
  14521. insideTableRng.setStart(rng.startContainer, rng.startOffset);
  14522. insideTableRng.setEndAfter(cell.dom.lastChild);
  14523. } else {
  14524. insideTableRng.setStartBefore(cell.dom.firstChild);
  14525. insideTableRng.setEnd(rng.endContainer, rng.endOffset);
  14526. }
  14527. deleteCellContents(editor, insideTableRng, cell, false);
  14528. };
  14529. var collapseAndRestoreCellSelection = function (editor) {
  14530. var selectedCells = getCellsFromEditor(editor);
  14531. var selectedNode = SugarElement.fromDom(editor.selection.getNode());
  14532. if (isTableCell$5(selectedNode.dom) && isEmpty$2(selectedNode)) {
  14533. editor.selection.setCursorLocation(selectedNode.dom, 0);
  14534. } else {
  14535. editor.selection.collapse(true);
  14536. }
  14537. if (selectedCells.length > 1 && exists(selectedCells, function (cell) {
  14538. return eq(cell, selectedNode);
  14539. })) {
  14540. set$1(selectedNode, 'data-mce-selected', '1');
  14541. }
  14542. };
  14543. var emptySingleTableCells = function (editor, cells, outsideDetails) {
  14544. var editorRng = editor.selection.getRng();
  14545. var cellsToClean = outsideDetails.bind(function (_a) {
  14546. var rng = _a.rng, isStartInTable = _a.isStartInTable;
  14547. var outsideBlock = getOutsideBlock(editor, isStartInTable ? rng.endContainer : rng.startContainer);
  14548. rng.deleteContents();
  14549. handleEmptyBlock(editor, isStartInTable, outsideBlock.filter(isEmpty$2));
  14550. var endPointCell = isStartInTable ? cells[0] : cells[cells.length - 1];
  14551. deleteContentInsideCell(editor, endPointCell, editorRng, isStartInTable);
  14552. if (!isEmpty$2(endPointCell)) {
  14553. return Optional.some(isStartInTable ? cells.slice(1) : cells.slice(0, -1));
  14554. } else {
  14555. return Optional.none();
  14556. }
  14557. }).getOr(cells);
  14558. cleanCells(cellsToClean);
  14559. collapseAndRestoreCellSelection(editor);
  14560. return true;
  14561. };
  14562. var emptyMultiTableCells = function (editor, startTableCells, endTableCells, betweenRng) {
  14563. var rng = editor.selection.getRng();
  14564. var startCell = startTableCells[0];
  14565. var endCell = endTableCells[endTableCells.length - 1];
  14566. deleteContentInsideCell(editor, startCell, rng, true);
  14567. deleteContentInsideCell(editor, endCell, rng, false);
  14568. var startTableCellsToClean = isEmpty$2(startCell) ? startTableCells : startTableCells.slice(1);
  14569. var endTableCellsToClean = isEmpty$2(endCell) ? endTableCells : endTableCells.slice(0, -1);
  14570. cleanCells(startTableCellsToClean.concat(endTableCellsToClean));
  14571. betweenRng.deleteContents();
  14572. collapseAndRestoreCellSelection(editor);
  14573. return true;
  14574. };
  14575. var deleteCellContents = function (editor, rng, cell, moveSelection) {
  14576. if (moveSelection === void 0) {
  14577. moveSelection = true;
  14578. }
  14579. rng.deleteContents();
  14580. var lastNode = freefallRtl(cell).getOr(cell);
  14581. var lastBlock = SugarElement.fromDom(editor.dom.getParent(lastNode.dom, editor.dom.isBlock));
  14582. if (isEmpty$2(lastBlock)) {
  14583. fillWithPaddingBr(lastBlock);
  14584. if (moveSelection) {
  14585. editor.selection.setCursorLocation(lastBlock.dom, 0);
  14586. }
  14587. }
  14588. if (!eq(cell, lastBlock)) {
  14589. var additionalCleanupNodes = is$1(parent(lastBlock), cell) ? [] : siblings(lastBlock);
  14590. each$k(additionalCleanupNodes.concat(children(cell)), function (node) {
  14591. if (!eq(node, lastBlock) && !contains$1(node, lastBlock) && isEmpty$2(node)) {
  14592. remove$7(node);
  14593. }
  14594. });
  14595. }
  14596. return true;
  14597. };
  14598. var deleteTableElement = function (editor, table) {
  14599. deleteElement$2(editor, false, table);
  14600. return true;
  14601. };
  14602. var deleteCellRange = function (editor, rootElm, rng) {
  14603. return getActionFromRange(rootElm, rng).map(function (action) {
  14604. return action.fold(curry(deleteCellContents, editor), curry(deleteTableElement, editor), curry(emptySingleTableCells, editor), curry(emptyMultiTableCells, editor));
  14605. });
  14606. };
  14607. var deleteCaptionRange = function (editor, caption) {
  14608. return emptyElement(editor, caption);
  14609. };
  14610. var deleteTableRange = function (editor, rootElm, rng, startElm) {
  14611. return getParentCaption(rootElm, startElm).fold(function () {
  14612. return deleteCellRange(editor, rootElm, rng);
  14613. }, function (caption) {
  14614. return deleteCaptionRange(editor, caption);
  14615. }).getOr(false);
  14616. };
  14617. var deleteRange$2 = function (editor, startElm, selectedCells) {
  14618. var rootNode = SugarElement.fromDom(editor.getBody());
  14619. var rng = editor.selection.getRng();
  14620. return selectedCells.length !== 0 ? emptySingleTableCells(editor, selectedCells, Optional.none()) : deleteTableRange(editor, rootNode, rng, startElm);
  14621. };
  14622. var getParentCell = function (rootElm, elm) {
  14623. return find$3(parentsAndSelf(elm, rootElm), isTableCell$4);
  14624. };
  14625. var getParentCaption = function (rootElm, elm) {
  14626. return find$3(parentsAndSelf(elm, rootElm), isTag('caption'));
  14627. };
  14628. var deleteBetweenCells = function (editor, rootElm, forward, fromCell, from) {
  14629. return navigate(forward, editor.getBody(), from).bind(function (to) {
  14630. return getParentCell(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCell) {
  14631. return eq(toCell, fromCell) === false;
  14632. });
  14633. });
  14634. };
  14635. var emptyElement = function (editor, elm) {
  14636. fillWithPaddingBr(elm);
  14637. editor.selection.setCursorLocation(elm.dom, 0);
  14638. return Optional.some(true);
  14639. };
  14640. var isDeleteOfLastCharPos = function (fromCaption, forward, from, to) {
  14641. return firstPositionIn(fromCaption.dom).bind(function (first) {
  14642. return lastPositionIn(fromCaption.dom).map(function (last) {
  14643. return forward ? from.isEqual(first) && to.isEqual(last) : from.isEqual(last) && to.isEqual(first);
  14644. });
  14645. }).getOr(true);
  14646. };
  14647. var emptyCaretCaption = function (editor, elm) {
  14648. return emptyElement(editor, elm);
  14649. };
  14650. var validateCaretCaption = function (rootElm, fromCaption, to) {
  14651. return getParentCaption(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCaption) {
  14652. return eq(toCaption, fromCaption) === false;
  14653. });
  14654. };
  14655. var deleteCaretInsideCaption = function (editor, rootElm, forward, fromCaption, from) {
  14656. return navigate(forward, editor.getBody(), from).bind(function (to) {
  14657. return isDeleteOfLastCharPos(fromCaption, forward, from, to) ? emptyCaretCaption(editor, fromCaption) : validateCaretCaption(rootElm, fromCaption, to);
  14658. }).or(Optional.some(true));
  14659. };
  14660. var deleteCaretCells = function (editor, forward, rootElm, startElm) {
  14661. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  14662. return getParentCell(rootElm, startElm).bind(function (fromCell) {
  14663. return isEmpty$2(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from);
  14664. }).getOr(false);
  14665. };
  14666. var deleteCaretCaption = function (editor, forward, rootElm, fromCaption) {
  14667. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  14668. return isEmpty$2(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from);
  14669. };
  14670. var isNearTable = function (forward, pos) {
  14671. return forward ? isBeforeTable(pos) : isAfterTable(pos);
  14672. };
  14673. var isBeforeOrAfterTable = function (editor, forward) {
  14674. var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  14675. return isNearTable(forward, fromPos) || fromPosition(forward, editor.getBody(), fromPos).exists(function (pos) {
  14676. return isNearTable(forward, pos);
  14677. });
  14678. };
  14679. var deleteCaret$3 = function (editor, forward, startElm) {
  14680. var rootElm = SugarElement.fromDom(editor.getBody());
  14681. return getParentCaption(rootElm, startElm).fold(function () {
  14682. return deleteCaretCells(editor, forward, rootElm, startElm) || isBeforeOrAfterTable(editor, forward);
  14683. }, function (fromCaption) {
  14684. return deleteCaretCaption(editor, forward, rootElm, fromCaption).getOr(false);
  14685. });
  14686. };
  14687. var backspaceDelete$9 = function (editor, forward) {
  14688. var startElm = SugarElement.fromDom(editor.selection.getStart(true));
  14689. var cells = getCellsFromEditor(editor);
  14690. return editor.selection.isCollapsed() && cells.length === 0 ? deleteCaret$3(editor, forward, startElm) : deleteRange$2(editor, startElm, cells);
  14691. };
  14692. var createRange = function (sc, so, ec, eo) {
  14693. var rng = document.createRange();
  14694. rng.setStart(sc, so);
  14695. rng.setEnd(ec, eo);
  14696. return rng;
  14697. };
  14698. var normalizeBlockSelectionRange = function (rng) {
  14699. var startPos = CaretPosition.fromRangeStart(rng);
  14700. var endPos = CaretPosition.fromRangeEnd(rng);
  14701. var rootNode = rng.commonAncestorContainer;
  14702. return fromPosition(false, rootNode, endPos).map(function (newEndPos) {
  14703. if (!isInSameBlock(startPos, endPos, rootNode) && isInSameBlock(startPos, newEndPos, rootNode)) {
  14704. return createRange(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
  14705. } else {
  14706. return rng;
  14707. }
  14708. }).getOr(rng);
  14709. };
  14710. var normalize = function (rng) {
  14711. return rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
  14712. };
  14713. var hasOnlyOneChild$1 = function (node) {
  14714. return node.firstChild && node.firstChild === node.lastChild;
  14715. };
  14716. var isPaddingNode = function (node) {
  14717. return node.name === 'br' || node.value === nbsp;
  14718. };
  14719. var isPaddedEmptyBlock = function (schema, node) {
  14720. var blockElements = schema.getBlockElements();
  14721. return blockElements[node.name] && hasOnlyOneChild$1(node) && isPaddingNode(node.firstChild);
  14722. };
  14723. var isEmptyFragmentElement = function (schema, node) {
  14724. var nonEmptyElements = schema.getNonEmptyElements();
  14725. return node && (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
  14726. };
  14727. var isListFragment = function (schema, fragment) {
  14728. var firstChild = fragment.firstChild;
  14729. var lastChild = fragment.lastChild;
  14730. if (firstChild && firstChild.name === 'meta') {
  14731. firstChild = firstChild.next;
  14732. }
  14733. if (lastChild && lastChild.attr('id') === 'mce_marker') {
  14734. lastChild = lastChild.prev;
  14735. }
  14736. if (isEmptyFragmentElement(schema, lastChild)) {
  14737. lastChild = lastChild.prev;
  14738. }
  14739. if (!firstChild || firstChild !== lastChild) {
  14740. return false;
  14741. }
  14742. return firstChild.name === 'ul' || firstChild.name === 'ol';
  14743. };
  14744. var cleanupDomFragment = function (domFragment) {
  14745. var firstChild = domFragment.firstChild;
  14746. var lastChild = domFragment.lastChild;
  14747. if (firstChild && firstChild.nodeName === 'META') {
  14748. firstChild.parentNode.removeChild(firstChild);
  14749. }
  14750. if (lastChild && lastChild.id === 'mce_marker') {
  14751. lastChild.parentNode.removeChild(lastChild);
  14752. }
  14753. return domFragment;
  14754. };
  14755. var toDomFragment = function (dom, serializer, fragment) {
  14756. var html = serializer.serialize(fragment);
  14757. var domFragment = dom.createFragment(html);
  14758. return cleanupDomFragment(domFragment);
  14759. };
  14760. var listItems = function (elm) {
  14761. return filter$4(elm.childNodes, function (child) {
  14762. return child.nodeName === 'LI';
  14763. });
  14764. };
  14765. var isPadding = function (node) {
  14766. return node.data === nbsp || isBr$5(node);
  14767. };
  14768. var isListItemPadded = function (node) {
  14769. return node && node.firstChild && node.firstChild === node.lastChild && isPadding(node.firstChild);
  14770. };
  14771. var isEmptyOrPadded = function (elm) {
  14772. return !elm.firstChild || isListItemPadded(elm);
  14773. };
  14774. var trimListItems = function (elms) {
  14775. return elms.length > 0 && isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
  14776. };
  14777. var getParentLi = function (dom, node) {
  14778. var parentBlock = dom.getParent(node, dom.isBlock);
  14779. return parentBlock && parentBlock.nodeName === 'LI' ? parentBlock : null;
  14780. };
  14781. var isParentBlockLi = function (dom, node) {
  14782. return !!getParentLi(dom, node);
  14783. };
  14784. var getSplit = function (parentNode, rng) {
  14785. var beforeRng = rng.cloneRange();
  14786. var afterRng = rng.cloneRange();
  14787. beforeRng.setStartBefore(parentNode);
  14788. afterRng.setEndAfter(parentNode);
  14789. return [
  14790. beforeRng.cloneContents(),
  14791. afterRng.cloneContents()
  14792. ];
  14793. };
  14794. var findFirstIn = function (node, rootNode) {
  14795. var caretPos = CaretPosition.before(node);
  14796. var caretWalker = CaretWalker(rootNode);
  14797. var newCaretPos = caretWalker.next(caretPos);
  14798. return newCaretPos ? newCaretPos.toRange() : null;
  14799. };
  14800. var findLastOf = function (node, rootNode) {
  14801. var caretPos = CaretPosition.after(node);
  14802. var caretWalker = CaretWalker(rootNode);
  14803. var newCaretPos = caretWalker.prev(caretPos);
  14804. return newCaretPos ? newCaretPos.toRange() : null;
  14805. };
  14806. var insertMiddle = function (target, elms, rootNode, rng) {
  14807. var parts = getSplit(target, rng);
  14808. var parentElm = target.parentNode;
  14809. parentElm.insertBefore(parts[0], target);
  14810. Tools.each(elms, function (li) {
  14811. parentElm.insertBefore(li, target);
  14812. });
  14813. parentElm.insertBefore(parts[1], target);
  14814. parentElm.removeChild(target);
  14815. return findLastOf(elms[elms.length - 1], rootNode);
  14816. };
  14817. var insertBefore$1 = function (target, elms, rootNode) {
  14818. var parentElm = target.parentNode;
  14819. Tools.each(elms, function (elm) {
  14820. parentElm.insertBefore(elm, target);
  14821. });
  14822. return findFirstIn(target, rootNode);
  14823. };
  14824. var insertAfter$1 = function (target, elms, rootNode, dom) {
  14825. dom.insertAfter(elms.reverse(), target);
  14826. return findLastOf(elms[0], rootNode);
  14827. };
  14828. var insertAtCaret$1 = function (serializer, dom, rng, fragment) {
  14829. var domFragment = toDomFragment(dom, serializer, fragment);
  14830. var liTarget = getParentLi(dom, rng.startContainer);
  14831. var liElms = trimListItems(listItems(domFragment.firstChild));
  14832. var BEGINNING = 1, END = 2;
  14833. var rootNode = dom.getRoot();
  14834. var isAt = function (location) {
  14835. var caretPos = CaretPosition.fromRangeStart(rng);
  14836. var caretWalker = CaretWalker(dom.getRoot());
  14837. var newPos = location === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
  14838. return newPos ? getParentLi(dom, newPos.getNode()) !== liTarget : true;
  14839. };
  14840. if (isAt(BEGINNING)) {
  14841. return insertBefore$1(liTarget, liElms, rootNode);
  14842. } else if (isAt(END)) {
  14843. return insertAfter$1(liTarget, liElms, rootNode, dom);
  14844. }
  14845. return insertMiddle(liTarget, liElms, rootNode, rng);
  14846. };
  14847. var trimOrPadLeftRight = function (dom, rng, html) {
  14848. var root = SugarElement.fromDom(dom.getRoot());
  14849. if (needsToBeNbspLeft(root, CaretPosition.fromRangeStart(rng))) {
  14850. html = html.replace(/^ /, '&nbsp;');
  14851. } else {
  14852. html = html.replace(/^&nbsp;/, ' ');
  14853. }
  14854. if (needsToBeNbspRight(root, CaretPosition.fromRangeEnd(rng))) {
  14855. html = html.replace(/(&nbsp;| )(<br( \/)>)?$/, '&nbsp;');
  14856. } else {
  14857. html = html.replace(/&nbsp;(<br( \/)?>)?$/, ' ');
  14858. }
  14859. return html;
  14860. };
  14861. var isTableCell$1 = isTableCell$5;
  14862. var isTableCellContentSelected = function (dom, rng, cell) {
  14863. if (cell !== null) {
  14864. var endCell = dom.getParent(rng.endContainer, isTableCell$1);
  14865. return cell === endCell && hasAllContentsSelected(SugarElement.fromDom(cell), rng);
  14866. } else {
  14867. return false;
  14868. }
  14869. };
  14870. var validInsertion = function (editor, value, parentNode) {
  14871. if (parentNode.getAttribute('data-mce-bogus') === 'all') {
  14872. parentNode.parentNode.insertBefore(editor.dom.createFragment(value), parentNode);
  14873. } else {
  14874. var node = parentNode.firstChild;
  14875. var node2 = parentNode.lastChild;
  14876. if (!node || node === node2 && node.nodeName === 'BR') {
  14877. editor.dom.setHTML(parentNode, value);
  14878. } else {
  14879. editor.selection.setContent(value);
  14880. }
  14881. }
  14882. };
  14883. var trimBrsFromTableCell = function (dom, elm) {
  14884. Optional.from(dom.getParent(elm, 'td,th')).map(SugarElement.fromDom).each(trimBlockTrailingBr);
  14885. };
  14886. var reduceInlineTextElements = function (editor, merge) {
  14887. var textInlineElements = editor.schema.getTextInlineElements();
  14888. var dom = editor.dom;
  14889. if (merge) {
  14890. var root_1 = editor.getBody();
  14891. var elementUtils_1 = ElementUtils(dom);
  14892. Tools.each(dom.select('*[data-mce-fragment]'), function (node) {
  14893. var isInline = isNonNullable(textInlineElements[node.nodeName.toLowerCase()]);
  14894. if (isInline && hasInheritableStyles(dom, node)) {
  14895. for (var parentNode = node.parentNode; isNonNullable(parentNode) && parentNode !== root_1; parentNode = parentNode.parentNode) {
  14896. var styleConflict = hasStyleConflict(dom, node, parentNode);
  14897. if (styleConflict) {
  14898. break;
  14899. }
  14900. if (elementUtils_1.compare(parentNode, node)) {
  14901. dom.remove(node, true);
  14902. break;
  14903. }
  14904. }
  14905. }
  14906. });
  14907. }
  14908. };
  14909. var markFragmentElements = function (fragment) {
  14910. var node = fragment;
  14911. while (node = node.walk()) {
  14912. if (node.type === 1) {
  14913. node.attr('data-mce-fragment', '1');
  14914. }
  14915. }
  14916. };
  14917. var unmarkFragmentElements = function (elm) {
  14918. Tools.each(elm.getElementsByTagName('*'), function (elm) {
  14919. elm.removeAttribute('data-mce-fragment');
  14920. });
  14921. };
  14922. var isPartOfFragment = function (node) {
  14923. return !!node.getAttribute('data-mce-fragment');
  14924. };
  14925. var canHaveChildren = function (editor, node) {
  14926. return node && !editor.schema.getShortEndedElements()[node.nodeName];
  14927. };
  14928. var moveSelectionToMarker = function (editor, marker) {
  14929. var nextRng;
  14930. var dom = editor.dom;
  14931. var selection = editor.selection;
  14932. if (!marker) {
  14933. return;
  14934. }
  14935. selection.scrollIntoView(marker);
  14936. var parentEditableElm = getContentEditableRoot$1(editor.getBody(), marker);
  14937. if (dom.getContentEditable(parentEditableElm) === 'false') {
  14938. dom.remove(marker);
  14939. selection.select(parentEditableElm);
  14940. return;
  14941. }
  14942. var rng = dom.createRng();
  14943. var node = marker.previousSibling;
  14944. if (isText$7(node)) {
  14945. rng.setStart(node, node.nodeValue.length);
  14946. if (!Env.ie) {
  14947. var node2 = marker.nextSibling;
  14948. if (isText$7(node2)) {
  14949. node.appendData(node2.data);
  14950. node2.parentNode.removeChild(node2);
  14951. }
  14952. }
  14953. } else {
  14954. rng.setStartBefore(marker);
  14955. rng.setEndBefore(marker);
  14956. }
  14957. var findNextCaretRng = function (rng) {
  14958. var caretPos = CaretPosition.fromRangeStart(rng);
  14959. var caretWalker = CaretWalker(editor.getBody());
  14960. caretPos = caretWalker.next(caretPos);
  14961. if (caretPos) {
  14962. return caretPos.toRange();
  14963. }
  14964. };
  14965. var parentBlock = dom.getParent(marker, dom.isBlock);
  14966. dom.remove(marker);
  14967. if (parentBlock && dom.isEmpty(parentBlock)) {
  14968. editor.$(parentBlock).empty();
  14969. rng.setStart(parentBlock, 0);
  14970. rng.setEnd(parentBlock, 0);
  14971. if (!isTableCell$1(parentBlock) && !isPartOfFragment(parentBlock) && (nextRng = findNextCaretRng(rng))) {
  14972. rng = nextRng;
  14973. dom.remove(parentBlock);
  14974. } else {
  14975. dom.add(parentBlock, dom.create('br', { 'data-mce-bogus': '1' }));
  14976. }
  14977. }
  14978. selection.setRng(rng);
  14979. };
  14980. var deleteSelectedContent = function (editor) {
  14981. var dom = editor.dom;
  14982. var rng = normalize(editor.selection.getRng());
  14983. editor.selection.setRng(rng);
  14984. var startCell = dom.getParent(rng.startContainer, isTableCell$1);
  14985. if (isTableCellContentSelected(dom, rng, startCell)) {
  14986. deleteCellContents(editor, rng, SugarElement.fromDom(startCell));
  14987. } else {
  14988. editor.getDoc().execCommand('Delete', false, null);
  14989. }
  14990. };
  14991. var insertHtmlAtCaret = function (editor, value, details) {
  14992. var parentNode;
  14993. var rng, node;
  14994. var selection = editor.selection;
  14995. var dom = editor.dom;
  14996. if (/^ | $/.test(value)) {
  14997. value = trimOrPadLeftRight(dom, selection.getRng(), value);
  14998. }
  14999. var parser = editor.parser;
  15000. var merge = details.merge;
  15001. var serializer = HtmlSerializer({ validate: shouldValidate(editor) }, editor.schema);
  15002. var bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>';
  15003. var args = editor.fire('BeforeSetContent', {
  15004. content: value,
  15005. format: 'html',
  15006. selection: true,
  15007. paste: details.paste
  15008. });
  15009. if (args.isDefaultPrevented()) {
  15010. editor.fire('SetContent', {
  15011. content: args.content,
  15012. format: 'html',
  15013. selection: true,
  15014. paste: details.paste
  15015. });
  15016. return;
  15017. }
  15018. value = args.content;
  15019. if (value.indexOf('{$caret}') === -1) {
  15020. value += '{$caret}';
  15021. }
  15022. value = value.replace(/\{\$caret\}/, bookmarkHtml);
  15023. rng = selection.getRng();
  15024. var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
  15025. var body = editor.getBody();
  15026. if (caretElement === body && selection.isCollapsed()) {
  15027. if (dom.isBlock(body.firstChild) && canHaveChildren(editor, body.firstChild) && dom.isEmpty(body.firstChild)) {
  15028. rng = dom.createRng();
  15029. rng.setStart(body.firstChild, 0);
  15030. rng.setEnd(body.firstChild, 0);
  15031. selection.setRng(rng);
  15032. }
  15033. }
  15034. if (!selection.isCollapsed()) {
  15035. deleteSelectedContent(editor);
  15036. }
  15037. parentNode = selection.getNode();
  15038. var parserArgs = {
  15039. context: parentNode.nodeName.toLowerCase(),
  15040. data: details.data,
  15041. insert: true
  15042. };
  15043. var fragment = parser.parse(value, parserArgs);
  15044. if (details.paste === true && isListFragment(editor.schema, fragment) && isParentBlockLi(dom, parentNode)) {
  15045. rng = insertAtCaret$1(serializer, dom, selection.getRng(), fragment);
  15046. selection.setRng(rng);
  15047. editor.fire('SetContent', args);
  15048. return;
  15049. }
  15050. markFragmentElements(fragment);
  15051. node = fragment.lastChild;
  15052. if (node.attr('id') === 'mce_marker') {
  15053. var marker = node;
  15054. for (node = node.prev; node; node = node.walk(true)) {
  15055. if (node.type === 3 || !dom.isBlock(node.name)) {
  15056. if (editor.schema.isValidChild(node.parent.name, 'span')) {
  15057. node.parent.insert(marker, node, node.name === 'br');
  15058. }
  15059. break;
  15060. }
  15061. }
  15062. }
  15063. editor._selectionOverrides.showBlockCaretContainer(parentNode);
  15064. if (!parserArgs.invalid) {
  15065. value = serializer.serialize(fragment);
  15066. validInsertion(editor, value, parentNode);
  15067. } else {
  15068. editor.selection.setContent(bookmarkHtml);
  15069. parentNode = selection.getNode();
  15070. var rootNode = editor.getBody();
  15071. if (parentNode.nodeType === 9) {
  15072. parentNode = node = rootNode;
  15073. } else {
  15074. node = parentNode;
  15075. }
  15076. while (node !== rootNode) {
  15077. parentNode = node;
  15078. node = node.parentNode;
  15079. }
  15080. value = parentNode === rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
  15081. value = serializer.serialize(parser.parse(value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function () {
  15082. return serializer.serialize(fragment);
  15083. })));
  15084. if (parentNode === rootNode) {
  15085. dom.setHTML(rootNode, value);
  15086. } else {
  15087. dom.setOuterHTML(parentNode, value);
  15088. }
  15089. }
  15090. reduceInlineTextElements(editor, merge);
  15091. moveSelectionToMarker(editor, dom.get('mce_marker'));
  15092. unmarkFragmentElements(editor.getBody());
  15093. trimBrsFromTableCell(dom, selection.getStart());
  15094. editor.fire('SetContent', args);
  15095. editor.addVisual();
  15096. };
  15097. var traverse = function (node, fn) {
  15098. fn(node);
  15099. if (node.firstChild) {
  15100. traverse(node.firstChild, fn);
  15101. }
  15102. if (node.next) {
  15103. traverse(node.next, fn);
  15104. }
  15105. };
  15106. var findMatchingNodes = function (nodeFilters, attributeFilters, node) {
  15107. var nodeMatches = {};
  15108. var attrMatches = {};
  15109. var matches = [];
  15110. if (node.firstChild) {
  15111. traverse(node.firstChild, function (node) {
  15112. each$k(nodeFilters, function (filter) {
  15113. if (filter.name === node.name) {
  15114. if (nodeMatches[filter.name]) {
  15115. nodeMatches[filter.name].nodes.push(node);
  15116. } else {
  15117. nodeMatches[filter.name] = {
  15118. filter: filter,
  15119. nodes: [node]
  15120. };
  15121. }
  15122. }
  15123. });
  15124. each$k(attributeFilters, function (filter) {
  15125. if (typeof node.attr(filter.name) === 'string') {
  15126. if (attrMatches[filter.name]) {
  15127. attrMatches[filter.name].nodes.push(node);
  15128. } else {
  15129. attrMatches[filter.name] = {
  15130. filter: filter,
  15131. nodes: [node]
  15132. };
  15133. }
  15134. }
  15135. });
  15136. });
  15137. }
  15138. for (var name_1 in nodeMatches) {
  15139. if (has$2(nodeMatches, name_1)) {
  15140. matches.push(nodeMatches[name_1]);
  15141. }
  15142. }
  15143. for (var name_2 in attrMatches) {
  15144. if (has$2(attrMatches, name_2)) {
  15145. matches.push(attrMatches[name_2]);
  15146. }
  15147. }
  15148. return matches;
  15149. };
  15150. var filter$1 = function (nodeFilters, attributeFilters, node) {
  15151. var matches = findMatchingNodes(nodeFilters, attributeFilters, node);
  15152. each$k(matches, function (match) {
  15153. each$k(match.filter.callbacks, function (callback) {
  15154. callback(match.nodes, match.filter.name, {});
  15155. });
  15156. });
  15157. };
  15158. var defaultFormat$1 = 'html';
  15159. var isTreeNode = function (content) {
  15160. return content instanceof AstNode;
  15161. };
  15162. var moveSelection = function (editor) {
  15163. if (hasFocus(editor)) {
  15164. firstPositionIn(editor.getBody()).each(function (pos) {
  15165. var node = pos.getNode();
  15166. var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  15167. editor.selection.setRng(caretPos.toRange());
  15168. });
  15169. }
  15170. };
  15171. var setEditorHtml = function (editor, html, noSelection) {
  15172. editor.dom.setHTML(editor.getBody(), html);
  15173. if (noSelection !== true) {
  15174. moveSelection(editor);
  15175. }
  15176. };
  15177. var setContentString = function (editor, body, content, args) {
  15178. if (content.length === 0 || /^\s+$/.test(content)) {
  15179. var padd = '<br data-mce-bogus="1">';
  15180. if (body.nodeName === 'TABLE') {
  15181. content = '<tr><td>' + padd + '</td></tr>';
  15182. } else if (/^(UL|OL)$/.test(body.nodeName)) {
  15183. content = '<li>' + padd + '</li>';
  15184. }
  15185. var forcedRootBlockName = getForcedRootBlock(editor);
  15186. if (forcedRootBlockName && editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
  15187. content = padd;
  15188. content = editor.dom.createHTML(forcedRootBlockName, getForcedRootBlockAttrs(editor), content);
  15189. } else if (!content) {
  15190. content = '<br data-mce-bogus="1">';
  15191. }
  15192. setEditorHtml(editor, content, args.no_selection);
  15193. editor.fire('SetContent', args);
  15194. } else {
  15195. if (args.format !== 'raw') {
  15196. content = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(editor.parser.parse(content, {
  15197. isRootContent: true,
  15198. insert: true
  15199. }));
  15200. }
  15201. args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? content : Tools.trim(content);
  15202. setEditorHtml(editor, args.content, args.no_selection);
  15203. if (!args.no_events) {
  15204. editor.fire('SetContent', args);
  15205. }
  15206. }
  15207. return args.content;
  15208. };
  15209. var setContentTree = function (editor, body, content, args) {
  15210. filter$1(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
  15211. var html = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(content);
  15212. args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? html : Tools.trim(html);
  15213. setEditorHtml(editor, args.content, args.no_selection);
  15214. if (!args.no_events) {
  15215. editor.fire('SetContent', args);
  15216. }
  15217. return content;
  15218. };
  15219. var setupArgs$2 = function (args, content) {
  15220. return __assign(__assign({ format: defaultFormat$1 }, args), {
  15221. set: true,
  15222. content: isTreeNode(content) ? '' : content
  15223. });
  15224. };
  15225. var setContentInternal = function (editor, content, args) {
  15226. var defaultedArgs = setupArgs$2(args, content);
  15227. var updatedArgs = args.no_events ? defaultedArgs : editor.fire('BeforeSetContent', defaultedArgs);
  15228. if (!isTreeNode(content)) {
  15229. content = updatedArgs.content;
  15230. }
  15231. return Optional.from(editor.getBody()).fold(constant(content), function (body) {
  15232. return isTreeNode(content) ? setContentTree(editor, body, content, updatedArgs) : setContentString(editor, body, content, updatedArgs);
  15233. });
  15234. };
  15235. var sibling = function (scope, predicate) {
  15236. return sibling$2(scope, predicate).isSome();
  15237. };
  15238. var ensureIsRoot = function (isRoot) {
  15239. return isFunction(isRoot) ? isRoot : never;
  15240. };
  15241. var ancestor = function (scope, transform, isRoot) {
  15242. var element = scope.dom;
  15243. var stop = ensureIsRoot(isRoot);
  15244. while (element.parentNode) {
  15245. element = element.parentNode;
  15246. var el = SugarElement.fromDom(element);
  15247. var transformed = transform(el);
  15248. if (transformed.isSome()) {
  15249. return transformed;
  15250. } else if (stop(el)) {
  15251. break;
  15252. }
  15253. }
  15254. return Optional.none();
  15255. };
  15256. var closest$1 = function (scope, transform, isRoot) {
  15257. var current = transform(scope);
  15258. var stop = ensureIsRoot(isRoot);
  15259. return current.orThunk(function () {
  15260. return stop(scope) ? Optional.none() : ancestor(scope, transform, stop);
  15261. });
  15262. };
  15263. var isEq$3 = isEq$5;
  15264. var matchesUnInheritedFormatSelector = function (ed, node, name) {
  15265. var formatList = ed.formatter.get(name);
  15266. if (formatList) {
  15267. for (var i = 0; i < formatList.length; i++) {
  15268. var format = formatList[i];
  15269. if (isSelectorFormat(format) && format.inherit === false && ed.dom.is(node, format.selector)) {
  15270. return true;
  15271. }
  15272. }
  15273. }
  15274. return false;
  15275. };
  15276. var matchParents = function (editor, node, name, vars, similar) {
  15277. var root = editor.dom.getRoot();
  15278. if (node === root) {
  15279. return false;
  15280. }
  15281. node = editor.dom.getParent(node, function (node) {
  15282. if (matchesUnInheritedFormatSelector(editor, node, name)) {
  15283. return true;
  15284. }
  15285. return node.parentNode === root || !!matchNode(editor, node, name, vars, true);
  15286. });
  15287. return !!matchNode(editor, node, name, vars, similar);
  15288. };
  15289. var matchName$1 = function (dom, node, format) {
  15290. if (isEq$3(node, format.inline)) {
  15291. return true;
  15292. }
  15293. if (isEq$3(node, format.block)) {
  15294. return true;
  15295. }
  15296. if (format.selector) {
  15297. return node.nodeType === 1 && dom.is(node, format.selector);
  15298. }
  15299. };
  15300. var matchItems = function (dom, node, format, itemName, similar, vars) {
  15301. var items = format[itemName];
  15302. if (isFunction(format.onmatch)) {
  15303. return format.onmatch(node, format, itemName);
  15304. }
  15305. if (items) {
  15306. if (isUndefined(items.length)) {
  15307. for (var key in items) {
  15308. if (has$2(items, key)) {
  15309. var value = itemName === 'attributes' ? dom.getAttrib(node, key) : getStyle(dom, node, key);
  15310. var expectedValue = replaceVars(items[key], vars);
  15311. var isEmptyValue = isNullable(value) || isEmpty$3(value);
  15312. if (isEmptyValue && isNullable(expectedValue)) {
  15313. continue;
  15314. }
  15315. if (similar && isEmptyValue && !format.exact) {
  15316. return false;
  15317. }
  15318. if ((!similar || format.exact) && !isEq$3(value, normalizeStyleValue(dom, expectedValue, key))) {
  15319. return false;
  15320. }
  15321. }
  15322. }
  15323. } else {
  15324. for (var i = 0; i < items.length; i++) {
  15325. if (itemName === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(dom, node, items[i])) {
  15326. return true;
  15327. }
  15328. }
  15329. }
  15330. }
  15331. return true;
  15332. };
  15333. var matchNode = function (ed, node, name, vars, similar) {
  15334. var formatList = ed.formatter.get(name);
  15335. var dom = ed.dom;
  15336. if (formatList && node) {
  15337. for (var i = 0; i < formatList.length; i++) {
  15338. var format = formatList[i];
  15339. if (matchName$1(ed.dom, node, format) && matchItems(dom, node, format, 'attributes', similar, vars) && matchItems(dom, node, format, 'styles', similar, vars)) {
  15340. var classes = format.classes;
  15341. if (classes) {
  15342. for (var x = 0; x < classes.length; x++) {
  15343. if (!ed.dom.hasClass(node, replaceVars(classes[x], vars))) {
  15344. return;
  15345. }
  15346. }
  15347. }
  15348. return format;
  15349. }
  15350. }
  15351. }
  15352. };
  15353. var match$2 = function (editor, name, vars, node, similar) {
  15354. if (node) {
  15355. return matchParents(editor, node, name, vars, similar);
  15356. }
  15357. node = editor.selection.getNode();
  15358. if (matchParents(editor, node, name, vars, similar)) {
  15359. return true;
  15360. }
  15361. var startNode = editor.selection.getStart();
  15362. if (startNode !== node) {
  15363. if (matchParents(editor, startNode, name, vars, similar)) {
  15364. return true;
  15365. }
  15366. }
  15367. return false;
  15368. };
  15369. var matchAll = function (editor, names, vars) {
  15370. var matchedFormatNames = [];
  15371. var checkedMap = {};
  15372. var startElement = editor.selection.getStart();
  15373. editor.dom.getParent(startElement, function (node) {
  15374. for (var i = 0; i < names.length; i++) {
  15375. var name_1 = names[i];
  15376. if (!checkedMap[name_1] && matchNode(editor, node, name_1, vars)) {
  15377. checkedMap[name_1] = true;
  15378. matchedFormatNames.push(name_1);
  15379. }
  15380. }
  15381. }, editor.dom.getRoot());
  15382. return matchedFormatNames;
  15383. };
  15384. var closest = function (editor, names) {
  15385. var isRoot = function (elm) {
  15386. return eq(elm, SugarElement.fromDom(editor.getBody()));
  15387. };
  15388. var match = function (elm, name) {
  15389. return matchNode(editor, elm.dom, name) ? Optional.some(name) : Optional.none();
  15390. };
  15391. return Optional.from(editor.selection.getStart(true)).bind(function (rawElm) {
  15392. return closest$1(SugarElement.fromDom(rawElm), function (elm) {
  15393. return findMap(names, function (name) {
  15394. return match(elm, name);
  15395. });
  15396. }, isRoot);
  15397. }).getOrNull();
  15398. };
  15399. var canApply = function (editor, name) {
  15400. var formatList = editor.formatter.get(name);
  15401. var dom = editor.dom;
  15402. if (formatList) {
  15403. var startNode = editor.selection.getStart();
  15404. var parents = getParents$2(dom, startNode);
  15405. for (var x = formatList.length - 1; x >= 0; x--) {
  15406. var format = formatList[x];
  15407. if (!isSelectorFormat(format) || isNonNullable(format.defaultBlock)) {
  15408. return true;
  15409. }
  15410. for (var i = parents.length - 1; i >= 0; i--) {
  15411. if (dom.is(parents[i], format.selector)) {
  15412. return true;
  15413. }
  15414. }
  15415. }
  15416. }
  15417. return false;
  15418. };
  15419. var matchAllOnNode = function (editor, node, formatNames) {
  15420. return foldl(formatNames, function (acc, name) {
  15421. var matchSimilar = isVariableFormatName(editor, name);
  15422. if (editor.formatter.matchNode(node, name, {}, matchSimilar)) {
  15423. return acc.concat([name]);
  15424. } else {
  15425. return acc;
  15426. }
  15427. }, []);
  15428. };
  15429. var ZWSP = ZWSP$1, CARET_ID = '_mce_caret';
  15430. var importNode = function (ownerDocument, node) {
  15431. return ownerDocument.importNode(node, true);
  15432. };
  15433. var getEmptyCaretContainers = function (node) {
  15434. var nodes = [];
  15435. while (node) {
  15436. if (node.nodeType === 3 && node.nodeValue !== ZWSP || node.childNodes.length > 1) {
  15437. return [];
  15438. }
  15439. if (node.nodeType === 1) {
  15440. nodes.push(node);
  15441. }
  15442. node = node.firstChild;
  15443. }
  15444. return nodes;
  15445. };
  15446. var isCaretContainerEmpty = function (node) {
  15447. return getEmptyCaretContainers(node).length > 0;
  15448. };
  15449. var findFirstTextNode = function (node) {
  15450. if (node) {
  15451. var walker = new DomTreeWalker(node, node);
  15452. for (node = walker.current(); node; node = walker.next()) {
  15453. if (isText$7(node)) {
  15454. return node;
  15455. }
  15456. }
  15457. }
  15458. return null;
  15459. };
  15460. var createCaretContainer = function (fill) {
  15461. var caretContainer = SugarElement.fromTag('span');
  15462. setAll$1(caretContainer, {
  15463. 'id': CARET_ID,
  15464. 'data-mce-bogus': '1',
  15465. 'data-mce-type': 'format-caret'
  15466. });
  15467. if (fill) {
  15468. append$1(caretContainer, SugarElement.fromText(ZWSP));
  15469. }
  15470. return caretContainer;
  15471. };
  15472. var trimZwspFromCaretContainer = function (caretContainerNode) {
  15473. var textNode = findFirstTextNode(caretContainerNode);
  15474. if (textNode && textNode.nodeValue.charAt(0) === ZWSP) {
  15475. textNode.deleteData(0, 1);
  15476. }
  15477. return textNode;
  15478. };
  15479. var removeCaretContainerNode = function (editor, node, moveCaret) {
  15480. if (moveCaret === void 0) {
  15481. moveCaret = true;
  15482. }
  15483. var dom = editor.dom, selection = editor.selection;
  15484. if (isCaretContainerEmpty(node)) {
  15485. deleteElement$2(editor, false, SugarElement.fromDom(node), moveCaret);
  15486. } else {
  15487. var rng = selection.getRng();
  15488. var block = dom.getParent(node, dom.isBlock);
  15489. var startContainer = rng.startContainer;
  15490. var startOffset = rng.startOffset;
  15491. var endContainer = rng.endContainer;
  15492. var endOffset = rng.endOffset;
  15493. var textNode = trimZwspFromCaretContainer(node);
  15494. dom.remove(node, true);
  15495. if (startContainer === textNode && startOffset > 0) {
  15496. rng.setStart(textNode, startOffset - 1);
  15497. }
  15498. if (endContainer === textNode && endOffset > 0) {
  15499. rng.setEnd(textNode, endOffset - 1);
  15500. }
  15501. if (block && dom.isEmpty(block)) {
  15502. fillWithPaddingBr(SugarElement.fromDom(block));
  15503. }
  15504. selection.setRng(rng);
  15505. }
  15506. };
  15507. var removeCaretContainer = function (editor, node, moveCaret) {
  15508. if (moveCaret === void 0) {
  15509. moveCaret = true;
  15510. }
  15511. var dom = editor.dom, selection = editor.selection;
  15512. if (!node) {
  15513. node = getParentCaretContainer(editor.getBody(), selection.getStart());
  15514. if (!node) {
  15515. while (node = dom.get(CARET_ID)) {
  15516. removeCaretContainerNode(editor, node, false);
  15517. }
  15518. }
  15519. } else {
  15520. removeCaretContainerNode(editor, node, moveCaret);
  15521. }
  15522. };
  15523. var insertCaretContainerNode = function (editor, caretContainer, formatNode) {
  15524. var dom = editor.dom, block = dom.getParent(formatNode, curry(isTextBlock$1, editor));
  15525. if (block && dom.isEmpty(block)) {
  15526. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15527. } else {
  15528. removeTrailingBr(SugarElement.fromDom(formatNode));
  15529. if (dom.isEmpty(formatNode)) {
  15530. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15531. } else {
  15532. dom.insertAfter(caretContainer, formatNode);
  15533. }
  15534. }
  15535. };
  15536. var appendNode = function (parentNode, node) {
  15537. parentNode.appendChild(node);
  15538. return node;
  15539. };
  15540. var insertFormatNodesIntoCaretContainer = function (formatNodes, caretContainer) {
  15541. var innerMostFormatNode = foldr(formatNodes, function (parentNode, formatNode) {
  15542. return appendNode(parentNode, formatNode.cloneNode(false));
  15543. }, caretContainer);
  15544. return appendNode(innerMostFormatNode, innerMostFormatNode.ownerDocument.createTextNode(ZWSP));
  15545. };
  15546. var cleanFormatNode = function (editor, caretContainer, formatNode, name, vars, similar) {
  15547. var formatter = editor.formatter;
  15548. var dom = editor.dom;
  15549. var validFormats = filter$4(keys(formatter.get()), function (formatName) {
  15550. return formatName !== name && !contains$2(formatName, 'removeformat');
  15551. });
  15552. var matchedFormats = matchAllOnNode(editor, formatNode, validFormats);
  15553. var uniqueFormats = filter$4(matchedFormats, function (fmtName) {
  15554. return !areSimilarFormats(editor, fmtName, name);
  15555. });
  15556. if (uniqueFormats.length > 0) {
  15557. var clonedFormatNode = formatNode.cloneNode(false);
  15558. dom.add(caretContainer, clonedFormatNode);
  15559. formatter.remove(name, vars, clonedFormatNode, similar);
  15560. dom.remove(clonedFormatNode);
  15561. return Optional.some(clonedFormatNode);
  15562. } else {
  15563. return Optional.none();
  15564. }
  15565. };
  15566. var applyCaretFormat = function (editor, name, vars) {
  15567. var caretContainer, textNode;
  15568. var selection = editor.selection;
  15569. var selectionRng = selection.getRng();
  15570. var offset = selectionRng.startOffset;
  15571. var container = selectionRng.startContainer;
  15572. var text = container.nodeValue;
  15573. caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
  15574. if (caretContainer) {
  15575. textNode = findFirstTextNode(caretContainer);
  15576. }
  15577. var wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
  15578. if (text && offset > 0 && offset < text.length && wordcharRegex.test(text.charAt(offset)) && wordcharRegex.test(text.charAt(offset - 1))) {
  15579. var bookmark = selection.getBookmark();
  15580. selectionRng.collapse(true);
  15581. var rng = expandRng(editor, selectionRng, editor.formatter.get(name));
  15582. rng = split(rng);
  15583. editor.formatter.apply(name, vars, rng);
  15584. selection.moveToBookmark(bookmark);
  15585. } else {
  15586. if (!caretContainer || textNode.nodeValue !== ZWSP) {
  15587. caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom);
  15588. textNode = caretContainer.firstChild;
  15589. selectionRng.insertNode(caretContainer);
  15590. offset = 1;
  15591. editor.formatter.apply(name, vars, caretContainer);
  15592. } else {
  15593. editor.formatter.apply(name, vars, caretContainer);
  15594. }
  15595. selection.setCursorLocation(textNode, offset);
  15596. }
  15597. };
  15598. var removeCaretFormat = function (editor, name, vars, similar) {
  15599. var dom = editor.dom;
  15600. var selection = editor.selection;
  15601. var hasContentAfter, node, formatNode;
  15602. var parents = [];
  15603. var rng = selection.getRng();
  15604. var container = rng.startContainer;
  15605. var offset = rng.startOffset;
  15606. node = container;
  15607. if (container.nodeType === 3) {
  15608. if (offset !== container.nodeValue.length) {
  15609. hasContentAfter = true;
  15610. }
  15611. node = node.parentNode;
  15612. }
  15613. while (node) {
  15614. if (matchNode(editor, node, name, vars, similar)) {
  15615. formatNode = node;
  15616. break;
  15617. }
  15618. if (node.nextSibling) {
  15619. hasContentAfter = true;
  15620. }
  15621. parents.push(node);
  15622. node = node.parentNode;
  15623. }
  15624. if (!formatNode) {
  15625. return;
  15626. }
  15627. if (hasContentAfter) {
  15628. var bookmark = selection.getBookmark();
  15629. rng.collapse(true);
  15630. var expandedRng = expandRng(editor, rng, editor.formatter.get(name), true);
  15631. expandedRng = split(expandedRng);
  15632. editor.formatter.remove(name, vars, expandedRng, similar);
  15633. selection.moveToBookmark(bookmark);
  15634. } else {
  15635. var caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
  15636. var newCaretContainer = createCaretContainer(false).dom;
  15637. insertCaretContainerNode(editor, newCaretContainer, caretContainer !== null ? caretContainer : formatNode);
  15638. var cleanedFormatNode = cleanFormatNode(editor, newCaretContainer, formatNode, name, vars, similar);
  15639. var caretTextNode = insertFormatNodesIntoCaretContainer(parents.concat(cleanedFormatNode.toArray()), newCaretContainer);
  15640. removeCaretContainerNode(editor, caretContainer, false);
  15641. selection.setCursorLocation(caretTextNode, 1);
  15642. if (dom.isEmpty(formatNode)) {
  15643. dom.remove(formatNode);
  15644. }
  15645. }
  15646. };
  15647. var disableCaretContainer = function (editor, keyCode) {
  15648. var selection = editor.selection, body = editor.getBody();
  15649. removeCaretContainer(editor, null, false);
  15650. if ((keyCode === 8 || keyCode === 46) && selection.isCollapsed() && selection.getStart().innerHTML === ZWSP) {
  15651. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15652. }
  15653. if (keyCode === 37 || keyCode === 39) {
  15654. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15655. }
  15656. };
  15657. var setup$k = function (editor) {
  15658. editor.on('mouseup keydown', function (e) {
  15659. disableCaretContainer(editor, e.keyCode);
  15660. });
  15661. };
  15662. var replaceWithCaretFormat = function (targetNode, formatNodes) {
  15663. var caretContainer = createCaretContainer(false);
  15664. var innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom);
  15665. before$4(SugarElement.fromDom(targetNode), caretContainer);
  15666. remove$7(SugarElement.fromDom(targetNode));
  15667. return CaretPosition(innerMost, 0);
  15668. };
  15669. var isFormatElement = function (editor, element) {
  15670. var inlineElements = editor.schema.getTextInlineElements();
  15671. return has$2(inlineElements, name(element)) && !isCaretNode(element.dom) && !isBogus$2(element.dom);
  15672. };
  15673. var isEmptyCaretFormatElement = function (element) {
  15674. return isCaretNode(element.dom) && isCaretContainerEmpty(element.dom);
  15675. };
  15676. var postProcessHooks = {};
  15677. var filter = filter$2;
  15678. var each$b = each$i;
  15679. var addPostProcessHook = function (name, hook) {
  15680. var hooks = postProcessHooks[name];
  15681. if (!hooks) {
  15682. postProcessHooks[name] = [];
  15683. }
  15684. postProcessHooks[name].push(hook);
  15685. };
  15686. var postProcess$1 = function (name, editor) {
  15687. each$b(postProcessHooks[name], function (hook) {
  15688. hook(editor);
  15689. });
  15690. };
  15691. addPostProcessHook('pre', function (editor) {
  15692. var rng = editor.selection.getRng();
  15693. var blocks;
  15694. var hasPreSibling = function (pre) {
  15695. return isPre(pre.previousSibling) && indexOf$1(blocks, pre.previousSibling) !== -1;
  15696. };
  15697. var joinPre = function (pre1, pre2) {
  15698. DomQuery(pre2).remove();
  15699. DomQuery(pre1).append('<br><br>').append(pre2.childNodes);
  15700. };
  15701. var isPre = matchNodeNames(['pre']);
  15702. if (!rng.collapsed) {
  15703. blocks = editor.selection.getSelectedBlocks();
  15704. each$b(filter(filter(blocks, isPre), hasPreSibling), function (pre) {
  15705. joinPre(pre.previousSibling, pre);
  15706. });
  15707. }
  15708. });
  15709. var each$a = Tools.each;
  15710. var isElementNode$1 = function (node) {
  15711. return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  15712. };
  15713. var findElementSibling = function (node, siblingName) {
  15714. for (var sibling = node; sibling; sibling = sibling[siblingName]) {
  15715. if (isText$7(sibling) && isNotEmpty(sibling.data)) {
  15716. return node;
  15717. }
  15718. if (isElement$5(sibling) && !isBookmarkNode$1(sibling)) {
  15719. return sibling;
  15720. }
  15721. }
  15722. return node;
  15723. };
  15724. var mergeSiblingsNodes = function (dom, prev, next) {
  15725. var elementUtils = ElementUtils(dom);
  15726. if (prev && next) {
  15727. prev = findElementSibling(prev, 'previousSibling');
  15728. next = findElementSibling(next, 'nextSibling');
  15729. if (elementUtils.compare(prev, next)) {
  15730. for (var sibling = prev.nextSibling; sibling && sibling !== next;) {
  15731. var tmpSibling = sibling;
  15732. sibling = sibling.nextSibling;
  15733. prev.appendChild(tmpSibling);
  15734. }
  15735. dom.remove(next);
  15736. Tools.each(Tools.grep(next.childNodes), function (node) {
  15737. prev.appendChild(node);
  15738. });
  15739. return prev;
  15740. }
  15741. }
  15742. return next;
  15743. };
  15744. var mergeSiblings = function (dom, format, vars, node) {
  15745. if (node && format.merge_siblings !== false) {
  15746. var newNode = mergeSiblingsNodes(dom, getNonWhiteSpaceSibling(node), node);
  15747. mergeSiblingsNodes(dom, newNode, getNonWhiteSpaceSibling(newNode, true));
  15748. }
  15749. };
  15750. var clearChildStyles = function (dom, format, node) {
  15751. if (format.clear_child_styles) {
  15752. var selector = format.links ? '*:not(a)' : '*';
  15753. each$a(dom.select(selector, node), function (node) {
  15754. if (isElementNode$1(node)) {
  15755. each$a(format.styles, function (value, name) {
  15756. dom.setStyle(node, name, '');
  15757. });
  15758. }
  15759. });
  15760. }
  15761. };
  15762. var processChildElements = function (node, filter, process) {
  15763. each$a(node.childNodes, function (node) {
  15764. if (isElementNode$1(node)) {
  15765. if (filter(node)) {
  15766. process(node);
  15767. }
  15768. if (node.hasChildNodes()) {
  15769. processChildElements(node, filter, process);
  15770. }
  15771. }
  15772. });
  15773. };
  15774. var unwrapEmptySpan = function (dom, node) {
  15775. if (node.nodeName === 'SPAN' && dom.getAttribs(node).length === 0) {
  15776. dom.remove(node, true);
  15777. }
  15778. };
  15779. var hasStyle = function (dom, name) {
  15780. return function (node) {
  15781. return !!(node && getStyle(dom, node, name));
  15782. };
  15783. };
  15784. var applyStyle = function (dom, name, value) {
  15785. return function (node) {
  15786. dom.setStyle(node, name, value);
  15787. if (node.getAttribute('style') === '') {
  15788. node.removeAttribute('style');
  15789. }
  15790. unwrapEmptySpan(dom, node);
  15791. };
  15792. };
  15793. var removeResult = Adt.generate([
  15794. { keep: [] },
  15795. { rename: ['name'] },
  15796. { removed: [] }
  15797. ]);
  15798. var MCE_ATTR_RE = /^(src|href|style)$/;
  15799. var each$9 = Tools.each;
  15800. var isEq$2 = isEq$5;
  15801. var isTableCellOrRow = function (node) {
  15802. return /^(TR|TH|TD)$/.test(node.nodeName);
  15803. };
  15804. var isChildOfInlineParent = function (dom, node, parent) {
  15805. return dom.isChildOf(node, parent) && node !== parent && !dom.isBlock(parent);
  15806. };
  15807. var getContainer = function (ed, rng, start) {
  15808. var container = rng[start ? 'startContainer' : 'endContainer'];
  15809. var offset = rng[start ? 'startOffset' : 'endOffset'];
  15810. if (isElement$5(container)) {
  15811. var lastIdx = container.childNodes.length - 1;
  15812. if (!start && offset) {
  15813. offset--;
  15814. }
  15815. container = container.childNodes[offset > lastIdx ? lastIdx : offset];
  15816. }
  15817. if (isText$7(container) && start && offset >= container.nodeValue.length) {
  15818. container = new DomTreeWalker(container, ed.getBody()).next() || container;
  15819. }
  15820. if (isText$7(container) && !start && offset === 0) {
  15821. container = new DomTreeWalker(container, ed.getBody()).prev() || container;
  15822. }
  15823. return container;
  15824. };
  15825. var normalizeTableSelection = function (node, start) {
  15826. var prop = start ? 'firstChild' : 'lastChild';
  15827. if (isTableCellOrRow(node) && node[prop]) {
  15828. var childNode = node[prop];
  15829. if (node.nodeName === 'TR') {
  15830. return childNode[prop] || childNode;
  15831. } else {
  15832. return childNode;
  15833. }
  15834. }
  15835. return node;
  15836. };
  15837. var wrap$1 = function (dom, node, name, attrs) {
  15838. var wrapper = dom.create(name, attrs);
  15839. node.parentNode.insertBefore(wrapper, node);
  15840. wrapper.appendChild(node);
  15841. return wrapper;
  15842. };
  15843. var wrapWithSiblings = function (dom, node, next, name, attrs) {
  15844. var start = SugarElement.fromDom(node);
  15845. var wrapper = SugarElement.fromDom(dom.create(name, attrs));
  15846. var siblings = next ? nextSiblings(start) : prevSiblings(start);
  15847. append(wrapper, siblings);
  15848. if (next) {
  15849. before$4(start, wrapper);
  15850. prepend(wrapper, start);
  15851. } else {
  15852. after$3(start, wrapper);
  15853. append$1(wrapper, start);
  15854. }
  15855. return wrapper.dom;
  15856. };
  15857. var matchName = function (dom, node, format) {
  15858. if (isInlineFormat(format) && isEq$2(node, format.inline)) {
  15859. return true;
  15860. }
  15861. if (isBlockFormat(format) && isEq$2(node, format.block)) {
  15862. return true;
  15863. }
  15864. if (isSelectorFormat(format)) {
  15865. return isElement$5(node) && dom.is(node, format.selector);
  15866. }
  15867. };
  15868. var isColorFormatAndAnchor = function (node, format) {
  15869. return format.links && node.nodeName === 'A';
  15870. };
  15871. var find = function (dom, node, next, inc) {
  15872. var sibling = getNonWhiteSpaceSibling(node, next, inc);
  15873. return isNullable(sibling) || sibling.nodeName === 'BR' || dom.isBlock(sibling);
  15874. };
  15875. var removeNode = function (ed, node, format) {
  15876. var parentNode = node.parentNode;
  15877. var rootBlockElm;
  15878. var dom = ed.dom, forcedRootBlock = getForcedRootBlock(ed);
  15879. if (isBlockFormat(format)) {
  15880. if (!forcedRootBlock) {
  15881. if (dom.isBlock(node) && !dom.isBlock(parentNode)) {
  15882. if (!find(dom, node, false) && !find(dom, node.firstChild, true, true)) {
  15883. node.insertBefore(dom.create('br'), node.firstChild);
  15884. }
  15885. if (!find(dom, node, true) && !find(dom, node.lastChild, false, true)) {
  15886. node.appendChild(dom.create('br'));
  15887. }
  15888. }
  15889. } else {
  15890. if (parentNode === dom.getRoot()) {
  15891. if (!format.list_block || !isEq$2(node, format.list_block)) {
  15892. each$k(from(node.childNodes), function (node) {
  15893. if (isValid(ed, forcedRootBlock, node.nodeName.toLowerCase())) {
  15894. if (!rootBlockElm) {
  15895. rootBlockElm = wrap$1(dom, node, forcedRootBlock);
  15896. dom.setAttribs(rootBlockElm, ed.settings.forced_root_block_attrs);
  15897. } else {
  15898. rootBlockElm.appendChild(node);
  15899. }
  15900. } else {
  15901. rootBlockElm = null;
  15902. }
  15903. });
  15904. }
  15905. }
  15906. }
  15907. }
  15908. if (isMixedFormat(format) && !isEq$2(format.inline, node)) {
  15909. return;
  15910. }
  15911. dom.remove(node, true);
  15912. };
  15913. var removeFormatInternal = function (ed, format, vars, node, compareNode) {
  15914. var stylesModified;
  15915. var dom = ed.dom;
  15916. if (!matchName(dom, node, format) && !isColorFormatAndAnchor(node, format)) {
  15917. return removeResult.keep();
  15918. }
  15919. var elm = node;
  15920. if (isInlineFormat(format) && format.remove === 'all' && isArray$1(format.preserve_attributes)) {
  15921. var attrsToPreserve = filter$4(dom.getAttribs(elm), function (attr) {
  15922. return contains$3(format.preserve_attributes, attr.name.toLowerCase());
  15923. });
  15924. dom.removeAllAttribs(elm);
  15925. each$k(attrsToPreserve, function (attr) {
  15926. return dom.setAttrib(elm, attr.name, attr.value);
  15927. });
  15928. if (attrsToPreserve.length > 0) {
  15929. return removeResult.rename('span');
  15930. }
  15931. }
  15932. if (format.remove !== 'all') {
  15933. each$9(format.styles, function (value, name) {
  15934. value = normalizeStyleValue(dom, replaceVars(value, vars), name + '');
  15935. if (isNumber(name)) {
  15936. name = value;
  15937. compareNode = null;
  15938. }
  15939. if (format.remove_similar || (!compareNode || isEq$2(getStyle(dom, compareNode, name), value))) {
  15940. dom.setStyle(elm, name, '');
  15941. }
  15942. stylesModified = true;
  15943. });
  15944. if (stylesModified && dom.getAttrib(elm, 'style') === '') {
  15945. elm.removeAttribute('style');
  15946. elm.removeAttribute('data-mce-style');
  15947. }
  15948. each$9(format.attributes, function (value, name) {
  15949. var valueOut;
  15950. value = replaceVars(value, vars);
  15951. if (isNumber(name)) {
  15952. name = value;
  15953. compareNode = null;
  15954. }
  15955. if (format.remove_similar || (!compareNode || isEq$2(dom.getAttrib(compareNode, name), value))) {
  15956. if (name === 'class') {
  15957. value = dom.getAttrib(elm, name);
  15958. if (value) {
  15959. valueOut = '';
  15960. each$k(value.split(/\s+/), function (cls) {
  15961. if (/mce\-\w+/.test(cls)) {
  15962. valueOut += (valueOut ? ' ' : '') + cls;
  15963. }
  15964. });
  15965. if (valueOut) {
  15966. dom.setAttrib(elm, name, valueOut);
  15967. return;
  15968. }
  15969. }
  15970. }
  15971. if (MCE_ATTR_RE.test(name)) {
  15972. elm.removeAttribute('data-mce-' + name);
  15973. }
  15974. if (name === 'style' && matchNodeNames(['li'])(elm) && dom.getStyle(elm, 'list-style-type') === 'none') {
  15975. elm.removeAttribute(name);
  15976. dom.setStyle(elm, 'list-style-type', 'none');
  15977. return;
  15978. }
  15979. if (name === 'class') {
  15980. elm.removeAttribute('className');
  15981. }
  15982. elm.removeAttribute(name);
  15983. }
  15984. });
  15985. each$9(format.classes, function (value) {
  15986. value = replaceVars(value, vars);
  15987. if (!compareNode || dom.hasClass(compareNode, value)) {
  15988. dom.removeClass(elm, value);
  15989. }
  15990. });
  15991. var attrs = dom.getAttribs(elm);
  15992. for (var i = 0; i < attrs.length; i++) {
  15993. var attrName = attrs[i].nodeName;
  15994. if (attrName.indexOf('_') !== 0 && attrName.indexOf('data-') !== 0) {
  15995. return removeResult.keep();
  15996. }
  15997. }
  15998. }
  15999. if (format.remove !== 'none') {
  16000. removeNode(ed, elm, format);
  16001. return removeResult.removed();
  16002. }
  16003. return removeResult.keep();
  16004. };
  16005. var removeFormat$1 = function (ed, format, vars, node, compareNode) {
  16006. return removeFormatInternal(ed, format, vars, node, compareNode).fold(never, function (newName) {
  16007. ed.dom.rename(node, newName);
  16008. return true;
  16009. }, always);
  16010. };
  16011. var findFormatRoot = function (editor, container, name, vars, similar) {
  16012. var formatRoot;
  16013. each$k(getParents$2(editor.dom, container.parentNode).reverse(), function (parent) {
  16014. if (!formatRoot && parent.id !== '_start' && parent.id !== '_end') {
  16015. var format = matchNode(editor, parent, name, vars, similar);
  16016. if (format && format.split !== false) {
  16017. formatRoot = parent;
  16018. }
  16019. }
  16020. });
  16021. return formatRoot;
  16022. };
  16023. var removeFormatFromClone = function (editor, format, vars, clone) {
  16024. return removeFormatInternal(editor, format, vars, clone, clone).fold(constant(clone), function (newName) {
  16025. var fragment = editor.dom.createFragment();
  16026. fragment.appendChild(clone);
  16027. return editor.dom.rename(clone, newName);
  16028. }, constant(null));
  16029. };
  16030. var wrapAndSplit = function (editor, formatList, formatRoot, container, target, split, format, vars) {
  16031. var clone, lastClone, firstClone;
  16032. var dom = editor.dom;
  16033. if (formatRoot) {
  16034. var formatRootParent = formatRoot.parentNode;
  16035. for (var parent_1 = container.parentNode; parent_1 && parent_1 !== formatRootParent; parent_1 = parent_1.parentNode) {
  16036. clone = dom.clone(parent_1, false);
  16037. for (var i = 0; i < formatList.length; i++) {
  16038. clone = removeFormatFromClone(editor, formatList[i], vars, clone);
  16039. if (clone === null) {
  16040. break;
  16041. }
  16042. }
  16043. if (clone) {
  16044. if (lastClone) {
  16045. clone.appendChild(lastClone);
  16046. }
  16047. if (!firstClone) {
  16048. firstClone = clone;
  16049. }
  16050. lastClone = clone;
  16051. }
  16052. }
  16053. if (split && (!format.mixed || !dom.isBlock(formatRoot))) {
  16054. container = dom.split(formatRoot, container);
  16055. }
  16056. if (lastClone) {
  16057. target.parentNode.insertBefore(lastClone, target);
  16058. firstClone.appendChild(target);
  16059. if (isInlineFormat(format)) {
  16060. mergeSiblings(dom, format, vars, lastClone);
  16061. }
  16062. }
  16063. }
  16064. return container;
  16065. };
  16066. var remove$1 = function (ed, name, vars, node, similar) {
  16067. var formatList = ed.formatter.get(name);
  16068. var format = formatList[0];
  16069. var contentEditable = true;
  16070. var dom = ed.dom;
  16071. var selection = ed.selection;
  16072. var splitToFormatRoot = function (container) {
  16073. var formatRoot = findFormatRoot(ed, container, name, vars, similar);
  16074. return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format, vars);
  16075. };
  16076. var isRemoveBookmarkNode = function (node) {
  16077. return isBookmarkNode$1(node) && isElement$5(node) && (node.id === '_start' || node.id === '_end');
  16078. };
  16079. var removeNodeFormat = function (node) {
  16080. return exists(formatList, function (fmt) {
  16081. return removeFormat$1(ed, fmt, vars, node, node);
  16082. });
  16083. };
  16084. var process = function (node) {
  16085. var lastContentEditable = true;
  16086. var hasContentEditableState = false;
  16087. if (isElement$5(node) && dom.getContentEditable(node)) {
  16088. lastContentEditable = contentEditable;
  16089. contentEditable = dom.getContentEditable(node) === 'true';
  16090. hasContentEditableState = true;
  16091. }
  16092. var children = from(node.childNodes);
  16093. if (contentEditable && !hasContentEditableState) {
  16094. var removed = removeNodeFormat(node);
  16095. var parentNode = node.parentNode;
  16096. if (!removed && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  16097. removeNodeFormat(parentNode);
  16098. }
  16099. }
  16100. if (format.deep) {
  16101. if (children.length) {
  16102. for (var i = 0; i < children.length; i++) {
  16103. process(children[i]);
  16104. }
  16105. if (hasContentEditableState) {
  16106. contentEditable = lastContentEditable;
  16107. }
  16108. }
  16109. }
  16110. var textDecorations = [
  16111. 'underline',
  16112. 'line-through',
  16113. 'overline'
  16114. ];
  16115. each$k(textDecorations, function (decoration) {
  16116. if (isElement$5(node) && ed.dom.getStyle(node, 'text-decoration') === decoration && node.parentNode && getTextDecoration(dom, node.parentNode) === decoration) {
  16117. removeFormat$1(ed, {
  16118. deep: false,
  16119. exact: true,
  16120. inline: 'span',
  16121. styles: { textDecoration: decoration }
  16122. }, null, node);
  16123. }
  16124. });
  16125. };
  16126. var unwrap = function (start) {
  16127. var node = dom.get(start ? '_start' : '_end');
  16128. var out = node[start ? 'firstChild' : 'lastChild'];
  16129. if (isRemoveBookmarkNode(out)) {
  16130. out = out[start ? 'firstChild' : 'lastChild'];
  16131. }
  16132. if (isText$7(out) && out.data.length === 0) {
  16133. out = start ? node.previousSibling || node.nextSibling : node.nextSibling || node.previousSibling;
  16134. }
  16135. dom.remove(node, true);
  16136. return out;
  16137. };
  16138. var removeRngStyle = function (rng) {
  16139. var startContainer, endContainer;
  16140. var expandedRng = expandRng(ed, rng, formatList, rng.collapsed);
  16141. if (format.split) {
  16142. expandedRng = split(expandedRng);
  16143. startContainer = getContainer(ed, expandedRng, true);
  16144. endContainer = getContainer(ed, expandedRng);
  16145. if (startContainer !== endContainer) {
  16146. startContainer = normalizeTableSelection(startContainer, true);
  16147. endContainer = normalizeTableSelection(endContainer, false);
  16148. if (isChildOfInlineParent(dom, startContainer, endContainer)) {
  16149. var marker = Optional.from(startContainer.firstChild).getOr(startContainer);
  16150. splitToFormatRoot(wrapWithSiblings(dom, marker, true, 'span', {
  16151. 'id': '_start',
  16152. 'data-mce-type': 'bookmark'
  16153. }));
  16154. unwrap(true);
  16155. return;
  16156. }
  16157. if (isChildOfInlineParent(dom, endContainer, startContainer)) {
  16158. var marker = Optional.from(endContainer.lastChild).getOr(endContainer);
  16159. splitToFormatRoot(wrapWithSiblings(dom, marker, false, 'span', {
  16160. 'id': '_end',
  16161. 'data-mce-type': 'bookmark'
  16162. }));
  16163. unwrap(false);
  16164. return;
  16165. }
  16166. startContainer = wrap$1(dom, startContainer, 'span', {
  16167. 'id': '_start',
  16168. 'data-mce-type': 'bookmark'
  16169. });
  16170. endContainer = wrap$1(dom, endContainer, 'span', {
  16171. 'id': '_end',
  16172. 'data-mce-type': 'bookmark'
  16173. });
  16174. var newRng = dom.createRng();
  16175. newRng.setStartAfter(startContainer);
  16176. newRng.setEndBefore(endContainer);
  16177. walk$2(dom, newRng, function (nodes) {
  16178. each$k(nodes, function (n) {
  16179. if (!isBookmarkNode$1(n) && !isBookmarkNode$1(n.parentNode)) {
  16180. splitToFormatRoot(n);
  16181. }
  16182. });
  16183. });
  16184. splitToFormatRoot(startContainer);
  16185. splitToFormatRoot(endContainer);
  16186. startContainer = unwrap(true);
  16187. endContainer = unwrap();
  16188. } else {
  16189. startContainer = endContainer = splitToFormatRoot(startContainer);
  16190. }
  16191. expandedRng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
  16192. expandedRng.startOffset = dom.nodeIndex(startContainer);
  16193. expandedRng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
  16194. expandedRng.endOffset = dom.nodeIndex(endContainer) + 1;
  16195. }
  16196. walk$2(dom, expandedRng, function (nodes) {
  16197. each$k(nodes, process);
  16198. });
  16199. };
  16200. if (node) {
  16201. if (isNode(node)) {
  16202. var rng = dom.createRng();
  16203. rng.setStartBefore(node);
  16204. rng.setEndAfter(node);
  16205. removeRngStyle(rng);
  16206. } else {
  16207. removeRngStyle(node);
  16208. }
  16209. fireFormatRemove(ed, name, node, vars);
  16210. return;
  16211. }
  16212. if (dom.getContentEditable(selection.getNode()) === 'false') {
  16213. node = selection.getNode();
  16214. for (var i = 0; i < formatList.length; i++) {
  16215. if (formatList[i].ceFalseOverride) {
  16216. if (removeFormat$1(ed, formatList[i], vars, node, node)) {
  16217. break;
  16218. }
  16219. }
  16220. }
  16221. fireFormatRemove(ed, name, node, vars);
  16222. return;
  16223. }
  16224. if (!selection.isCollapsed() || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  16225. preserve(selection, true, function () {
  16226. runOnRanges(ed, removeRngStyle);
  16227. });
  16228. if (isInlineFormat(format) && match$2(ed, name, vars, selection.getStart())) {
  16229. moveStart(dom, selection, selection.getRng());
  16230. }
  16231. ed.nodeChanged();
  16232. } else {
  16233. removeCaretFormat(ed, name, vars, similar);
  16234. }
  16235. fireFormatRemove(ed, name, node, vars);
  16236. };
  16237. var each$8 = Tools.each;
  16238. var mergeTextDecorationsAndColor = function (dom, format, vars, node) {
  16239. var processTextDecorationsAndColor = function (n) {
  16240. if (n.nodeType === 1 && n.parentNode && n.parentNode.nodeType === 1) {
  16241. var textDecoration = getTextDecoration(dom, n.parentNode);
  16242. if (dom.getStyle(n, 'color') && textDecoration) {
  16243. dom.setStyle(n, 'text-decoration', textDecoration);
  16244. } else if (dom.getStyle(n, 'text-decoration') === textDecoration) {
  16245. dom.setStyle(n, 'text-decoration', null);
  16246. }
  16247. }
  16248. };
  16249. if (format.styles && (format.styles.color || format.styles.textDecoration)) {
  16250. Tools.walk(node, processTextDecorationsAndColor, 'childNodes');
  16251. processTextDecorationsAndColor(node);
  16252. }
  16253. };
  16254. var mergeBackgroundColorAndFontSize = function (dom, format, vars, node) {
  16255. if (format.styles && format.styles.backgroundColor) {
  16256. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'backgroundColor', replaceVars(format.styles.backgroundColor, vars)));
  16257. }
  16258. };
  16259. var mergeSubSup = function (dom, format, vars, node) {
  16260. if (isInlineFormat(format) && (format.inline === 'sub' || format.inline === 'sup')) {
  16261. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'fontSize', ''));
  16262. dom.remove(dom.select(format.inline === 'sup' ? 'sub' : 'sup', node), true);
  16263. }
  16264. };
  16265. var mergeWithChildren = function (editor, formatList, vars, node) {
  16266. each$8(formatList, function (format) {
  16267. if (isInlineFormat(format)) {
  16268. each$8(editor.dom.select(format.inline, node), function (child) {
  16269. if (!isElementNode$1(child)) {
  16270. return;
  16271. }
  16272. removeFormat$1(editor, format, vars, child, format.exact ? child : null);
  16273. });
  16274. }
  16275. clearChildStyles(editor.dom, format, node);
  16276. });
  16277. };
  16278. var mergeWithParents = function (editor, format, name, vars, node) {
  16279. if (matchNode(editor, node.parentNode, name, vars)) {
  16280. if (removeFormat$1(editor, format, vars, node)) {
  16281. return;
  16282. }
  16283. }
  16284. if (format.merge_with_parents) {
  16285. editor.dom.getParent(node.parentNode, function (parent) {
  16286. if (matchNode(editor, parent, name, vars)) {
  16287. removeFormat$1(editor, format, vars, node);
  16288. return true;
  16289. }
  16290. });
  16291. }
  16292. };
  16293. var each$7 = Tools.each;
  16294. var isElementNode = function (node) {
  16295. return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  16296. };
  16297. var canFormatBR = function (editor, format, node, parentName) {
  16298. if (canFormatEmptyLines(editor) && isInlineFormat(format)) {
  16299. var validBRParentElements = __assign(__assign({}, editor.schema.getTextBlockElements()), {
  16300. td: {},
  16301. th: {},
  16302. li: {},
  16303. dt: {},
  16304. dd: {},
  16305. figcaption: {},
  16306. caption: {},
  16307. details: {},
  16308. summary: {}
  16309. });
  16310. var hasCaretNodeSibling = sibling(SugarElement.fromDom(node), function (sibling) {
  16311. return isCaretNode(sibling.dom);
  16312. });
  16313. return hasNonNullableKey(validBRParentElements, parentName) && isEmpty$2(SugarElement.fromDom(node.parentNode), false) && !hasCaretNodeSibling;
  16314. } else {
  16315. return false;
  16316. }
  16317. };
  16318. var applyFormat$1 = function (ed, name, vars, node) {
  16319. var formatList = ed.formatter.get(name);
  16320. var format = formatList[0];
  16321. var isCollapsed = !node && ed.selection.isCollapsed();
  16322. var dom = ed.dom;
  16323. var selection = ed.selection;
  16324. var setElementFormat = function (elm, fmt) {
  16325. if (fmt === void 0) {
  16326. fmt = format;
  16327. }
  16328. if (isFunction(fmt.onformat)) {
  16329. fmt.onformat(elm, fmt, vars, node);
  16330. }
  16331. each$7(fmt.styles, function (value, name) {
  16332. dom.setStyle(elm, name, replaceVars(value, vars));
  16333. });
  16334. if (fmt.styles) {
  16335. var styleVal = dom.getAttrib(elm, 'style');
  16336. if (styleVal) {
  16337. dom.setAttrib(elm, 'data-mce-style', styleVal);
  16338. }
  16339. }
  16340. each$7(fmt.attributes, function (value, name) {
  16341. dom.setAttrib(elm, name, replaceVars(value, vars));
  16342. });
  16343. each$7(fmt.classes, function (value) {
  16344. value = replaceVars(value, vars);
  16345. if (!dom.hasClass(elm, value)) {
  16346. dom.addClass(elm, value);
  16347. }
  16348. });
  16349. };
  16350. var applyNodeStyle = function (formatList, node) {
  16351. var found = false;
  16352. each$7(formatList, function (format) {
  16353. if (!isSelectorFormat(format)) {
  16354. return false;
  16355. }
  16356. if (isNonNullable(format.collapsed) && format.collapsed !== isCollapsed) {
  16357. return;
  16358. }
  16359. if (dom.is(node, format.selector) && !isCaretNode(node)) {
  16360. setElementFormat(node, format);
  16361. found = true;
  16362. return false;
  16363. }
  16364. });
  16365. return found;
  16366. };
  16367. var createWrapElement = function (wrapName) {
  16368. if (isString$1(wrapName)) {
  16369. var wrapElm = dom.create(wrapName);
  16370. setElementFormat(wrapElm);
  16371. return wrapElm;
  16372. } else {
  16373. return null;
  16374. }
  16375. };
  16376. var applyRngStyle = function (dom, rng, nodeSpecific) {
  16377. var newWrappers = [];
  16378. var contentEditable = true;
  16379. var wrapName = format.inline || format.block;
  16380. var wrapElm = createWrapElement(wrapName);
  16381. walk$2(dom, rng, function (nodes) {
  16382. var currentWrapElm;
  16383. var process = function (node) {
  16384. var hasContentEditableState = false;
  16385. var lastContentEditable = contentEditable;
  16386. var nodeName = node.nodeName.toLowerCase();
  16387. var parentNode = node.parentNode;
  16388. var parentName = parentNode.nodeName.toLowerCase();
  16389. if (isElement$5(node) && dom.getContentEditable(node)) {
  16390. lastContentEditable = contentEditable;
  16391. contentEditable = dom.getContentEditable(node) === 'true';
  16392. hasContentEditableState = true;
  16393. }
  16394. if (isBr$5(node) && !canFormatBR(ed, format, node, parentName)) {
  16395. currentWrapElm = null;
  16396. if (isBlockFormat(format)) {
  16397. dom.remove(node);
  16398. }
  16399. return;
  16400. }
  16401. if (isBlockFormat(format) && format.wrapper && matchNode(ed, node, name, vars)) {
  16402. currentWrapElm = null;
  16403. return;
  16404. }
  16405. if (contentEditable && !hasContentEditableState && isBlockFormat(format) && !format.wrapper && isTextBlock$1(ed, nodeName) && isValid(ed, parentName, wrapName)) {
  16406. var elm = dom.rename(node, wrapName);
  16407. setElementFormat(elm);
  16408. newWrappers.push(elm);
  16409. currentWrapElm = null;
  16410. return;
  16411. }
  16412. if (isSelectorFormat(format)) {
  16413. var found = applyNodeStyle(formatList, node);
  16414. if (!found && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  16415. found = applyNodeStyle(formatList, parentNode);
  16416. }
  16417. if (!isInlineFormat(format) || found) {
  16418. currentWrapElm = null;
  16419. return;
  16420. }
  16421. }
  16422. if (contentEditable && !hasContentEditableState && isValid(ed, wrapName, nodeName) && isValid(ed, parentName, wrapName) && !(!nodeSpecific && isText$7(node) && isZwsp(node.data)) && !isCaretNode(node) && (!isInlineFormat(format) || !dom.isBlock(node))) {
  16423. if (!currentWrapElm) {
  16424. currentWrapElm = dom.clone(wrapElm, false);
  16425. node.parentNode.insertBefore(currentWrapElm, node);
  16426. newWrappers.push(currentWrapElm);
  16427. }
  16428. currentWrapElm.appendChild(node);
  16429. } else {
  16430. currentWrapElm = null;
  16431. each$k(from(node.childNodes), process);
  16432. if (hasContentEditableState) {
  16433. contentEditable = lastContentEditable;
  16434. }
  16435. currentWrapElm = null;
  16436. }
  16437. };
  16438. each$k(nodes, process);
  16439. });
  16440. if (format.links === true) {
  16441. each$k(newWrappers, function (node) {
  16442. var process = function (node) {
  16443. if (node.nodeName === 'A') {
  16444. setElementFormat(node, format);
  16445. }
  16446. each$k(from(node.childNodes), process);
  16447. };
  16448. process(node);
  16449. });
  16450. }
  16451. each$k(newWrappers, function (node) {
  16452. var getChildCount = function (node) {
  16453. var count = 0;
  16454. each$k(node.childNodes, function (node) {
  16455. if (!isEmptyTextNode$1(node) && !isBookmarkNode$1(node)) {
  16456. count++;
  16457. }
  16458. });
  16459. return count;
  16460. };
  16461. var mergeStyles = function (node) {
  16462. var childElement = find$3(node.childNodes, isElementNode).filter(function (child) {
  16463. return matchName$1(dom, child, format);
  16464. });
  16465. return childElement.map(function (child) {
  16466. var clone = dom.clone(child, false);
  16467. setElementFormat(clone);
  16468. dom.replace(clone, node, true);
  16469. dom.remove(child, true);
  16470. return clone;
  16471. }).getOr(node);
  16472. };
  16473. var childCount = getChildCount(node);
  16474. if ((newWrappers.length > 1 || !dom.isBlock(node)) && childCount === 0) {
  16475. dom.remove(node, true);
  16476. return;
  16477. }
  16478. if (isInlineFormat(format) || isBlockFormat(format) && format.wrapper) {
  16479. if (!format.exact && childCount === 1) {
  16480. node = mergeStyles(node);
  16481. }
  16482. mergeWithChildren(ed, formatList, vars, node);
  16483. mergeWithParents(ed, format, name, vars, node);
  16484. mergeBackgroundColorAndFontSize(dom, format, vars, node);
  16485. mergeTextDecorationsAndColor(dom, format, vars, node);
  16486. mergeSubSup(dom, format, vars, node);
  16487. mergeSiblings(dom, format, vars, node);
  16488. }
  16489. });
  16490. };
  16491. if (dom.getContentEditable(selection.getNode()) === 'false') {
  16492. node = selection.getNode();
  16493. for (var i = 0, l = formatList.length; i < l; i++) {
  16494. var formatItem = formatList[i];
  16495. if (formatItem.ceFalseOverride && isSelectorFormat(formatItem) && dom.is(node, formatItem.selector)) {
  16496. setElementFormat(node, formatItem);
  16497. break;
  16498. }
  16499. }
  16500. fireFormatApply(ed, name, node, vars);
  16501. return;
  16502. }
  16503. if (format) {
  16504. if (node) {
  16505. if (isNode(node)) {
  16506. if (!applyNodeStyle(formatList, node)) {
  16507. var rng = dom.createRng();
  16508. rng.setStartBefore(node);
  16509. rng.setEndAfter(node);
  16510. applyRngStyle(dom, expandRng(ed, rng, formatList), true);
  16511. }
  16512. } else {
  16513. applyRngStyle(dom, node, true);
  16514. }
  16515. } else {
  16516. if (!isCollapsed || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  16517. var curSelNode = selection.getNode();
  16518. var firstFormat = formatList[0];
  16519. if (!ed.settings.forced_root_block && firstFormat.defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) {
  16520. applyFormat$1(ed, firstFormat.defaultBlock);
  16521. }
  16522. selection.setRng(normalize(selection.getRng()));
  16523. preserve(selection, true, function () {
  16524. runOnRanges(ed, function (selectionRng, fake) {
  16525. var expandedRng = fake ? selectionRng : expandRng(ed, selectionRng, formatList);
  16526. applyRngStyle(dom, expandedRng, false);
  16527. });
  16528. });
  16529. moveStart(dom, selection, selection.getRng());
  16530. ed.nodeChanged();
  16531. } else {
  16532. applyCaretFormat(ed, name, vars);
  16533. }
  16534. }
  16535. postProcess$1(name, ed);
  16536. }
  16537. fireFormatApply(ed, name, node, vars);
  16538. };
  16539. var hasVars = function (value) {
  16540. return has$2(value, 'vars');
  16541. };
  16542. var setup$j = function (registeredFormatListeners, editor) {
  16543. registeredFormatListeners.set({});
  16544. editor.on('NodeChange', function (e) {
  16545. updateAndFireChangeCallbacks(editor, e.element, registeredFormatListeners.get());
  16546. });
  16547. editor.on('FormatApply FormatRemove', function (e) {
  16548. var element = Optional.from(e.node).map(function (nodeOrRange) {
  16549. return isNode(nodeOrRange) ? nodeOrRange : nodeOrRange.startContainer;
  16550. }).bind(function (node) {
  16551. return isElement$5(node) ? Optional.some(node) : Optional.from(node.parentElement);
  16552. }).getOrThunk(function () {
  16553. return fallbackElement(editor);
  16554. });
  16555. updateAndFireChangeCallbacks(editor, element, registeredFormatListeners.get());
  16556. });
  16557. };
  16558. var fallbackElement = function (editor) {
  16559. return editor.selection.getStart();
  16560. };
  16561. var matchingNode = function (editor, parents, format, similar, vars) {
  16562. var isMatchingNode = function (node) {
  16563. var matchingFormat = editor.formatter.matchNode(node, format, vars !== null && vars !== void 0 ? vars : {}, similar);
  16564. return !isUndefined(matchingFormat);
  16565. };
  16566. var isUnableToMatch = function (node) {
  16567. if (matchesUnInheritedFormatSelector(editor, node, format)) {
  16568. return true;
  16569. } else {
  16570. if (!similar) {
  16571. return isNonNullable(editor.formatter.matchNode(node, format, vars, true));
  16572. } else {
  16573. return false;
  16574. }
  16575. }
  16576. };
  16577. return findUntil$1(parents, isMatchingNode, isUnableToMatch);
  16578. };
  16579. var getParents = function (editor, elm) {
  16580. var element = elm !== null && elm !== void 0 ? elm : fallbackElement(editor);
  16581. return filter$4(getParents$2(editor.dom, element), function (node) {
  16582. return isElement$5(node) && !isBogus$2(node);
  16583. });
  16584. };
  16585. var updateAndFireChangeCallbacks = function (editor, elm, registeredCallbacks) {
  16586. var parents = getParents(editor, elm);
  16587. each$j(registeredCallbacks, function (data, format) {
  16588. var runIfChanged = function (spec) {
  16589. var match = matchingNode(editor, parents, format, spec.similar, hasVars(spec) ? spec.vars : undefined);
  16590. var isSet = match.isSome();
  16591. if (spec.state.get() !== isSet) {
  16592. spec.state.set(isSet);
  16593. var node_1 = match.getOr(elm);
  16594. if (hasVars(spec)) {
  16595. spec.callback(isSet, {
  16596. node: node_1,
  16597. format: format,
  16598. parents: parents
  16599. });
  16600. } else {
  16601. each$k(spec.callbacks, function (callback) {
  16602. return callback(isSet, {
  16603. node: node_1,
  16604. format: format,
  16605. parents: parents
  16606. });
  16607. });
  16608. }
  16609. }
  16610. };
  16611. each$k([
  16612. data.withSimilar,
  16613. data.withoutSimilar
  16614. ], runIfChanged);
  16615. each$k(data.withVars, runIfChanged);
  16616. });
  16617. };
  16618. var addListeners = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  16619. var formatChangeItems = registeredFormatListeners.get();
  16620. each$k(formats.split(','), function (format) {
  16621. var group = get$9(formatChangeItems, format).getOrThunk(function () {
  16622. var base = {
  16623. withSimilar: {
  16624. state: Cell(false),
  16625. similar: true,
  16626. callbacks: []
  16627. },
  16628. withoutSimilar: {
  16629. state: Cell(false),
  16630. similar: false,
  16631. callbacks: []
  16632. },
  16633. withVars: []
  16634. };
  16635. formatChangeItems[format] = base;
  16636. return base;
  16637. });
  16638. var getCurrent = function () {
  16639. var parents = getParents(editor);
  16640. return matchingNode(editor, parents, format, similar, vars).isSome();
  16641. };
  16642. if (isUndefined(vars)) {
  16643. var toAppendTo = similar ? group.withSimilar : group.withoutSimilar;
  16644. toAppendTo.callbacks.push(callback);
  16645. if (toAppendTo.callbacks.length === 1) {
  16646. toAppendTo.state.set(getCurrent());
  16647. }
  16648. } else {
  16649. group.withVars.push({
  16650. state: Cell(getCurrent()),
  16651. similar: similar,
  16652. vars: vars,
  16653. callback: callback
  16654. });
  16655. }
  16656. });
  16657. registeredFormatListeners.set(formatChangeItems);
  16658. };
  16659. var removeListeners = function (registeredFormatListeners, formats, callback) {
  16660. var formatChangeItems = registeredFormatListeners.get();
  16661. each$k(formats.split(','), function (format) {
  16662. return get$9(formatChangeItems, format).each(function (group) {
  16663. formatChangeItems[format] = {
  16664. withSimilar: __assign(__assign({}, group.withSimilar), {
  16665. callbacks: filter$4(group.withSimilar.callbacks, function (cb) {
  16666. return cb !== callback;
  16667. })
  16668. }),
  16669. withoutSimilar: __assign(__assign({}, group.withoutSimilar), {
  16670. callbacks: filter$4(group.withoutSimilar.callbacks, function (cb) {
  16671. return cb !== callback;
  16672. })
  16673. }),
  16674. withVars: filter$4(group.withVars, function (item) {
  16675. return item.callback !== callback;
  16676. })
  16677. };
  16678. });
  16679. });
  16680. registeredFormatListeners.set(formatChangeItems);
  16681. };
  16682. var formatChangedInternal = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  16683. if (registeredFormatListeners.get() === null) {
  16684. setup$j(registeredFormatListeners, editor);
  16685. }
  16686. addListeners(editor, registeredFormatListeners, formats, callback, similar, vars);
  16687. return {
  16688. unbind: function () {
  16689. return removeListeners(registeredFormatListeners, formats, callback);
  16690. }
  16691. };
  16692. };
  16693. var toggle = function (editor, name, vars, node) {
  16694. var fmt = editor.formatter.get(name);
  16695. if (match$2(editor, name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) {
  16696. remove$1(editor, name, vars, node);
  16697. } else {
  16698. applyFormat$1(editor, name, vars, node);
  16699. }
  16700. };
  16701. var fromElements = function (elements, scope) {
  16702. var doc = scope || document;
  16703. var fragment = doc.createDocumentFragment();
  16704. each$k(elements, function (element) {
  16705. fragment.appendChild(element.dom);
  16706. });
  16707. return SugarElement.fromDom(fragment);
  16708. };
  16709. var tableModel = function (element, width, rows) {
  16710. return {
  16711. element: element,
  16712. width: width,
  16713. rows: rows
  16714. };
  16715. };
  16716. var tableRow = function (element, cells) {
  16717. return {
  16718. element: element,
  16719. cells: cells
  16720. };
  16721. };
  16722. var cellPosition = function (x, y) {
  16723. return {
  16724. x: x,
  16725. y: y
  16726. };
  16727. };
  16728. var getSpan = function (td, key) {
  16729. var value = parseInt(get$6(td, key), 10);
  16730. return isNaN(value) ? 1 : value;
  16731. };
  16732. var fillout = function (table, x, y, tr, td) {
  16733. var rowspan = getSpan(td, 'rowspan');
  16734. var colspan = getSpan(td, 'colspan');
  16735. var rows = table.rows;
  16736. for (var y2 = y; y2 < y + rowspan; y2++) {
  16737. if (!rows[y2]) {
  16738. rows[y2] = tableRow(deep$1(tr), []);
  16739. }
  16740. for (var x2 = x; x2 < x + colspan; x2++) {
  16741. var cells = rows[y2].cells;
  16742. cells[x2] = y2 === y && x2 === x ? td : shallow(td);
  16743. }
  16744. }
  16745. };
  16746. var cellExists = function (table, x, y) {
  16747. var rows = table.rows;
  16748. var cells = rows[y] ? rows[y].cells : [];
  16749. return !!cells[x];
  16750. };
  16751. var skipCellsX = function (table, x, y) {
  16752. while (cellExists(table, x, y)) {
  16753. x++;
  16754. }
  16755. return x;
  16756. };
  16757. var getWidth = function (rows) {
  16758. return foldl(rows, function (acc, row) {
  16759. return row.cells.length > acc ? row.cells.length : acc;
  16760. }, 0);
  16761. };
  16762. var findElementPos = function (table, element) {
  16763. var rows = table.rows;
  16764. for (var y = 0; y < rows.length; y++) {
  16765. var cells = rows[y].cells;
  16766. for (var x = 0; x < cells.length; x++) {
  16767. if (eq(cells[x], element)) {
  16768. return Optional.some(cellPosition(x, y));
  16769. }
  16770. }
  16771. }
  16772. return Optional.none();
  16773. };
  16774. var extractRows = function (table, sx, sy, ex, ey) {
  16775. var newRows = [];
  16776. var rows = table.rows;
  16777. for (var y = sy; y <= ey; y++) {
  16778. var cells = rows[y].cells;
  16779. var slice = sx < ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
  16780. newRows.push(tableRow(rows[y].element, slice));
  16781. }
  16782. return newRows;
  16783. };
  16784. var subTable = function (table, startPos, endPos) {
  16785. var sx = startPos.x, sy = startPos.y;
  16786. var ex = endPos.x, ey = endPos.y;
  16787. var newRows = sy < ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
  16788. return tableModel(table.element, getWidth(newRows), newRows);
  16789. };
  16790. var createDomTable = function (table, rows) {
  16791. var tableElement = shallow(table.element);
  16792. var tableBody = SugarElement.fromTag('tbody');
  16793. append(tableBody, rows);
  16794. append$1(tableElement, tableBody);
  16795. return tableElement;
  16796. };
  16797. var modelRowsToDomRows = function (table) {
  16798. return map$3(table.rows, function (row) {
  16799. var cells = map$3(row.cells, function (cell) {
  16800. var td = deep$1(cell);
  16801. remove$6(td, 'colspan');
  16802. remove$6(td, 'rowspan');
  16803. return td;
  16804. });
  16805. var tr = shallow(row.element);
  16806. append(tr, cells);
  16807. return tr;
  16808. });
  16809. };
  16810. var fromDom = function (tableElm) {
  16811. var table = tableModel(shallow(tableElm), 0, []);
  16812. each$k(descendants(tableElm, 'tr'), function (tr, y) {
  16813. each$k(descendants(tr, 'td,th'), function (td, x) {
  16814. fillout(table, skipCellsX(table, x, y), y, tr, td);
  16815. });
  16816. });
  16817. return tableModel(table.element, getWidth(table.rows), table.rows);
  16818. };
  16819. var toDom = function (table) {
  16820. return createDomTable(table, modelRowsToDomRows(table));
  16821. };
  16822. var subsection = function (table, startElement, endElement) {
  16823. return findElementPos(table, startElement).bind(function (startPos) {
  16824. return findElementPos(table, endElement).map(function (endPos) {
  16825. return subTable(table, startPos, endPos);
  16826. });
  16827. });
  16828. };
  16829. var findParentListContainer = function (parents) {
  16830. return find$3(parents, function (elm) {
  16831. return name(elm) === 'ul' || name(elm) === 'ol';
  16832. });
  16833. };
  16834. var getFullySelectedListWrappers = function (parents, rng) {
  16835. return find$3(parents, function (elm) {
  16836. return name(elm) === 'li' && hasAllContentsSelected(elm, rng);
  16837. }).fold(constant([]), function (_li) {
  16838. return findParentListContainer(parents).map(function (listCont) {
  16839. var listElm = SugarElement.fromTag(name(listCont));
  16840. var listStyles = filter$3(getAllRaw(listCont), function (_style, name) {
  16841. return startsWith(name, 'list-style');
  16842. });
  16843. setAll(listElm, listStyles);
  16844. return [
  16845. SugarElement.fromTag('li'),
  16846. listElm
  16847. ];
  16848. }).getOr([]);
  16849. });
  16850. };
  16851. var wrap = function (innerElm, elms) {
  16852. var wrapped = foldl(elms, function (acc, elm) {
  16853. append$1(elm, acc);
  16854. return elm;
  16855. }, innerElm);
  16856. return elms.length > 0 ? fromElements([wrapped]) : wrapped;
  16857. };
  16858. var directListWrappers = function (commonAnchorContainer) {
  16859. if (isListItem(commonAnchorContainer)) {
  16860. return parent(commonAnchorContainer).filter(isList).fold(constant([]), function (listElm) {
  16861. return [
  16862. commonAnchorContainer,
  16863. listElm
  16864. ];
  16865. });
  16866. } else {
  16867. return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
  16868. }
  16869. };
  16870. var getWrapElements = function (rootNode, rng) {
  16871. var commonAnchorContainer = SugarElement.fromDom(rng.commonAncestorContainer);
  16872. var parents = parentsAndSelf(commonAnchorContainer, rootNode);
  16873. var wrapElements = filter$4(parents, function (elm) {
  16874. return isInline$1(elm) || isHeading(elm);
  16875. });
  16876. var listWrappers = getFullySelectedListWrappers(parents, rng);
  16877. var allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
  16878. return map$3(allWrappers, shallow);
  16879. };
  16880. var emptyFragment = function () {
  16881. return fromElements([]);
  16882. };
  16883. var getFragmentFromRange = function (rootNode, rng) {
  16884. return wrap(SugarElement.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
  16885. };
  16886. var getParentTable = function (rootElm, cell) {
  16887. return ancestor$2(cell, 'table', curry(eq, rootElm));
  16888. };
  16889. var getTableFragment = function (rootNode, selectedTableCells) {
  16890. return getParentTable(rootNode, selectedTableCells[0]).bind(function (tableElm) {
  16891. var firstCell = selectedTableCells[0];
  16892. var lastCell = selectedTableCells[selectedTableCells.length - 1];
  16893. var fullTableModel = fromDom(tableElm);
  16894. return subsection(fullTableModel, firstCell, lastCell).map(function (sectionedTableModel) {
  16895. return fromElements([toDom(sectionedTableModel)]);
  16896. });
  16897. }).getOrThunk(emptyFragment);
  16898. };
  16899. var getSelectionFragment = function (rootNode, ranges) {
  16900. return ranges.length > 0 && ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
  16901. };
  16902. var read$3 = function (rootNode, ranges) {
  16903. var selectedCells = getCellsFromElementOrRanges(ranges, rootNode);
  16904. return selectedCells.length > 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
  16905. };
  16906. var trimLeadingCollapsibleText = function (text) {
  16907. return text.replace(/^[ \f\n\r\t\v]+/, '');
  16908. };
  16909. var isCollapsibleWhitespace = function (text, index) {
  16910. return index >= 0 && index < text.length && isWhiteSpace(text.charAt(index));
  16911. };
  16912. var getInnerText = function (bin, shouldTrim) {
  16913. var text = trim$2(bin.innerText);
  16914. return shouldTrim ? trimLeadingCollapsibleText(text) : text;
  16915. };
  16916. var getContextNodeName = function (parentBlockOpt) {
  16917. return parentBlockOpt.map(function (block) {
  16918. return block.nodeName;
  16919. }).getOr('div').toLowerCase();
  16920. };
  16921. var getTextContent = function (editor) {
  16922. return Optional.from(editor.selection.getRng()).map(function (rng) {
  16923. var parentBlockOpt = Optional.from(editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock));
  16924. var body = editor.getBody();
  16925. var contextNodeName = getContextNodeName(parentBlockOpt);
  16926. var shouldTrimSpaces = Env.browser.isIE() && contextNodeName !== 'pre';
  16927. var bin = editor.dom.add(body, contextNodeName, {
  16928. 'data-mce-bogus': 'all',
  16929. 'style': 'overflow: hidden; opacity: 0;'
  16930. }, rng.cloneContents());
  16931. var text = getInnerText(bin, shouldTrimSpaces);
  16932. var nonRenderedText = trim$2(bin.textContent);
  16933. editor.dom.remove(bin);
  16934. if (isCollapsibleWhitespace(nonRenderedText, 0) || isCollapsibleWhitespace(nonRenderedText, nonRenderedText.length - 1)) {
  16935. var parentBlock = parentBlockOpt.getOr(body);
  16936. var parentBlockText = getInnerText(parentBlock, shouldTrimSpaces);
  16937. var textIndex = parentBlockText.indexOf(text);
  16938. if (textIndex === -1) {
  16939. return text;
  16940. } else {
  16941. var hasProceedingSpace = isCollapsibleWhitespace(parentBlockText, textIndex - 1);
  16942. var hasTrailingSpace = isCollapsibleWhitespace(parentBlockText, textIndex + text.length);
  16943. return (hasProceedingSpace ? ' ' : '') + text + (hasTrailingSpace ? ' ' : '');
  16944. }
  16945. } else {
  16946. return text;
  16947. }
  16948. }).getOr('');
  16949. };
  16950. var getSerializedContent = function (editor, args) {
  16951. var rng = editor.selection.getRng(), tmpElm = editor.dom.create('body');
  16952. var sel = editor.selection.getSel();
  16953. var ranges = processRanges(editor, getRanges(sel));
  16954. var fragment = args.contextual ? read$3(SugarElement.fromDom(editor.getBody()), ranges).dom : rng.cloneContents();
  16955. if (fragment) {
  16956. tmpElm.appendChild(fragment);
  16957. }
  16958. return editor.selection.serializer.serialize(tmpElm, args);
  16959. };
  16960. var setupArgs$1 = function (args, format) {
  16961. return __assign(__assign({}, args), {
  16962. format: format,
  16963. get: true,
  16964. selection: true
  16965. });
  16966. };
  16967. var getSelectedContentInternal = function (editor, format, args) {
  16968. if (args === void 0) {
  16969. args = {};
  16970. }
  16971. var defaultedArgs = setupArgs$1(args, format);
  16972. var updatedArgs = editor.fire('BeforeGetContent', defaultedArgs);
  16973. if (updatedArgs.isDefaultPrevented()) {
  16974. editor.fire('GetContent', updatedArgs);
  16975. return updatedArgs.content;
  16976. }
  16977. if (updatedArgs.format === 'text') {
  16978. return getTextContent(editor);
  16979. } else {
  16980. updatedArgs.getInner = true;
  16981. var content = getSerializedContent(editor, updatedArgs);
  16982. if (updatedArgs.format === 'tree') {
  16983. return content;
  16984. } else {
  16985. updatedArgs.content = editor.selection.isCollapsed() ? '' : content;
  16986. editor.fire('GetContent', updatedArgs);
  16987. return updatedArgs.content;
  16988. }
  16989. }
  16990. };
  16991. var KEEP = 0, INSERT = 1, DELETE = 2;
  16992. var diff = function (left, right) {
  16993. var size = left.length + right.length + 2;
  16994. var vDown = new Array(size);
  16995. var vUp = new Array(size);
  16996. var snake = function (start, end, diag) {
  16997. return {
  16998. start: start,
  16999. end: end,
  17000. diag: diag
  17001. };
  17002. };
  17003. var buildScript = function (start1, end1, start2, end2, script) {
  17004. var middle = getMiddleSnake(start1, end1, start2, end2);
  17005. if (middle === null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) {
  17006. var i = start1;
  17007. var j = start2;
  17008. while (i < end1 || j < end2) {
  17009. if (i < end1 && j < end2 && left[i] === right[j]) {
  17010. script.push([
  17011. KEEP,
  17012. left[i]
  17013. ]);
  17014. ++i;
  17015. ++j;
  17016. } else {
  17017. if (end1 - start1 > end2 - start2) {
  17018. script.push([
  17019. DELETE,
  17020. left[i]
  17021. ]);
  17022. ++i;
  17023. } else {
  17024. script.push([
  17025. INSERT,
  17026. right[j]
  17027. ]);
  17028. ++j;
  17029. }
  17030. }
  17031. }
  17032. } else {
  17033. buildScript(start1, middle.start, start2, middle.start - middle.diag, script);
  17034. for (var i2 = middle.start; i2 < middle.end; ++i2) {
  17035. script.push([
  17036. KEEP,
  17037. left[i2]
  17038. ]);
  17039. }
  17040. buildScript(middle.end, end1, middle.end - middle.diag, end2, script);
  17041. }
  17042. };
  17043. var buildSnake = function (start, diag, end1, end2) {
  17044. var end = start;
  17045. while (end - diag < end2 && end < end1 && left[end] === right[end - diag]) {
  17046. ++end;
  17047. }
  17048. return snake(start, end, diag);
  17049. };
  17050. var getMiddleSnake = function (start1, end1, start2, end2) {
  17051. var m = end1 - start1;
  17052. var n = end2 - start2;
  17053. if (m === 0 || n === 0) {
  17054. return null;
  17055. }
  17056. var delta = m - n;
  17057. var sum = n + m;
  17058. var offset = (sum % 2 === 0 ? sum : sum + 1) / 2;
  17059. vDown[1 + offset] = start1;
  17060. vUp[1 + offset] = end1 + 1;
  17061. var d, k, i, x, y;
  17062. for (d = 0; d <= offset; ++d) {
  17063. for (k = -d; k <= d; k += 2) {
  17064. i = k + offset;
  17065. if (k === -d || k !== d && vDown[i - 1] < vDown[i + 1]) {
  17066. vDown[i] = vDown[i + 1];
  17067. } else {
  17068. vDown[i] = vDown[i - 1] + 1;
  17069. }
  17070. x = vDown[i];
  17071. y = x - start1 + start2 - k;
  17072. while (x < end1 && y < end2 && left[x] === right[y]) {
  17073. vDown[i] = ++x;
  17074. ++y;
  17075. }
  17076. if (delta % 2 !== 0 && delta - d <= k && k <= delta + d) {
  17077. if (vUp[i - delta] <= vDown[i]) {
  17078. return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2);
  17079. }
  17080. }
  17081. }
  17082. for (k = delta - d; k <= delta + d; k += 2) {
  17083. i = k + offset - delta;
  17084. if (k === delta - d || k !== delta + d && vUp[i + 1] <= vUp[i - 1]) {
  17085. vUp[i] = vUp[i + 1] - 1;
  17086. } else {
  17087. vUp[i] = vUp[i - 1];
  17088. }
  17089. x = vUp[i] - 1;
  17090. y = x - start1 + start2 - k;
  17091. while (x >= start1 && y >= start2 && left[x] === right[y]) {
  17092. vUp[i] = x--;
  17093. y--;
  17094. }
  17095. if (delta % 2 === 0 && -d <= k && k <= d) {
  17096. if (vUp[i] <= vDown[i + delta]) {
  17097. return buildSnake(vUp[i], k + start1 - start2, end1, end2);
  17098. }
  17099. }
  17100. }
  17101. }
  17102. };
  17103. var script = [];
  17104. buildScript(0, left.length, 0, right.length, script);
  17105. return script;
  17106. };
  17107. var getOuterHtml = function (elm) {
  17108. if (isElement$5(elm)) {
  17109. return elm.outerHTML;
  17110. } else if (isText$7(elm)) {
  17111. return Entities.encodeRaw(elm.data, false);
  17112. } else if (isComment(elm)) {
  17113. return '<!--' + elm.data + '-->';
  17114. }
  17115. return '';
  17116. };
  17117. var createFragment = function (html) {
  17118. var node;
  17119. var container = document.createElement('div');
  17120. var frag = document.createDocumentFragment();
  17121. if (html) {
  17122. container.innerHTML = html;
  17123. }
  17124. while (node = container.firstChild) {
  17125. frag.appendChild(node);
  17126. }
  17127. return frag;
  17128. };
  17129. var insertAt = function (elm, html, index) {
  17130. var fragment = createFragment(html);
  17131. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  17132. var target = elm.childNodes[index];
  17133. target.parentNode.insertBefore(fragment, target);
  17134. } else {
  17135. elm.appendChild(fragment);
  17136. }
  17137. };
  17138. var removeAt = function (elm, index) {
  17139. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  17140. var target = elm.childNodes[index];
  17141. target.parentNode.removeChild(target);
  17142. }
  17143. };
  17144. var applyDiff = function (diff, elm) {
  17145. var index = 0;
  17146. each$k(diff, function (action) {
  17147. if (action[0] === KEEP) {
  17148. index++;
  17149. } else if (action[0] === INSERT) {
  17150. insertAt(elm, action[1], index);
  17151. index++;
  17152. } else if (action[0] === DELETE) {
  17153. removeAt(elm, index);
  17154. }
  17155. });
  17156. };
  17157. var read$2 = function (elm) {
  17158. return filter$4(map$3(from(elm.childNodes), getOuterHtml), function (item) {
  17159. return item.length > 0;
  17160. });
  17161. };
  17162. var write = function (fragments, elm) {
  17163. var currentFragments = map$3(from(elm.childNodes), getOuterHtml);
  17164. applyDiff(diff(currentFragments, fragments), elm);
  17165. return elm;
  17166. };
  17167. var lazyTempDocument = cached(function () {
  17168. return document.implementation.createHTMLDocument('undo');
  17169. });
  17170. var hasIframes = function (html) {
  17171. return html.indexOf('</iframe>') !== -1;
  17172. };
  17173. var createFragmentedLevel = function (fragments) {
  17174. return {
  17175. type: 'fragmented',
  17176. fragments: fragments,
  17177. content: '',
  17178. bookmark: null,
  17179. beforeBookmark: null
  17180. };
  17181. };
  17182. var createCompleteLevel = function (content) {
  17183. return {
  17184. type: 'complete',
  17185. fragments: null,
  17186. content: content,
  17187. bookmark: null,
  17188. beforeBookmark: null
  17189. };
  17190. };
  17191. var createFromEditor = function (editor) {
  17192. var fragments = read$2(editor.getBody());
  17193. var trimmedFragments = bind(fragments, function (html) {
  17194. var trimmed = trimInternal(editor.serializer, html);
  17195. return trimmed.length > 0 ? [trimmed] : [];
  17196. });
  17197. var content = trimmedFragments.join('');
  17198. return hasIframes(content) ? createFragmentedLevel(trimmedFragments) : createCompleteLevel(content);
  17199. };
  17200. var applyToEditor = function (editor, level, before) {
  17201. var bookmark = before ? level.beforeBookmark : level.bookmark;
  17202. if (level.type === 'fragmented') {
  17203. write(level.fragments, editor.getBody());
  17204. } else {
  17205. editor.setContent(level.content, {
  17206. format: 'raw',
  17207. no_selection: isNonNullable(bookmark) && isPathBookmark(bookmark) ? !bookmark.isFakeCaret : true
  17208. });
  17209. }
  17210. editor.selection.moveToBookmark(bookmark);
  17211. };
  17212. var getLevelContent = function (level) {
  17213. return level.type === 'fragmented' ? level.fragments.join('') : level.content;
  17214. };
  17215. var getCleanLevelContent = function (level) {
  17216. var elm = SugarElement.fromTag('body', lazyTempDocument());
  17217. set(elm, getLevelContent(level));
  17218. each$k(descendants(elm, '*[data-mce-bogus]'), unwrap);
  17219. return get$3(elm);
  17220. };
  17221. var hasEqualContent = function (level1, level2) {
  17222. return getLevelContent(level1) === getLevelContent(level2);
  17223. };
  17224. var hasEqualCleanedContent = function (level1, level2) {
  17225. return getCleanLevelContent(level1) === getCleanLevelContent(level2);
  17226. };
  17227. var isEq$1 = function (level1, level2) {
  17228. if (!level1 || !level2) {
  17229. return false;
  17230. } else if (hasEqualContent(level1, level2)) {
  17231. return true;
  17232. } else {
  17233. return hasEqualCleanedContent(level1, level2);
  17234. }
  17235. };
  17236. var isUnlocked = function (locks) {
  17237. return locks.get() === 0;
  17238. };
  17239. var setTyping = function (undoManager, typing, locks) {
  17240. if (isUnlocked(locks)) {
  17241. undoManager.typing = typing;
  17242. }
  17243. };
  17244. var endTyping = function (undoManager, locks) {
  17245. if (undoManager.typing) {
  17246. setTyping(undoManager, false, locks);
  17247. undoManager.add();
  17248. }
  17249. };
  17250. var endTypingLevelIgnoreLocks = function (undoManager) {
  17251. if (undoManager.typing) {
  17252. undoManager.typing = false;
  17253. undoManager.add();
  17254. }
  17255. };
  17256. var beforeChange$1 = function (editor, locks, beforeBookmark) {
  17257. if (isUnlocked(locks)) {
  17258. beforeBookmark.set(getUndoBookmark(editor.selection));
  17259. }
  17260. };
  17261. var addUndoLevel$1 = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  17262. var currentLevel = createFromEditor(editor);
  17263. level = level || {};
  17264. level = Tools.extend(level, currentLevel);
  17265. if (isUnlocked(locks) === false || editor.removed) {
  17266. return null;
  17267. }
  17268. var lastLevel = undoManager.data[index.get()];
  17269. if (editor.fire('BeforeAddUndo', {
  17270. level: level,
  17271. lastLevel: lastLevel,
  17272. originalEvent: event
  17273. }).isDefaultPrevented()) {
  17274. return null;
  17275. }
  17276. if (lastLevel && isEq$1(lastLevel, level)) {
  17277. return null;
  17278. }
  17279. if (undoManager.data[index.get()]) {
  17280. beforeBookmark.get().each(function (bm) {
  17281. undoManager.data[index.get()].beforeBookmark = bm;
  17282. });
  17283. }
  17284. var customUndoRedoLevels = getCustomUndoRedoLevels(editor);
  17285. if (customUndoRedoLevels) {
  17286. if (undoManager.data.length > customUndoRedoLevels) {
  17287. for (var i = 0; i < undoManager.data.length - 1; i++) {
  17288. undoManager.data[i] = undoManager.data[i + 1];
  17289. }
  17290. undoManager.data.length--;
  17291. index.set(undoManager.data.length);
  17292. }
  17293. }
  17294. level.bookmark = getUndoBookmark(editor.selection);
  17295. if (index.get() < undoManager.data.length - 1) {
  17296. undoManager.data.length = index.get() + 1;
  17297. }
  17298. undoManager.data.push(level);
  17299. index.set(undoManager.data.length - 1);
  17300. var args = {
  17301. level: level,
  17302. lastLevel: lastLevel,
  17303. originalEvent: event
  17304. };
  17305. if (index.get() > 0) {
  17306. editor.setDirty(true);
  17307. editor.fire('AddUndo', args);
  17308. editor.fire('change', args);
  17309. } else {
  17310. editor.fire('AddUndo', args);
  17311. }
  17312. return level;
  17313. };
  17314. var clear$1 = function (editor, undoManager, index) {
  17315. undoManager.data = [];
  17316. index.set(0);
  17317. undoManager.typing = false;
  17318. editor.fire('ClearUndos');
  17319. };
  17320. var extra$1 = function (editor, undoManager, index, callback1, callback2) {
  17321. if (undoManager.transact(callback1)) {
  17322. var bookmark = undoManager.data[index.get()].bookmark;
  17323. var lastLevel = undoManager.data[index.get() - 1];
  17324. applyToEditor(editor, lastLevel, true);
  17325. if (undoManager.transact(callback2)) {
  17326. undoManager.data[index.get() - 1].beforeBookmark = bookmark;
  17327. }
  17328. }
  17329. };
  17330. var redo$1 = function (editor, index, data) {
  17331. var level;
  17332. if (index.get() < data.length - 1) {
  17333. index.set(index.get() + 1);
  17334. level = data[index.get()];
  17335. applyToEditor(editor, level, false);
  17336. editor.setDirty(true);
  17337. editor.fire('Redo', { level: level });
  17338. }
  17339. return level;
  17340. };
  17341. var undo$1 = function (editor, undoManager, locks, index) {
  17342. var level;
  17343. if (undoManager.typing) {
  17344. undoManager.add();
  17345. undoManager.typing = false;
  17346. setTyping(undoManager, false, locks);
  17347. }
  17348. if (index.get() > 0) {
  17349. index.set(index.get() - 1);
  17350. level = undoManager.data[index.get()];
  17351. applyToEditor(editor, level, true);
  17352. editor.setDirty(true);
  17353. editor.fire('Undo', { level: level });
  17354. }
  17355. return level;
  17356. };
  17357. var reset$1 = function (undoManager) {
  17358. undoManager.clear();
  17359. undoManager.add();
  17360. };
  17361. var hasUndo$1 = function (editor, undoManager, index) {
  17362. return index.get() > 0 || undoManager.typing && undoManager.data[0] && !isEq$1(createFromEditor(editor), undoManager.data[0]);
  17363. };
  17364. var hasRedo$1 = function (undoManager, index) {
  17365. return index.get() < undoManager.data.length - 1 && !undoManager.typing;
  17366. };
  17367. var transact$1 = function (undoManager, locks, callback) {
  17368. endTyping(undoManager, locks);
  17369. undoManager.beforeChange();
  17370. undoManager.ignore(callback);
  17371. return undoManager.add();
  17372. };
  17373. var ignore$1 = function (locks, callback) {
  17374. try {
  17375. locks.set(locks.get() + 1);
  17376. callback();
  17377. } finally {
  17378. locks.set(locks.get() - 1);
  17379. }
  17380. };
  17381. var addVisualInternal = function (editor, elm) {
  17382. var dom = editor.dom;
  17383. var scope = isNonNullable(elm) ? elm : editor.getBody();
  17384. if (isUndefined(editor.hasVisual)) {
  17385. editor.hasVisual = isVisualAidsEnabled(editor);
  17386. }
  17387. each$k(dom.select('table,a', scope), function (matchedElm) {
  17388. switch (matchedElm.nodeName) {
  17389. case 'TABLE':
  17390. var cls = getVisualAidsTableClass(editor);
  17391. var value = dom.getAttrib(matchedElm, 'border');
  17392. if ((!value || value === '0') && editor.hasVisual) {
  17393. dom.addClass(matchedElm, cls);
  17394. } else {
  17395. dom.removeClass(matchedElm, cls);
  17396. }
  17397. break;
  17398. case 'A':
  17399. if (!dom.getAttrib(matchedElm, 'href')) {
  17400. var value_1 = dom.getAttrib(matchedElm, 'name') || matchedElm.id;
  17401. var cls_1 = getVisualAidsAnchorClass(editor);
  17402. if (value_1 && editor.hasVisual) {
  17403. dom.addClass(matchedElm, cls_1);
  17404. } else {
  17405. dom.removeClass(matchedElm, cls_1);
  17406. }
  17407. }
  17408. break;
  17409. }
  17410. });
  17411. editor.fire('VisualAid', {
  17412. element: elm,
  17413. hasVisual: editor.hasVisual
  17414. });
  17415. };
  17416. var makePlainAdaptor = function (editor) {
  17417. return {
  17418. undoManager: {
  17419. beforeChange: function (locks, beforeBookmark) {
  17420. return beforeChange$1(editor, locks, beforeBookmark);
  17421. },
  17422. add: function (undoManager, index, locks, beforeBookmark, level, event) {
  17423. return addUndoLevel$1(editor, undoManager, index, locks, beforeBookmark, level, event);
  17424. },
  17425. undo: function (undoManager, locks, index) {
  17426. return undo$1(editor, undoManager, locks, index);
  17427. },
  17428. redo: function (index, data) {
  17429. return redo$1(editor, index, data);
  17430. },
  17431. clear: function (undoManager, index) {
  17432. return clear$1(editor, undoManager, index);
  17433. },
  17434. reset: function (undoManager) {
  17435. return reset$1(undoManager);
  17436. },
  17437. hasUndo: function (undoManager, index) {
  17438. return hasUndo$1(editor, undoManager, index);
  17439. },
  17440. hasRedo: function (undoManager, index) {
  17441. return hasRedo$1(undoManager, index);
  17442. },
  17443. transact: function (undoManager, locks, callback) {
  17444. return transact$1(undoManager, locks, callback);
  17445. },
  17446. ignore: function (locks, callback) {
  17447. return ignore$1(locks, callback);
  17448. },
  17449. extra: function (undoManager, index, callback1, callback2) {
  17450. return extra$1(editor, undoManager, index, callback1, callback2);
  17451. }
  17452. },
  17453. formatter: {
  17454. match: function (name, vars, node, similar) {
  17455. return match$2(editor, name, vars, node, similar);
  17456. },
  17457. matchAll: function (names, vars) {
  17458. return matchAll(editor, names, vars);
  17459. },
  17460. matchNode: function (node, name, vars, similar) {
  17461. return matchNode(editor, node, name, vars, similar);
  17462. },
  17463. canApply: function (name) {
  17464. return canApply(editor, name);
  17465. },
  17466. closest: function (names) {
  17467. return closest(editor, names);
  17468. },
  17469. apply: function (name, vars, node) {
  17470. return applyFormat$1(editor, name, vars, node);
  17471. },
  17472. remove: function (name, vars, node, similar) {
  17473. return remove$1(editor, name, vars, node, similar);
  17474. },
  17475. toggle: function (name, vars, node) {
  17476. return toggle(editor, name, vars, node);
  17477. },
  17478. formatChanged: function (registeredFormatListeners, formats, callback, similar, vars) {
  17479. return formatChangedInternal(editor, registeredFormatListeners, formats, callback, similar, vars);
  17480. }
  17481. },
  17482. editor: {
  17483. getContent: function (args, format) {
  17484. return getContentInternal(editor, args, format);
  17485. },
  17486. setContent: function (content, args) {
  17487. return setContentInternal(editor, content, args);
  17488. },
  17489. insertContent: function (value, details) {
  17490. return insertHtmlAtCaret(editor, value, details);
  17491. },
  17492. addVisual: function (elm) {
  17493. return addVisualInternal(editor, elm);
  17494. }
  17495. },
  17496. selection: {
  17497. getContent: function (format, args) {
  17498. return getSelectedContentInternal(editor, format, args);
  17499. }
  17500. },
  17501. raw: {
  17502. getModel: function () {
  17503. return Optional.none();
  17504. }
  17505. }
  17506. };
  17507. };
  17508. var makeRtcAdaptor = function (rtcEditor) {
  17509. var defaultVars = function (vars) {
  17510. return isObject(vars) ? vars : {};
  17511. };
  17512. var undoManager = rtcEditor.undoManager, formatter = rtcEditor.formatter, editor = rtcEditor.editor, selection = rtcEditor.selection, raw = rtcEditor.raw;
  17513. return {
  17514. undoManager: {
  17515. beforeChange: undoManager.beforeChange,
  17516. add: undoManager.add,
  17517. undo: undoManager.undo,
  17518. redo: undoManager.redo,
  17519. clear: undoManager.clear,
  17520. reset: undoManager.reset,
  17521. hasUndo: undoManager.hasUndo,
  17522. hasRedo: undoManager.hasRedo,
  17523. transact: function (_undoManager, _locks, fn) {
  17524. return undoManager.transact(fn);
  17525. },
  17526. ignore: function (_locks, callback) {
  17527. return undoManager.ignore(callback);
  17528. },
  17529. extra: function (_undoManager, _index, callback1, callback2) {
  17530. return undoManager.extra(callback1, callback2);
  17531. }
  17532. },
  17533. formatter: {
  17534. match: function (name, vars, _node, similar) {
  17535. return formatter.match(name, defaultVars(vars), similar);
  17536. },
  17537. matchAll: formatter.matchAll,
  17538. matchNode: formatter.matchNode,
  17539. canApply: function (name) {
  17540. return formatter.canApply(name);
  17541. },
  17542. closest: function (names) {
  17543. return formatter.closest(names);
  17544. },
  17545. apply: function (name, vars, _node) {
  17546. return formatter.apply(name, defaultVars(vars));
  17547. },
  17548. remove: function (name, vars, _node, _similar) {
  17549. return formatter.remove(name, defaultVars(vars));
  17550. },
  17551. toggle: function (name, vars, _node) {
  17552. return formatter.toggle(name, defaultVars(vars));
  17553. },
  17554. formatChanged: function (_rfl, formats, callback, similar, vars) {
  17555. return formatter.formatChanged(formats, callback, similar, vars);
  17556. }
  17557. },
  17558. editor: {
  17559. getContent: function (args, _format) {
  17560. return editor.getContent(args);
  17561. },
  17562. setContent: function (content, args) {
  17563. return editor.setContent(content, args);
  17564. },
  17565. insertContent: function (content, _details) {
  17566. return editor.insertContent(content);
  17567. },
  17568. addVisual: editor.addVisual
  17569. },
  17570. selection: {
  17571. getContent: function (_format, args) {
  17572. return selection.getContent(args);
  17573. }
  17574. },
  17575. raw: {
  17576. getModel: function () {
  17577. return Optional.some(raw.getRawModel());
  17578. }
  17579. }
  17580. };
  17581. };
  17582. var makeNoopAdaptor = function () {
  17583. var nul = constant(null);
  17584. var empty = constant('');
  17585. return {
  17586. undoManager: {
  17587. beforeChange: noop,
  17588. add: nul,
  17589. undo: nul,
  17590. redo: nul,
  17591. clear: noop,
  17592. reset: noop,
  17593. hasUndo: never,
  17594. hasRedo: never,
  17595. transact: nul,
  17596. ignore: noop,
  17597. extra: noop
  17598. },
  17599. formatter: {
  17600. match: never,
  17601. matchAll: constant([]),
  17602. matchNode: constant(undefined),
  17603. canApply: never,
  17604. closest: empty,
  17605. apply: noop,
  17606. remove: noop,
  17607. toggle: noop,
  17608. formatChanged: constant({ unbind: noop })
  17609. },
  17610. editor: {
  17611. getContent: empty,
  17612. setContent: empty,
  17613. insertContent: noop,
  17614. addVisual: noop
  17615. },
  17616. selection: { getContent: empty },
  17617. raw: { getModel: constant(Optional.none()) }
  17618. };
  17619. };
  17620. var isRtc = function (editor) {
  17621. return has$2(editor.plugins, 'rtc');
  17622. };
  17623. var getRtcSetup = function (editor) {
  17624. return get$9(editor.plugins, 'rtc').bind(function (rtcPlugin) {
  17625. return Optional.from(rtcPlugin.setup);
  17626. });
  17627. };
  17628. var setup$i = function (editor) {
  17629. var editorCast = editor;
  17630. return getRtcSetup(editor).fold(function () {
  17631. editorCast.rtcInstance = makePlainAdaptor(editor);
  17632. return Optional.none();
  17633. }, function (setup) {
  17634. editorCast.rtcInstance = makeNoopAdaptor();
  17635. return Optional.some(function () {
  17636. return setup().then(function (rtcEditor) {
  17637. editorCast.rtcInstance = makeRtcAdaptor(rtcEditor);
  17638. return rtcEditor.rtc.isRemote;
  17639. });
  17640. });
  17641. });
  17642. };
  17643. var getRtcInstanceWithFallback = function (editor) {
  17644. return editor.rtcInstance ? editor.rtcInstance : makePlainAdaptor(editor);
  17645. };
  17646. var getRtcInstanceWithError = function (editor) {
  17647. var rtcInstance = editor.rtcInstance;
  17648. if (!rtcInstance) {
  17649. throw new Error('Failed to get RTC instance not yet initialized.');
  17650. } else {
  17651. return rtcInstance;
  17652. }
  17653. };
  17654. var beforeChange = function (editor, locks, beforeBookmark) {
  17655. getRtcInstanceWithError(editor).undoManager.beforeChange(locks, beforeBookmark);
  17656. };
  17657. var addUndoLevel = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  17658. return getRtcInstanceWithError(editor).undoManager.add(undoManager, index, locks, beforeBookmark, level, event);
  17659. };
  17660. var undo = function (editor, undoManager, locks, index) {
  17661. return getRtcInstanceWithError(editor).undoManager.undo(undoManager, locks, index);
  17662. };
  17663. var redo = function (editor, index, data) {
  17664. return getRtcInstanceWithError(editor).undoManager.redo(index, data);
  17665. };
  17666. var clear = function (editor, undoManager, index) {
  17667. getRtcInstanceWithError(editor).undoManager.clear(undoManager, index);
  17668. };
  17669. var reset = function (editor, undoManager) {
  17670. getRtcInstanceWithError(editor).undoManager.reset(undoManager);
  17671. };
  17672. var hasUndo = function (editor, undoManager, index) {
  17673. return getRtcInstanceWithError(editor).undoManager.hasUndo(undoManager, index);
  17674. };
  17675. var hasRedo = function (editor, undoManager, index) {
  17676. return getRtcInstanceWithError(editor).undoManager.hasRedo(undoManager, index);
  17677. };
  17678. var transact = function (editor, undoManager, locks, callback) {
  17679. return getRtcInstanceWithError(editor).undoManager.transact(undoManager, locks, callback);
  17680. };
  17681. var ignore = function (editor, locks, callback) {
  17682. getRtcInstanceWithError(editor).undoManager.ignore(locks, callback);
  17683. };
  17684. var extra = function (editor, undoManager, index, callback1, callback2) {
  17685. getRtcInstanceWithError(editor).undoManager.extra(undoManager, index, callback1, callback2);
  17686. };
  17687. var matchFormat = function (editor, name, vars, node, similar) {
  17688. return getRtcInstanceWithError(editor).formatter.match(name, vars, node, similar);
  17689. };
  17690. var matchAllFormats = function (editor, names, vars) {
  17691. return getRtcInstanceWithError(editor).formatter.matchAll(names, vars);
  17692. };
  17693. var matchNodeFormat = function (editor, node, name, vars, similar) {
  17694. return getRtcInstanceWithError(editor).formatter.matchNode(node, name, vars, similar);
  17695. };
  17696. var canApplyFormat = function (editor, name) {
  17697. return getRtcInstanceWithError(editor).formatter.canApply(name);
  17698. };
  17699. var closestFormat = function (editor, names) {
  17700. return getRtcInstanceWithError(editor).formatter.closest(names);
  17701. };
  17702. var applyFormat = function (editor, name, vars, node) {
  17703. getRtcInstanceWithError(editor).formatter.apply(name, vars, node);
  17704. };
  17705. var removeFormat = function (editor, name, vars, node, similar) {
  17706. getRtcInstanceWithError(editor).formatter.remove(name, vars, node, similar);
  17707. };
  17708. var toggleFormat = function (editor, name, vars, node) {
  17709. getRtcInstanceWithError(editor).formatter.toggle(name, vars, node);
  17710. };
  17711. var formatChanged = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  17712. return getRtcInstanceWithError(editor).formatter.formatChanged(registeredFormatListeners, formats, callback, similar, vars);
  17713. };
  17714. var getContent$2 = function (editor, args, format) {
  17715. return getRtcInstanceWithFallback(editor).editor.getContent(args, format);
  17716. };
  17717. var setContent$2 = function (editor, content, args) {
  17718. return getRtcInstanceWithFallback(editor).editor.setContent(content, args);
  17719. };
  17720. var insertContent = function (editor, value, details) {
  17721. return getRtcInstanceWithFallback(editor).editor.insertContent(value, details);
  17722. };
  17723. var getSelectedContent = function (editor, format, args) {
  17724. return getRtcInstanceWithError(editor).selection.getContent(format, args);
  17725. };
  17726. var addVisual$1 = function (editor, elm) {
  17727. return getRtcInstanceWithError(editor).editor.addVisual(elm);
  17728. };
  17729. var getContent$1 = function (editor, args) {
  17730. if (args === void 0) {
  17731. args = {};
  17732. }
  17733. var format = args.format ? args.format : 'html';
  17734. return getSelectedContent(editor, format, args);
  17735. };
  17736. var removeEmpty = function (text) {
  17737. if (text.dom.length === 0) {
  17738. remove$7(text);
  17739. return Optional.none();
  17740. } else {
  17741. return Optional.some(text);
  17742. }
  17743. };
  17744. var walkPastBookmark = function (node, start) {
  17745. return node.filter(function (elm) {
  17746. return BookmarkManager.isBookmarkNode(elm.dom);
  17747. }).bind(start ? nextSibling : prevSibling);
  17748. };
  17749. var merge = function (outer, inner, rng, start) {
  17750. var outerElm = outer.dom;
  17751. var innerElm = inner.dom;
  17752. var oldLength = start ? outerElm.length : innerElm.length;
  17753. if (start) {
  17754. mergeTextNodes(outerElm, innerElm, false, !start);
  17755. rng.setStart(innerElm, oldLength);
  17756. } else {
  17757. mergeTextNodes(innerElm, outerElm, false, !start);
  17758. rng.setEnd(innerElm, oldLength);
  17759. }
  17760. };
  17761. var normalizeTextIfRequired = function (inner, start) {
  17762. parent(inner).each(function (root) {
  17763. var text = inner.dom;
  17764. if (start && needsToBeNbspLeft(root, CaretPosition(text, 0))) {
  17765. normalizeWhitespaceAfter(text, 0);
  17766. } else if (!start && needsToBeNbspRight(root, CaretPosition(text, text.length))) {
  17767. normalizeWhitespaceBefore(text, text.length);
  17768. }
  17769. });
  17770. };
  17771. var mergeAndNormalizeText = function (outerNode, innerNode, rng, start) {
  17772. outerNode.bind(function (outer) {
  17773. var normalizer = start ? normalizeWhitespaceBefore : normalizeWhitespaceAfter;
  17774. normalizer(outer.dom, start ? outer.dom.length : 0);
  17775. return innerNode.filter(isText$8).map(function (inner) {
  17776. return merge(outer, inner, rng, start);
  17777. });
  17778. }).orThunk(function () {
  17779. var innerTextNode = walkPastBookmark(innerNode, start).or(innerNode).filter(isText$8);
  17780. return innerTextNode.map(function (inner) {
  17781. return normalizeTextIfRequired(inner, start);
  17782. });
  17783. });
  17784. };
  17785. var rngSetContent = function (rng, fragment) {
  17786. var firstChild = Optional.from(fragment.firstChild).map(SugarElement.fromDom);
  17787. var lastChild = Optional.from(fragment.lastChild).map(SugarElement.fromDom);
  17788. rng.deleteContents();
  17789. rng.insertNode(fragment);
  17790. var prevText = firstChild.bind(prevSibling).filter(isText$8).bind(removeEmpty);
  17791. var nextText = lastChild.bind(nextSibling).filter(isText$8).bind(removeEmpty);
  17792. mergeAndNormalizeText(prevText, firstChild, rng, true);
  17793. mergeAndNormalizeText(nextText, lastChild, rng, false);
  17794. rng.collapse(false);
  17795. };
  17796. var setupArgs = function (args, content) {
  17797. return __assign(__assign({ format: 'html' }, args), {
  17798. set: true,
  17799. selection: true,
  17800. content: content
  17801. });
  17802. };
  17803. var cleanContent = function (editor, args) {
  17804. if (args.format !== 'raw') {
  17805. var rng = editor.selection.getRng();
  17806. var contextBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
  17807. var contextArgs = contextBlock ? { context: contextBlock.nodeName.toLowerCase() } : {};
  17808. var node = editor.parser.parse(args.content, __assign(__assign({
  17809. isRootContent: true,
  17810. forced_root_block: false
  17811. }, contextArgs), args));
  17812. return HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(node);
  17813. } else {
  17814. return args.content;
  17815. }
  17816. };
  17817. var setContent$1 = function (editor, content, args) {
  17818. if (args === void 0) {
  17819. args = {};
  17820. }
  17821. var defaultedArgs = setupArgs(args, content);
  17822. var updatedArgs = defaultedArgs;
  17823. if (!defaultedArgs.no_events) {
  17824. var eventArgs = editor.fire('BeforeSetContent', defaultedArgs);
  17825. if (eventArgs.isDefaultPrevented()) {
  17826. editor.fire('SetContent', eventArgs);
  17827. return;
  17828. } else {
  17829. updatedArgs = eventArgs;
  17830. }
  17831. }
  17832. updatedArgs.content = cleanContent(editor, updatedArgs);
  17833. var rng = editor.selection.getRng();
  17834. rngSetContent(rng, rng.createContextualFragment(updatedArgs.content));
  17835. editor.selection.setRng(rng);
  17836. scrollRangeIntoView(editor, rng);
  17837. if (!updatedArgs.no_events) {
  17838. editor.fire('SetContent', updatedArgs);
  17839. }
  17840. };
  17841. var deleteFromCallbackMap = function (callbackMap, selector, callback) {
  17842. if (callbackMap && has$2(callbackMap, selector)) {
  17843. var newCallbacks = filter$4(callbackMap[selector], function (cb) {
  17844. return cb !== callback;
  17845. });
  17846. if (newCallbacks.length === 0) {
  17847. delete callbackMap[selector];
  17848. } else {
  17849. callbackMap[selector] = newCallbacks;
  17850. }
  17851. }
  17852. };
  17853. function SelectorChanged (dom, editor) {
  17854. var selectorChangedData;
  17855. var currentSelectors;
  17856. var findMatchingNode = function (selector, nodes) {
  17857. return find$3(nodes, function (node) {
  17858. return dom.is(node, selector);
  17859. });
  17860. };
  17861. var getParents = function (elem) {
  17862. return dom.getParents(elem, null, dom.getRoot());
  17863. };
  17864. return {
  17865. selectorChangedWithUnbind: function (selector, callback) {
  17866. if (!selectorChangedData) {
  17867. selectorChangedData = {};
  17868. currentSelectors = {};
  17869. editor.on('NodeChange', function (e) {
  17870. var node = e.element;
  17871. var parents = getParents(node);
  17872. var matchedSelectors = {};
  17873. Tools.each(selectorChangedData, function (callbacks, selector) {
  17874. findMatchingNode(selector, parents).each(function (node) {
  17875. if (!currentSelectors[selector]) {
  17876. each$k(callbacks, function (callback) {
  17877. callback(true, {
  17878. node: node,
  17879. selector: selector,
  17880. parents: parents
  17881. });
  17882. });
  17883. currentSelectors[selector] = callbacks;
  17884. }
  17885. matchedSelectors[selector] = callbacks;
  17886. });
  17887. });
  17888. Tools.each(currentSelectors, function (callbacks, selector) {
  17889. if (!matchedSelectors[selector]) {
  17890. delete currentSelectors[selector];
  17891. Tools.each(callbacks, function (callback) {
  17892. callback(false, {
  17893. node: node,
  17894. selector: selector,
  17895. parents: parents
  17896. });
  17897. });
  17898. }
  17899. });
  17900. });
  17901. }
  17902. if (!selectorChangedData[selector]) {
  17903. selectorChangedData[selector] = [];
  17904. }
  17905. selectorChangedData[selector].push(callback);
  17906. findMatchingNode(selector, getParents(editor.selection.getStart())).each(function () {
  17907. currentSelectors[selector] = selectorChangedData[selector];
  17908. });
  17909. return {
  17910. unbind: function () {
  17911. deleteFromCallbackMap(selectorChangedData, selector, callback);
  17912. deleteFromCallbackMap(currentSelectors, selector, callback);
  17913. }
  17914. };
  17915. }
  17916. };
  17917. }
  17918. var isNativeIeSelection = function (rng) {
  17919. return !!rng.select;
  17920. };
  17921. var isAttachedToDom = function (node) {
  17922. return !!(node && node.ownerDocument) && contains$1(SugarElement.fromDom(node.ownerDocument), SugarElement.fromDom(node));
  17923. };
  17924. var isValidRange = function (rng) {
  17925. if (!rng) {
  17926. return false;
  17927. } else if (isNativeIeSelection(rng)) {
  17928. return true;
  17929. } else {
  17930. return isAttachedToDom(rng.startContainer) && isAttachedToDom(rng.endContainer);
  17931. }
  17932. };
  17933. var EditorSelection = function (dom, win, serializer, editor) {
  17934. var selectedRange;
  17935. var explicitRange;
  17936. var selectorChangedWithUnbind = SelectorChanged(dom, editor).selectorChangedWithUnbind;
  17937. var setCursorLocation = function (node, offset) {
  17938. var rng = dom.createRng();
  17939. if (isNonNullable(node) && isNonNullable(offset)) {
  17940. rng.setStart(node, offset);
  17941. rng.setEnd(node, offset);
  17942. setRng(rng);
  17943. collapse(false);
  17944. } else {
  17945. moveEndPoint(dom, rng, editor.getBody(), true);
  17946. setRng(rng);
  17947. }
  17948. };
  17949. var getContent = function (args) {
  17950. return getContent$1(editor, args);
  17951. };
  17952. var setContent = function (content, args) {
  17953. return setContent$1(editor, content, args);
  17954. };
  17955. var getStart$1 = function (real) {
  17956. return getStart(editor.getBody(), getRng$1(), real);
  17957. };
  17958. var getEnd$1 = function (real) {
  17959. return getEnd(editor.getBody(), getRng$1(), real);
  17960. };
  17961. var getBookmark = function (type, normalized) {
  17962. return bookmarkManager.getBookmark(type, normalized);
  17963. };
  17964. var moveToBookmark = function (bookmark) {
  17965. return bookmarkManager.moveToBookmark(bookmark);
  17966. };
  17967. var select$1 = function (node, content) {
  17968. select(dom, node, content).each(setRng);
  17969. return node;
  17970. };
  17971. var isCollapsed = function () {
  17972. var rng = getRng$1(), sel = getSel();
  17973. if (!rng || rng.item) {
  17974. return false;
  17975. }
  17976. if (rng.compareEndPoints) {
  17977. return rng.compareEndPoints('StartToEnd', rng) === 0;
  17978. }
  17979. return !sel || rng.collapsed;
  17980. };
  17981. var collapse = function (toStart) {
  17982. var rng = getRng$1();
  17983. rng.collapse(!!toStart);
  17984. setRng(rng);
  17985. };
  17986. var getSel = function () {
  17987. return win.getSelection ? win.getSelection() : win.document.selection;
  17988. };
  17989. var getRng$1 = function () {
  17990. var selection, rng, elm;
  17991. var tryCompareBoundaryPoints = function (how, sourceRange, destinationRange) {
  17992. try {
  17993. return sourceRange.compareBoundaryPoints(how, destinationRange);
  17994. } catch (ex) {
  17995. return -1;
  17996. }
  17997. };
  17998. var doc = win.document;
  17999. if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  18000. var bookmark = getRng(editor);
  18001. if (bookmark.isSome()) {
  18002. return bookmark.map(function (r) {
  18003. return processRanges(editor, [r])[0];
  18004. }).getOr(doc.createRange());
  18005. }
  18006. }
  18007. try {
  18008. if ((selection = getSel()) && !isRestrictedNode(selection.anchorNode)) {
  18009. if (selection.rangeCount > 0) {
  18010. rng = selection.getRangeAt(0);
  18011. } else {
  18012. rng = selection.createRange ? selection.createRange() : doc.createRange();
  18013. }
  18014. rng = processRanges(editor, [rng])[0];
  18015. }
  18016. } catch (ex) {
  18017. }
  18018. if (!rng) {
  18019. rng = doc.createRange ? doc.createRange() : doc.body.createTextRange();
  18020. }
  18021. if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
  18022. elm = dom.getRoot();
  18023. rng.setStart(elm, 0);
  18024. rng.setEnd(elm, 0);
  18025. }
  18026. if (selectedRange && explicitRange) {
  18027. if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 && tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
  18028. rng = explicitRange;
  18029. } else {
  18030. selectedRange = null;
  18031. explicitRange = null;
  18032. }
  18033. }
  18034. return rng;
  18035. };
  18036. var setRng = function (rng, forward) {
  18037. var node;
  18038. if (!isValidRange(rng)) {
  18039. return;
  18040. }
  18041. var ieRange = isNativeIeSelection(rng) ? rng : null;
  18042. if (ieRange) {
  18043. explicitRange = null;
  18044. try {
  18045. ieRange.select();
  18046. } catch (ex) {
  18047. }
  18048. return;
  18049. }
  18050. var sel = getSel();
  18051. var evt = editor.fire('SetSelectionRange', {
  18052. range: rng,
  18053. forward: forward
  18054. });
  18055. rng = evt.range;
  18056. if (sel) {
  18057. explicitRange = rng;
  18058. try {
  18059. sel.removeAllRanges();
  18060. sel.addRange(rng);
  18061. } catch (ex) {
  18062. }
  18063. if (forward === false && sel.extend) {
  18064. sel.collapse(rng.endContainer, rng.endOffset);
  18065. sel.extend(rng.startContainer, rng.startOffset);
  18066. }
  18067. selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
  18068. }
  18069. if (!rng.collapsed && rng.startContainer === rng.endContainer && sel.setBaseAndExtent && !Env.ie) {
  18070. if (rng.endOffset - rng.startOffset < 2) {
  18071. if (rng.startContainer.hasChildNodes()) {
  18072. node = rng.startContainer.childNodes[rng.startOffset];
  18073. if (node && node.tagName === 'IMG') {
  18074. sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
  18075. if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
  18076. sel.setBaseAndExtent(node, 0, node, 1);
  18077. }
  18078. }
  18079. }
  18080. }
  18081. }
  18082. editor.fire('AfterSetSelectionRange', {
  18083. range: rng,
  18084. forward: forward
  18085. });
  18086. };
  18087. var setNode = function (elm) {
  18088. setContent(dom.getOuterHTML(elm));
  18089. return elm;
  18090. };
  18091. var getNode$1 = function () {
  18092. return getNode(editor.getBody(), getRng$1());
  18093. };
  18094. var getSelectedBlocks$1 = function (startElm, endElm) {
  18095. return getSelectedBlocks(dom, getRng$1(), startElm, endElm);
  18096. };
  18097. var isForward = function () {
  18098. var sel = getSel();
  18099. var anchorNode = sel === null || sel === void 0 ? void 0 : sel.anchorNode;
  18100. var focusNode = sel === null || sel === void 0 ? void 0 : sel.focusNode;
  18101. if (!sel || !anchorNode || !focusNode || isRestrictedNode(anchorNode) || isRestrictedNode(focusNode)) {
  18102. return true;
  18103. }
  18104. var anchorRange = dom.createRng();
  18105. anchorRange.setStart(anchorNode, sel.anchorOffset);
  18106. anchorRange.collapse(true);
  18107. var focusRange = dom.createRng();
  18108. focusRange.setStart(focusNode, sel.focusOffset);
  18109. focusRange.collapse(true);
  18110. return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
  18111. };
  18112. var normalize = function () {
  18113. var rng = getRng$1();
  18114. var sel = getSel();
  18115. if (!hasMultipleRanges(sel) && hasAnyRanges(editor)) {
  18116. var normRng = normalize$2(dom, rng);
  18117. normRng.each(function (normRng) {
  18118. setRng(normRng, isForward());
  18119. });
  18120. return normRng.getOr(rng);
  18121. }
  18122. return rng;
  18123. };
  18124. var selectorChanged = function (selector, callback) {
  18125. selectorChangedWithUnbind(selector, callback);
  18126. return exports;
  18127. };
  18128. var getScrollContainer = function () {
  18129. var scrollContainer;
  18130. var node = dom.getRoot();
  18131. while (node && node.nodeName !== 'BODY') {
  18132. if (node.scrollHeight > node.clientHeight) {
  18133. scrollContainer = node;
  18134. break;
  18135. }
  18136. node = node.parentNode;
  18137. }
  18138. return scrollContainer;
  18139. };
  18140. var scrollIntoView = function (elm, alignToTop) {
  18141. if (isNonNullable(elm)) {
  18142. scrollElementIntoView(editor, elm, alignToTop);
  18143. } else {
  18144. scrollRangeIntoView(editor, getRng$1(), alignToTop);
  18145. }
  18146. };
  18147. var placeCaretAt = function (clientX, clientY) {
  18148. return setRng(fromPoint(clientX, clientY, editor.getDoc()));
  18149. };
  18150. var getBoundingClientRect = function () {
  18151. var rng = getRng$1();
  18152. return rng.collapsed ? CaretPosition.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
  18153. };
  18154. var destroy = function () {
  18155. win = selectedRange = explicitRange = null;
  18156. controlSelection.destroy();
  18157. };
  18158. var exports = {
  18159. bookmarkManager: null,
  18160. controlSelection: null,
  18161. dom: dom,
  18162. win: win,
  18163. serializer: serializer,
  18164. editor: editor,
  18165. collapse: collapse,
  18166. setCursorLocation: setCursorLocation,
  18167. getContent: getContent,
  18168. setContent: setContent,
  18169. getBookmark: getBookmark,
  18170. moveToBookmark: moveToBookmark,
  18171. select: select$1,
  18172. isCollapsed: isCollapsed,
  18173. isForward: isForward,
  18174. setNode: setNode,
  18175. getNode: getNode$1,
  18176. getSel: getSel,
  18177. setRng: setRng,
  18178. getRng: getRng$1,
  18179. getStart: getStart$1,
  18180. getEnd: getEnd$1,
  18181. getSelectedBlocks: getSelectedBlocks$1,
  18182. normalize: normalize,
  18183. selectorChanged: selectorChanged,
  18184. selectorChangedWithUnbind: selectorChangedWithUnbind,
  18185. getScrollContainer: getScrollContainer,
  18186. scrollIntoView: scrollIntoView,
  18187. placeCaretAt: placeCaretAt,
  18188. getBoundingClientRect: getBoundingClientRect,
  18189. destroy: destroy
  18190. };
  18191. var bookmarkManager = BookmarkManager(exports);
  18192. var controlSelection = ControlSelection(exports, editor);
  18193. exports.bookmarkManager = bookmarkManager;
  18194. exports.controlSelection = controlSelection;
  18195. return exports;
  18196. };
  18197. var removeAttrs = function (node, names) {
  18198. each$k(names, function (name) {
  18199. node.attr(name, null);
  18200. });
  18201. };
  18202. var addFontToSpansFilter = function (domParser, styles, fontSizes) {
  18203. domParser.addNodeFilter('font', function (nodes) {
  18204. each$k(nodes, function (node) {
  18205. var props = styles.parse(node.attr('style'));
  18206. var color = node.attr('color');
  18207. var face = node.attr('face');
  18208. var size = node.attr('size');
  18209. if (color) {
  18210. props.color = color;
  18211. }
  18212. if (face) {
  18213. props['font-family'] = face;
  18214. }
  18215. if (size) {
  18216. props['font-size'] = fontSizes[parseInt(node.attr('size'), 10) - 1];
  18217. }
  18218. node.name = 'span';
  18219. node.attr('style', styles.serialize(props));
  18220. removeAttrs(node, [
  18221. 'color',
  18222. 'face',
  18223. 'size'
  18224. ]);
  18225. });
  18226. });
  18227. };
  18228. var addStrikeToSpanFilter = function (domParser, styles) {
  18229. domParser.addNodeFilter('strike', function (nodes) {
  18230. each$k(nodes, function (node) {
  18231. var props = styles.parse(node.attr('style'));
  18232. props['text-decoration'] = 'line-through';
  18233. node.name = 'span';
  18234. node.attr('style', styles.serialize(props));
  18235. });
  18236. });
  18237. };
  18238. var addFilters = function (domParser, settings) {
  18239. var styles = Styles();
  18240. if (settings.convert_fonts_to_spans) {
  18241. addFontToSpansFilter(domParser, styles, Tools.explode(settings.font_size_legacy_values));
  18242. }
  18243. addStrikeToSpanFilter(domParser, styles);
  18244. };
  18245. var register$2 = function (domParser, settings) {
  18246. if (settings.inline_styles) {
  18247. addFilters(domParser, settings);
  18248. }
  18249. };
  18250. var blobUriToBlob = function (url) {
  18251. return new promiseObj(function (resolve, reject) {
  18252. var rejectWithError = function () {
  18253. reject('Cannot convert ' + url + ' to Blob. Resource might not exist or is inaccessible.');
  18254. };
  18255. try {
  18256. var xhr_1 = new XMLHttpRequest();
  18257. xhr_1.open('GET', url, true);
  18258. xhr_1.responseType = 'blob';
  18259. xhr_1.onload = function () {
  18260. if (xhr_1.status === 200) {
  18261. resolve(xhr_1.response);
  18262. } else {
  18263. rejectWithError();
  18264. }
  18265. };
  18266. xhr_1.onerror = rejectWithError;
  18267. xhr_1.send();
  18268. } catch (ex) {
  18269. rejectWithError();
  18270. }
  18271. });
  18272. };
  18273. var parseDataUri = function (uri) {
  18274. var type;
  18275. var uriParts = decodeURIComponent(uri).split(',');
  18276. var matches = /data:([^;]+)/.exec(uriParts[0]);
  18277. if (matches) {
  18278. type = matches[1];
  18279. }
  18280. return {
  18281. type: type,
  18282. data: uriParts[1]
  18283. };
  18284. };
  18285. var buildBlob = function (type, data) {
  18286. var str;
  18287. try {
  18288. str = atob(data);
  18289. } catch (e) {
  18290. return Optional.none();
  18291. }
  18292. var arr = new Uint8Array(str.length);
  18293. for (var i = 0; i < arr.length; i++) {
  18294. arr[i] = str.charCodeAt(i);
  18295. }
  18296. return Optional.some(new Blob([arr], { type: type }));
  18297. };
  18298. var dataUriToBlob = function (uri) {
  18299. return new promiseObj(function (resolve) {
  18300. var _a = parseDataUri(uri), type = _a.type, data = _a.data;
  18301. buildBlob(type, data).fold(function () {
  18302. return resolve(new Blob([]));
  18303. }, resolve);
  18304. });
  18305. };
  18306. var uriToBlob = function (url) {
  18307. if (url.indexOf('blob:') === 0) {
  18308. return blobUriToBlob(url);
  18309. }
  18310. if (url.indexOf('data:') === 0) {
  18311. return dataUriToBlob(url);
  18312. }
  18313. return null;
  18314. };
  18315. var blobToDataUri = function (blob) {
  18316. return new promiseObj(function (resolve) {
  18317. var reader = new FileReader();
  18318. reader.onloadend = function () {
  18319. resolve(reader.result);
  18320. };
  18321. reader.readAsDataURL(blob);
  18322. });
  18323. };
  18324. var count$1 = 0;
  18325. var uniqueId = function (prefix) {
  18326. return (prefix || 'blobid') + count$1++;
  18327. };
  18328. var imageToBlobInfo = function (blobCache, img, resolve, reject) {
  18329. var base64, blobInfo;
  18330. if (img.src.indexOf('blob:') === 0) {
  18331. blobInfo = blobCache.getByUri(img.src);
  18332. if (blobInfo) {
  18333. resolve({
  18334. image: img,
  18335. blobInfo: blobInfo
  18336. });
  18337. } else {
  18338. uriToBlob(img.src).then(function (blob) {
  18339. blobToDataUri(blob).then(function (dataUri) {
  18340. base64 = parseDataUri(dataUri).data;
  18341. blobInfo = blobCache.create(uniqueId(), blob, base64);
  18342. blobCache.add(blobInfo);
  18343. resolve({
  18344. image: img,
  18345. blobInfo: blobInfo
  18346. });
  18347. });
  18348. }, function (err) {
  18349. reject(err);
  18350. });
  18351. }
  18352. return;
  18353. }
  18354. var _a = parseDataUri(img.src), data = _a.data, type = _a.type;
  18355. base64 = data;
  18356. blobInfo = blobCache.getByData(base64, type);
  18357. if (blobInfo) {
  18358. resolve({
  18359. image: img,
  18360. blobInfo: blobInfo
  18361. });
  18362. } else {
  18363. uriToBlob(img.src).then(function (blob) {
  18364. blobInfo = blobCache.create(uniqueId(), blob, base64);
  18365. blobCache.add(blobInfo);
  18366. resolve({
  18367. image: img,
  18368. blobInfo: blobInfo
  18369. });
  18370. }, function (err) {
  18371. reject(err);
  18372. });
  18373. }
  18374. };
  18375. var getAllImages = function (elm) {
  18376. return elm ? from(elm.getElementsByTagName('img')) : [];
  18377. };
  18378. var ImageScanner = function (uploadStatus, blobCache) {
  18379. var cachedPromises = {};
  18380. var findAll = function (elm, predicate) {
  18381. if (!predicate) {
  18382. predicate = always;
  18383. }
  18384. var images = filter$4(getAllImages(elm), function (img) {
  18385. var src = img.src;
  18386. if (!Env.fileApi) {
  18387. return false;
  18388. }
  18389. if (img.hasAttribute('data-mce-bogus')) {
  18390. return false;
  18391. }
  18392. if (img.hasAttribute('data-mce-placeholder')) {
  18393. return false;
  18394. }
  18395. if (!src || src === Env.transparentSrc) {
  18396. return false;
  18397. }
  18398. if (src.indexOf('blob:') === 0) {
  18399. return !uploadStatus.isUploaded(src) && predicate(img);
  18400. }
  18401. if (src.indexOf('data:') === 0) {
  18402. return predicate(img);
  18403. }
  18404. return false;
  18405. });
  18406. var promises = map$3(images, function (img) {
  18407. if (cachedPromises[img.src] !== undefined) {
  18408. return new promiseObj(function (resolve) {
  18409. cachedPromises[img.src].then(function (imageInfo) {
  18410. if (typeof imageInfo === 'string') {
  18411. return imageInfo;
  18412. }
  18413. resolve({
  18414. image: img,
  18415. blobInfo: imageInfo.blobInfo
  18416. });
  18417. });
  18418. });
  18419. }
  18420. var newPromise = new promiseObj(function (resolve, reject) {
  18421. imageToBlobInfo(blobCache, img, resolve, reject);
  18422. }).then(function (result) {
  18423. delete cachedPromises[result.image.src];
  18424. return result;
  18425. }).catch(function (error) {
  18426. delete cachedPromises[img.src];
  18427. return error;
  18428. });
  18429. cachedPromises[img.src] = newPromise;
  18430. return newPromise;
  18431. });
  18432. return promiseObj.all(promises);
  18433. };
  18434. return { findAll: findAll };
  18435. };
  18436. var paddEmptyNode = function (settings, args, blockElements, node) {
  18437. var brPreferred = settings.padd_empty_with_br || args.insert;
  18438. if (brPreferred && blockElements[node.name]) {
  18439. node.empty().append(new AstNode('br', 1)).shortEnded = true;
  18440. } else {
  18441. node.empty().append(new AstNode('#text', 3)).value = nbsp;
  18442. }
  18443. };
  18444. var isPaddedWithNbsp = function (node) {
  18445. return hasOnlyChild(node, '#text') && node.firstChild.value === nbsp;
  18446. };
  18447. var hasOnlyChild = function (node, name) {
  18448. return node && node.firstChild && node.firstChild === node.lastChild && node.firstChild.name === name;
  18449. };
  18450. var isPadded = function (schema, node) {
  18451. var rule = schema.getElementRule(node.name);
  18452. return rule && rule.paddEmpty;
  18453. };
  18454. var isEmpty = function (schema, nonEmptyElements, whitespaceElements, node) {
  18455. return node.isEmpty(nonEmptyElements, whitespaceElements, function (node) {
  18456. return isPadded(schema, node);
  18457. });
  18458. };
  18459. var isLineBreakNode = function (node, blockElements) {
  18460. return node && (has$2(blockElements, node.name) || node.name === 'br');
  18461. };
  18462. var isBogusImage = function (img) {
  18463. return isNonNullable(img.attr('data-mce-bogus'));
  18464. };
  18465. var isInternalImageSource = function (img) {
  18466. return img.attr('src') === Env.transparentSrc || isNonNullable(img.attr('data-mce-placeholder'));
  18467. };
  18468. var isValidDataImg = function (img, settings) {
  18469. if (settings.images_dataimg_filter) {
  18470. var imgElem_1 = new Image();
  18471. imgElem_1.src = img.attr('src');
  18472. each$j(img.attributes.map, function (value, key) {
  18473. imgElem_1.setAttribute(key, value);
  18474. });
  18475. return settings.images_dataimg_filter(imgElem_1);
  18476. } else {
  18477. return true;
  18478. }
  18479. };
  18480. var registerBase64ImageFilter = function (parser, settings) {
  18481. var blobCache = settings.blob_cache;
  18482. var processImage = function (img) {
  18483. var inputSrc = img.attr('src');
  18484. if (isInternalImageSource(img) || isBogusImage(img)) {
  18485. return;
  18486. }
  18487. parseDataUri$1(inputSrc).filter(function () {
  18488. return isValidDataImg(img, settings);
  18489. }).bind(function (_a) {
  18490. var type = _a.type, data = _a.data;
  18491. return Optional.from(blobCache.getByData(data, type)).orThunk(function () {
  18492. return buildBlob(type, data).map(function (blob) {
  18493. var blobInfo = blobCache.create(uniqueId(), blob, data);
  18494. blobCache.add(blobInfo);
  18495. return blobInfo;
  18496. });
  18497. });
  18498. }).each(function (blobInfo) {
  18499. img.attr('src', blobInfo.blobUri());
  18500. });
  18501. };
  18502. if (blobCache) {
  18503. parser.addAttributeFilter('src', function (nodes) {
  18504. return each$k(nodes, processImage);
  18505. });
  18506. }
  18507. };
  18508. var register$1 = function (parser, settings) {
  18509. var schema = parser.schema;
  18510. if (settings.remove_trailing_brs) {
  18511. parser.addNodeFilter('br', function (nodes, _, args) {
  18512. var i;
  18513. var l = nodes.length;
  18514. var node;
  18515. var blockElements = Tools.extend({}, schema.getBlockElements());
  18516. var nonEmptyElements = schema.getNonEmptyElements();
  18517. var parent, lastParent, prev, prevName;
  18518. var whiteSpaceElements = schema.getWhiteSpaceElements();
  18519. var elementRule, textNode;
  18520. blockElements.body = 1;
  18521. for (i = 0; i < l; i++) {
  18522. node = nodes[i];
  18523. parent = node.parent;
  18524. if (blockElements[node.parent.name] && node === parent.lastChild) {
  18525. prev = node.prev;
  18526. while (prev) {
  18527. prevName = prev.name;
  18528. if (prevName !== 'span' || prev.attr('data-mce-type') !== 'bookmark') {
  18529. if (prevName === 'br') {
  18530. node = null;
  18531. }
  18532. break;
  18533. }
  18534. prev = prev.prev;
  18535. }
  18536. if (node) {
  18537. node.remove();
  18538. if (isEmpty(schema, nonEmptyElements, whiteSpaceElements, parent)) {
  18539. elementRule = schema.getElementRule(parent.name);
  18540. if (elementRule) {
  18541. if (elementRule.removeEmpty) {
  18542. parent.remove();
  18543. } else if (elementRule.paddEmpty) {
  18544. paddEmptyNode(settings, args, blockElements, parent);
  18545. }
  18546. }
  18547. }
  18548. }
  18549. } else {
  18550. lastParent = node;
  18551. while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) {
  18552. lastParent = parent;
  18553. if (blockElements[parent.name]) {
  18554. break;
  18555. }
  18556. parent = parent.parent;
  18557. }
  18558. if (lastParent === parent && settings.padd_empty_with_br !== true) {
  18559. textNode = new AstNode('#text', 3);
  18560. textNode.value = nbsp;
  18561. node.replace(textNode);
  18562. }
  18563. }
  18564. }
  18565. });
  18566. }
  18567. parser.addAttributeFilter('href', function (nodes) {
  18568. var i = nodes.length;
  18569. var appendRel = function (rel) {
  18570. var parts = rel.split(' ').filter(function (p) {
  18571. return p.length > 0;
  18572. });
  18573. return parts.concat(['noopener']).sort().join(' ');
  18574. };
  18575. var addNoOpener = function (rel) {
  18576. var newRel = rel ? Tools.trim(rel) : '';
  18577. if (!/\b(noopener)\b/g.test(newRel)) {
  18578. return appendRel(newRel);
  18579. } else {
  18580. return newRel;
  18581. }
  18582. };
  18583. if (!settings.allow_unsafe_link_target) {
  18584. while (i--) {
  18585. var node = nodes[i];
  18586. if (node.name === 'a' && node.attr('target') === '_blank') {
  18587. node.attr('rel', addNoOpener(node.attr('rel')));
  18588. }
  18589. }
  18590. }
  18591. });
  18592. if (!settings.allow_html_in_named_anchor) {
  18593. parser.addAttributeFilter('id,name', function (nodes) {
  18594. var i = nodes.length, sibling, prevSibling, parent, node;
  18595. while (i--) {
  18596. node = nodes[i];
  18597. if (node.name === 'a' && node.firstChild && !node.attr('href')) {
  18598. parent = node.parent;
  18599. sibling = node.lastChild;
  18600. do {
  18601. prevSibling = sibling.prev;
  18602. parent.insert(sibling, node);
  18603. sibling = prevSibling;
  18604. } while (sibling);
  18605. }
  18606. }
  18607. });
  18608. }
  18609. if (settings.fix_list_elements) {
  18610. parser.addNodeFilter('ul,ol', function (nodes) {
  18611. var i = nodes.length, node, parentNode;
  18612. while (i--) {
  18613. node = nodes[i];
  18614. parentNode = node.parent;
  18615. if (parentNode.name === 'ul' || parentNode.name === 'ol') {
  18616. if (node.prev && node.prev.name === 'li') {
  18617. node.prev.append(node);
  18618. } else {
  18619. var li = new AstNode('li', 1);
  18620. li.attr('style', 'list-style-type: none');
  18621. node.wrap(li);
  18622. }
  18623. }
  18624. }
  18625. });
  18626. }
  18627. if (settings.validate && schema.getValidClasses()) {
  18628. parser.addAttributeFilter('class', function (nodes) {
  18629. var validClasses = schema.getValidClasses();
  18630. var i = nodes.length;
  18631. while (i--) {
  18632. var node = nodes[i];
  18633. var classList = node.attr('class').split(' ');
  18634. var classValue = '';
  18635. for (var ci = 0; ci < classList.length; ci++) {
  18636. var className = classList[ci];
  18637. var valid = false;
  18638. var validClassesMap = validClasses['*'];
  18639. if (validClassesMap && validClassesMap[className]) {
  18640. valid = true;
  18641. }
  18642. validClassesMap = validClasses[node.name];
  18643. if (!valid && validClassesMap && validClassesMap[className]) {
  18644. valid = true;
  18645. }
  18646. if (valid) {
  18647. if (classValue) {
  18648. classValue += ' ';
  18649. }
  18650. classValue += className;
  18651. }
  18652. }
  18653. if (!classValue.length) {
  18654. classValue = null;
  18655. }
  18656. node.attr('class', classValue);
  18657. }
  18658. });
  18659. }
  18660. registerBase64ImageFilter(parser, settings);
  18661. };
  18662. var makeMap = Tools.makeMap, each$6 = Tools.each, explode$2 = Tools.explode, extend$4 = Tools.extend;
  18663. var DomParser = function (settings, schema) {
  18664. if (schema === void 0) {
  18665. schema = Schema();
  18666. }
  18667. var nodeFilters = {};
  18668. var attributeFilters = [];
  18669. var matchedNodes = {};
  18670. var matchedAttributes = {};
  18671. settings = settings || {};
  18672. settings.validate = 'validate' in settings ? settings.validate : true;
  18673. settings.root_name = settings.root_name || 'body';
  18674. var fixInvalidChildren = function (nodes) {
  18675. var nonSplitableElements = makeMap('tr,td,th,tbody,thead,tfoot,table');
  18676. var nonEmptyElements = schema.getNonEmptyElements();
  18677. var whitespaceElements = schema.getWhiteSpaceElements();
  18678. var textBlockElements = schema.getTextBlockElements();
  18679. var specialElements = schema.getSpecialElements();
  18680. var removeOrUnwrapInvalidNode = function (node, originalNodeParent) {
  18681. if (originalNodeParent === void 0) {
  18682. originalNodeParent = node.parent;
  18683. }
  18684. if (specialElements[node.name]) {
  18685. node.empty().remove();
  18686. } else {
  18687. var children = node.children();
  18688. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  18689. var childNode = children_1[_i];
  18690. if (!schema.isValidChild(originalNodeParent.name, childNode.name)) {
  18691. removeOrUnwrapInvalidNode(childNode, originalNodeParent);
  18692. }
  18693. }
  18694. node.unwrap();
  18695. }
  18696. };
  18697. for (var ni = 0; ni < nodes.length; ni++) {
  18698. var node = nodes[ni];
  18699. var parent_1 = void 0, newParent = void 0, tempNode = void 0;
  18700. if (!node.parent || node.fixed) {
  18701. continue;
  18702. }
  18703. if (textBlockElements[node.name] && node.parent.name === 'li') {
  18704. var sibling = node.next;
  18705. while (sibling) {
  18706. if (textBlockElements[sibling.name]) {
  18707. sibling.name = 'li';
  18708. sibling.fixed = true;
  18709. node.parent.insert(sibling, node.parent);
  18710. } else {
  18711. break;
  18712. }
  18713. sibling = sibling.next;
  18714. }
  18715. node.unwrap();
  18716. continue;
  18717. }
  18718. var parents = [node];
  18719. for (parent_1 = node.parent; parent_1 && !schema.isValidChild(parent_1.name, node.name) && !nonSplitableElements[parent_1.name]; parent_1 = parent_1.parent) {
  18720. parents.push(parent_1);
  18721. }
  18722. if (parent_1 && parents.length > 1) {
  18723. if (schema.isValidChild(parent_1.name, node.name)) {
  18724. parents.reverse();
  18725. newParent = filterNode(parents[0].clone());
  18726. var currentNode = newParent;
  18727. for (var i = 0; i < parents.length - 1; i++) {
  18728. if (schema.isValidChild(currentNode.name, parents[i].name)) {
  18729. tempNode = filterNode(parents[i].clone());
  18730. currentNode.append(tempNode);
  18731. } else {
  18732. tempNode = currentNode;
  18733. }
  18734. for (var childNode = parents[i].firstChild; childNode && childNode !== parents[i + 1];) {
  18735. var nextNode = childNode.next;
  18736. tempNode.append(childNode);
  18737. childNode = nextNode;
  18738. }
  18739. currentNode = tempNode;
  18740. }
  18741. if (!isEmpty(schema, nonEmptyElements, whitespaceElements, newParent)) {
  18742. parent_1.insert(newParent, parents[0], true);
  18743. parent_1.insert(node, newParent);
  18744. } else {
  18745. parent_1.insert(node, parents[0], true);
  18746. }
  18747. parent_1 = parents[0];
  18748. if (isEmpty(schema, nonEmptyElements, whitespaceElements, parent_1) || hasOnlyChild(parent_1, 'br')) {
  18749. parent_1.empty().remove();
  18750. }
  18751. } else {
  18752. removeOrUnwrapInvalidNode(node);
  18753. }
  18754. } else if (node.parent) {
  18755. if (node.name === 'li') {
  18756. var sibling = node.prev;
  18757. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  18758. sibling.append(node);
  18759. continue;
  18760. }
  18761. sibling = node.next;
  18762. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  18763. sibling.insert(node, sibling.firstChild, true);
  18764. continue;
  18765. }
  18766. node.wrap(filterNode(new AstNode('ul', 1)));
  18767. continue;
  18768. }
  18769. if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
  18770. node.wrap(filterNode(new AstNode('div', 1)));
  18771. } else {
  18772. removeOrUnwrapInvalidNode(node);
  18773. }
  18774. }
  18775. }
  18776. };
  18777. var filterNode = function (node) {
  18778. var name = node.name;
  18779. if (name in nodeFilters) {
  18780. var list = matchedNodes[name];
  18781. if (list) {
  18782. list.push(node);
  18783. } else {
  18784. matchedNodes[name] = [node];
  18785. }
  18786. }
  18787. var i = attributeFilters.length;
  18788. while (i--) {
  18789. var attrName = attributeFilters[i].name;
  18790. if (attrName in node.attributes.map) {
  18791. var list = matchedAttributes[attrName];
  18792. if (list) {
  18793. list.push(node);
  18794. } else {
  18795. matchedAttributes[attrName] = [node];
  18796. }
  18797. }
  18798. }
  18799. return node;
  18800. };
  18801. var addNodeFilter = function (name, callback) {
  18802. each$6(explode$2(name), function (name) {
  18803. var list = nodeFilters[name];
  18804. if (!list) {
  18805. nodeFilters[name] = list = [];
  18806. }
  18807. list.push(callback);
  18808. });
  18809. };
  18810. var getNodeFilters = function () {
  18811. var out = [];
  18812. for (var name_1 in nodeFilters) {
  18813. if (has$2(nodeFilters, name_1)) {
  18814. out.push({
  18815. name: name_1,
  18816. callbacks: nodeFilters[name_1]
  18817. });
  18818. }
  18819. }
  18820. return out;
  18821. };
  18822. var addAttributeFilter = function (name, callback) {
  18823. each$6(explode$2(name), function (name) {
  18824. var i;
  18825. for (i = 0; i < attributeFilters.length; i++) {
  18826. if (attributeFilters[i].name === name) {
  18827. attributeFilters[i].callbacks.push(callback);
  18828. return;
  18829. }
  18830. }
  18831. attributeFilters.push({
  18832. name: name,
  18833. callbacks: [callback]
  18834. });
  18835. });
  18836. };
  18837. var getAttributeFilters = function () {
  18838. return [].concat(attributeFilters);
  18839. };
  18840. var parse = function (html, args) {
  18841. var nodes, i, l, fi, fl, list, name;
  18842. var invalidChildren = [];
  18843. var node;
  18844. var getRootBlockName = function (name) {
  18845. if (name === false) {
  18846. return '';
  18847. } else if (name === true) {
  18848. return 'p';
  18849. } else {
  18850. return name;
  18851. }
  18852. };
  18853. args = args || {};
  18854. matchedNodes = {};
  18855. matchedAttributes = {};
  18856. var blockElements = extend$4(makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  18857. var nonEmptyElements = schema.getNonEmptyElements();
  18858. var children = schema.children;
  18859. var validate = settings.validate;
  18860. var forcedRootBlockName = 'forced_root_block' in args ? args.forced_root_block : settings.forced_root_block;
  18861. var rootBlockName = getRootBlockName(forcedRootBlockName);
  18862. var whiteSpaceElements = schema.getWhiteSpaceElements();
  18863. var startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  18864. var endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  18865. var allWhiteSpaceRegExp = /[ \t\r\n]+/g;
  18866. var isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/;
  18867. var isInWhiteSpacePreservedElement = has$2(whiteSpaceElements, args.context) || has$2(whiteSpaceElements, settings.root_name);
  18868. var addRootBlocks = function () {
  18869. var node = rootNode.firstChild, rootBlockNode = null;
  18870. var trim = function (rootBlock) {
  18871. if (rootBlock) {
  18872. node = rootBlock.firstChild;
  18873. if (node && node.type === 3) {
  18874. node.value = node.value.replace(startWhiteSpaceRegExp, '');
  18875. }
  18876. node = rootBlock.lastChild;
  18877. if (node && node.type === 3) {
  18878. node.value = node.value.replace(endWhiteSpaceRegExp, '');
  18879. }
  18880. }
  18881. };
  18882. if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
  18883. return;
  18884. }
  18885. while (node) {
  18886. var next = node.next;
  18887. if (node.type === 3 || node.type === 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type')) {
  18888. if (!rootBlockNode) {
  18889. rootBlockNode = createNode(rootBlockName, 1);
  18890. rootBlockNode.attr(settings.forced_root_block_attrs);
  18891. rootNode.insert(rootBlockNode, node);
  18892. rootBlockNode.append(node);
  18893. } else {
  18894. rootBlockNode.append(node);
  18895. }
  18896. } else {
  18897. trim(rootBlockNode);
  18898. rootBlockNode = null;
  18899. }
  18900. node = next;
  18901. }
  18902. trim(rootBlockNode);
  18903. };
  18904. var createNode = function (name, type) {
  18905. var node = new AstNode(name, type);
  18906. var list;
  18907. if (name in nodeFilters) {
  18908. list = matchedNodes[name];
  18909. if (list) {
  18910. list.push(node);
  18911. } else {
  18912. matchedNodes[name] = [node];
  18913. }
  18914. }
  18915. return node;
  18916. };
  18917. var removeWhitespaceBefore = function (node) {
  18918. var blockElements = schema.getBlockElements();
  18919. for (var textNode = node.prev; textNode && textNode.type === 3;) {
  18920. var textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
  18921. if (textVal.length > 0) {
  18922. textNode.value = textVal;
  18923. return;
  18924. }
  18925. var textNodeNext = textNode.next;
  18926. if (textNodeNext) {
  18927. if (textNodeNext.type === 3 && textNodeNext.value.length) {
  18928. textNode = textNode.prev;
  18929. continue;
  18930. }
  18931. if (!blockElements[textNodeNext.name] && textNodeNext.name !== 'script' && textNodeNext.name !== 'style') {
  18932. textNode = textNode.prev;
  18933. continue;
  18934. }
  18935. }
  18936. var sibling = textNode.prev;
  18937. textNode.remove();
  18938. textNode = sibling;
  18939. }
  18940. };
  18941. var cloneAndExcludeBlocks = function (input) {
  18942. var output = {};
  18943. for (var name_2 in input) {
  18944. if (name_2 !== 'li' && name_2 !== 'p') {
  18945. output[name_2] = input[name_2];
  18946. }
  18947. }
  18948. return output;
  18949. };
  18950. var parser = SaxParser({
  18951. validate: validate,
  18952. document: settings.document,
  18953. allow_html_data_urls: settings.allow_html_data_urls,
  18954. allow_svg_data_urls: settings.allow_svg_data_urls,
  18955. allow_script_urls: settings.allow_script_urls,
  18956. allow_conditional_comments: settings.allow_conditional_comments,
  18957. preserve_cdata: settings.preserve_cdata,
  18958. self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()),
  18959. cdata: function (text) {
  18960. node.append(createNode('#cdata', 4)).value = text;
  18961. },
  18962. text: function (text, raw) {
  18963. var textNode;
  18964. if (!isInWhiteSpacePreservedElement) {
  18965. text = text.replace(allWhiteSpaceRegExp, ' ');
  18966. if (isLineBreakNode(node.lastChild, blockElements)) {
  18967. text = text.replace(startWhiteSpaceRegExp, '');
  18968. }
  18969. }
  18970. if (text.length !== 0) {
  18971. textNode = createNode('#text', 3);
  18972. textNode.raw = !!raw;
  18973. node.append(textNode).value = text;
  18974. }
  18975. },
  18976. comment: function (text) {
  18977. node.append(createNode('#comment', 8)).value = text;
  18978. },
  18979. pi: function (name, text) {
  18980. node.append(createNode(name, 7)).value = text;
  18981. removeWhitespaceBefore(node);
  18982. },
  18983. doctype: function (text) {
  18984. var newNode = node.append(createNode('#doctype', 10));
  18985. newNode.value = text;
  18986. removeWhitespaceBefore(node);
  18987. },
  18988. start: function (name, attrs, empty) {
  18989. var elementRule = validate ? schema.getElementRule(name) : {};
  18990. if (elementRule) {
  18991. var newNode = createNode(elementRule.outputName || name, 1);
  18992. newNode.attributes = attrs;
  18993. newNode.shortEnded = empty;
  18994. node.append(newNode);
  18995. var parent_2 = children[node.name];
  18996. if (parent_2 && children[newNode.name] && !parent_2[newNode.name]) {
  18997. invalidChildren.push(newNode);
  18998. }
  18999. var attrFiltersLen = attributeFilters.length;
  19000. while (attrFiltersLen--) {
  19001. var attrName = attributeFilters[attrFiltersLen].name;
  19002. if (attrName in attrs.map) {
  19003. list = matchedAttributes[attrName];
  19004. if (list) {
  19005. list.push(newNode);
  19006. } else {
  19007. matchedAttributes[attrName] = [newNode];
  19008. }
  19009. }
  19010. }
  19011. if (blockElements[name]) {
  19012. removeWhitespaceBefore(newNode);
  19013. }
  19014. if (!empty) {
  19015. node = newNode;
  19016. }
  19017. if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  19018. isInWhiteSpacePreservedElement = true;
  19019. }
  19020. }
  19021. },
  19022. end: function (name) {
  19023. var textNode, text, sibling, tempNode;
  19024. var elementRule = validate ? schema.getElementRule(name) : {};
  19025. if (elementRule) {
  19026. if (blockElements[name]) {
  19027. if (!isInWhiteSpacePreservedElement) {
  19028. textNode = node.firstChild;
  19029. if (textNode && textNode.type === 3) {
  19030. text = textNode.value.replace(startWhiteSpaceRegExp, '');
  19031. if (text.length > 0) {
  19032. textNode.value = text;
  19033. textNode = textNode.next;
  19034. } else {
  19035. sibling = textNode.next;
  19036. textNode.remove();
  19037. textNode = sibling;
  19038. while (textNode && textNode.type === 3) {
  19039. text = textNode.value;
  19040. sibling = textNode.next;
  19041. if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  19042. textNode.remove();
  19043. textNode = sibling;
  19044. }
  19045. textNode = sibling;
  19046. }
  19047. }
  19048. }
  19049. textNode = node.lastChild;
  19050. if (textNode && textNode.type === 3) {
  19051. text = textNode.value.replace(endWhiteSpaceRegExp, '');
  19052. if (text.length > 0) {
  19053. textNode.value = text;
  19054. textNode = textNode.prev;
  19055. } else {
  19056. sibling = textNode.prev;
  19057. textNode.remove();
  19058. textNode = sibling;
  19059. while (textNode && textNode.type === 3) {
  19060. text = textNode.value;
  19061. sibling = textNode.prev;
  19062. if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  19063. textNode.remove();
  19064. textNode = sibling;
  19065. }
  19066. textNode = sibling;
  19067. }
  19068. }
  19069. }
  19070. }
  19071. }
  19072. if (isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  19073. isInWhiteSpacePreservedElement = false;
  19074. }
  19075. if (elementRule.removeEmpty && isEmpty(schema, nonEmptyElements, whiteSpaceElements, node)) {
  19076. tempNode = node.parent;
  19077. if (blockElements[node.name]) {
  19078. node.empty().remove();
  19079. } else {
  19080. node.unwrap();
  19081. }
  19082. node = tempNode;
  19083. return;
  19084. }
  19085. if (elementRule.paddEmpty && (isPaddedWithNbsp(node) || isEmpty(schema, nonEmptyElements, whiteSpaceElements, node))) {
  19086. paddEmptyNode(settings, args, blockElements, node);
  19087. }
  19088. node = node.parent;
  19089. }
  19090. }
  19091. }, schema);
  19092. var rootNode = node = new AstNode(args.context || settings.root_name, 11);
  19093. parser.parse(html, args.format);
  19094. if (validate && invalidChildren.length) {
  19095. if (!args.context) {
  19096. fixInvalidChildren(invalidChildren);
  19097. } else {
  19098. args.invalid = true;
  19099. }
  19100. }
  19101. if (rootBlockName && (rootNode.name === 'body' || args.isRootContent)) {
  19102. addRootBlocks();
  19103. }
  19104. if (!args.invalid) {
  19105. for (name in matchedNodes) {
  19106. if (!has$2(matchedNodes, name)) {
  19107. continue;
  19108. }
  19109. list = nodeFilters[name];
  19110. nodes = matchedNodes[name];
  19111. fi = nodes.length;
  19112. while (fi--) {
  19113. if (!nodes[fi].parent) {
  19114. nodes.splice(fi, 1);
  19115. }
  19116. }
  19117. for (i = 0, l = list.length; i < l; i++) {
  19118. list[i](nodes, name, args);
  19119. }
  19120. }
  19121. for (i = 0, l = attributeFilters.length; i < l; i++) {
  19122. list = attributeFilters[i];
  19123. if (list.name in matchedAttributes) {
  19124. nodes = matchedAttributes[list.name];
  19125. fi = nodes.length;
  19126. while (fi--) {
  19127. if (!nodes[fi].parent) {
  19128. nodes.splice(fi, 1);
  19129. }
  19130. }
  19131. for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) {
  19132. list.callbacks[fi](nodes, list.name, args);
  19133. }
  19134. }
  19135. }
  19136. }
  19137. return rootNode;
  19138. };
  19139. var exports = {
  19140. schema: schema,
  19141. addAttributeFilter: addAttributeFilter,
  19142. getAttributeFilters: getAttributeFilters,
  19143. addNodeFilter: addNodeFilter,
  19144. getNodeFilters: getNodeFilters,
  19145. filterNode: filterNode,
  19146. parse: parse
  19147. };
  19148. register$1(exports, settings);
  19149. register$2(exports, settings);
  19150. return exports;
  19151. };
  19152. var register = function (htmlParser, settings, dom) {
  19153. htmlParser.addAttributeFilter('data-mce-tabindex', function (nodes, name) {
  19154. var i = nodes.length;
  19155. while (i--) {
  19156. var node = nodes[i];
  19157. node.attr('tabindex', node.attr('data-mce-tabindex'));
  19158. node.attr(name, null);
  19159. }
  19160. });
  19161. htmlParser.addAttributeFilter('src,href,style', function (nodes, name) {
  19162. var internalName = 'data-mce-' + name;
  19163. var urlConverter = settings.url_converter;
  19164. var urlConverterScope = settings.url_converter_scope;
  19165. var i = nodes.length;
  19166. while (i--) {
  19167. var node = nodes[i];
  19168. var value = node.attr(internalName);
  19169. if (value !== undefined) {
  19170. node.attr(name, value.length > 0 ? value : null);
  19171. node.attr(internalName, null);
  19172. } else {
  19173. value = node.attr(name);
  19174. if (name === 'style') {
  19175. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  19176. } else if (urlConverter) {
  19177. value = urlConverter.call(urlConverterScope, value, name, node.name);
  19178. }
  19179. node.attr(name, value.length > 0 ? value : null);
  19180. }
  19181. }
  19182. });
  19183. htmlParser.addAttributeFilter('class', function (nodes) {
  19184. var i = nodes.length;
  19185. while (i--) {
  19186. var node = nodes[i];
  19187. var value = node.attr('class');
  19188. if (value) {
  19189. value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
  19190. node.attr('class', value.length > 0 ? value : null);
  19191. }
  19192. }
  19193. });
  19194. htmlParser.addAttributeFilter('data-mce-type', function (nodes, name, args) {
  19195. var i = nodes.length;
  19196. while (i--) {
  19197. var node = nodes[i];
  19198. if (node.attr('data-mce-type') === 'bookmark' && !args.cleanup) {
  19199. var hasChildren = Optional.from(node.firstChild).exists(function (firstChild) {
  19200. return !isZwsp(firstChild.value);
  19201. });
  19202. if (hasChildren) {
  19203. node.unwrap();
  19204. } else {
  19205. node.remove();
  19206. }
  19207. }
  19208. }
  19209. });
  19210. htmlParser.addNodeFilter('noscript', function (nodes) {
  19211. var i = nodes.length;
  19212. while (i--) {
  19213. var node = nodes[i].firstChild;
  19214. if (node) {
  19215. node.value = Entities.decode(node.value);
  19216. }
  19217. }
  19218. });
  19219. htmlParser.addNodeFilter('script,style', function (nodes, name) {
  19220. var trim = function (value) {
  19221. return value.replace(/(<!--\[CDATA\[|\]\]-->)/g, '\n').replace(/^[\r\n]*|[\r\n]*$/g, '').replace(/^\s*((<!--)?(\s*\/\/)?\s*<!\[CDATA\[|(<!--\s*)?\/\*\s*<!\[CDATA\[\s*\*\/|(\/\/)?\s*<!--|\/\*\s*<!--\s*\*\/)\s*[\r\n]*/gi, '').replace(/\s*(\/\*\s*\]\]>\s*\*\/(-->)?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, '');
  19222. };
  19223. var i = nodes.length;
  19224. while (i--) {
  19225. var node = nodes[i];
  19226. var value = node.firstChild ? node.firstChild.value : '';
  19227. if (name === 'script') {
  19228. var type = node.attr('type');
  19229. if (type) {
  19230. node.attr('type', type === 'mce-no/type' ? null : type.replace(/^mce\-/, ''));
  19231. }
  19232. if (settings.element_format === 'xhtml' && value.length > 0) {
  19233. node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
  19234. }
  19235. } else {
  19236. if (settings.element_format === 'xhtml' && value.length > 0) {
  19237. node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
  19238. }
  19239. }
  19240. }
  19241. });
  19242. htmlParser.addNodeFilter('#comment', function (nodes) {
  19243. var i = nodes.length;
  19244. while (i--) {
  19245. var node = nodes[i];
  19246. if (settings.preserve_cdata && node.value.indexOf('[CDATA[') === 0) {
  19247. node.name = '#cdata';
  19248. node.type = 4;
  19249. node.value = dom.decode(node.value.replace(/^\[CDATA\[|\]\]$/g, ''));
  19250. } else if (node.value.indexOf('mce:protected ') === 0) {
  19251. node.name = '#text';
  19252. node.type = 3;
  19253. node.raw = true;
  19254. node.value = unescape(node.value).substr(14);
  19255. }
  19256. }
  19257. });
  19258. htmlParser.addNodeFilter('xml:namespace,input', function (nodes, name) {
  19259. var i = nodes.length;
  19260. while (i--) {
  19261. var node = nodes[i];
  19262. if (node.type === 7) {
  19263. node.remove();
  19264. } else if (node.type === 1) {
  19265. if (name === 'input' && !node.attr('type')) {
  19266. node.attr('type', 'text');
  19267. }
  19268. }
  19269. }
  19270. });
  19271. htmlParser.addAttributeFilter('data-mce-type', function (nodes) {
  19272. each$k(nodes, function (node) {
  19273. if (node.attr('data-mce-type') === 'format-caret') {
  19274. if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
  19275. node.remove();
  19276. } else {
  19277. node.unwrap();
  19278. }
  19279. }
  19280. });
  19281. });
  19282. htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style,' + 'data-mce-selected,data-mce-expando,' + 'data-mce-type,data-mce-resize,data-mce-placeholder', function (nodes, name) {
  19283. var i = nodes.length;
  19284. while (i--) {
  19285. nodes[i].attr(name, null);
  19286. }
  19287. });
  19288. };
  19289. var trimTrailingBr = function (rootNode) {
  19290. var isBr = function (node) {
  19291. return node && node.name === 'br';
  19292. };
  19293. var brNode1 = rootNode.lastChild;
  19294. if (isBr(brNode1)) {
  19295. var brNode2 = brNode1.prev;
  19296. if (isBr(brNode2)) {
  19297. brNode1.remove();
  19298. brNode2.remove();
  19299. }
  19300. }
  19301. };
  19302. var preProcess = function (editor, node, args) {
  19303. var oldDoc;
  19304. var dom = editor.dom;
  19305. var clonedNode = node.cloneNode(true);
  19306. var impl = document.implementation;
  19307. if (impl.createHTMLDocument) {
  19308. var doc_1 = impl.createHTMLDocument('');
  19309. Tools.each(clonedNode.nodeName === 'BODY' ? clonedNode.childNodes : [clonedNode], function (node) {
  19310. doc_1.body.appendChild(doc_1.importNode(node, true));
  19311. });
  19312. if (clonedNode.nodeName !== 'BODY') {
  19313. clonedNode = doc_1.body.firstChild;
  19314. } else {
  19315. clonedNode = doc_1.body;
  19316. }
  19317. oldDoc = dom.doc;
  19318. dom.doc = doc_1;
  19319. }
  19320. firePreProcess(editor, __assign(__assign({}, args), { node: clonedNode }));
  19321. if (oldDoc) {
  19322. dom.doc = oldDoc;
  19323. }
  19324. return clonedNode;
  19325. };
  19326. var shouldFireEvent = function (editor, args) {
  19327. return editor && editor.hasEventListeners('PreProcess') && !args.no_events;
  19328. };
  19329. var process = function (editor, node, args) {
  19330. return shouldFireEvent(editor, args) ? preProcess(editor, node, args) : node;
  19331. };
  19332. var addTempAttr = function (htmlParser, tempAttrs, name) {
  19333. if (Tools.inArray(tempAttrs, name) === -1) {
  19334. htmlParser.addAttributeFilter(name, function (nodes, name) {
  19335. var i = nodes.length;
  19336. while (i--) {
  19337. nodes[i].attr(name, null);
  19338. }
  19339. });
  19340. tempAttrs.push(name);
  19341. }
  19342. };
  19343. var postProcess = function (editor, args, content) {
  19344. if (!args.no_events && editor) {
  19345. var outArgs = firePostProcess(editor, __assign(__assign({}, args), { content: content }));
  19346. return outArgs.content;
  19347. } else {
  19348. return content;
  19349. }
  19350. };
  19351. var getHtmlFromNode = function (dom, node, args) {
  19352. var html = trim$2(args.getInner ? node.innerHTML : dom.getOuterHTML(node));
  19353. return args.selection || isWsPreserveElement(SugarElement.fromDom(node)) ? html : Tools.trim(html);
  19354. };
  19355. var parseHtml = function (htmlParser, html, args) {
  19356. var parserArgs = args.selection ? __assign({ forced_root_block: false }, args) : args;
  19357. var rootNode = htmlParser.parse(html, parserArgs);
  19358. trimTrailingBr(rootNode);
  19359. return rootNode;
  19360. };
  19361. var serializeNode = function (settings, schema, node) {
  19362. var htmlSerializer = HtmlSerializer(settings, schema);
  19363. return htmlSerializer.serialize(node);
  19364. };
  19365. var toHtml = function (editor, settings, schema, rootNode, args) {
  19366. var content = serializeNode(settings, schema, rootNode);
  19367. return postProcess(editor, args, content);
  19368. };
  19369. var DomSerializerImpl = function (settings, editor) {
  19370. var tempAttrs = ['data-mce-selected'];
  19371. var dom = editor && editor.dom ? editor.dom : DOMUtils.DOM;
  19372. var schema = editor && editor.schema ? editor.schema : Schema(settings);
  19373. settings.entity_encoding = settings.entity_encoding || 'named';
  19374. settings.remove_trailing_brs = 'remove_trailing_brs' in settings ? settings.remove_trailing_brs : true;
  19375. var htmlParser = DomParser(settings, schema);
  19376. register(htmlParser, settings, dom);
  19377. var serialize = function (node, parserArgs) {
  19378. if (parserArgs === void 0) {
  19379. parserArgs = {};
  19380. }
  19381. var args = __assign({ format: 'html' }, parserArgs);
  19382. var targetNode = process(editor, node, args);
  19383. var html = getHtmlFromNode(dom, targetNode, args);
  19384. var rootNode = parseHtml(htmlParser, html, args);
  19385. return args.format === 'tree' ? rootNode : toHtml(editor, settings, schema, rootNode, args);
  19386. };
  19387. return {
  19388. schema: schema,
  19389. addNodeFilter: htmlParser.addNodeFilter,
  19390. addAttributeFilter: htmlParser.addAttributeFilter,
  19391. serialize: serialize,
  19392. addRules: schema.addValidElements,
  19393. setRules: schema.setValidElements,
  19394. addTempAttr: curry(addTempAttr, htmlParser, tempAttrs),
  19395. getTempAttrs: constant(tempAttrs),
  19396. getNodeFilters: htmlParser.getNodeFilters,
  19397. getAttributeFilters: htmlParser.getAttributeFilters
  19398. };
  19399. };
  19400. var DomSerializer = function (settings, editor) {
  19401. var domSerializer = DomSerializerImpl(settings, editor);
  19402. return {
  19403. schema: domSerializer.schema,
  19404. addNodeFilter: domSerializer.addNodeFilter,
  19405. addAttributeFilter: domSerializer.addAttributeFilter,
  19406. serialize: domSerializer.serialize,
  19407. addRules: domSerializer.addRules,
  19408. setRules: domSerializer.setRules,
  19409. addTempAttr: domSerializer.addTempAttr,
  19410. getTempAttrs: domSerializer.getTempAttrs,
  19411. getNodeFilters: domSerializer.getNodeFilters,
  19412. getAttributeFilters: domSerializer.getAttributeFilters
  19413. };
  19414. };
  19415. var defaultFormat = 'html';
  19416. var getContent = function (editor, args) {
  19417. if (args === void 0) {
  19418. args = {};
  19419. }
  19420. var format = args.format ? args.format : defaultFormat;
  19421. return getContent$2(editor, args, format);
  19422. };
  19423. var setContent = function (editor, content, args) {
  19424. if (args === void 0) {
  19425. args = {};
  19426. }
  19427. return setContent$2(editor, content, args);
  19428. };
  19429. var DOM$7 = DOMUtils.DOM;
  19430. var restoreOriginalStyles = function (editor) {
  19431. DOM$7.setStyle(editor.id, 'display', editor.orgDisplay);
  19432. };
  19433. var safeDestroy = function (x) {
  19434. return Optional.from(x).each(function (x) {
  19435. return x.destroy();
  19436. });
  19437. };
  19438. var clearDomReferences = function (editor) {
  19439. editor.contentAreaContainer = editor.formElement = editor.container = editor.editorContainer = null;
  19440. editor.bodyElement = editor.contentDocument = editor.contentWindow = null;
  19441. editor.iframeElement = editor.targetElm = null;
  19442. if (editor.selection) {
  19443. editor.selection = editor.selection.win = editor.selection.dom = editor.selection.dom.doc = null;
  19444. }
  19445. };
  19446. var restoreForm = function (editor) {
  19447. var form = editor.formElement;
  19448. if (form) {
  19449. if (form._mceOldSubmit) {
  19450. form.submit = form._mceOldSubmit;
  19451. form._mceOldSubmit = null;
  19452. }
  19453. DOM$7.unbind(form, 'submit reset', editor.formEventDelegate);
  19454. }
  19455. };
  19456. var remove = function (editor) {
  19457. if (!editor.removed) {
  19458. var _selectionOverrides = editor._selectionOverrides, editorUpload = editor.editorUpload;
  19459. var body = editor.getBody();
  19460. var element = editor.getElement();
  19461. if (body) {
  19462. editor.save({ is_removing: true });
  19463. }
  19464. editor.removed = true;
  19465. editor.unbindAllNativeEvents();
  19466. if (editor.hasHiddenInput && element) {
  19467. DOM$7.remove(element.nextSibling);
  19468. }
  19469. fireRemove(editor);
  19470. editor.editorManager.remove(editor);
  19471. if (!editor.inline && body) {
  19472. restoreOriginalStyles(editor);
  19473. }
  19474. fireDetach(editor);
  19475. DOM$7.remove(editor.getContainer());
  19476. safeDestroy(_selectionOverrides);
  19477. safeDestroy(editorUpload);
  19478. editor.destroy();
  19479. }
  19480. };
  19481. var destroy = function (editor, automatic) {
  19482. var selection = editor.selection, dom = editor.dom;
  19483. if (editor.destroyed) {
  19484. return;
  19485. }
  19486. if (!automatic && !editor.removed) {
  19487. editor.remove();
  19488. return;
  19489. }
  19490. if (!automatic) {
  19491. editor.editorManager.off('beforeunload', editor._beforeUnload);
  19492. if (editor.theme && editor.theme.destroy) {
  19493. editor.theme.destroy();
  19494. }
  19495. safeDestroy(selection);
  19496. safeDestroy(dom);
  19497. }
  19498. restoreForm(editor);
  19499. clearDomReferences(editor);
  19500. editor.destroyed = true;
  19501. };
  19502. var deep = function (old, nu) {
  19503. var bothObjects = isObject(old) && isObject(nu);
  19504. return bothObjects ? deepMerge(old, nu) : nu;
  19505. };
  19506. var baseMerge = function (merger) {
  19507. return function () {
  19508. var objects = [];
  19509. for (var _i = 0; _i < arguments.length; _i++) {
  19510. objects[_i] = arguments[_i];
  19511. }
  19512. if (objects.length === 0) {
  19513. throw new Error('Can\'t merge zero objects');
  19514. }
  19515. var ret = {};
  19516. for (var j = 0; j < objects.length; j++) {
  19517. var curObject = objects[j];
  19518. for (var key in curObject) {
  19519. if (has$2(curObject, key)) {
  19520. ret[key] = merger(ret[key], curObject[key]);
  19521. }
  19522. }
  19523. }
  19524. return ret;
  19525. };
  19526. };
  19527. var deepMerge = baseMerge(deep);
  19528. var deprecatedSettings = ('autoresize_on_init,content_editable_state,convert_fonts_to_spans,inline_styles,padd_empty_with_br,block_elements,' + 'boolean_attributes,editor_deselector,editor_selector,elements,file_browser_callback_types,filepicker_validator_handler,' + 'force_hex_style_colors,force_p_newlines,gecko_spellcheck,images_dataimg_filter,media_scripts,mode,move_caret_before_on_enter_elements,' + 'non_empty_elements,self_closing_elements,short_ended_elements,special,spellchecker_select_languages,spellchecker_whitelist,' + 'tab_focus,table_responsive_width,text_block_elements,text_inline_elements,toolbar_drawer,types,validate,whitespace_elements,' + 'paste_word_valid_elements,paste_retain_style_properties,paste_convert_word_fake_lists').split(',');
  19529. var deprecatedPlugins = 'bbcode,colorpicker,contextmenu,fullpage,legacyoutput,spellchecker,textcolor'.split(',');
  19530. var movedToPremiumPlugins = 'imagetools,toc'.split(',');
  19531. var getDeprecatedSettings = function (settings) {
  19532. var settingNames = filter$4(deprecatedSettings, function (setting) {
  19533. return has$2(settings, setting);
  19534. });
  19535. var forcedRootBlock = settings.forced_root_block;
  19536. if (forcedRootBlock === false || forcedRootBlock === '') {
  19537. settingNames.push('forced_root_block (false only)');
  19538. }
  19539. return sort(settingNames);
  19540. };
  19541. var getDeprecatedPlugins = function (settings) {
  19542. var plugins = Tools.makeMap(settings.plugins, ' ');
  19543. var hasPlugin = function (plugin) {
  19544. return has$2(plugins, plugin);
  19545. };
  19546. var pluginNames = __spreadArray(__spreadArray([], filter$4(deprecatedPlugins, hasPlugin), true), bind(movedToPremiumPlugins, function (plugin) {
  19547. return hasPlugin(plugin) ? [plugin + ' (moving to premium)'] : [];
  19548. }), true);
  19549. return sort(pluginNames);
  19550. };
  19551. var logDeprecationsWarning = function (rawSettings, finalSettings) {
  19552. var deprecatedSettings = getDeprecatedSettings(rawSettings);
  19553. var deprecatedPlugins = getDeprecatedPlugins(finalSettings);
  19554. var hasDeprecatedPlugins = deprecatedPlugins.length > 0;
  19555. var hasDeprecatedSettings = deprecatedSettings.length > 0;
  19556. var isLegacyMobileTheme = finalSettings.theme === 'mobile';
  19557. if (hasDeprecatedPlugins || hasDeprecatedSettings || isLegacyMobileTheme) {
  19558. var listJoiner = '\n- ';
  19559. var themesMessage = isLegacyMobileTheme ? '\n\nThemes:' + listJoiner + 'mobile' : '';
  19560. var pluginsMessage = hasDeprecatedPlugins ? '\n\nPlugins:' + listJoiner + deprecatedPlugins.join(listJoiner) : '';
  19561. var settingsMessage = hasDeprecatedSettings ? '\n\nSettings:' + listJoiner + deprecatedSettings.join(listJoiner) : '';
  19562. console.warn('The following deprecated features are currently enabled, these will be removed in TinyMCE 6.0. ' + 'See https://www.tiny.cloud/docs/release-notes/6.0-upcoming-changes/ for more information.' + themesMessage + pluginsMessage + settingsMessage);
  19563. }
  19564. };
  19565. var sectionResult = function (sections, settings) {
  19566. return {
  19567. sections: constant(sections),
  19568. settings: constant(settings)
  19569. };
  19570. };
  19571. var deviceDetection = detect().deviceType;
  19572. var isTouch = deviceDetection.isTouch();
  19573. var isPhone = deviceDetection.isPhone();
  19574. var isTablet = deviceDetection.isTablet();
  19575. var legacyMobilePlugins = [
  19576. 'lists',
  19577. 'autolink',
  19578. 'autosave'
  19579. ];
  19580. var defaultTouchSettings = {
  19581. table_grid: false,
  19582. object_resizing: false,
  19583. resize: false
  19584. };
  19585. var normalizePlugins = function (plugins) {
  19586. var pluginNames = isArray$1(plugins) ? plugins.join(' ') : plugins;
  19587. var trimmedPlugins = map$3(isString$1(pluginNames) ? pluginNames.split(' ') : [], trim$4);
  19588. return filter$4(trimmedPlugins, function (item) {
  19589. return item.length > 0;
  19590. });
  19591. };
  19592. var filterLegacyMobilePlugins = function (plugins) {
  19593. return filter$4(plugins, curry(contains$3, legacyMobilePlugins));
  19594. };
  19595. var extractSections = function (keys, settings) {
  19596. var result = bifilter(settings, function (value, key) {
  19597. return contains$3(keys, key);
  19598. });
  19599. return sectionResult(result.t, result.f);
  19600. };
  19601. var getSection = function (sectionResult, name, defaults) {
  19602. if (defaults === void 0) {
  19603. defaults = {};
  19604. }
  19605. var sections = sectionResult.sections();
  19606. var sectionSettings = get$9(sections, name).getOr({});
  19607. return Tools.extend({}, defaults, sectionSettings);
  19608. };
  19609. var hasSection = function (sectionResult, name) {
  19610. return has$2(sectionResult.sections(), name);
  19611. };
  19612. var isSectionTheme = function (sectionResult, name, theme) {
  19613. var section = sectionResult.sections();
  19614. return hasSection(sectionResult, name) && section[name].theme === theme;
  19615. };
  19616. var getSectionConfig = function (sectionResult, name) {
  19617. return hasSection(sectionResult, name) ? sectionResult.sections()[name] : {};
  19618. };
  19619. var getToolbarMode = function (settings, defaultVal) {
  19620. return get$9(settings, 'toolbar_mode').orThunk(function () {
  19621. return get$9(settings, 'toolbar_drawer').map(function (val) {
  19622. return val === false ? 'wrap' : val;
  19623. });
  19624. }).getOr(defaultVal);
  19625. };
  19626. var getDefaultSettings = function (settings, id, documentBaseUrl, isTouch, editor) {
  19627. var baseDefaults = {
  19628. id: id,
  19629. theme: 'silver',
  19630. toolbar_mode: getToolbarMode(settings, 'floating'),
  19631. plugins: '',
  19632. document_base_url: documentBaseUrl,
  19633. add_form_submit_trigger: true,
  19634. submit_patch: true,
  19635. add_unload_trigger: true,
  19636. convert_urls: true,
  19637. relative_urls: true,
  19638. remove_script_host: true,
  19639. object_resizing: true,
  19640. doctype: '<!DOCTYPE html>',
  19641. visual: true,
  19642. font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%',
  19643. forced_root_block: 'p',
  19644. hidden_input: true,
  19645. inline_styles: true,
  19646. convert_fonts_to_spans: true,
  19647. indent: true,
  19648. indent_before: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,' + 'tfoot,tbody,tr,section,summary,article,hgroup,aside,figure,figcaption,option,optgroup,datalist',
  19649. indent_after: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,' + 'tfoot,tbody,tr,section,summary,article,hgroup,aside,figure,figcaption,option,optgroup,datalist',
  19650. entity_encoding: 'named',
  19651. url_converter: editor.convertURL,
  19652. url_converter_scope: editor
  19653. };
  19654. return __assign(__assign({}, baseDefaults), isTouch ? defaultTouchSettings : {});
  19655. };
  19656. var getDefaultMobileSettings = function (mobileSettings, isPhone) {
  19657. var defaultMobileSettings = {
  19658. resize: false,
  19659. toolbar_mode: getToolbarMode(mobileSettings, 'scrolling'),
  19660. toolbar_sticky: false
  19661. };
  19662. var defaultPhoneSettings = { menubar: false };
  19663. return __assign(__assign(__assign({}, defaultTouchSettings), defaultMobileSettings), isPhone ? defaultPhoneSettings : {});
  19664. };
  19665. var getExternalPlugins = function (overrideSettings, settings) {
  19666. var userDefinedExternalPlugins = settings.external_plugins ? settings.external_plugins : {};
  19667. if (overrideSettings && overrideSettings.external_plugins) {
  19668. return Tools.extend({}, overrideSettings.external_plugins, userDefinedExternalPlugins);
  19669. } else {
  19670. return userDefinedExternalPlugins;
  19671. }
  19672. };
  19673. var combinePlugins = function (forcedPlugins, plugins) {
  19674. return [].concat(normalizePlugins(forcedPlugins)).concat(normalizePlugins(plugins));
  19675. };
  19676. var getPlatformPlugins = function (isMobileDevice, sectionResult, desktopPlugins, mobilePlugins) {
  19677. if (isMobileDevice && isSectionTheme(sectionResult, 'mobile', 'mobile')) {
  19678. return filterLegacyMobilePlugins(mobilePlugins);
  19679. } else if (isMobileDevice && hasSection(sectionResult, 'mobile')) {
  19680. return mobilePlugins;
  19681. } else {
  19682. return desktopPlugins;
  19683. }
  19684. };
  19685. var processPlugins = function (isMobileDevice, sectionResult, defaultOverrideSettings, settings) {
  19686. var forcedPlugins = normalizePlugins(defaultOverrideSettings.forced_plugins);
  19687. var desktopPlugins = normalizePlugins(settings.plugins);
  19688. var mobileConfig = getSectionConfig(sectionResult, 'mobile');
  19689. var mobilePlugins = mobileConfig.plugins ? normalizePlugins(mobileConfig.plugins) : desktopPlugins;
  19690. var platformPlugins = getPlatformPlugins(isMobileDevice, sectionResult, desktopPlugins, mobilePlugins);
  19691. var combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
  19692. if (Env.browser.isIE() && contains$3(combinedPlugins, 'rtc')) {
  19693. throw new Error('RTC plugin is not supported on IE 11.');
  19694. }
  19695. return Tools.extend(settings, { plugins: combinedPlugins.join(' ') });
  19696. };
  19697. var isOnMobile = function (isMobileDevice, sectionResult) {
  19698. return isMobileDevice && hasSection(sectionResult, 'mobile');
  19699. };
  19700. var combineSettings = function (isMobileDevice, isPhone, defaultSettings, defaultOverrideSettings, settings) {
  19701. var defaultDeviceSettings = isMobileDevice ? { mobile: getDefaultMobileSettings(settings.mobile || {}, isPhone) } : {};
  19702. var sectionResult = extractSections(['mobile'], deepMerge(defaultDeviceSettings, settings));
  19703. var extendedSettings = Tools.extend(defaultSettings, defaultOverrideSettings, sectionResult.settings(), isOnMobile(isMobileDevice, sectionResult) ? getSection(sectionResult, 'mobile') : {}, {
  19704. validate: true,
  19705. external_plugins: getExternalPlugins(defaultOverrideSettings, sectionResult.settings())
  19706. });
  19707. return processPlugins(isMobileDevice, sectionResult, defaultOverrideSettings, extendedSettings);
  19708. };
  19709. var getEditorSettings = function (editor, id, documentBaseUrl, defaultOverrideSettings, settings) {
  19710. var defaultSettings = getDefaultSettings(settings, id, documentBaseUrl, isTouch, editor);
  19711. var finalSettings = combineSettings(isPhone || isTablet, isPhone, defaultSettings, defaultOverrideSettings, settings);
  19712. if (finalSettings.deprecation_warnings !== false) {
  19713. logDeprecationsWarning(settings, finalSettings);
  19714. }
  19715. return finalSettings;
  19716. };
  19717. var getFiltered = function (predicate, editor, name) {
  19718. return Optional.from(editor.settings[name]).filter(predicate);
  19719. };
  19720. var getParamObject = function (value) {
  19721. var output = {};
  19722. if (typeof value === 'string') {
  19723. each$k(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function (val) {
  19724. var arr = val.split('=');
  19725. if (arr.length > 1) {
  19726. output[Tools.trim(arr[0])] = Tools.trim(arr[1]);
  19727. } else {
  19728. output[Tools.trim(arr[0])] = Tools.trim(arr[0]);
  19729. }
  19730. });
  19731. } else {
  19732. output = value;
  19733. }
  19734. return output;
  19735. };
  19736. var isArrayOf = function (p) {
  19737. return function (a) {
  19738. return isArray$1(a) && forall(a, p);
  19739. };
  19740. };
  19741. var getParam = function (editor, name, defaultVal, type) {
  19742. var value = name in editor.settings ? editor.settings[name] : defaultVal;
  19743. if (type === 'hash') {
  19744. return getParamObject(value);
  19745. } else if (type === 'string') {
  19746. return getFiltered(isString$1, editor, name).getOr(defaultVal);
  19747. } else if (type === 'number') {
  19748. return getFiltered(isNumber, editor, name).getOr(defaultVal);
  19749. } else if (type === 'boolean') {
  19750. return getFiltered(isBoolean, editor, name).getOr(defaultVal);
  19751. } else if (type === 'object') {
  19752. return getFiltered(isObject, editor, name).getOr(defaultVal);
  19753. } else if (type === 'array') {
  19754. return getFiltered(isArray$1, editor, name).getOr(defaultVal);
  19755. } else if (type === 'string[]') {
  19756. return getFiltered(isArrayOf(isString$1), editor, name).getOr(defaultVal);
  19757. } else if (type === 'function') {
  19758. return getFiltered(isFunction, editor, name).getOr(defaultVal);
  19759. } else {
  19760. return value;
  19761. }
  19762. };
  19763. var CreateIconManager = function () {
  19764. var lookup = {};
  19765. var add = function (id, iconPack) {
  19766. lookup[id] = iconPack;
  19767. };
  19768. var get = function (id) {
  19769. if (lookup[id]) {
  19770. return lookup[id];
  19771. }
  19772. return { icons: {} };
  19773. };
  19774. var has = function (id) {
  19775. return has$2(lookup, id);
  19776. };
  19777. return {
  19778. add: add,
  19779. get: get,
  19780. has: has
  19781. };
  19782. };
  19783. var IconManager = CreateIconManager();
  19784. var getProp = function (propName, elm) {
  19785. var rawElm = elm.dom;
  19786. return rawElm[propName];
  19787. };
  19788. var getComputedSizeProp = function (propName, elm) {
  19789. return parseInt(get$5(elm, propName), 10);
  19790. };
  19791. var getClientWidth = curry(getProp, 'clientWidth');
  19792. var getClientHeight = curry(getProp, 'clientHeight');
  19793. var getMarginTop = curry(getComputedSizeProp, 'margin-top');
  19794. var getMarginLeft = curry(getComputedSizeProp, 'margin-left');
  19795. var getBoundingClientRect = function (elm) {
  19796. return elm.dom.getBoundingClientRect();
  19797. };
  19798. var isInsideElementContentArea = function (bodyElm, clientX, clientY) {
  19799. var clientWidth = getClientWidth(bodyElm);
  19800. var clientHeight = getClientHeight(bodyElm);
  19801. return clientX >= 0 && clientY >= 0 && clientX <= clientWidth && clientY <= clientHeight;
  19802. };
  19803. var transpose = function (inline, elm, clientX, clientY) {
  19804. var clientRect = getBoundingClientRect(elm);
  19805. var deltaX = inline ? clientRect.left + elm.dom.clientLeft + getMarginLeft(elm) : 0;
  19806. var deltaY = inline ? clientRect.top + elm.dom.clientTop + getMarginTop(elm) : 0;
  19807. var x = clientX - deltaX;
  19808. var y = clientY - deltaY;
  19809. return {
  19810. x: x,
  19811. y: y
  19812. };
  19813. };
  19814. var isXYInContentArea = function (editor, clientX, clientY) {
  19815. var bodyElm = SugarElement.fromDom(editor.getBody());
  19816. var targetElm = editor.inline ? bodyElm : documentElement(bodyElm);
  19817. var transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
  19818. return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
  19819. };
  19820. var fromDomSafe = function (node) {
  19821. return Optional.from(node).map(SugarElement.fromDom);
  19822. };
  19823. var isEditorAttachedToDom = function (editor) {
  19824. var rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
  19825. return fromDomSafe(rawContainer).map(inBody).getOr(false);
  19826. };
  19827. var NotificationManagerImpl = function () {
  19828. var unimplemented = function () {
  19829. throw new Error('Theme did not provide a NotificationManager implementation.');
  19830. };
  19831. return {
  19832. open: unimplemented,
  19833. close: unimplemented,
  19834. reposition: unimplemented,
  19835. getArgs: unimplemented
  19836. };
  19837. };
  19838. var NotificationManager = function (editor) {
  19839. var notifications = [];
  19840. var getImplementation = function () {
  19841. var theme = editor.theme;
  19842. return theme && theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
  19843. };
  19844. var getTopNotification = function () {
  19845. return Optional.from(notifications[0]);
  19846. };
  19847. var isEqual = function (a, b) {
  19848. return a.type === b.type && a.text === b.text && !a.progressBar && !a.timeout && !b.progressBar && !b.timeout;
  19849. };
  19850. var reposition = function () {
  19851. if (notifications.length > 0) {
  19852. getImplementation().reposition(notifications);
  19853. }
  19854. };
  19855. var addNotification = function (notification) {
  19856. notifications.push(notification);
  19857. };
  19858. var closeNotification = function (notification) {
  19859. findIndex$2(notifications, function (otherNotification) {
  19860. return otherNotification === notification;
  19861. }).each(function (index) {
  19862. notifications.splice(index, 1);
  19863. });
  19864. };
  19865. var open = function (spec, fireEvent) {
  19866. if (fireEvent === void 0) {
  19867. fireEvent = true;
  19868. }
  19869. if (editor.removed || !isEditorAttachedToDom(editor)) {
  19870. return;
  19871. }
  19872. if (fireEvent) {
  19873. editor.fire('BeforeOpenNotification', { notification: spec });
  19874. }
  19875. return find$3(notifications, function (notification) {
  19876. return isEqual(getImplementation().getArgs(notification), spec);
  19877. }).getOrThunk(function () {
  19878. editor.editorManager.setActive(editor);
  19879. var notification = getImplementation().open(spec, function () {
  19880. closeNotification(notification);
  19881. reposition();
  19882. getTopNotification().fold(function () {
  19883. return editor.focus();
  19884. }, function (top) {
  19885. return focus$1(SugarElement.fromDom(top.getEl()));
  19886. });
  19887. });
  19888. addNotification(notification);
  19889. reposition();
  19890. editor.fire('OpenNotification', { notification: __assign({}, notification) });
  19891. return notification;
  19892. });
  19893. };
  19894. var close = function () {
  19895. getTopNotification().each(function (notification) {
  19896. getImplementation().close(notification);
  19897. closeNotification(notification);
  19898. reposition();
  19899. });
  19900. };
  19901. var getNotifications = constant(notifications);
  19902. var registerEvents = function (editor) {
  19903. editor.on('SkinLoaded', function () {
  19904. var serviceMessage = getServiceMessage(editor);
  19905. if (serviceMessage) {
  19906. open({
  19907. text: serviceMessage,
  19908. type: 'warning',
  19909. timeout: 0
  19910. }, false);
  19911. }
  19912. reposition();
  19913. });
  19914. editor.on('show ResizeEditor ResizeWindow NodeChange', function () {
  19915. Delay.requestAnimationFrame(reposition);
  19916. });
  19917. editor.on('remove', function () {
  19918. each$k(notifications.slice(), function (notification) {
  19919. getImplementation().close(notification);
  19920. });
  19921. });
  19922. };
  19923. registerEvents(editor);
  19924. return {
  19925. open: open,
  19926. close: close,
  19927. getNotifications: getNotifications
  19928. };
  19929. };
  19930. var PluginManager = AddOnManager.PluginManager;
  19931. var ThemeManager = AddOnManager.ThemeManager;
  19932. function WindowManagerImpl () {
  19933. var unimplemented = function () {
  19934. throw new Error('Theme did not provide a WindowManager implementation.');
  19935. };
  19936. return {
  19937. open: unimplemented,
  19938. openUrl: unimplemented,
  19939. alert: unimplemented,
  19940. confirm: unimplemented,
  19941. close: unimplemented,
  19942. getParams: unimplemented,
  19943. setParams: unimplemented
  19944. };
  19945. }
  19946. var WindowManager = function (editor) {
  19947. var dialogs = [];
  19948. var getImplementation = function () {
  19949. var theme = editor.theme;
  19950. return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
  19951. };
  19952. var funcBind = function (scope, f) {
  19953. return function () {
  19954. var args = [];
  19955. for (var _i = 0; _i < arguments.length; _i++) {
  19956. args[_i] = arguments[_i];
  19957. }
  19958. return f ? f.apply(scope, args) : undefined;
  19959. };
  19960. };
  19961. var fireOpenEvent = function (dialog) {
  19962. editor.fire('OpenWindow', { dialog: dialog });
  19963. };
  19964. var fireCloseEvent = function (dialog) {
  19965. editor.fire('CloseWindow', { dialog: dialog });
  19966. };
  19967. var addDialog = function (dialog) {
  19968. dialogs.push(dialog);
  19969. fireOpenEvent(dialog);
  19970. };
  19971. var closeDialog = function (dialog) {
  19972. fireCloseEvent(dialog);
  19973. dialogs = filter$4(dialogs, function (otherDialog) {
  19974. return otherDialog !== dialog;
  19975. });
  19976. if (dialogs.length === 0) {
  19977. editor.focus();
  19978. }
  19979. };
  19980. var getTopDialog = function () {
  19981. return Optional.from(dialogs[dialogs.length - 1]);
  19982. };
  19983. var storeSelectionAndOpenDialog = function (openDialog) {
  19984. editor.editorManager.setActive(editor);
  19985. store(editor);
  19986. var dialog = openDialog();
  19987. addDialog(dialog);
  19988. return dialog;
  19989. };
  19990. var open = function (args, params) {
  19991. return storeSelectionAndOpenDialog(function () {
  19992. return getImplementation().open(args, params, closeDialog);
  19993. });
  19994. };
  19995. var openUrl = function (args) {
  19996. return storeSelectionAndOpenDialog(function () {
  19997. return getImplementation().openUrl(args, closeDialog);
  19998. });
  19999. };
  20000. var alert = function (message, callback, scope) {
  20001. var windowManagerImpl = getImplementation();
  20002. windowManagerImpl.alert(message, funcBind(scope ? scope : windowManagerImpl, callback));
  20003. };
  20004. var confirm = function (message, callback, scope) {
  20005. var windowManagerImpl = getImplementation();
  20006. windowManagerImpl.confirm(message, funcBind(scope ? scope : windowManagerImpl, callback));
  20007. };
  20008. var close = function () {
  20009. getTopDialog().each(function (dialog) {
  20010. getImplementation().close(dialog);
  20011. closeDialog(dialog);
  20012. });
  20013. };
  20014. editor.on('remove', function () {
  20015. each$k(dialogs, function (dialog) {
  20016. getImplementation().close(dialog);
  20017. });
  20018. });
  20019. return {
  20020. open: open,
  20021. openUrl: openUrl,
  20022. alert: alert,
  20023. confirm: confirm,
  20024. close: close
  20025. };
  20026. };
  20027. var displayNotification = function (editor, message) {
  20028. editor.notificationManager.open({
  20029. type: 'error',
  20030. text: message
  20031. });
  20032. };
  20033. var displayError = function (editor, message) {
  20034. if (editor._skinLoaded) {
  20035. displayNotification(editor, message);
  20036. } else {
  20037. editor.on('SkinLoaded', function () {
  20038. displayNotification(editor, message);
  20039. });
  20040. }
  20041. };
  20042. var uploadError = function (editor, message) {
  20043. displayError(editor, I18n.translate([
  20044. 'Failed to upload image: {0}',
  20045. message
  20046. ]));
  20047. };
  20048. var logError = function (editor, errorType, msg) {
  20049. fireError(editor, errorType, { message: msg });
  20050. console.error(msg);
  20051. };
  20052. var createLoadError = function (type, url, name) {
  20053. return name ? 'Failed to load ' + type + ': ' + name + ' from url ' + url : 'Failed to load ' + type + ' url: ' + url;
  20054. };
  20055. var pluginLoadError = function (editor, url, name) {
  20056. logError(editor, 'PluginLoadError', createLoadError('plugin', url, name));
  20057. };
  20058. var iconsLoadError = function (editor, url, name) {
  20059. logError(editor, 'IconsLoadError', createLoadError('icons', url, name));
  20060. };
  20061. var languageLoadError = function (editor, url, name) {
  20062. logError(editor, 'LanguageLoadError', createLoadError('language', url, name));
  20063. };
  20064. var pluginInitError = function (editor, name, err) {
  20065. var message = I18n.translate([
  20066. 'Failed to initialize plugin: {0}',
  20067. name
  20068. ]);
  20069. fireError(editor, 'PluginLoadError', { message: message });
  20070. initError(message, err);
  20071. displayError(editor, message);
  20072. };
  20073. var initError = function (message) {
  20074. var x = [];
  20075. for (var _i = 1; _i < arguments.length; _i++) {
  20076. x[_i - 1] = arguments[_i];
  20077. }
  20078. var console = window.console;
  20079. if (console) {
  20080. if (console.error) {
  20081. console.error.apply(console, __spreadArray([message], x, false));
  20082. } else {
  20083. console.log.apply(console, __spreadArray([message], x, false));
  20084. }
  20085. }
  20086. };
  20087. var isContentCssSkinName = function (url) {
  20088. return /^[a-z0-9\-]+$/i.test(url);
  20089. };
  20090. var getContentCssUrls = function (editor) {
  20091. return transformToUrls(editor, getContentCss(editor));
  20092. };
  20093. var getFontCssUrls = function (editor) {
  20094. return transformToUrls(editor, getFontCss(editor));
  20095. };
  20096. var transformToUrls = function (editor, cssLinks) {
  20097. var skinUrl = editor.editorManager.baseURL + '/skins/content';
  20098. var suffix = editor.editorManager.suffix;
  20099. var contentCssFile = 'content' + suffix + '.css';
  20100. var inline = editor.inline === true;
  20101. return map$3(cssLinks, function (url) {
  20102. if (isContentCssSkinName(url) && !inline) {
  20103. return skinUrl + '/' + url + '/' + contentCssFile;
  20104. } else {
  20105. return editor.documentBaseURI.toAbsolute(url);
  20106. }
  20107. });
  20108. };
  20109. var appendContentCssFromSettings = function (editor) {
  20110. editor.contentCSS = editor.contentCSS.concat(getContentCssUrls(editor), getFontCssUrls(editor));
  20111. };
  20112. var UploadStatus = function () {
  20113. var PENDING = 1, UPLOADED = 2;
  20114. var blobUriStatuses = {};
  20115. var createStatus = function (status, resultUri) {
  20116. return {
  20117. status: status,
  20118. resultUri: resultUri
  20119. };
  20120. };
  20121. var hasBlobUri = function (blobUri) {
  20122. return blobUri in blobUriStatuses;
  20123. };
  20124. var getResultUri = function (blobUri) {
  20125. var result = blobUriStatuses[blobUri];
  20126. return result ? result.resultUri : null;
  20127. };
  20128. var isPending = function (blobUri) {
  20129. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
  20130. };
  20131. var isUploaded = function (blobUri) {
  20132. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
  20133. };
  20134. var markPending = function (blobUri) {
  20135. blobUriStatuses[blobUri] = createStatus(PENDING, null);
  20136. };
  20137. var markUploaded = function (blobUri, resultUri) {
  20138. blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
  20139. };
  20140. var removeFailed = function (blobUri) {
  20141. delete blobUriStatuses[blobUri];
  20142. };
  20143. var destroy = function () {
  20144. blobUriStatuses = {};
  20145. };
  20146. return {
  20147. hasBlobUri: hasBlobUri,
  20148. getResultUri: getResultUri,
  20149. isPending: isPending,
  20150. isUploaded: isUploaded,
  20151. markPending: markPending,
  20152. markUploaded: markUploaded,
  20153. removeFailed: removeFailed,
  20154. destroy: destroy
  20155. };
  20156. };
  20157. var count = 0;
  20158. var seed = function () {
  20159. var rnd = function () {
  20160. return Math.round(Math.random() * 4294967295).toString(36);
  20161. };
  20162. var now = new Date().getTime();
  20163. return 's' + now.toString(36) + rnd() + rnd() + rnd();
  20164. };
  20165. var uuid = function (prefix) {
  20166. return prefix + count++ + seed();
  20167. };
  20168. var BlobCache = function () {
  20169. var cache = [];
  20170. var mimeToExt = function (mime) {
  20171. var mimes = {
  20172. 'image/jpeg': 'jpg',
  20173. 'image/jpg': 'jpg',
  20174. 'image/gif': 'gif',
  20175. 'image/png': 'png',
  20176. 'image/apng': 'apng',
  20177. 'image/avif': 'avif',
  20178. 'image/svg+xml': 'svg',
  20179. 'image/webp': 'webp',
  20180. 'image/bmp': 'bmp',
  20181. 'image/tiff': 'tiff'
  20182. };
  20183. return mimes[mime.toLowerCase()] || 'dat';
  20184. };
  20185. var create = function (o, blob, base64, name, filename) {
  20186. if (isString$1(o)) {
  20187. var id = o;
  20188. return toBlobInfo({
  20189. id: id,
  20190. name: name,
  20191. filename: filename,
  20192. blob: blob,
  20193. base64: base64
  20194. });
  20195. } else if (isObject(o)) {
  20196. return toBlobInfo(o);
  20197. } else {
  20198. throw new Error('Unknown input type');
  20199. }
  20200. };
  20201. var toBlobInfo = function (o) {
  20202. if (!o.blob || !o.base64) {
  20203. throw new Error('blob and base64 representations of the image are required for BlobInfo to be created');
  20204. }
  20205. var id = o.id || uuid('blobid');
  20206. var name = o.name || id;
  20207. var blob = o.blob;
  20208. return {
  20209. id: constant(id),
  20210. name: constant(name),
  20211. filename: constant(o.filename || name + '.' + mimeToExt(blob.type)),
  20212. blob: constant(blob),
  20213. base64: constant(o.base64),
  20214. blobUri: constant(o.blobUri || URL.createObjectURL(blob)),
  20215. uri: constant(o.uri)
  20216. };
  20217. };
  20218. var add = function (blobInfo) {
  20219. if (!get(blobInfo.id())) {
  20220. cache.push(blobInfo);
  20221. }
  20222. };
  20223. var findFirst = function (predicate) {
  20224. return find$3(cache, predicate).getOrUndefined();
  20225. };
  20226. var get = function (id) {
  20227. return findFirst(function (cachedBlobInfo) {
  20228. return cachedBlobInfo.id() === id;
  20229. });
  20230. };
  20231. var getByUri = function (blobUri) {
  20232. return findFirst(function (blobInfo) {
  20233. return blobInfo.blobUri() === blobUri;
  20234. });
  20235. };
  20236. var getByData = function (base64, type) {
  20237. return findFirst(function (blobInfo) {
  20238. return blobInfo.base64() === base64 && blobInfo.blob().type === type;
  20239. });
  20240. };
  20241. var removeByUri = function (blobUri) {
  20242. cache = filter$4(cache, function (blobInfo) {
  20243. if (blobInfo.blobUri() === blobUri) {
  20244. URL.revokeObjectURL(blobInfo.blobUri());
  20245. return false;
  20246. }
  20247. return true;
  20248. });
  20249. };
  20250. var destroy = function () {
  20251. each$k(cache, function (cachedBlobInfo) {
  20252. URL.revokeObjectURL(cachedBlobInfo.blobUri());
  20253. });
  20254. cache = [];
  20255. };
  20256. return {
  20257. create: create,
  20258. add: add,
  20259. get: get,
  20260. getByUri: getByUri,
  20261. getByData: getByData,
  20262. findFirst: findFirst,
  20263. removeByUri: removeByUri,
  20264. destroy: destroy
  20265. };
  20266. };
  20267. var Uploader = function (uploadStatus, settings) {
  20268. var pendingPromises = {};
  20269. var pathJoin = function (path1, path2) {
  20270. if (path1) {
  20271. return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
  20272. }
  20273. return path2;
  20274. };
  20275. var defaultHandler = function (blobInfo, success, failure, progress) {
  20276. var xhr = new XMLHttpRequest();
  20277. xhr.open('POST', settings.url);
  20278. xhr.withCredentials = settings.credentials;
  20279. xhr.upload.onprogress = function (e) {
  20280. progress(e.loaded / e.total * 100);
  20281. };
  20282. xhr.onerror = function () {
  20283. failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  20284. };
  20285. xhr.onload = function () {
  20286. if (xhr.status < 200 || xhr.status >= 300) {
  20287. failure('HTTP Error: ' + xhr.status);
  20288. return;
  20289. }
  20290. var json = JSON.parse(xhr.responseText);
  20291. if (!json || typeof json.location !== 'string') {
  20292. failure('Invalid JSON: ' + xhr.responseText);
  20293. return;
  20294. }
  20295. success(pathJoin(settings.basePath, json.location));
  20296. };
  20297. var formData = new FormData();
  20298. formData.append('file', blobInfo.blob(), blobInfo.filename());
  20299. xhr.send(formData);
  20300. };
  20301. var noUpload = function () {
  20302. return new promiseObj(function (resolve) {
  20303. resolve([]);
  20304. });
  20305. };
  20306. var handlerSuccess = function (blobInfo, url) {
  20307. return {
  20308. url: url,
  20309. blobInfo: blobInfo,
  20310. status: true
  20311. };
  20312. };
  20313. var handlerFailure = function (blobInfo, message, options) {
  20314. return {
  20315. url: '',
  20316. blobInfo: blobInfo,
  20317. status: false,
  20318. error: {
  20319. message: message,
  20320. options: options
  20321. }
  20322. };
  20323. };
  20324. var resolvePending = function (blobUri, result) {
  20325. Tools.each(pendingPromises[blobUri], function (resolve) {
  20326. resolve(result);
  20327. });
  20328. delete pendingPromises[blobUri];
  20329. };
  20330. var uploadBlobInfo = function (blobInfo, handler, openNotification) {
  20331. uploadStatus.markPending(blobInfo.blobUri());
  20332. return new promiseObj(function (resolve) {
  20333. var notification, progress;
  20334. try {
  20335. var closeNotification_1 = function () {
  20336. if (notification) {
  20337. notification.close();
  20338. progress = noop;
  20339. }
  20340. };
  20341. var success = function (url) {
  20342. closeNotification_1();
  20343. uploadStatus.markUploaded(blobInfo.blobUri(), url);
  20344. resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
  20345. resolve(handlerSuccess(blobInfo, url));
  20346. };
  20347. var failure = function (error, options) {
  20348. var failureOptions = options ? options : {};
  20349. closeNotification_1();
  20350. uploadStatus.removeFailed(blobInfo.blobUri());
  20351. resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error, failureOptions));
  20352. resolve(handlerFailure(blobInfo, error, failureOptions));
  20353. };
  20354. progress = function (percent) {
  20355. if (percent < 0 || percent > 100) {
  20356. return;
  20357. }
  20358. Optional.from(notification).orThunk(function () {
  20359. return Optional.from(openNotification).map(apply);
  20360. }).each(function (n) {
  20361. notification = n;
  20362. n.progressBar.value(percent);
  20363. });
  20364. };
  20365. handler(blobInfo, success, failure, progress);
  20366. } catch (ex) {
  20367. resolve(handlerFailure(blobInfo, ex.message, {}));
  20368. }
  20369. });
  20370. };
  20371. var isDefaultHandler = function (handler) {
  20372. return handler === defaultHandler;
  20373. };
  20374. var pendingUploadBlobInfo = function (blobInfo) {
  20375. var blobUri = blobInfo.blobUri();
  20376. return new promiseObj(function (resolve) {
  20377. pendingPromises[blobUri] = pendingPromises[blobUri] || [];
  20378. pendingPromises[blobUri].push(resolve);
  20379. });
  20380. };
  20381. var uploadBlobs = function (blobInfos, openNotification) {
  20382. blobInfos = Tools.grep(blobInfos, function (blobInfo) {
  20383. return !uploadStatus.isUploaded(blobInfo.blobUri());
  20384. });
  20385. return promiseObj.all(Tools.map(blobInfos, function (blobInfo) {
  20386. return uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification);
  20387. }));
  20388. };
  20389. var upload = function (blobInfos, openNotification) {
  20390. return !settings.url && isDefaultHandler(settings.handler) ? noUpload() : uploadBlobs(blobInfos, openNotification);
  20391. };
  20392. if (isFunction(settings.handler) === false) {
  20393. settings.handler = defaultHandler;
  20394. }
  20395. return { upload: upload };
  20396. };
  20397. var openNotification = function (editor) {
  20398. return function () {
  20399. return editor.notificationManager.open({
  20400. text: editor.translate('Image uploading...'),
  20401. type: 'info',
  20402. timeout: -1,
  20403. progressBar: true
  20404. });
  20405. };
  20406. };
  20407. var createUploader = function (editor, uploadStatus) {
  20408. return Uploader(uploadStatus, {
  20409. url: getImageUploadUrl(editor),
  20410. basePath: getImageUploadBasePath(editor),
  20411. credentials: getImagesUploadCredentials(editor),
  20412. handler: getImagesUploadHandler(editor)
  20413. });
  20414. };
  20415. var ImageUploader = function (editor) {
  20416. var uploadStatus = UploadStatus();
  20417. var uploader = createUploader(editor, uploadStatus);
  20418. return {
  20419. upload: function (blobInfos, showNotification) {
  20420. if (showNotification === void 0) {
  20421. showNotification = true;
  20422. }
  20423. return uploader.upload(blobInfos, showNotification ? openNotification(editor) : undefined);
  20424. }
  20425. };
  20426. };
  20427. var UploadChangeHandler = function (editor) {
  20428. var lastChangedLevel = Cell(null);
  20429. editor.on('change AddUndo', function (e) {
  20430. lastChangedLevel.set(__assign({}, e.level));
  20431. });
  20432. var fireIfChanged = function () {
  20433. var data = editor.undoManager.data;
  20434. last$2(data).filter(function (level) {
  20435. return !isEq$1(lastChangedLevel.get(), level);
  20436. }).each(function (level) {
  20437. editor.setDirty(true);
  20438. editor.fire('change', {
  20439. level: level,
  20440. lastLevel: get$a(data, data.length - 2).getOrNull()
  20441. });
  20442. });
  20443. };
  20444. return { fireIfChanged: fireIfChanged };
  20445. };
  20446. var EditorUpload = function (editor) {
  20447. var blobCache = BlobCache();
  20448. var uploader, imageScanner;
  20449. var uploadStatus = UploadStatus();
  20450. var urlFilters = [];
  20451. var changeHandler = UploadChangeHandler(editor);
  20452. var aliveGuard = function (callback) {
  20453. return function (result) {
  20454. if (editor.selection) {
  20455. return callback(result);
  20456. }
  20457. return [];
  20458. };
  20459. };
  20460. var cacheInvalidator = function (url) {
  20461. return url + (url.indexOf('?') === -1 ? '?' : '&') + new Date().getTime();
  20462. };
  20463. var replaceString = function (content, search, replace) {
  20464. var index = 0;
  20465. do {
  20466. index = content.indexOf(search, index);
  20467. if (index !== -1) {
  20468. content = content.substring(0, index) + replace + content.substr(index + search.length);
  20469. index += replace.length - search.length + 1;
  20470. }
  20471. } while (index !== -1);
  20472. return content;
  20473. };
  20474. var replaceImageUrl = function (content, targetUrl, replacementUrl) {
  20475. var replacementString = 'src="' + replacementUrl + '"' + (replacementUrl === Env.transparentSrc ? ' data-mce-placeholder="1"' : '');
  20476. content = replaceString(content, 'src="' + targetUrl + '"', replacementString);
  20477. content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
  20478. return content;
  20479. };
  20480. var replaceUrlInUndoStack = function (targetUrl, replacementUrl) {
  20481. each$k(editor.undoManager.data, function (level) {
  20482. if (level.type === 'fragmented') {
  20483. level.fragments = map$3(level.fragments, function (fragment) {
  20484. return replaceImageUrl(fragment, targetUrl, replacementUrl);
  20485. });
  20486. } else {
  20487. level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
  20488. }
  20489. });
  20490. };
  20491. var replaceImageUriInView = function (image, resultUri) {
  20492. var src = editor.convertURL(resultUri, 'src');
  20493. replaceUrlInUndoStack(image.src, resultUri);
  20494. editor.$(image).attr({
  20495. 'src': shouldReuseFileName(editor) ? cacheInvalidator(resultUri) : resultUri,
  20496. 'data-mce-src': src
  20497. });
  20498. };
  20499. var uploadImages = function (callback) {
  20500. if (!uploader) {
  20501. uploader = createUploader(editor, uploadStatus);
  20502. }
  20503. return scanForImages().then(aliveGuard(function (imageInfos) {
  20504. var blobInfos = map$3(imageInfos, function (imageInfo) {
  20505. return imageInfo.blobInfo;
  20506. });
  20507. return uploader.upload(blobInfos, openNotification(editor)).then(aliveGuard(function (result) {
  20508. var imagesToRemove = [];
  20509. var filteredResult = map$3(result, function (uploadInfo, index) {
  20510. var blobInfo = imageInfos[index].blobInfo;
  20511. var image = imageInfos[index].image;
  20512. if (uploadInfo.status && shouldReplaceBlobUris(editor)) {
  20513. blobCache.removeByUri(image.src);
  20514. if (isRtc(editor)) ; else {
  20515. replaceImageUriInView(image, uploadInfo.url);
  20516. }
  20517. } else if (uploadInfo.error) {
  20518. if (uploadInfo.error.options.remove) {
  20519. replaceUrlInUndoStack(image.getAttribute('src'), Env.transparentSrc);
  20520. imagesToRemove.push(image);
  20521. }
  20522. uploadError(editor, uploadInfo.error.message);
  20523. }
  20524. return {
  20525. element: image,
  20526. status: uploadInfo.status,
  20527. uploadUri: uploadInfo.url,
  20528. blobInfo: blobInfo
  20529. };
  20530. });
  20531. if (filteredResult.length > 0) {
  20532. changeHandler.fireIfChanged();
  20533. }
  20534. if (imagesToRemove.length > 0) {
  20535. if (isRtc(editor)) {
  20536. console.error('Removing images on failed uploads is currently unsupported for RTC');
  20537. } else {
  20538. editor.undoManager.transact(function () {
  20539. each$k(imagesToRemove, function (element) {
  20540. editor.dom.remove(element);
  20541. blobCache.removeByUri(element.src);
  20542. });
  20543. });
  20544. }
  20545. }
  20546. if (callback) {
  20547. callback(filteredResult);
  20548. }
  20549. return filteredResult;
  20550. }));
  20551. }));
  20552. };
  20553. var uploadImagesAuto = function (callback) {
  20554. if (isAutomaticUploadsEnabled(editor)) {
  20555. return uploadImages(callback);
  20556. }
  20557. };
  20558. var isValidDataUriImage = function (imgElm) {
  20559. if (forall(urlFilters, function (filter) {
  20560. return filter(imgElm);
  20561. }) === false) {
  20562. return false;
  20563. }
  20564. if (imgElm.getAttribute('src').indexOf('data:') === 0) {
  20565. var dataImgFilter = getImagesDataImgFilter(editor);
  20566. return dataImgFilter(imgElm);
  20567. }
  20568. return true;
  20569. };
  20570. var addFilter = function (filter) {
  20571. urlFilters.push(filter);
  20572. };
  20573. var scanForImages = function () {
  20574. if (!imageScanner) {
  20575. imageScanner = ImageScanner(uploadStatus, blobCache);
  20576. }
  20577. return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(function (result) {
  20578. result = filter$4(result, function (resultItem) {
  20579. if (typeof resultItem === 'string') {
  20580. displayError(editor, resultItem);
  20581. return false;
  20582. }
  20583. return true;
  20584. });
  20585. if (isRtc(editor)) ; else {
  20586. each$k(result, function (resultItem) {
  20587. replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
  20588. resultItem.image.src = resultItem.blobInfo.blobUri();
  20589. resultItem.image.removeAttribute('data-mce-src');
  20590. });
  20591. }
  20592. return result;
  20593. }));
  20594. };
  20595. var destroy = function () {
  20596. blobCache.destroy();
  20597. uploadStatus.destroy();
  20598. imageScanner = uploader = null;
  20599. };
  20600. var replaceBlobUris = function (content) {
  20601. return content.replace(/src="(blob:[^"]+)"/g, function (match, blobUri) {
  20602. var resultUri = uploadStatus.getResultUri(blobUri);
  20603. if (resultUri) {
  20604. return 'src="' + resultUri + '"';
  20605. }
  20606. var blobInfo = blobCache.getByUri(blobUri);
  20607. if (!blobInfo) {
  20608. blobInfo = foldl(editor.editorManager.get(), function (result, editor) {
  20609. return result || editor.editorUpload && editor.editorUpload.blobCache.getByUri(blobUri);
  20610. }, null);
  20611. }
  20612. if (blobInfo) {
  20613. var blob = blobInfo.blob();
  20614. return 'src="data:' + blob.type + ';base64,' + blobInfo.base64() + '"';
  20615. }
  20616. return match;
  20617. });
  20618. };
  20619. editor.on('SetContent', function () {
  20620. if (isAutomaticUploadsEnabled(editor)) {
  20621. uploadImagesAuto();
  20622. } else {
  20623. scanForImages();
  20624. }
  20625. });
  20626. editor.on('RawSaveContent', function (e) {
  20627. e.content = replaceBlobUris(e.content);
  20628. });
  20629. editor.on('GetContent', function (e) {
  20630. if (e.source_view || e.format === 'raw' || e.format === 'tree') {
  20631. return;
  20632. }
  20633. e.content = replaceBlobUris(e.content);
  20634. });
  20635. editor.on('PostRender', function () {
  20636. editor.parser.addNodeFilter('img', function (images) {
  20637. each$k(images, function (img) {
  20638. var src = img.attr('src');
  20639. if (blobCache.getByUri(src)) {
  20640. return;
  20641. }
  20642. var resultUri = uploadStatus.getResultUri(src);
  20643. if (resultUri) {
  20644. img.attr('src', resultUri);
  20645. }
  20646. });
  20647. });
  20648. });
  20649. return {
  20650. blobCache: blobCache,
  20651. addFilter: addFilter,
  20652. uploadImages: uploadImages,
  20653. uploadImagesAuto: uploadImagesAuto,
  20654. scanForImages: scanForImages,
  20655. destroy: destroy
  20656. };
  20657. };
  20658. var get = function (dom) {
  20659. var formats = {
  20660. valigntop: [{
  20661. selector: 'td,th',
  20662. styles: { verticalAlign: 'top' }
  20663. }],
  20664. valignmiddle: [{
  20665. selector: 'td,th',
  20666. styles: { verticalAlign: 'middle' }
  20667. }],
  20668. valignbottom: [{
  20669. selector: 'td,th',
  20670. styles: { verticalAlign: 'bottom' }
  20671. }],
  20672. alignleft: [
  20673. {
  20674. selector: 'figure.image',
  20675. collapsed: false,
  20676. classes: 'align-left',
  20677. ceFalseOverride: true,
  20678. preview: 'font-family font-size'
  20679. },
  20680. {
  20681. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20682. styles: { textAlign: 'left' },
  20683. inherit: false,
  20684. preview: false,
  20685. defaultBlock: 'div'
  20686. },
  20687. {
  20688. selector: 'img,table,audio,video',
  20689. collapsed: false,
  20690. styles: { float: 'left' },
  20691. preview: 'font-family font-size'
  20692. }
  20693. ],
  20694. aligncenter: [
  20695. {
  20696. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20697. styles: { textAlign: 'center' },
  20698. inherit: false,
  20699. preview: 'font-family font-size',
  20700. defaultBlock: 'div'
  20701. },
  20702. {
  20703. selector: 'figure.image',
  20704. collapsed: false,
  20705. classes: 'align-center',
  20706. ceFalseOverride: true,
  20707. preview: 'font-family font-size'
  20708. },
  20709. {
  20710. selector: 'img,audio,video',
  20711. collapsed: false,
  20712. styles: {
  20713. display: 'block',
  20714. marginLeft: 'auto',
  20715. marginRight: 'auto'
  20716. },
  20717. preview: false
  20718. },
  20719. {
  20720. selector: 'table',
  20721. collapsed: false,
  20722. styles: {
  20723. marginLeft: 'auto',
  20724. marginRight: 'auto'
  20725. },
  20726. preview: 'font-family font-size'
  20727. }
  20728. ],
  20729. alignright: [
  20730. {
  20731. selector: 'figure.image',
  20732. collapsed: false,
  20733. classes: 'align-right',
  20734. ceFalseOverride: true,
  20735. preview: 'font-family font-size'
  20736. },
  20737. {
  20738. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20739. styles: { textAlign: 'right' },
  20740. inherit: false,
  20741. preview: 'font-family font-size',
  20742. defaultBlock: 'div'
  20743. },
  20744. {
  20745. selector: 'img,table,audio,video',
  20746. collapsed: false,
  20747. styles: { float: 'right' },
  20748. preview: 'font-family font-size'
  20749. }
  20750. ],
  20751. alignjustify: [{
  20752. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20753. styles: { textAlign: 'justify' },
  20754. inherit: false,
  20755. defaultBlock: 'div',
  20756. preview: 'font-family font-size'
  20757. }],
  20758. bold: [
  20759. {
  20760. inline: 'strong',
  20761. remove: 'all',
  20762. preserve_attributes: [
  20763. 'class',
  20764. 'style'
  20765. ]
  20766. },
  20767. {
  20768. inline: 'span',
  20769. styles: { fontWeight: 'bold' }
  20770. },
  20771. {
  20772. inline: 'b',
  20773. remove: 'all',
  20774. preserve_attributes: [
  20775. 'class',
  20776. 'style'
  20777. ]
  20778. }
  20779. ],
  20780. italic: [
  20781. {
  20782. inline: 'em',
  20783. remove: 'all',
  20784. preserve_attributes: [
  20785. 'class',
  20786. 'style'
  20787. ]
  20788. },
  20789. {
  20790. inline: 'span',
  20791. styles: { fontStyle: 'italic' }
  20792. },
  20793. {
  20794. inline: 'i',
  20795. remove: 'all',
  20796. preserve_attributes: [
  20797. 'class',
  20798. 'style'
  20799. ]
  20800. }
  20801. ],
  20802. underline: [
  20803. {
  20804. inline: 'span',
  20805. styles: { textDecoration: 'underline' },
  20806. exact: true
  20807. },
  20808. {
  20809. inline: 'u',
  20810. remove: 'all',
  20811. preserve_attributes: [
  20812. 'class',
  20813. 'style'
  20814. ]
  20815. }
  20816. ],
  20817. strikethrough: [
  20818. {
  20819. inline: 'span',
  20820. styles: { textDecoration: 'line-through' },
  20821. exact: true
  20822. },
  20823. {
  20824. inline: 'strike',
  20825. remove: 'all',
  20826. preserve_attributes: [
  20827. 'class',
  20828. 'style'
  20829. ]
  20830. },
  20831. {
  20832. inline: 's',
  20833. remove: 'all',
  20834. preserve_attributes: [
  20835. 'class',
  20836. 'style'
  20837. ]
  20838. }
  20839. ],
  20840. forecolor: {
  20841. inline: 'span',
  20842. styles: { color: '%value' },
  20843. links: true,
  20844. remove_similar: true,
  20845. clear_child_styles: true
  20846. },
  20847. hilitecolor: {
  20848. inline: 'span',
  20849. styles: { backgroundColor: '%value' },
  20850. links: true,
  20851. remove_similar: true,
  20852. clear_child_styles: true
  20853. },
  20854. fontname: {
  20855. inline: 'span',
  20856. toggle: false,
  20857. styles: { fontFamily: '%value' },
  20858. clear_child_styles: true
  20859. },
  20860. fontsize: {
  20861. inline: 'span',
  20862. toggle: false,
  20863. styles: { fontSize: '%value' },
  20864. clear_child_styles: true
  20865. },
  20866. lineheight: {
  20867. selector: 'h1,h2,h3,h4,h5,h6,p,li,td,th,div',
  20868. defaultBlock: 'p',
  20869. styles: { lineHeight: '%value' }
  20870. },
  20871. fontsize_class: {
  20872. inline: 'span',
  20873. attributes: { class: '%value' }
  20874. },
  20875. blockquote: {
  20876. block: 'blockquote',
  20877. wrapper: true,
  20878. remove: 'all'
  20879. },
  20880. subscript: { inline: 'sub' },
  20881. superscript: { inline: 'sup' },
  20882. code: { inline: 'code' },
  20883. link: {
  20884. inline: 'a',
  20885. selector: 'a',
  20886. remove: 'all',
  20887. split: true,
  20888. deep: true,
  20889. onmatch: function (node, _fmt, _itemName) {
  20890. return isElement$5(node) && node.hasAttribute('href');
  20891. },
  20892. onformat: function (elm, _fmt, vars) {
  20893. Tools.each(vars, function (value, key) {
  20894. dom.setAttrib(elm, key, value);
  20895. });
  20896. }
  20897. },
  20898. lang: {
  20899. inline: 'span',
  20900. clear_child_styles: true,
  20901. remove_similar: true,
  20902. attributes: {
  20903. 'lang': '%value',
  20904. 'data-mce-lang': function (vars) {
  20905. var _a;
  20906. return (_a = vars === null || vars === void 0 ? void 0 : vars.customValue) !== null && _a !== void 0 ? _a : null;
  20907. }
  20908. }
  20909. },
  20910. removeformat: [
  20911. {
  20912. selector: 'b,strong,em,i,font,u,strike,s,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins,small',
  20913. remove: 'all',
  20914. split: true,
  20915. expand: false,
  20916. block_expand: true,
  20917. deep: true
  20918. },
  20919. {
  20920. selector: 'span',
  20921. attributes: [
  20922. 'style',
  20923. 'class'
  20924. ],
  20925. remove: 'empty',
  20926. split: true,
  20927. expand: false,
  20928. deep: true
  20929. },
  20930. {
  20931. selector: '*',
  20932. attributes: [
  20933. 'style',
  20934. 'class'
  20935. ],
  20936. split: false,
  20937. expand: false,
  20938. deep: true
  20939. }
  20940. ]
  20941. };
  20942. Tools.each('p h1 h2 h3 h4 h5 h6 div address pre dt dd samp'.split(/\s/), function (name) {
  20943. formats[name] = {
  20944. block: name,
  20945. remove: 'all'
  20946. };
  20947. });
  20948. return formats;
  20949. };
  20950. var FormatRegistry = function (editor) {
  20951. var formats = {};
  20952. var get$1 = function (name) {
  20953. return isNonNullable(name) ? formats[name] : formats;
  20954. };
  20955. var has = function (name) {
  20956. return has$2(formats, name);
  20957. };
  20958. var register = function (name, format) {
  20959. if (name) {
  20960. if (!isString$1(name)) {
  20961. each$j(name, function (format, name) {
  20962. register(name, format);
  20963. });
  20964. } else {
  20965. if (!isArray$1(format)) {
  20966. format = [format];
  20967. }
  20968. each$k(format, function (format) {
  20969. if (isUndefined(format.deep)) {
  20970. format.deep = !isSelectorFormat(format);
  20971. }
  20972. if (isUndefined(format.split)) {
  20973. format.split = !isSelectorFormat(format) || isInlineFormat(format);
  20974. }
  20975. if (isUndefined(format.remove) && isSelectorFormat(format) && !isInlineFormat(format)) {
  20976. format.remove = 'none';
  20977. }
  20978. if (isSelectorFormat(format) && isInlineFormat(format)) {
  20979. format.mixed = true;
  20980. format.block_expand = true;
  20981. }
  20982. if (isString$1(format.classes)) {
  20983. format.classes = format.classes.split(/\s+/);
  20984. }
  20985. });
  20986. formats[name] = format;
  20987. }
  20988. }
  20989. };
  20990. var unregister = function (name) {
  20991. if (name && formats[name]) {
  20992. delete formats[name];
  20993. }
  20994. return formats;
  20995. };
  20996. register(get(editor.dom));
  20997. register(getFormats(editor));
  20998. return {
  20999. get: get$1,
  21000. has: has,
  21001. register: register,
  21002. unregister: unregister
  21003. };
  21004. };
  21005. var each$5 = Tools.each;
  21006. var dom = DOMUtils.DOM;
  21007. var parsedSelectorToHtml = function (ancestry, editor) {
  21008. var elm, item, fragment;
  21009. var schema = editor && editor.schema || Schema({});
  21010. var decorate = function (elm, item) {
  21011. if (item.classes.length) {
  21012. dom.addClass(elm, item.classes.join(' '));
  21013. }
  21014. dom.setAttribs(elm, item.attrs);
  21015. };
  21016. var createElement = function (sItem) {
  21017. item = typeof sItem === 'string' ? {
  21018. name: sItem,
  21019. classes: [],
  21020. attrs: {}
  21021. } : sItem;
  21022. var elm = dom.create(item.name);
  21023. decorate(elm, item);
  21024. return elm;
  21025. };
  21026. var getRequiredParent = function (elm, candidate) {
  21027. var name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm;
  21028. var elmRule = schema.getElementRule(name);
  21029. var parentsRequired = elmRule && elmRule.parentsRequired;
  21030. if (parentsRequired && parentsRequired.length) {
  21031. return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
  21032. } else {
  21033. return false;
  21034. }
  21035. };
  21036. var wrapInHtml = function (elm, ancestry, siblings) {
  21037. var parent, parentCandidate;
  21038. var ancestor = ancestry.length > 0 && ancestry[0];
  21039. var ancestorName = ancestor && ancestor.name;
  21040. var parentRequired = getRequiredParent(elm, ancestorName);
  21041. if (parentRequired) {
  21042. if (ancestorName === parentRequired) {
  21043. parentCandidate = ancestry[0];
  21044. ancestry = ancestry.slice(1);
  21045. } else {
  21046. parentCandidate = parentRequired;
  21047. }
  21048. } else if (ancestor) {
  21049. parentCandidate = ancestry[0];
  21050. ancestry = ancestry.slice(1);
  21051. } else if (!siblings) {
  21052. return elm;
  21053. }
  21054. if (parentCandidate) {
  21055. parent = createElement(parentCandidate);
  21056. parent.appendChild(elm);
  21057. }
  21058. if (siblings) {
  21059. if (!parent) {
  21060. parent = dom.create('div');
  21061. parent.appendChild(elm);
  21062. }
  21063. Tools.each(siblings, function (sibling) {
  21064. var siblingElm = createElement(sibling);
  21065. parent.insertBefore(siblingElm, elm);
  21066. });
  21067. }
  21068. return wrapInHtml(parent, ancestry, parentCandidate && parentCandidate.siblings);
  21069. };
  21070. if (ancestry && ancestry.length) {
  21071. item = ancestry[0];
  21072. elm = createElement(item);
  21073. fragment = dom.create('div');
  21074. fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
  21075. return fragment;
  21076. } else {
  21077. return '';
  21078. }
  21079. };
  21080. var parseSelectorItem = function (item) {
  21081. var tagName;
  21082. var obj = {
  21083. classes: [],
  21084. attrs: {}
  21085. };
  21086. item = obj.selector = Tools.trim(item);
  21087. if (item !== '*') {
  21088. tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function ($0, $1, $2, $3, $4) {
  21089. switch ($1) {
  21090. case '#':
  21091. obj.attrs.id = $2;
  21092. break;
  21093. case '.':
  21094. obj.classes.push($2);
  21095. break;
  21096. case ':':
  21097. if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
  21098. obj.attrs[$2] = $2;
  21099. }
  21100. break;
  21101. }
  21102. if ($3 === '[') {
  21103. var m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
  21104. if (m) {
  21105. obj.attrs[m[1]] = m[2];
  21106. }
  21107. }
  21108. return '';
  21109. });
  21110. }
  21111. obj.name = tagName || 'div';
  21112. return obj;
  21113. };
  21114. var parseSelector = function (selector) {
  21115. if (!selector || typeof selector !== 'string') {
  21116. return [];
  21117. }
  21118. selector = selector.split(/\s*,\s*/)[0];
  21119. selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1');
  21120. return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), function (item) {
  21121. var siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
  21122. var obj = siblings.pop();
  21123. if (siblings.length) {
  21124. obj.siblings = siblings;
  21125. }
  21126. return obj;
  21127. }).reverse();
  21128. };
  21129. var getCssText = function (editor, format) {
  21130. var name, previewFrag;
  21131. var previewCss = '', parentFontSize;
  21132. var previewStyles = getPreviewStyles(editor);
  21133. if (previewStyles === '') {
  21134. return '';
  21135. }
  21136. var removeVars = function (val) {
  21137. return val.replace(/%(\w+)/g, '');
  21138. };
  21139. if (typeof format === 'string') {
  21140. format = editor.formatter.get(format);
  21141. if (!format) {
  21142. return;
  21143. }
  21144. format = format[0];
  21145. }
  21146. if ('preview' in format) {
  21147. var previewOpt = get$9(format, 'preview');
  21148. if (is$1(previewOpt, false)) {
  21149. return '';
  21150. } else {
  21151. previewStyles = previewOpt.getOr(previewStyles);
  21152. }
  21153. }
  21154. name = format.block || format.inline || 'span';
  21155. var items = parseSelector(format.selector);
  21156. if (items.length) {
  21157. if (!items[0].name) {
  21158. items[0].name = name;
  21159. }
  21160. name = format.selector;
  21161. previewFrag = parsedSelectorToHtml(items, editor);
  21162. } else {
  21163. previewFrag = parsedSelectorToHtml([name], editor);
  21164. }
  21165. var previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;
  21166. each$5(format.styles, function (value, name) {
  21167. var newValue = removeVars(value);
  21168. if (newValue) {
  21169. dom.setStyle(previewElm, name, newValue);
  21170. }
  21171. });
  21172. each$5(format.attributes, function (value, name) {
  21173. var newValue = removeVars(value);
  21174. if (newValue) {
  21175. dom.setAttrib(previewElm, name, newValue);
  21176. }
  21177. });
  21178. each$5(format.classes, function (value) {
  21179. var newValue = removeVars(value);
  21180. if (!dom.hasClass(previewElm, newValue)) {
  21181. dom.addClass(previewElm, newValue);
  21182. }
  21183. });
  21184. editor.fire('PreviewFormats');
  21185. dom.setStyles(previewFrag, {
  21186. position: 'absolute',
  21187. left: -65535
  21188. });
  21189. editor.getBody().appendChild(previewFrag);
  21190. parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
  21191. parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
  21192. each$5(previewStyles.split(' '), function (name) {
  21193. var value = dom.getStyle(previewElm, name, true);
  21194. if (name === 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
  21195. value = dom.getStyle(editor.getBody(), name, true);
  21196. if (dom.toHex(value).toLowerCase() === '#ffffff') {
  21197. return;
  21198. }
  21199. }
  21200. if (name === 'color') {
  21201. if (dom.toHex(value).toLowerCase() === '#000000') {
  21202. return;
  21203. }
  21204. }
  21205. if (name === 'font-size') {
  21206. if (/em|%$/.test(value)) {
  21207. if (parentFontSize === 0) {
  21208. return;
  21209. }
  21210. var numValue = parseFloat(value) / (/%$/.test(value) ? 100 : 1);
  21211. value = numValue * parentFontSize + 'px';
  21212. }
  21213. }
  21214. if (name === 'border' && value) {
  21215. previewCss += 'padding:0 2px;';
  21216. }
  21217. previewCss += name + ':' + value + ';';
  21218. });
  21219. editor.fire('AfterPreviewFormats');
  21220. dom.remove(previewFrag);
  21221. return previewCss;
  21222. };
  21223. var setup$h = function (editor) {
  21224. editor.addShortcut('meta+b', '', 'Bold');
  21225. editor.addShortcut('meta+i', '', 'Italic');
  21226. editor.addShortcut('meta+u', '', 'Underline');
  21227. for (var i = 1; i <= 6; i++) {
  21228. editor.addShortcut('access+' + i, '', [
  21229. 'FormatBlock',
  21230. false,
  21231. 'h' + i
  21232. ]);
  21233. }
  21234. editor.addShortcut('access+7', '', [
  21235. 'FormatBlock',
  21236. false,
  21237. 'p'
  21238. ]);
  21239. editor.addShortcut('access+8', '', [
  21240. 'FormatBlock',
  21241. false,
  21242. 'div'
  21243. ]);
  21244. editor.addShortcut('access+9', '', [
  21245. 'FormatBlock',
  21246. false,
  21247. 'address'
  21248. ]);
  21249. };
  21250. var Formatter = function (editor) {
  21251. var formats = FormatRegistry(editor);
  21252. var formatChangeState = Cell(null);
  21253. setup$h(editor);
  21254. setup$k(editor);
  21255. return {
  21256. get: formats.get,
  21257. has: formats.has,
  21258. register: formats.register,
  21259. unregister: formats.unregister,
  21260. apply: function (name, vars, node) {
  21261. applyFormat(editor, name, vars, node);
  21262. },
  21263. remove: function (name, vars, node, similar) {
  21264. removeFormat(editor, name, vars, node, similar);
  21265. },
  21266. toggle: function (name, vars, node) {
  21267. toggleFormat(editor, name, vars, node);
  21268. },
  21269. match: function (name, vars, node, similar) {
  21270. return matchFormat(editor, name, vars, node, similar);
  21271. },
  21272. closest: function (names) {
  21273. return closestFormat(editor, names);
  21274. },
  21275. matchAll: function (names, vars) {
  21276. return matchAllFormats(editor, names, vars);
  21277. },
  21278. matchNode: function (node, name, vars, similar) {
  21279. return matchNodeFormat(editor, node, name, vars, similar);
  21280. },
  21281. canApply: function (name) {
  21282. return canApplyFormat(editor, name);
  21283. },
  21284. formatChanged: function (formats, callback, similar, vars) {
  21285. return formatChanged(editor, formatChangeState, formats, callback, similar, vars);
  21286. },
  21287. getCssText: curry(getCssText, editor)
  21288. };
  21289. };
  21290. var shouldIgnoreCommand = function (cmd) {
  21291. switch (cmd.toLowerCase()) {
  21292. case 'undo':
  21293. case 'redo':
  21294. case 'mcerepaint':
  21295. case 'mcefocus':
  21296. return true;
  21297. default:
  21298. return false;
  21299. }
  21300. };
  21301. var registerEvents = function (editor, undoManager, locks) {
  21302. var isFirstTypedCharacter = Cell(false);
  21303. var addNonTypingUndoLevel = function (e) {
  21304. setTyping(undoManager, false, locks);
  21305. undoManager.add({}, e);
  21306. };
  21307. editor.on('init', function () {
  21308. undoManager.add();
  21309. });
  21310. editor.on('BeforeExecCommand', function (e) {
  21311. var cmd = e.command;
  21312. if (!shouldIgnoreCommand(cmd)) {
  21313. endTyping(undoManager, locks);
  21314. undoManager.beforeChange();
  21315. }
  21316. });
  21317. editor.on('ExecCommand', function (e) {
  21318. var cmd = e.command;
  21319. if (!shouldIgnoreCommand(cmd)) {
  21320. addNonTypingUndoLevel(e);
  21321. }
  21322. });
  21323. editor.on('ObjectResizeStart cut', function () {
  21324. undoManager.beforeChange();
  21325. });
  21326. editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
  21327. editor.on('dragend', addNonTypingUndoLevel);
  21328. editor.on('keyup', function (e) {
  21329. var keyCode = e.keyCode;
  21330. if (e.isDefaultPrevented()) {
  21331. return;
  21332. }
  21333. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45 || e.ctrlKey) {
  21334. addNonTypingUndoLevel();
  21335. editor.nodeChanged();
  21336. }
  21337. if (keyCode === 46 || keyCode === 8) {
  21338. editor.nodeChanged();
  21339. }
  21340. if (isFirstTypedCharacter.get() && undoManager.typing && isEq$1(createFromEditor(editor), undoManager.data[0]) === false) {
  21341. if (editor.isDirty() === false) {
  21342. editor.setDirty(true);
  21343. editor.fire('change', {
  21344. level: undoManager.data[0],
  21345. lastLevel: null
  21346. });
  21347. }
  21348. editor.fire('TypingUndo');
  21349. isFirstTypedCharacter.set(false);
  21350. editor.nodeChanged();
  21351. }
  21352. });
  21353. editor.on('keydown', function (e) {
  21354. var keyCode = e.keyCode;
  21355. if (e.isDefaultPrevented()) {
  21356. return;
  21357. }
  21358. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45) {
  21359. if (undoManager.typing) {
  21360. addNonTypingUndoLevel(e);
  21361. }
  21362. return;
  21363. }
  21364. var modKey = e.ctrlKey && !e.altKey || e.metaKey;
  21365. if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !undoManager.typing && !modKey) {
  21366. undoManager.beforeChange();
  21367. setTyping(undoManager, true, locks);
  21368. undoManager.add({}, e);
  21369. isFirstTypedCharacter.set(true);
  21370. }
  21371. });
  21372. editor.on('mousedown', function (e) {
  21373. if (undoManager.typing) {
  21374. addNonTypingUndoLevel(e);
  21375. }
  21376. });
  21377. var isInsertReplacementText = function (event) {
  21378. return event.inputType === 'insertReplacementText';
  21379. };
  21380. var isInsertTextDataNull = function (event) {
  21381. return event.inputType === 'insertText' && event.data === null;
  21382. };
  21383. var isInsertFromPasteOrDrop = function (event) {
  21384. return event.inputType === 'insertFromPaste' || event.inputType === 'insertFromDrop';
  21385. };
  21386. editor.on('input', function (e) {
  21387. if (e.inputType && (isInsertReplacementText(e) || isInsertTextDataNull(e) || isInsertFromPasteOrDrop(e))) {
  21388. addNonTypingUndoLevel(e);
  21389. }
  21390. });
  21391. editor.on('AddUndo Undo Redo ClearUndos', function (e) {
  21392. if (!e.isDefaultPrevented()) {
  21393. editor.nodeChanged();
  21394. }
  21395. });
  21396. };
  21397. var addKeyboardShortcuts = function (editor) {
  21398. editor.addShortcut('meta+z', '', 'Undo');
  21399. editor.addShortcut('meta+y,meta+shift+z', '', 'Redo');
  21400. };
  21401. var UndoManager = function (editor) {
  21402. var beforeBookmark = value();
  21403. var locks = Cell(0);
  21404. var index = Cell(0);
  21405. var undoManager = {
  21406. data: [],
  21407. typing: false,
  21408. beforeChange: function () {
  21409. beforeChange(editor, locks, beforeBookmark);
  21410. },
  21411. add: function (level, event) {
  21412. return addUndoLevel(editor, undoManager, index, locks, beforeBookmark, level, event);
  21413. },
  21414. undo: function () {
  21415. return undo(editor, undoManager, locks, index);
  21416. },
  21417. redo: function () {
  21418. return redo(editor, index, undoManager.data);
  21419. },
  21420. clear: function () {
  21421. clear(editor, undoManager, index);
  21422. },
  21423. reset: function () {
  21424. reset(editor, undoManager);
  21425. },
  21426. hasUndo: function () {
  21427. return hasUndo(editor, undoManager, index);
  21428. },
  21429. hasRedo: function () {
  21430. return hasRedo(editor, undoManager, index);
  21431. },
  21432. transact: function (callback) {
  21433. return transact(editor, undoManager, locks, callback);
  21434. },
  21435. ignore: function (callback) {
  21436. ignore(editor, locks, callback);
  21437. },
  21438. extra: function (callback1, callback2) {
  21439. extra(editor, undoManager, index, callback1, callback2);
  21440. }
  21441. };
  21442. if (!isRtc(editor)) {
  21443. registerEvents(editor, undoManager, locks);
  21444. }
  21445. addKeyboardShortcuts(editor);
  21446. return undoManager;
  21447. };
  21448. var nonTypingKeycodes = [
  21449. 9,
  21450. 27,
  21451. VK.HOME,
  21452. VK.END,
  21453. 19,
  21454. 20,
  21455. 44,
  21456. 144,
  21457. 145,
  21458. 33,
  21459. 34,
  21460. 45,
  21461. 16,
  21462. 17,
  21463. 18,
  21464. 91,
  21465. 92,
  21466. 93,
  21467. VK.DOWN,
  21468. VK.UP,
  21469. VK.LEFT,
  21470. VK.RIGHT
  21471. ].concat(Env.browser.isFirefox() ? [224] : []);
  21472. var placeholderAttr = 'data-mce-placeholder';
  21473. var isKeyboardEvent = function (e) {
  21474. return e.type === 'keydown' || e.type === 'keyup';
  21475. };
  21476. var isDeleteEvent = function (e) {
  21477. var keyCode = e.keyCode;
  21478. return keyCode === VK.BACKSPACE || keyCode === VK.DELETE;
  21479. };
  21480. var isNonTypingKeyboardEvent = function (e) {
  21481. if (isKeyboardEvent(e)) {
  21482. var keyCode = e.keyCode;
  21483. return !isDeleteEvent(e) && (VK.metaKeyPressed(e) || e.altKey || keyCode >= 112 && keyCode <= 123 || contains$3(nonTypingKeycodes, keyCode));
  21484. } else {
  21485. return false;
  21486. }
  21487. };
  21488. var isTypingKeyboardEvent = function (e) {
  21489. return isKeyboardEvent(e) && !(isDeleteEvent(e) || e.type === 'keyup' && e.keyCode === 229);
  21490. };
  21491. var isVisuallyEmpty = function (dom, rootElm, forcedRootBlock) {
  21492. if (isEmpty$2(SugarElement.fromDom(rootElm), false)) {
  21493. var isForcedRootBlockFalse = forcedRootBlock === '';
  21494. var firstElement = rootElm.firstElementChild;
  21495. if (!firstElement) {
  21496. return true;
  21497. } else if (dom.getStyle(rootElm.firstElementChild, 'padding-left') || dom.getStyle(rootElm.firstElementChild, 'padding-right')) {
  21498. return false;
  21499. } else {
  21500. return isForcedRootBlockFalse ? !dom.isBlock(firstElement) : forcedRootBlock === firstElement.nodeName.toLowerCase();
  21501. }
  21502. } else {
  21503. return false;
  21504. }
  21505. };
  21506. var setup$g = function (editor) {
  21507. var dom = editor.dom;
  21508. var rootBlock = getForcedRootBlock(editor);
  21509. var placeholder = getPlaceholder(editor);
  21510. var updatePlaceholder = function (e, initial) {
  21511. if (isNonTypingKeyboardEvent(e)) {
  21512. return;
  21513. }
  21514. var body = editor.getBody();
  21515. var showPlaceholder = isTypingKeyboardEvent(e) ? false : isVisuallyEmpty(dom, body, rootBlock);
  21516. var isPlaceholderShown = dom.getAttrib(body, placeholderAttr) !== '';
  21517. if (isPlaceholderShown !== showPlaceholder || initial) {
  21518. dom.setAttrib(body, placeholderAttr, showPlaceholder ? placeholder : null);
  21519. dom.setAttrib(body, 'aria-placeholder', showPlaceholder ? placeholder : null);
  21520. firePlaceholderToggle(editor, showPlaceholder);
  21521. editor.on(showPlaceholder ? 'keydown' : 'keyup', updatePlaceholder);
  21522. editor.off(showPlaceholder ? 'keyup' : 'keydown', updatePlaceholder);
  21523. }
  21524. };
  21525. if (placeholder) {
  21526. editor.on('init', function (e) {
  21527. updatePlaceholder(e, true);
  21528. editor.on('change SetContent ExecCommand', updatePlaceholder);
  21529. editor.on('paste', function (e) {
  21530. return Delay.setEditorTimeout(editor, function () {
  21531. return updatePlaceholder(e);
  21532. });
  21533. });
  21534. });
  21535. }
  21536. };
  21537. var strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
  21538. var hasStrongRtl = function (text) {
  21539. return strongRtl.test(text);
  21540. };
  21541. var isInlineTarget = function (editor, elm) {
  21542. return is$2(SugarElement.fromDom(elm), getInlineBoundarySelector(editor));
  21543. };
  21544. var isRtl = function (element) {
  21545. return DOMUtils.DOM.getStyle(element, 'direction', true) === 'rtl' || hasStrongRtl(element.textContent);
  21546. };
  21547. var findInlineParents = function (isInlineTarget, rootNode, pos) {
  21548. return filter$4(DOMUtils.DOM.getParents(pos.container(), '*', rootNode), isInlineTarget);
  21549. };
  21550. var findRootInline = function (isInlineTarget, rootNode, pos) {
  21551. var parents = findInlineParents(isInlineTarget, rootNode, pos);
  21552. return Optional.from(parents[parents.length - 1]);
  21553. };
  21554. var hasSameParentBlock = function (rootNode, node1, node2) {
  21555. var block1 = getParentBlock$2(node1, rootNode);
  21556. var block2 = getParentBlock$2(node2, rootNode);
  21557. return block1 && block1 === block2;
  21558. };
  21559. var isAtZwsp = function (pos) {
  21560. return isBeforeInline(pos) || isAfterInline(pos);
  21561. };
  21562. var normalizePosition = function (forward, pos) {
  21563. if (!pos) {
  21564. return pos;
  21565. }
  21566. var container = pos.container(), offset = pos.offset();
  21567. if (forward) {
  21568. if (isCaretContainerInline(container)) {
  21569. if (isText$7(container.nextSibling)) {
  21570. return CaretPosition(container.nextSibling, 0);
  21571. } else {
  21572. return CaretPosition.after(container);
  21573. }
  21574. } else {
  21575. return isBeforeInline(pos) ? CaretPosition(container, offset + 1) : pos;
  21576. }
  21577. } else {
  21578. if (isCaretContainerInline(container)) {
  21579. if (isText$7(container.previousSibling)) {
  21580. return CaretPosition(container.previousSibling, container.previousSibling.data.length);
  21581. } else {
  21582. return CaretPosition.before(container);
  21583. }
  21584. } else {
  21585. return isAfterInline(pos) ? CaretPosition(container, offset - 1) : pos;
  21586. }
  21587. }
  21588. };
  21589. var normalizeForwards = curry(normalizePosition, true);
  21590. var normalizeBackwards = curry(normalizePosition, false);
  21591. var isBeforeRoot = function (rootNode) {
  21592. return function (elm) {
  21593. return eq(rootNode, SugarElement.fromDom(elm.dom.parentNode));
  21594. };
  21595. };
  21596. var isTextBlockOrListItem = function (element) {
  21597. return isTextBlock$2(element) || isListItem(element);
  21598. };
  21599. var getParentBlock$1 = function (rootNode, elm) {
  21600. if (contains$1(rootNode, elm)) {
  21601. return closest$3(elm, isTextBlockOrListItem, isBeforeRoot(rootNode));
  21602. } else {
  21603. return Optional.none();
  21604. }
  21605. };
  21606. var placeCaretInEmptyBody = function (editor) {
  21607. var body = editor.getBody();
  21608. var node = body.firstChild && editor.dom.isBlock(body.firstChild) ? body.firstChild : body;
  21609. editor.selection.setCursorLocation(node, 0);
  21610. };
  21611. var paddEmptyBody = function (editor) {
  21612. if (editor.dom.isEmpty(editor.getBody())) {
  21613. editor.setContent('');
  21614. placeCaretInEmptyBody(editor);
  21615. }
  21616. };
  21617. var willDeleteLastPositionInElement = function (forward, fromPos, elm) {
  21618. return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  21619. var normalizedFirstPos = normalizePosition(true, firstPos);
  21620. var normalizedLastPos = normalizePosition(false, lastPos);
  21621. var normalizedFromPos = normalizePosition(false, fromPos);
  21622. if (forward) {
  21623. return nextPosition(elm, normalizedFromPos).exists(function (nextPos) {
  21624. return nextPos.isEqual(normalizedLastPos) && fromPos.isEqual(normalizedFirstPos);
  21625. });
  21626. } else {
  21627. return prevPosition(elm, normalizedFromPos).exists(function (prevPos) {
  21628. return prevPos.isEqual(normalizedFirstPos) && fromPos.isEqual(normalizedLastPos);
  21629. });
  21630. }
  21631. }).getOr(true);
  21632. };
  21633. var blockPosition = function (block, position) {
  21634. return {
  21635. block: block,
  21636. position: position
  21637. };
  21638. };
  21639. var blockBoundary = function (from, to) {
  21640. return {
  21641. from: from,
  21642. to: to
  21643. };
  21644. };
  21645. var getBlockPosition = function (rootNode, pos) {
  21646. var rootElm = SugarElement.fromDom(rootNode);
  21647. var containerElm = SugarElement.fromDom(pos.container());
  21648. return getParentBlock$1(rootElm, containerElm).map(function (block) {
  21649. return blockPosition(block, pos);
  21650. });
  21651. };
  21652. var isDifferentBlocks = function (blockBoundary) {
  21653. return eq(blockBoundary.from.block, blockBoundary.to.block) === false;
  21654. };
  21655. var hasSameParent = function (blockBoundary) {
  21656. return parent(blockBoundary.from.block).bind(function (parent1) {
  21657. return parent(blockBoundary.to.block).filter(function (parent2) {
  21658. return eq(parent1, parent2);
  21659. });
  21660. }).isSome();
  21661. };
  21662. var isEditable$1 = function (blockBoundary) {
  21663. return isContentEditableFalse$b(blockBoundary.from.block.dom) === false && isContentEditableFalse$b(blockBoundary.to.block.dom) === false;
  21664. };
  21665. var skipLastBr = function (rootNode, forward, blockPosition) {
  21666. if (isBr$5(blockPosition.position.getNode()) && isEmpty$2(blockPosition.block) === false) {
  21667. return positionIn(false, blockPosition.block.dom).bind(function (lastPositionInBlock) {
  21668. if (lastPositionInBlock.isEqual(blockPosition.position)) {
  21669. return fromPosition(forward, rootNode, lastPositionInBlock).bind(function (to) {
  21670. return getBlockPosition(rootNode, to);
  21671. });
  21672. } else {
  21673. return Optional.some(blockPosition);
  21674. }
  21675. }).getOr(blockPosition);
  21676. } else {
  21677. return blockPosition;
  21678. }
  21679. };
  21680. var readFromRange = function (rootNode, forward, rng) {
  21681. var fromBlockPos = getBlockPosition(rootNode, CaretPosition.fromRangeStart(rng));
  21682. var toBlockPos = fromBlockPos.bind(function (blockPos) {
  21683. return fromPosition(forward, rootNode, blockPos.position).bind(function (to) {
  21684. return getBlockPosition(rootNode, to).map(function (blockPos) {
  21685. return skipLastBr(rootNode, forward, blockPos);
  21686. });
  21687. });
  21688. });
  21689. return lift2(fromBlockPos, toBlockPos, blockBoundary).filter(function (blockBoundary) {
  21690. return isDifferentBlocks(blockBoundary) && hasSameParent(blockBoundary) && isEditable$1(blockBoundary);
  21691. });
  21692. };
  21693. var read$1 = function (rootNode, forward, rng) {
  21694. return rng.collapsed ? readFromRange(rootNode, forward, rng) : Optional.none();
  21695. };
  21696. var getChildrenUntilBlockBoundary = function (block) {
  21697. var children$1 = children(block);
  21698. return findIndex$2(children$1, isBlock$2).fold(constant(children$1), function (index) {
  21699. return children$1.slice(0, index);
  21700. });
  21701. };
  21702. var extractChildren = function (block) {
  21703. var children = getChildrenUntilBlockBoundary(block);
  21704. each$k(children, remove$7);
  21705. return children;
  21706. };
  21707. var removeEmptyRoot = function (rootNode, block) {
  21708. var parents = parentsAndSelf(block, rootNode);
  21709. return find$3(parents.reverse(), function (element) {
  21710. return isEmpty$2(element);
  21711. }).each(remove$7);
  21712. };
  21713. var isEmptyBefore = function (el) {
  21714. return filter$4(prevSiblings(el), function (el) {
  21715. return !isEmpty$2(el);
  21716. }).length === 0;
  21717. };
  21718. var nestedBlockMerge = function (rootNode, fromBlock, toBlock, insertionPoint) {
  21719. if (isEmpty$2(toBlock)) {
  21720. fillWithPaddingBr(toBlock);
  21721. return firstPositionIn(toBlock.dom);
  21722. }
  21723. if (isEmptyBefore(insertionPoint) && isEmpty$2(fromBlock)) {
  21724. before$4(insertionPoint, SugarElement.fromTag('br'));
  21725. }
  21726. var position = prevPosition(toBlock.dom, CaretPosition.before(insertionPoint.dom));
  21727. each$k(extractChildren(fromBlock), function (child) {
  21728. before$4(insertionPoint, child);
  21729. });
  21730. removeEmptyRoot(rootNode, fromBlock);
  21731. return position;
  21732. };
  21733. var sidelongBlockMerge = function (rootNode, fromBlock, toBlock) {
  21734. if (isEmpty$2(toBlock)) {
  21735. remove$7(toBlock);
  21736. if (isEmpty$2(fromBlock)) {
  21737. fillWithPaddingBr(fromBlock);
  21738. }
  21739. return firstPositionIn(fromBlock.dom);
  21740. }
  21741. var position = lastPositionIn(toBlock.dom);
  21742. each$k(extractChildren(fromBlock), function (child) {
  21743. append$1(toBlock, child);
  21744. });
  21745. removeEmptyRoot(rootNode, fromBlock);
  21746. return position;
  21747. };
  21748. var findInsertionPoint = function (toBlock, block) {
  21749. var parentsAndSelf$1 = parentsAndSelf(block, toBlock);
  21750. return Optional.from(parentsAndSelf$1[parentsAndSelf$1.length - 1]);
  21751. };
  21752. var getInsertionPoint = function (fromBlock, toBlock) {
  21753. return contains$1(toBlock, fromBlock) ? findInsertionPoint(toBlock, fromBlock) : Optional.none();
  21754. };
  21755. var trimBr = function (first, block) {
  21756. positionIn(first, block.dom).map(function (position) {
  21757. return position.getNode();
  21758. }).map(SugarElement.fromDom).filter(isBr$4).each(remove$7);
  21759. };
  21760. var mergeBlockInto = function (rootNode, fromBlock, toBlock) {
  21761. trimBr(true, fromBlock);
  21762. trimBr(false, toBlock);
  21763. return getInsertionPoint(fromBlock, toBlock).fold(curry(sidelongBlockMerge, rootNode, fromBlock, toBlock), curry(nestedBlockMerge, rootNode, fromBlock, toBlock));
  21764. };
  21765. var mergeBlocks = function (rootNode, forward, block1, block2) {
  21766. return forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
  21767. };
  21768. var backspaceDelete$8 = function (editor, forward) {
  21769. var rootNode = SugarElement.fromDom(editor.getBody());
  21770. var position = read$1(rootNode.dom, forward, editor.selection.getRng()).bind(function (blockBoundary) {
  21771. return mergeBlocks(rootNode, forward, blockBoundary.from.block, blockBoundary.to.block);
  21772. });
  21773. position.each(function (pos) {
  21774. editor.selection.setRng(pos.toRange());
  21775. });
  21776. return position.isSome();
  21777. };
  21778. var deleteRangeMergeBlocks = function (rootNode, selection) {
  21779. var rng = selection.getRng();
  21780. return lift2(getParentBlock$1(rootNode, SugarElement.fromDom(rng.startContainer)), getParentBlock$1(rootNode, SugarElement.fromDom(rng.endContainer)), function (block1, block2) {
  21781. if (eq(block1, block2) === false) {
  21782. rng.deleteContents();
  21783. mergeBlocks(rootNode, true, block1, block2).each(function (pos) {
  21784. selection.setRng(pos.toRange());
  21785. });
  21786. return true;
  21787. } else {
  21788. return false;
  21789. }
  21790. }).getOr(false);
  21791. };
  21792. var isRawNodeInTable = function (root, rawNode) {
  21793. var node = SugarElement.fromDom(rawNode);
  21794. var isRoot = curry(eq, root);
  21795. return ancestor$3(node, isTableCell$4, isRoot).isSome();
  21796. };
  21797. var isSelectionInTable = function (root, rng) {
  21798. return isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
  21799. };
  21800. var isEverythingSelected = function (root, rng) {
  21801. var noPrevious = prevPosition(root.dom, CaretPosition.fromRangeStart(rng)).isNone();
  21802. var noNext = nextPosition(root.dom, CaretPosition.fromRangeEnd(rng)).isNone();
  21803. return !isSelectionInTable(root, rng) && noPrevious && noNext;
  21804. };
  21805. var emptyEditor = function (editor) {
  21806. editor.setContent('');
  21807. editor.selection.setCursorLocation();
  21808. return true;
  21809. };
  21810. var deleteRange$1 = function (editor) {
  21811. var rootNode = SugarElement.fromDom(editor.getBody());
  21812. var rng = editor.selection.getRng();
  21813. return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
  21814. };
  21815. var backspaceDelete$7 = function (editor, _forward) {
  21816. return editor.selection.isCollapsed() ? false : deleteRange$1(editor);
  21817. };
  21818. var isContentEditableTrue$2 = isContentEditableTrue$4;
  21819. var isContentEditableFalse$4 = isContentEditableFalse$b;
  21820. var showCaret = function (direction, editor, node, before, scrollIntoView) {
  21821. return Optional.from(editor._selectionOverrides.showCaret(direction, node, before, scrollIntoView));
  21822. };
  21823. var getNodeRange = function (node) {
  21824. var rng = node.ownerDocument.createRange();
  21825. rng.selectNode(node);
  21826. return rng;
  21827. };
  21828. var selectNode = function (editor, node) {
  21829. var e = editor.fire('BeforeObjectSelected', { target: node });
  21830. if (e.isDefaultPrevented()) {
  21831. return Optional.none();
  21832. }
  21833. return Optional.some(getNodeRange(node));
  21834. };
  21835. var renderCaretAtRange = function (editor, range, scrollIntoView) {
  21836. var normalizedRange = normalizeRange(1, editor.getBody(), range);
  21837. var caretPosition = CaretPosition.fromRangeStart(normalizedRange);
  21838. var caretPositionNode = caretPosition.getNode();
  21839. if (isInlineFakeCaretTarget(caretPositionNode)) {
  21840. return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
  21841. }
  21842. var caretPositionBeforeNode = caretPosition.getNode(true);
  21843. if (isInlineFakeCaretTarget(caretPositionBeforeNode)) {
  21844. return showCaret(1, editor, caretPositionBeforeNode, false, false);
  21845. }
  21846. var ceRoot = editor.dom.getParent(caretPosition.getNode(), function (node) {
  21847. return isContentEditableFalse$4(node) || isContentEditableTrue$2(node);
  21848. });
  21849. if (isInlineFakeCaretTarget(ceRoot)) {
  21850. return showCaret(1, editor, ceRoot, false, scrollIntoView);
  21851. }
  21852. return Optional.none();
  21853. };
  21854. var renderRangeCaret = function (editor, range, scrollIntoView) {
  21855. return range.collapsed ? renderCaretAtRange(editor, range, scrollIntoView).getOr(range) : range;
  21856. };
  21857. var isBeforeBoundary = function (pos) {
  21858. return isBeforeContentEditableFalse(pos) || isBeforeMedia(pos);
  21859. };
  21860. var isAfterBoundary = function (pos) {
  21861. return isAfterContentEditableFalse(pos) || isAfterMedia(pos);
  21862. };
  21863. var trimEmptyTextNode = function (dom, node) {
  21864. if (isText$7(node) && node.data.length === 0) {
  21865. dom.remove(node);
  21866. }
  21867. };
  21868. var deleteContentAndShowCaret = function (editor, range, node, direction, forward, peekCaretPosition) {
  21869. showCaret(direction, editor, peekCaretPosition.getNode(!forward), forward, true).each(function (caretRange) {
  21870. if (range.collapsed) {
  21871. var deleteRange = range.cloneRange();
  21872. if (forward) {
  21873. deleteRange.setEnd(caretRange.startContainer, caretRange.startOffset);
  21874. } else {
  21875. deleteRange.setStart(caretRange.endContainer, caretRange.endOffset);
  21876. }
  21877. deleteRange.deleteContents();
  21878. } else {
  21879. range.deleteContents();
  21880. }
  21881. editor.selection.setRng(caretRange);
  21882. });
  21883. trimEmptyTextNode(editor.dom, node);
  21884. return true;
  21885. };
  21886. var deleteBoundaryText = function (editor, forward) {
  21887. var range = editor.selection.getRng();
  21888. if (!isText$7(range.commonAncestorContainer)) {
  21889. return false;
  21890. }
  21891. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  21892. var caretWalker = CaretWalker(editor.getBody());
  21893. var getNextPosFn = curry(getVisualCaretPosition, forward ? caretWalker.next : caretWalker.prev);
  21894. var isBeforeFn = forward ? isBeforeBoundary : isAfterBoundary;
  21895. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  21896. var nextCaretPosition = normalizePosition(forward, getNextPosFn(caretPosition));
  21897. if (!nextCaretPosition || !isMoveInsideSameBlock(caretPosition, nextCaretPosition)) {
  21898. return false;
  21899. } else if (isBeforeFn(nextCaretPosition)) {
  21900. return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, nextCaretPosition);
  21901. }
  21902. var peekCaretPosition = getNextPosFn(nextCaretPosition);
  21903. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  21904. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  21905. return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, peekCaretPosition);
  21906. }
  21907. }
  21908. return false;
  21909. };
  21910. var backspaceDelete$6 = function (editor, forward) {
  21911. return deleteBoundaryText(editor, forward);
  21912. };
  21913. var isCompoundElement = function (node) {
  21914. return isTableCell$4(SugarElement.fromDom(node)) || isListItem(SugarElement.fromDom(node));
  21915. };
  21916. var DeleteAction = Adt.generate([
  21917. { remove: ['element'] },
  21918. { moveToElement: ['element'] },
  21919. { moveToPosition: ['position'] }
  21920. ]);
  21921. var isAtContentEditableBlockCaret = function (forward, from) {
  21922. var elm = from.getNode(forward === false);
  21923. var caretLocation = forward ? 'after' : 'before';
  21924. return isElement$5(elm) && elm.getAttribute('data-mce-caret') === caretLocation;
  21925. };
  21926. var isDeleteFromCefDifferentBlocks = function (root, forward, from, to) {
  21927. var inSameBlock = function (elm) {
  21928. return isInline$1(SugarElement.fromDom(elm)) && !isInSameBlock(from, to, root);
  21929. };
  21930. return getRelativeCefElm(!forward, from).fold(function () {
  21931. return getRelativeCefElm(forward, to).fold(never, inSameBlock);
  21932. }, inSameBlock);
  21933. };
  21934. var deleteEmptyBlockOrMoveToCef = function (root, forward, from, to) {
  21935. var toCefElm = to.getNode(forward === false);
  21936. return getParentBlock$1(SugarElement.fromDom(root), SugarElement.fromDom(from.getNode())).map(function (blockElm) {
  21937. return isEmpty$2(blockElm) ? DeleteAction.remove(blockElm.dom) : DeleteAction.moveToElement(toCefElm);
  21938. }).orThunk(function () {
  21939. return Optional.some(DeleteAction.moveToElement(toCefElm));
  21940. });
  21941. };
  21942. var findCefPosition = function (root, forward, from) {
  21943. return fromPosition(forward, root, from).bind(function (to) {
  21944. if (isCompoundElement(to.getNode())) {
  21945. return Optional.none();
  21946. } else if (isDeleteFromCefDifferentBlocks(root, forward, from, to)) {
  21947. return Optional.none();
  21948. } else if (forward && isContentEditableFalse$b(to.getNode())) {
  21949. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  21950. } else if (forward === false && isContentEditableFalse$b(to.getNode(true))) {
  21951. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  21952. } else if (forward && isAfterContentEditableFalse(from)) {
  21953. return Optional.some(DeleteAction.moveToPosition(to));
  21954. } else if (forward === false && isBeforeContentEditableFalse(from)) {
  21955. return Optional.some(DeleteAction.moveToPosition(to));
  21956. } else {
  21957. return Optional.none();
  21958. }
  21959. });
  21960. };
  21961. var getContentEditableBlockAction = function (forward, elm) {
  21962. if (forward && isContentEditableFalse$b(elm.nextSibling)) {
  21963. return Optional.some(DeleteAction.moveToElement(elm.nextSibling));
  21964. } else if (forward === false && isContentEditableFalse$b(elm.previousSibling)) {
  21965. return Optional.some(DeleteAction.moveToElement(elm.previousSibling));
  21966. } else {
  21967. return Optional.none();
  21968. }
  21969. };
  21970. var skipMoveToActionFromInlineCefToContent = function (root, from, deleteAction) {
  21971. return deleteAction.fold(function (elm) {
  21972. return Optional.some(DeleteAction.remove(elm));
  21973. }, function (elm) {
  21974. return Optional.some(DeleteAction.moveToElement(elm));
  21975. }, function (to) {
  21976. if (isInSameBlock(from, to, root)) {
  21977. return Optional.none();
  21978. } else {
  21979. return Optional.some(DeleteAction.moveToPosition(to));
  21980. }
  21981. });
  21982. };
  21983. var getContentEditableAction = function (root, forward, from) {
  21984. if (isAtContentEditableBlockCaret(forward, from)) {
  21985. return getContentEditableBlockAction(forward, from.getNode(forward === false)).fold(function () {
  21986. return findCefPosition(root, forward, from);
  21987. }, Optional.some);
  21988. } else {
  21989. return findCefPosition(root, forward, from).bind(function (deleteAction) {
  21990. return skipMoveToActionFromInlineCefToContent(root, from, deleteAction);
  21991. });
  21992. }
  21993. };
  21994. var read = function (root, forward, rng) {
  21995. var normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
  21996. var from = CaretPosition.fromRangeStart(normalizedRange);
  21997. var rootElement = SugarElement.fromDom(root);
  21998. if (forward === false && isAfterContentEditableFalse(from)) {
  21999. return Optional.some(DeleteAction.remove(from.getNode(true)));
  22000. } else if (forward && isBeforeContentEditableFalse(from)) {
  22001. return Optional.some(DeleteAction.remove(from.getNode()));
  22002. } else if (forward === false && isBeforeContentEditableFalse(from) && isAfterBr(rootElement, from)) {
  22003. return findPreviousBr(rootElement, from).map(function (br) {
  22004. return DeleteAction.remove(br.getNode());
  22005. });
  22006. } else if (forward && isAfterContentEditableFalse(from) && isBeforeBr$1(rootElement, from)) {
  22007. return findNextBr(rootElement, from).map(function (br) {
  22008. return DeleteAction.remove(br.getNode());
  22009. });
  22010. } else {
  22011. return getContentEditableAction(root, forward, from);
  22012. }
  22013. };
  22014. var deleteElement$1 = function (editor, forward) {
  22015. return function (element) {
  22016. editor._selectionOverrides.hideFakeCaret();
  22017. deleteElement$2(editor, forward, SugarElement.fromDom(element));
  22018. return true;
  22019. };
  22020. };
  22021. var moveToElement = function (editor, forward) {
  22022. return function (element) {
  22023. var pos = forward ? CaretPosition.before(element) : CaretPosition.after(element);
  22024. editor.selection.setRng(pos.toRange());
  22025. return true;
  22026. };
  22027. };
  22028. var moveToPosition = function (editor) {
  22029. return function (pos) {
  22030. editor.selection.setRng(pos.toRange());
  22031. return true;
  22032. };
  22033. };
  22034. var getAncestorCe = function (editor, node) {
  22035. return Optional.from(getContentEditableRoot$1(editor.getBody(), node));
  22036. };
  22037. var backspaceDeleteCaret = function (editor, forward) {
  22038. var selectedNode = editor.selection.getNode();
  22039. return getAncestorCe(editor, selectedNode).filter(isContentEditableFalse$b).fold(function () {
  22040. return read(editor.getBody(), forward, editor.selection.getRng()).exists(function (deleteAction) {
  22041. return deleteAction.fold(deleteElement$1(editor, forward), moveToElement(editor, forward), moveToPosition(editor));
  22042. });
  22043. }, always);
  22044. };
  22045. var deleteOffscreenSelection = function (rootElement) {
  22046. each$k(descendants(rootElement, '.mce-offscreen-selection'), remove$7);
  22047. };
  22048. var backspaceDeleteRange = function (editor, forward) {
  22049. var selectedNode = editor.selection.getNode();
  22050. if (isContentEditableFalse$b(selectedNode) && !isTableCell$5(selectedNode)) {
  22051. var hasCefAncestor = getAncestorCe(editor, selectedNode.parentNode).filter(isContentEditableFalse$b);
  22052. return hasCefAncestor.fold(function () {
  22053. deleteOffscreenSelection(SugarElement.fromDom(editor.getBody()));
  22054. deleteElement$2(editor, forward, SugarElement.fromDom(editor.selection.getNode()));
  22055. paddEmptyBody(editor);
  22056. return true;
  22057. }, always);
  22058. }
  22059. return false;
  22060. };
  22061. var paddEmptyElement = function (editor) {
  22062. var dom = editor.dom, selection = editor.selection;
  22063. var ceRoot = getContentEditableRoot$1(editor.getBody(), selection.getNode());
  22064. if (isContentEditableTrue$4(ceRoot) && dom.isBlock(ceRoot) && dom.isEmpty(ceRoot)) {
  22065. var br = dom.create('br', { 'data-mce-bogus': '1' });
  22066. dom.setHTML(ceRoot, '');
  22067. ceRoot.appendChild(br);
  22068. selection.setRng(CaretPosition.before(br).toRange());
  22069. }
  22070. return true;
  22071. };
  22072. var backspaceDelete$5 = function (editor, forward) {
  22073. if (editor.selection.isCollapsed()) {
  22074. return backspaceDeleteCaret(editor, forward);
  22075. } else {
  22076. return backspaceDeleteRange(editor, forward);
  22077. }
  22078. };
  22079. var deleteCaret$2 = function (editor, forward) {
  22080. var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22081. return fromPosition(forward, editor.getBody(), fromPos).filter(function (pos) {
  22082. return forward ? isBeforeImageBlock(pos) : isAfterImageBlock(pos);
  22083. }).bind(function (pos) {
  22084. return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, pos));
  22085. }).exists(function (elm) {
  22086. editor.selection.select(elm);
  22087. return true;
  22088. });
  22089. };
  22090. var backspaceDelete$4 = function (editor, forward) {
  22091. return editor.selection.isCollapsed() ? deleteCaret$2(editor, forward) : false;
  22092. };
  22093. var isText = isText$7;
  22094. var startsWithCaretContainer = function (node) {
  22095. return isText(node) && node.data[0] === ZWSP$1;
  22096. };
  22097. var endsWithCaretContainer = function (node) {
  22098. return isText(node) && node.data[node.data.length - 1] === ZWSP$1;
  22099. };
  22100. var createZwsp = function (node) {
  22101. return node.ownerDocument.createTextNode(ZWSP$1);
  22102. };
  22103. var insertBefore = function (node) {
  22104. if (isText(node.previousSibling)) {
  22105. if (endsWithCaretContainer(node.previousSibling)) {
  22106. return node.previousSibling;
  22107. } else {
  22108. node.previousSibling.appendData(ZWSP$1);
  22109. return node.previousSibling;
  22110. }
  22111. } else if (isText(node)) {
  22112. if (startsWithCaretContainer(node)) {
  22113. return node;
  22114. } else {
  22115. node.insertData(0, ZWSP$1);
  22116. return node;
  22117. }
  22118. } else {
  22119. var newNode = createZwsp(node);
  22120. node.parentNode.insertBefore(newNode, node);
  22121. return newNode;
  22122. }
  22123. };
  22124. var insertAfter = function (node) {
  22125. if (isText(node.nextSibling)) {
  22126. if (startsWithCaretContainer(node.nextSibling)) {
  22127. return node.nextSibling;
  22128. } else {
  22129. node.nextSibling.insertData(0, ZWSP$1);
  22130. return node.nextSibling;
  22131. }
  22132. } else if (isText(node)) {
  22133. if (endsWithCaretContainer(node)) {
  22134. return node;
  22135. } else {
  22136. node.appendData(ZWSP$1);
  22137. return node;
  22138. }
  22139. } else {
  22140. var newNode = createZwsp(node);
  22141. if (node.nextSibling) {
  22142. node.parentNode.insertBefore(newNode, node.nextSibling);
  22143. } else {
  22144. node.parentNode.appendChild(newNode);
  22145. }
  22146. return newNode;
  22147. }
  22148. };
  22149. var insertInline = function (before, node) {
  22150. return before ? insertBefore(node) : insertAfter(node);
  22151. };
  22152. var insertInlineBefore = curry(insertInline, true);
  22153. var insertInlineAfter = curry(insertInline, false);
  22154. var insertInlinePos = function (pos, before) {
  22155. if (isText$7(pos.container())) {
  22156. return insertInline(before, pos.container());
  22157. } else {
  22158. return insertInline(before, pos.getNode());
  22159. }
  22160. };
  22161. var isPosCaretContainer = function (pos, caret) {
  22162. var caretNode = caret.get();
  22163. return caretNode && pos.container() === caretNode && isCaretContainerInline(caretNode);
  22164. };
  22165. var renderCaret = function (caret, location) {
  22166. return location.fold(function (element) {
  22167. remove$2(caret.get());
  22168. var text = insertInlineBefore(element);
  22169. caret.set(text);
  22170. return Optional.some(CaretPosition(text, text.length - 1));
  22171. }, function (element) {
  22172. return firstPositionIn(element).map(function (pos) {
  22173. if (!isPosCaretContainer(pos, caret)) {
  22174. remove$2(caret.get());
  22175. var text = insertInlinePos(pos, true);
  22176. caret.set(text);
  22177. return CaretPosition(text, 1);
  22178. } else {
  22179. return CaretPosition(caret.get(), 1);
  22180. }
  22181. });
  22182. }, function (element) {
  22183. return lastPositionIn(element).map(function (pos) {
  22184. if (!isPosCaretContainer(pos, caret)) {
  22185. remove$2(caret.get());
  22186. var text = insertInlinePos(pos, false);
  22187. caret.set(text);
  22188. return CaretPosition(text, text.length - 1);
  22189. } else {
  22190. return CaretPosition(caret.get(), caret.get().length - 1);
  22191. }
  22192. });
  22193. }, function (element) {
  22194. remove$2(caret.get());
  22195. var text = insertInlineAfter(element);
  22196. caret.set(text);
  22197. return Optional.some(CaretPosition(text, 1));
  22198. });
  22199. };
  22200. var evaluateUntil = function (fns, args) {
  22201. for (var i = 0; i < fns.length; i++) {
  22202. var result = fns[i].apply(null, args);
  22203. if (result.isSome()) {
  22204. return result;
  22205. }
  22206. }
  22207. return Optional.none();
  22208. };
  22209. var Location = Adt.generate([
  22210. { before: ['element'] },
  22211. { start: ['element'] },
  22212. { end: ['element'] },
  22213. { after: ['element'] }
  22214. ]);
  22215. var rescope$1 = function (rootNode, node) {
  22216. var parentBlock = getParentBlock$2(node, rootNode);
  22217. return parentBlock ? parentBlock : rootNode;
  22218. };
  22219. var before = function (isInlineTarget, rootNode, pos) {
  22220. var nPos = normalizeForwards(pos);
  22221. var scope = rescope$1(rootNode, nPos.container());
  22222. return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  22223. return nextPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  22224. return Location.before(inline);
  22225. });
  22226. }, Optional.none);
  22227. };
  22228. var isNotInsideFormatCaretContainer = function (rootNode, elm) {
  22229. return getParentCaretContainer(rootNode, elm) === null;
  22230. };
  22231. var findInsideRootInline = function (isInlineTarget, rootNode, pos) {
  22232. return findRootInline(isInlineTarget, rootNode, pos).filter(curry(isNotInsideFormatCaretContainer, rootNode));
  22233. };
  22234. var start$1 = function (isInlineTarget, rootNode, pos) {
  22235. var nPos = normalizeBackwards(pos);
  22236. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  22237. var prevPos = prevPosition(inline, nPos);
  22238. return prevPos.isNone() ? Optional.some(Location.start(inline)) : Optional.none();
  22239. });
  22240. };
  22241. var end = function (isInlineTarget, rootNode, pos) {
  22242. var nPos = normalizeForwards(pos);
  22243. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  22244. var nextPos = nextPosition(inline, nPos);
  22245. return nextPos.isNone() ? Optional.some(Location.end(inline)) : Optional.none();
  22246. });
  22247. };
  22248. var after = function (isInlineTarget, rootNode, pos) {
  22249. var nPos = normalizeBackwards(pos);
  22250. var scope = rescope$1(rootNode, nPos.container());
  22251. return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  22252. return prevPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  22253. return Location.after(inline);
  22254. });
  22255. }, Optional.none);
  22256. };
  22257. var isValidLocation = function (location) {
  22258. return isRtl(getElement(location)) === false;
  22259. };
  22260. var readLocation = function (isInlineTarget, rootNode, pos) {
  22261. var location = evaluateUntil([
  22262. before,
  22263. start$1,
  22264. end,
  22265. after
  22266. ], [
  22267. isInlineTarget,
  22268. rootNode,
  22269. pos
  22270. ]);
  22271. return location.filter(isValidLocation);
  22272. };
  22273. var getElement = function (location) {
  22274. return location.fold(identity, identity, identity, identity);
  22275. };
  22276. var getName = function (location) {
  22277. return location.fold(constant('before'), constant('start'), constant('end'), constant('after'));
  22278. };
  22279. var outside = function (location) {
  22280. return location.fold(Location.before, Location.before, Location.after, Location.after);
  22281. };
  22282. var inside = function (location) {
  22283. return location.fold(Location.start, Location.start, Location.end, Location.end);
  22284. };
  22285. var isEq = function (location1, location2) {
  22286. return getName(location1) === getName(location2) && getElement(location1) === getElement(location2);
  22287. };
  22288. var betweenInlines = function (forward, isInlineTarget, rootNode, from, to, location) {
  22289. return lift2(findRootInline(isInlineTarget, rootNode, from), findRootInline(isInlineTarget, rootNode, to), function (fromInline, toInline) {
  22290. if (fromInline !== toInline && hasSameParentBlock(rootNode, fromInline, toInline)) {
  22291. return Location.after(forward ? fromInline : toInline);
  22292. } else {
  22293. return location;
  22294. }
  22295. }).getOr(location);
  22296. };
  22297. var skipNoMovement = function (fromLocation, toLocation) {
  22298. return fromLocation.fold(always, function (fromLocation) {
  22299. return !isEq(fromLocation, toLocation);
  22300. });
  22301. };
  22302. var findLocationTraverse = function (forward, isInlineTarget, rootNode, fromLocation, pos) {
  22303. var from = normalizePosition(forward, pos);
  22304. var to = fromPosition(forward, rootNode, from).map(curry(normalizePosition, forward));
  22305. var location = to.fold(function () {
  22306. return fromLocation.map(outside);
  22307. }, function (to) {
  22308. return readLocation(isInlineTarget, rootNode, to).map(curry(betweenInlines, forward, isInlineTarget, rootNode, from, to)).filter(curry(skipNoMovement, fromLocation));
  22309. });
  22310. return location.filter(isValidLocation);
  22311. };
  22312. var findLocationSimple = function (forward, location) {
  22313. if (forward) {
  22314. return location.fold(compose(Optional.some, Location.start), Optional.none, compose(Optional.some, Location.after), Optional.none);
  22315. } else {
  22316. return location.fold(Optional.none, compose(Optional.some, Location.before), Optional.none, compose(Optional.some, Location.end));
  22317. }
  22318. };
  22319. var findLocation$1 = function (forward, isInlineTarget, rootNode, pos) {
  22320. var from = normalizePosition(forward, pos);
  22321. var fromLocation = readLocation(isInlineTarget, rootNode, from);
  22322. return readLocation(isInlineTarget, rootNode, from).bind(curry(findLocationSimple, forward)).orThunk(function () {
  22323. return findLocationTraverse(forward, isInlineTarget, rootNode, fromLocation, pos);
  22324. });
  22325. };
  22326. curry(findLocation$1, false);
  22327. curry(findLocation$1, true);
  22328. var hasSelectionModifyApi = function (editor) {
  22329. return isFunction(editor.selection.getSel().modify);
  22330. };
  22331. var moveRel = function (forward, selection, pos) {
  22332. var delta = forward ? 1 : -1;
  22333. selection.setRng(CaretPosition(pos.container(), pos.offset() + delta).toRange());
  22334. selection.getSel().modify('move', forward ? 'forward' : 'backward', 'word');
  22335. return true;
  22336. };
  22337. var moveByWord = function (forward, editor) {
  22338. var rng = editor.selection.getRng();
  22339. var pos = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  22340. if (!hasSelectionModifyApi(editor)) {
  22341. return false;
  22342. } else if (forward && isBeforeInline(pos)) {
  22343. return moveRel(true, editor.selection, pos);
  22344. } else if (!forward && isAfterInline(pos)) {
  22345. return moveRel(false, editor.selection, pos);
  22346. } else {
  22347. return false;
  22348. }
  22349. };
  22350. var BreakType;
  22351. (function (BreakType) {
  22352. BreakType[BreakType['Br'] = 0] = 'Br';
  22353. BreakType[BreakType['Block'] = 1] = 'Block';
  22354. BreakType[BreakType['Wrap'] = 2] = 'Wrap';
  22355. BreakType[BreakType['Eol'] = 3] = 'Eol';
  22356. }(BreakType || (BreakType = {})));
  22357. var flip = function (direction, positions) {
  22358. return direction === HDirection.Backwards ? reverse(positions) : positions;
  22359. };
  22360. var walk = function (direction, caretWalker, pos) {
  22361. return direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
  22362. };
  22363. var getBreakType = function (scope, direction, currentPos, nextPos) {
  22364. if (isBr$5(nextPos.getNode(direction === HDirection.Forwards))) {
  22365. return BreakType.Br;
  22366. } else if (isInSameBlock(currentPos, nextPos) === false) {
  22367. return BreakType.Block;
  22368. } else {
  22369. return BreakType.Wrap;
  22370. }
  22371. };
  22372. var getPositionsUntil = function (predicate, direction, scope, start) {
  22373. var caretWalker = CaretWalker(scope);
  22374. var currentPos = start;
  22375. var positions = [];
  22376. while (currentPos) {
  22377. var nextPos = walk(direction, caretWalker, currentPos);
  22378. if (!nextPos) {
  22379. break;
  22380. }
  22381. if (isBr$5(nextPos.getNode(false))) {
  22382. if (direction === HDirection.Forwards) {
  22383. return {
  22384. positions: flip(direction, positions).concat([nextPos]),
  22385. breakType: BreakType.Br,
  22386. breakAt: Optional.some(nextPos)
  22387. };
  22388. } else {
  22389. return {
  22390. positions: flip(direction, positions),
  22391. breakType: BreakType.Br,
  22392. breakAt: Optional.some(nextPos)
  22393. };
  22394. }
  22395. }
  22396. if (!nextPos.isVisible()) {
  22397. currentPos = nextPos;
  22398. continue;
  22399. }
  22400. if (predicate(currentPos, nextPos)) {
  22401. var breakType = getBreakType(scope, direction, currentPos, nextPos);
  22402. return {
  22403. positions: flip(direction, positions),
  22404. breakType: breakType,
  22405. breakAt: Optional.some(nextPos)
  22406. };
  22407. }
  22408. positions.push(nextPos);
  22409. currentPos = nextPos;
  22410. }
  22411. return {
  22412. positions: flip(direction, positions),
  22413. breakType: BreakType.Eol,
  22414. breakAt: Optional.none()
  22415. };
  22416. };
  22417. var getAdjacentLinePositions = function (direction, getPositionsUntilBreak, scope, start) {
  22418. return getPositionsUntilBreak(scope, start).breakAt.map(function (pos) {
  22419. var positions = getPositionsUntilBreak(scope, pos).positions;
  22420. return direction === HDirection.Backwards ? positions.concat(pos) : [pos].concat(positions);
  22421. }).getOr([]);
  22422. };
  22423. var findClosestHorizontalPositionFromPoint = function (positions, x) {
  22424. return foldl(positions, function (acc, newPos) {
  22425. return acc.fold(function () {
  22426. return Optional.some(newPos);
  22427. }, function (lastPos) {
  22428. return lift2(head(lastPos.getClientRects()), head(newPos.getClientRects()), function (lastRect, newRect) {
  22429. var lastDist = Math.abs(x - lastRect.left);
  22430. var newDist = Math.abs(x - newRect.left);
  22431. return newDist <= lastDist ? newPos : lastPos;
  22432. }).or(acc);
  22433. });
  22434. }, Optional.none());
  22435. };
  22436. var findClosestHorizontalPosition = function (positions, pos) {
  22437. return head(pos.getClientRects()).bind(function (targetRect) {
  22438. return findClosestHorizontalPositionFromPoint(positions, targetRect.left);
  22439. });
  22440. };
  22441. var getPositionsUntilPreviousLine = curry(getPositionsUntil, CaretPosition.isAbove, -1);
  22442. var getPositionsUntilNextLine = curry(getPositionsUntil, CaretPosition.isBelow, 1);
  22443. var getPositionsAbove = curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
  22444. var getPositionsBelow = curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
  22445. var isAtFirstLine = function (scope, pos) {
  22446. return getPositionsUntilPreviousLine(scope, pos).breakAt.isNone();
  22447. };
  22448. var isAtLastLine = function (scope, pos) {
  22449. return getPositionsUntilNextLine(scope, pos).breakAt.isNone();
  22450. };
  22451. var getFirstLinePositions = function (scope) {
  22452. return firstPositionIn(scope).map(function (pos) {
  22453. return [pos].concat(getPositionsUntilNextLine(scope, pos).positions);
  22454. }).getOr([]);
  22455. };
  22456. var getLastLinePositions = function (scope) {
  22457. return lastPositionIn(scope).map(function (pos) {
  22458. return getPositionsUntilPreviousLine(scope, pos).positions.concat(pos);
  22459. }).getOr([]);
  22460. };
  22461. var getNodeClientRects = function (node) {
  22462. var toArrayWithNode = function (clientRects) {
  22463. return map$3(clientRects, function (rect) {
  22464. var clientRect = clone(rect);
  22465. clientRect.node = node;
  22466. return clientRect;
  22467. });
  22468. };
  22469. if (isElement$5(node)) {
  22470. return toArrayWithNode(node.getClientRects());
  22471. }
  22472. if (isText$7(node)) {
  22473. var rng = node.ownerDocument.createRange();
  22474. rng.setStart(node, 0);
  22475. rng.setEnd(node, node.data.length);
  22476. return toArrayWithNode(rng.getClientRects());
  22477. }
  22478. };
  22479. var getClientRects = function (nodes) {
  22480. return bind(nodes, getNodeClientRects);
  22481. };
  22482. var VDirection;
  22483. (function (VDirection) {
  22484. VDirection[VDirection['Up'] = -1] = 'Up';
  22485. VDirection[VDirection['Down'] = 1] = 'Down';
  22486. }(VDirection || (VDirection = {})));
  22487. var findUntil = function (direction, root, predicateFn, node) {
  22488. while (node = findNode$1(node, direction, isEditableCaretCandidate$1, root)) {
  22489. if (predicateFn(node)) {
  22490. return;
  22491. }
  22492. }
  22493. };
  22494. var walkUntil$1 = function (direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) {
  22495. var line = 0;
  22496. var result = [];
  22497. var add = function (node) {
  22498. var clientRects = getClientRects([node]);
  22499. if (direction === -1) {
  22500. clientRects = clientRects.reverse();
  22501. }
  22502. for (var i = 0; i < clientRects.length; i++) {
  22503. var clientRect = clientRects[i];
  22504. if (isBeflowFn(clientRect, targetClientRect)) {
  22505. continue;
  22506. }
  22507. if (result.length > 0 && isAboveFn(clientRect, last$1(result))) {
  22508. line++;
  22509. }
  22510. clientRect.line = line;
  22511. if (predicateFn(clientRect)) {
  22512. return true;
  22513. }
  22514. result.push(clientRect);
  22515. }
  22516. };
  22517. var targetClientRect = last$1(caretPosition.getClientRects());
  22518. if (!targetClientRect) {
  22519. return result;
  22520. }
  22521. var node = caretPosition.getNode();
  22522. add(node);
  22523. findUntil(direction, root, add, node);
  22524. return result;
  22525. };
  22526. var aboveLineNumber = function (lineNumber, clientRect) {
  22527. return clientRect.line > lineNumber;
  22528. };
  22529. var isLineNumber = function (lineNumber, clientRect) {
  22530. return clientRect.line === lineNumber;
  22531. };
  22532. var upUntil = curry(walkUntil$1, VDirection.Up, isAbove$1, isBelow$1);
  22533. var downUntil = curry(walkUntil$1, VDirection.Down, isBelow$1, isAbove$1);
  22534. var positionsUntil = function (direction, root, predicateFn, node) {
  22535. var caretWalker = CaretWalker(root);
  22536. var walkFn;
  22537. var isBelowFn;
  22538. var isAboveFn;
  22539. var caretPosition;
  22540. var result = [];
  22541. var line = 0;
  22542. var getClientRect = function (caretPosition) {
  22543. if (direction === 1) {
  22544. return last$1(caretPosition.getClientRects());
  22545. }
  22546. return last$1(caretPosition.getClientRects());
  22547. };
  22548. if (direction === 1) {
  22549. walkFn = caretWalker.next;
  22550. isBelowFn = isBelow$1;
  22551. isAboveFn = isAbove$1;
  22552. caretPosition = CaretPosition.after(node);
  22553. } else {
  22554. walkFn = caretWalker.prev;
  22555. isBelowFn = isAbove$1;
  22556. isAboveFn = isBelow$1;
  22557. caretPosition = CaretPosition.before(node);
  22558. }
  22559. var targetClientRect = getClientRect(caretPosition);
  22560. do {
  22561. if (!caretPosition.isVisible()) {
  22562. continue;
  22563. }
  22564. var rect = getClientRect(caretPosition);
  22565. if (isAboveFn(rect, targetClientRect)) {
  22566. continue;
  22567. }
  22568. if (result.length > 0 && isBelowFn(rect, last$1(result))) {
  22569. line++;
  22570. }
  22571. var clientRect = clone(rect);
  22572. clientRect.position = caretPosition;
  22573. clientRect.line = line;
  22574. if (predicateFn(clientRect)) {
  22575. return result;
  22576. }
  22577. result.push(clientRect);
  22578. } while (caretPosition = walkFn(caretPosition));
  22579. return result;
  22580. };
  22581. var isAboveLine = function (lineNumber) {
  22582. return function (clientRect) {
  22583. return aboveLineNumber(lineNumber, clientRect);
  22584. };
  22585. };
  22586. var isLine = function (lineNumber) {
  22587. return function (clientRect) {
  22588. return isLineNumber(lineNumber, clientRect);
  22589. };
  22590. };
  22591. var isContentEditableFalse$3 = isContentEditableFalse$b;
  22592. var findNode = findNode$1;
  22593. var distanceToRectLeft = function (clientRect, clientX) {
  22594. return Math.abs(clientRect.left - clientX);
  22595. };
  22596. var distanceToRectRight = function (clientRect, clientX) {
  22597. return Math.abs(clientRect.right - clientX);
  22598. };
  22599. var isInsideX = function (clientX, clientRect) {
  22600. return clientX >= clientRect.left && clientX <= clientRect.right;
  22601. };
  22602. var isInsideY = function (clientY, clientRect) {
  22603. return clientY >= clientRect.top && clientY <= clientRect.bottom;
  22604. };
  22605. var isNodeClientRect = function (rect) {
  22606. return hasNonNullableKey(rect, 'node');
  22607. };
  22608. var findClosestClientRect = function (clientRects, clientX, allowInside) {
  22609. if (allowInside === void 0) {
  22610. allowInside = always;
  22611. }
  22612. return reduce(clientRects, function (oldClientRect, clientRect) {
  22613. if (isInsideX(clientX, clientRect)) {
  22614. return allowInside(clientRect) ? clientRect : oldClientRect;
  22615. }
  22616. if (isInsideX(clientX, oldClientRect)) {
  22617. return allowInside(oldClientRect) ? oldClientRect : clientRect;
  22618. }
  22619. var oldDistance = Math.min(distanceToRectLeft(oldClientRect, clientX), distanceToRectRight(oldClientRect, clientX));
  22620. var newDistance = Math.min(distanceToRectLeft(clientRect, clientX), distanceToRectRight(clientRect, clientX));
  22621. if (newDistance === oldDistance && isNodeClientRect(clientRect) && isContentEditableFalse$3(clientRect.node)) {
  22622. return clientRect;
  22623. }
  22624. if (newDistance < oldDistance) {
  22625. return clientRect;
  22626. }
  22627. return oldClientRect;
  22628. });
  22629. };
  22630. var walkUntil = function (direction, root, predicateFn, startNode, includeChildren) {
  22631. var node = findNode(startNode, direction, isEditableCaretCandidate$1, root, !includeChildren);
  22632. do {
  22633. if (!node || predicateFn(node)) {
  22634. return;
  22635. }
  22636. } while (node = findNode(node, direction, isEditableCaretCandidate$1, root));
  22637. };
  22638. var findLineNodeRects = function (root, targetNodeRect, includeChildren) {
  22639. if (includeChildren === void 0) {
  22640. includeChildren = true;
  22641. }
  22642. var clientRects = [];
  22643. var collect = function (checkPosFn, node) {
  22644. var lineRects = filter$4(getClientRects([node]), function (clientRect) {
  22645. return !checkPosFn(clientRect, targetNodeRect);
  22646. });
  22647. clientRects = clientRects.concat(lineRects);
  22648. return lineRects.length === 0;
  22649. };
  22650. clientRects.push(targetNodeRect);
  22651. walkUntil(VDirection.Up, root, curry(collect, isAbove$1), targetNodeRect.node, includeChildren);
  22652. walkUntil(VDirection.Down, root, curry(collect, isBelow$1), targetNodeRect.node, includeChildren);
  22653. return clientRects;
  22654. };
  22655. var getFakeCaretTargets = function (root) {
  22656. return filter$4(from(root.getElementsByTagName('*')), isFakeCaretTarget);
  22657. };
  22658. var caretInfo = function (clientRect, clientX) {
  22659. return {
  22660. node: clientRect.node,
  22661. before: distanceToRectLeft(clientRect, clientX) < distanceToRectRight(clientRect, clientX)
  22662. };
  22663. };
  22664. var closestFakeCaret = function (root, clientX, clientY) {
  22665. var fakeTargetNodeRects = getClientRects(getFakeCaretTargets(root));
  22666. var targetNodeRects = filter$4(fakeTargetNodeRects, curry(isInsideY, clientY));
  22667. var checkInside = function (clientRect) {
  22668. return !isTable$3(clientRect.node) && !isMedia$2(clientRect.node);
  22669. };
  22670. var closestNodeRect = findClosestClientRect(targetNodeRects, clientX, checkInside);
  22671. if (closestNodeRect) {
  22672. var includeChildren = checkInside(closestNodeRect);
  22673. closestNodeRect = findClosestClientRect(findLineNodeRects(root, closestNodeRect, includeChildren), clientX, checkInside);
  22674. if (closestNodeRect && isFakeCaretTarget(closestNodeRect.node)) {
  22675. return caretInfo(closestNodeRect, clientX);
  22676. }
  22677. }
  22678. return null;
  22679. };
  22680. var moveToRange = function (editor, rng) {
  22681. editor.selection.setRng(rng);
  22682. scrollRangeIntoView(editor, editor.selection.getRng());
  22683. };
  22684. var renderRangeCaretOpt = function (editor, range, scrollIntoView) {
  22685. return Optional.some(renderRangeCaret(editor, range, scrollIntoView));
  22686. };
  22687. var moveHorizontally = function (editor, direction, range, isBefore, isAfter, isElement) {
  22688. var forwards = direction === HDirection.Forwards;
  22689. var caretWalker = CaretWalker(editor.getBody());
  22690. var getNextPosFn = curry(getVisualCaretPosition, forwards ? caretWalker.next : caretWalker.prev);
  22691. var isBeforeFn = forwards ? isBefore : isAfter;
  22692. if (!range.collapsed) {
  22693. var node = getSelectedNode(range);
  22694. if (isElement(node)) {
  22695. return showCaret(direction, editor, node, direction === HDirection.Backwards, false);
  22696. }
  22697. }
  22698. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22699. if (isBeforeFn(caretPosition)) {
  22700. return selectNode(editor, caretPosition.getNode(!forwards));
  22701. }
  22702. var nextCaretPosition = normalizePosition(forwards, getNextPosFn(caretPosition));
  22703. var rangeIsInContainerBlock = isRangeInCaretContainerBlock(range);
  22704. if (!nextCaretPosition) {
  22705. return rangeIsInContainerBlock ? Optional.some(range) : Optional.none();
  22706. }
  22707. if (isBeforeFn(nextCaretPosition)) {
  22708. return showCaret(direction, editor, nextCaretPosition.getNode(!forwards), forwards, false);
  22709. }
  22710. var peekCaretPosition = getNextPosFn(nextCaretPosition);
  22711. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  22712. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  22713. return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, false);
  22714. }
  22715. }
  22716. if (rangeIsInContainerBlock) {
  22717. return renderRangeCaretOpt(editor, nextCaretPosition.toRange(), false);
  22718. }
  22719. return Optional.none();
  22720. };
  22721. var moveVertically = function (editor, direction, range, isBefore, isAfter, isElement) {
  22722. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22723. var caretClientRect = last$1(caretPosition.getClientRects());
  22724. var forwards = direction === VDirection.Down;
  22725. if (!caretClientRect) {
  22726. return Optional.none();
  22727. }
  22728. var walkerFn = forwards ? downUntil : upUntil;
  22729. var linePositions = walkerFn(editor.getBody(), isAboveLine(1), caretPosition);
  22730. var nextLinePositions = filter$4(linePositions, isLine(1));
  22731. var clientX = caretClientRect.left;
  22732. var nextLineRect = findClosestClientRect(nextLinePositions, clientX);
  22733. if (nextLineRect && isElement(nextLineRect.node)) {
  22734. var dist1 = Math.abs(clientX - nextLineRect.left);
  22735. var dist2 = Math.abs(clientX - nextLineRect.right);
  22736. return showCaret(direction, editor, nextLineRect.node, dist1 < dist2, false);
  22737. }
  22738. var currentNode;
  22739. if (isBefore(caretPosition)) {
  22740. currentNode = caretPosition.getNode();
  22741. } else if (isAfter(caretPosition)) {
  22742. currentNode = caretPosition.getNode(true);
  22743. } else {
  22744. currentNode = getSelectedNode(range);
  22745. }
  22746. if (currentNode) {
  22747. var caretPositions = positionsUntil(direction, editor.getBody(), isAboveLine(1), currentNode);
  22748. var closestNextLineRect = findClosestClientRect(filter$4(caretPositions, isLine(1)), clientX);
  22749. if (closestNextLineRect) {
  22750. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  22751. }
  22752. closestNextLineRect = last$1(filter$4(caretPositions, isLine(0)));
  22753. if (closestNextLineRect) {
  22754. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  22755. }
  22756. }
  22757. if (nextLinePositions.length === 0) {
  22758. return getLineEndPoint(editor, forwards).filter(forwards ? isAfter : isBefore).map(function (pos) {
  22759. return renderRangeCaret(editor, pos.toRange(), false);
  22760. });
  22761. }
  22762. return Optional.none();
  22763. };
  22764. var getLineEndPoint = function (editor, forward) {
  22765. var rng = editor.selection.getRng();
  22766. var body = editor.getBody();
  22767. if (forward) {
  22768. var from = CaretPosition.fromRangeEnd(rng);
  22769. var result = getPositionsUntilNextLine(body, from);
  22770. return last$2(result.positions);
  22771. } else {
  22772. var from = CaretPosition.fromRangeStart(rng);
  22773. var result = getPositionsUntilPreviousLine(body, from);
  22774. return head(result.positions);
  22775. }
  22776. };
  22777. var moveToLineEndPoint$3 = function (editor, forward, isElementPosition) {
  22778. return getLineEndPoint(editor, forward).filter(isElementPosition).exists(function (pos) {
  22779. editor.selection.setRng(pos.toRange());
  22780. return true;
  22781. });
  22782. };
  22783. var setCaretPosition = function (editor, pos) {
  22784. var rng = editor.dom.createRng();
  22785. rng.setStart(pos.container(), pos.offset());
  22786. rng.setEnd(pos.container(), pos.offset());
  22787. editor.selection.setRng(rng);
  22788. };
  22789. var setSelected = function (state, elm) {
  22790. if (state) {
  22791. elm.setAttribute('data-mce-selected', 'inline-boundary');
  22792. } else {
  22793. elm.removeAttribute('data-mce-selected');
  22794. }
  22795. };
  22796. var renderCaretLocation = function (editor, caret, location) {
  22797. return renderCaret(caret, location).map(function (pos) {
  22798. setCaretPosition(editor, pos);
  22799. return location;
  22800. });
  22801. };
  22802. var findLocation = function (editor, caret, forward) {
  22803. var rootNode = editor.getBody();
  22804. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  22805. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22806. var location = findLocation$1(forward, isInlineTarget$1, rootNode, from);
  22807. return location.bind(function (location) {
  22808. return renderCaretLocation(editor, caret, location);
  22809. });
  22810. };
  22811. var toggleInlines = function (isInlineTarget, dom, elms) {
  22812. var inlineBoundaries = map$3(descendants(SugarElement.fromDom(dom.getRoot()), '*[data-mce-selected="inline-boundary"]'), function (e) {
  22813. return e.dom;
  22814. });
  22815. var selectedInlines = filter$4(inlineBoundaries, isInlineTarget);
  22816. var targetInlines = filter$4(elms, isInlineTarget);
  22817. each$k(difference(selectedInlines, targetInlines), curry(setSelected, false));
  22818. each$k(difference(targetInlines, selectedInlines), curry(setSelected, true));
  22819. };
  22820. var safeRemoveCaretContainer = function (editor, caret) {
  22821. if (editor.selection.isCollapsed() && editor.composing !== true && caret.get()) {
  22822. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22823. if (CaretPosition.isTextPosition(pos) && isAtZwsp(pos) === false) {
  22824. setCaretPosition(editor, removeAndReposition(caret.get(), pos));
  22825. caret.set(null);
  22826. }
  22827. }
  22828. };
  22829. var renderInsideInlineCaret = function (isInlineTarget, editor, caret, elms) {
  22830. if (editor.selection.isCollapsed()) {
  22831. var inlines = filter$4(elms, isInlineTarget);
  22832. each$k(inlines, function (_inline) {
  22833. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22834. readLocation(isInlineTarget, editor.getBody(), pos).bind(function (location) {
  22835. return renderCaretLocation(editor, caret, location);
  22836. });
  22837. });
  22838. }
  22839. };
  22840. var move$2 = function (editor, caret, forward) {
  22841. return isInlineBoundariesEnabled(editor) ? findLocation(editor, caret, forward).isSome() : false;
  22842. };
  22843. var moveWord = function (forward, editor, _caret) {
  22844. return isInlineBoundariesEnabled(editor) ? moveByWord(forward, editor) : false;
  22845. };
  22846. var setupSelectedState = function (editor) {
  22847. var caret = Cell(null);
  22848. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22849. editor.on('NodeChange', function (e) {
  22850. if (isInlineBoundariesEnabled(editor) && !(Env.browser.isIE() && e.initial)) {
  22851. toggleInlines(isInlineTarget$1, editor.dom, e.parents);
  22852. safeRemoveCaretContainer(editor, caret);
  22853. renderInsideInlineCaret(isInlineTarget$1, editor, caret, e.parents);
  22854. }
  22855. });
  22856. return caret;
  22857. };
  22858. var moveNextWord = curry(moveWord, true);
  22859. var movePrevWord = curry(moveWord, false);
  22860. var moveToLineEndPoint$2 = function (editor, forward, caret) {
  22861. if (isInlineBoundariesEnabled(editor)) {
  22862. var linePoint = getLineEndPoint(editor, forward).getOrThunk(function () {
  22863. var rng = editor.selection.getRng();
  22864. return forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  22865. });
  22866. return readLocation(curry(isInlineTarget, editor), editor.getBody(), linePoint).exists(function (loc) {
  22867. var outsideLoc = outside(loc);
  22868. return renderCaret(caret, outsideLoc).exists(function (pos) {
  22869. setCaretPosition(editor, pos);
  22870. return true;
  22871. });
  22872. });
  22873. } else {
  22874. return false;
  22875. }
  22876. };
  22877. var rangeFromPositions = function (from, to) {
  22878. var range = document.createRange();
  22879. range.setStart(from.container(), from.offset());
  22880. range.setEnd(to.container(), to.offset());
  22881. return range;
  22882. };
  22883. var hasOnlyTwoOrLessPositionsLeft = function (elm) {
  22884. return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  22885. var normalizedFirstPos = normalizePosition(true, firstPos);
  22886. var normalizedLastPos = normalizePosition(false, lastPos);
  22887. return nextPosition(elm, normalizedFirstPos).forall(function (pos) {
  22888. return pos.isEqual(normalizedLastPos);
  22889. });
  22890. }).getOr(true);
  22891. };
  22892. var setCaretLocation = function (editor, caret) {
  22893. return function (location) {
  22894. return renderCaret(caret, location).exists(function (pos) {
  22895. setCaretPosition(editor, pos);
  22896. return true;
  22897. });
  22898. };
  22899. };
  22900. var deleteFromTo = function (editor, caret, from, to) {
  22901. var rootNode = editor.getBody();
  22902. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22903. editor.undoManager.ignore(function () {
  22904. editor.selection.setRng(rangeFromPositions(from, to));
  22905. editor.execCommand('Delete');
  22906. readLocation(isInlineTarget$1, rootNode, CaretPosition.fromRangeStart(editor.selection.getRng())).map(inside).map(setCaretLocation(editor, caret));
  22907. });
  22908. editor.nodeChanged();
  22909. };
  22910. var rescope = function (rootNode, node) {
  22911. var parentBlock = getParentBlock$2(node, rootNode);
  22912. return parentBlock ? parentBlock : rootNode;
  22913. };
  22914. var backspaceDeleteCollapsed = function (editor, caret, forward, from) {
  22915. var rootNode = rescope(editor.getBody(), from.container());
  22916. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22917. var fromLocation = readLocation(isInlineTarget$1, rootNode, from);
  22918. return fromLocation.bind(function (location) {
  22919. if (forward) {
  22920. return location.fold(constant(Optional.some(inside(location))), Optional.none, constant(Optional.some(outside(location))), Optional.none);
  22921. } else {
  22922. return location.fold(Optional.none, constant(Optional.some(outside(location))), Optional.none, constant(Optional.some(inside(location))));
  22923. }
  22924. }).map(setCaretLocation(editor, caret)).getOrThunk(function () {
  22925. var toPosition = navigate(forward, rootNode, from);
  22926. var toLocation = toPosition.bind(function (pos) {
  22927. return readLocation(isInlineTarget$1, rootNode, pos);
  22928. });
  22929. return lift2(fromLocation, toLocation, function () {
  22930. return findRootInline(isInlineTarget$1, rootNode, from).exists(function (elm) {
  22931. if (hasOnlyTwoOrLessPositionsLeft(elm)) {
  22932. deleteElement$2(editor, forward, SugarElement.fromDom(elm));
  22933. return true;
  22934. } else {
  22935. return false;
  22936. }
  22937. });
  22938. }).orThunk(function () {
  22939. return toLocation.bind(function (_) {
  22940. return toPosition.map(function (to) {
  22941. if (forward) {
  22942. deleteFromTo(editor, caret, from, to);
  22943. } else {
  22944. deleteFromTo(editor, caret, to, from);
  22945. }
  22946. return true;
  22947. });
  22948. });
  22949. }).getOr(false);
  22950. });
  22951. };
  22952. var backspaceDelete$3 = function (editor, caret, forward) {
  22953. if (editor.selection.isCollapsed() && isInlineBoundariesEnabled(editor)) {
  22954. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  22955. return backspaceDeleteCollapsed(editor, caret, forward, from);
  22956. }
  22957. return false;
  22958. };
  22959. var getParentInlines = function (rootElm, startElm) {
  22960. var parents = parentsAndSelf(startElm, rootElm);
  22961. return findIndex$2(parents, isBlock$2).fold(constant(parents), function (index) {
  22962. return parents.slice(0, index);
  22963. });
  22964. };
  22965. var hasOnlyOneChild = function (elm) {
  22966. return childNodesCount(elm) === 1;
  22967. };
  22968. var deleteLastPosition = function (forward, editor, target, parentInlines) {
  22969. var isFormatElement$1 = curry(isFormatElement, editor);
  22970. var formatNodes = map$3(filter$4(parentInlines, isFormatElement$1), function (elm) {
  22971. return elm.dom;
  22972. });
  22973. if (formatNodes.length === 0) {
  22974. deleteElement$2(editor, forward, target);
  22975. } else {
  22976. var pos = replaceWithCaretFormat(target.dom, formatNodes);
  22977. editor.selection.setRng(pos.toRange());
  22978. }
  22979. };
  22980. var deleteCaret$1 = function (editor, forward) {
  22981. var rootElm = SugarElement.fromDom(editor.getBody());
  22982. var startElm = SugarElement.fromDom(editor.selection.getStart());
  22983. var parentInlines = filter$4(getParentInlines(rootElm, startElm), hasOnlyOneChild);
  22984. return last$2(parentInlines).exists(function (target) {
  22985. var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22986. if (willDeleteLastPositionInElement(forward, fromPos, target.dom) && !isEmptyCaretFormatElement(target)) {
  22987. deleteLastPosition(forward, editor, target, parentInlines);
  22988. return true;
  22989. } else {
  22990. return false;
  22991. }
  22992. });
  22993. };
  22994. var backspaceDelete$2 = function (editor, forward) {
  22995. return editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : false;
  22996. };
  22997. var deleteElement = function (editor, forward, element) {
  22998. editor._selectionOverrides.hideFakeCaret();
  22999. deleteElement$2(editor, forward, SugarElement.fromDom(element));
  23000. return true;
  23001. };
  23002. var deleteCaret = function (editor, forward) {
  23003. var isNearMedia = forward ? isBeforeMedia : isAfterMedia;
  23004. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23005. var fromPos = getNormalizedRangeEndPoint(direction, editor.getBody(), editor.selection.getRng());
  23006. if (isNearMedia(fromPos)) {
  23007. return deleteElement(editor, forward, fromPos.getNode(!forward));
  23008. } else {
  23009. return Optional.from(normalizePosition(forward, fromPos)).filter(function (pos) {
  23010. return isNearMedia(pos) && isMoveInsideSameBlock(fromPos, pos);
  23011. }).exists(function (pos) {
  23012. return deleteElement(editor, forward, pos.getNode(!forward));
  23013. });
  23014. }
  23015. };
  23016. var deleteRange = function (editor, forward) {
  23017. var selectedNode = editor.selection.getNode();
  23018. return isMedia$2(selectedNode) ? deleteElement(editor, forward, selectedNode) : false;
  23019. };
  23020. var backspaceDelete$1 = function (editor, forward) {
  23021. return editor.selection.isCollapsed() ? deleteCaret(editor, forward) : deleteRange(editor, forward);
  23022. };
  23023. var isEditable = function (target) {
  23024. return closest$3(target, function (elm) {
  23025. return isContentEditableTrue$4(elm.dom) || isContentEditableFalse$b(elm.dom);
  23026. }).exists(function (elm) {
  23027. return isContentEditableTrue$4(elm.dom);
  23028. });
  23029. };
  23030. var parseIndentValue = function (value) {
  23031. var number = parseInt(value, 10);
  23032. return isNaN(number) ? 0 : number;
  23033. };
  23034. var getIndentStyleName = function (useMargin, element) {
  23035. var indentStyleName = useMargin || isTable$2(element) ? 'margin' : 'padding';
  23036. var suffix = get$5(element, 'direction') === 'rtl' ? '-right' : '-left';
  23037. return indentStyleName + suffix;
  23038. };
  23039. var indentElement = function (dom, command, useMargin, value, unit, element) {
  23040. var indentStyleName = getIndentStyleName(useMargin, SugarElement.fromDom(element));
  23041. if (command === 'outdent') {
  23042. var styleValue = Math.max(0, parseIndentValue(element.style[indentStyleName]) - value);
  23043. dom.setStyle(element, indentStyleName, styleValue ? styleValue + unit : '');
  23044. } else {
  23045. var styleValue = parseIndentValue(element.style[indentStyleName]) + value + unit;
  23046. dom.setStyle(element, indentStyleName, styleValue);
  23047. }
  23048. };
  23049. var validateBlocks = function (editor, blocks) {
  23050. return forall(blocks, function (block) {
  23051. var indentStyleName = getIndentStyleName(shouldIndentUseMargin(editor), block);
  23052. var intentValue = getRaw(block, indentStyleName).map(parseIndentValue).getOr(0);
  23053. var contentEditable = editor.dom.getContentEditable(block.dom);
  23054. return contentEditable !== 'false' && intentValue > 0;
  23055. });
  23056. };
  23057. var canOutdent = function (editor) {
  23058. var blocks = getBlocksToIndent(editor);
  23059. return !editor.mode.isReadOnly() && (blocks.length > 1 || validateBlocks(editor, blocks));
  23060. };
  23061. var isListComponent = function (el) {
  23062. return isList(el) || isListItem(el);
  23063. };
  23064. var parentIsListComponent = function (el) {
  23065. return parent(el).exists(isListComponent);
  23066. };
  23067. var getBlocksToIndent = function (editor) {
  23068. return filter$4(fromDom$1(editor.selection.getSelectedBlocks()), function (el) {
  23069. return !isListComponent(el) && !parentIsListComponent(el) && isEditable(el);
  23070. });
  23071. };
  23072. var handle = function (editor, command) {
  23073. var dom = editor.dom, selection = editor.selection, formatter = editor.formatter;
  23074. var indentation = getIndentation(editor);
  23075. var indentUnit = /[a-z%]+$/i.exec(indentation)[0];
  23076. var indentValue = parseInt(indentation, 10);
  23077. var useMargin = shouldIndentUseMargin(editor);
  23078. var forcedRootBlock = getForcedRootBlock(editor);
  23079. if (!editor.queryCommandState('InsertUnorderedList') && !editor.queryCommandState('InsertOrderedList')) {
  23080. if (forcedRootBlock === '' && !dom.getParent(selection.getNode(), dom.isBlock)) {
  23081. formatter.apply('div');
  23082. }
  23083. }
  23084. each$k(getBlocksToIndent(editor), function (block) {
  23085. indentElement(dom, command, useMargin, indentValue, indentUnit, block.dom);
  23086. });
  23087. };
  23088. var backspaceDelete = function (editor, _forward) {
  23089. if (editor.selection.isCollapsed() && canOutdent(editor)) {
  23090. var dom = editor.dom;
  23091. var rng = editor.selection.getRng();
  23092. var pos = CaretPosition.fromRangeStart(rng);
  23093. var block = dom.getParent(rng.startContainer, dom.isBlock);
  23094. if (block !== null && isAtStartOfBlock(SugarElement.fromDom(block), pos)) {
  23095. handle(editor, 'outdent');
  23096. return true;
  23097. }
  23098. }
  23099. return false;
  23100. };
  23101. var nativeCommand = function (editor, command) {
  23102. editor.getDoc().execCommand(command, false, null);
  23103. };
  23104. var deleteCommand = function (editor, caret) {
  23105. if (backspaceDelete(editor)) {
  23106. return;
  23107. } else if (backspaceDelete$5(editor, false)) {
  23108. return;
  23109. } else if (backspaceDelete$6(editor, false)) {
  23110. return;
  23111. } else if (backspaceDelete$3(editor, caret, false)) {
  23112. return;
  23113. } else if (backspaceDelete$8(editor, false)) {
  23114. return;
  23115. } else if (backspaceDelete$9(editor)) {
  23116. return;
  23117. } else if (backspaceDelete$4(editor, false)) {
  23118. return;
  23119. } else if (backspaceDelete$1(editor, false)) {
  23120. return;
  23121. } else if (backspaceDelete$7(editor)) {
  23122. return;
  23123. } else if (backspaceDelete$2(editor, false)) {
  23124. return;
  23125. } else {
  23126. nativeCommand(editor, 'Delete');
  23127. paddEmptyBody(editor);
  23128. }
  23129. };
  23130. var forwardDeleteCommand = function (editor, caret) {
  23131. if (backspaceDelete$5(editor, true)) {
  23132. return;
  23133. } else if (backspaceDelete$6(editor, true)) {
  23134. return;
  23135. } else if (backspaceDelete$3(editor, caret, true)) {
  23136. return;
  23137. } else if (backspaceDelete$8(editor, true)) {
  23138. return;
  23139. } else if (backspaceDelete$9(editor)) {
  23140. return;
  23141. } else if (backspaceDelete$4(editor, true)) {
  23142. return;
  23143. } else if (backspaceDelete$1(editor, true)) {
  23144. return;
  23145. } else if (backspaceDelete$7(editor)) {
  23146. return;
  23147. } else if (backspaceDelete$2(editor, true)) {
  23148. return;
  23149. } else {
  23150. nativeCommand(editor, 'ForwardDelete');
  23151. }
  23152. };
  23153. var setup$f = function (editor, caret) {
  23154. editor.addCommand('delete', function () {
  23155. deleteCommand(editor, caret);
  23156. });
  23157. editor.addCommand('forwardDelete', function () {
  23158. forwardDeleteCommand(editor, caret);
  23159. });
  23160. };
  23161. var SIGNIFICANT_MOVE = 5;
  23162. var LONGPRESS_DELAY = 400;
  23163. var getTouch = function (event) {
  23164. if (event.touches === undefined || event.touches.length !== 1) {
  23165. return Optional.none();
  23166. }
  23167. return Optional.some(event.touches[0]);
  23168. };
  23169. var isFarEnough = function (touch, data) {
  23170. var distX = Math.abs(touch.clientX - data.x);
  23171. var distY = Math.abs(touch.clientY - data.y);
  23172. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  23173. };
  23174. var setup$e = function (editor) {
  23175. var startData = value();
  23176. var longpressFired = Cell(false);
  23177. var debounceLongpress = last(function (e) {
  23178. editor.fire('longpress', __assign(__assign({}, e), { type: 'longpress' }));
  23179. longpressFired.set(true);
  23180. }, LONGPRESS_DELAY);
  23181. editor.on('touchstart', function (e) {
  23182. getTouch(e).each(function (touch) {
  23183. debounceLongpress.cancel();
  23184. var data = {
  23185. x: touch.clientX,
  23186. y: touch.clientY,
  23187. target: e.target
  23188. };
  23189. debounceLongpress.throttle(e);
  23190. longpressFired.set(false);
  23191. startData.set(data);
  23192. });
  23193. }, true);
  23194. editor.on('touchmove', function (e) {
  23195. debounceLongpress.cancel();
  23196. getTouch(e).each(function (touch) {
  23197. startData.on(function (data) {
  23198. if (isFarEnough(touch, data)) {
  23199. startData.clear();
  23200. longpressFired.set(false);
  23201. editor.fire('longpresscancel');
  23202. }
  23203. });
  23204. });
  23205. }, true);
  23206. editor.on('touchend touchcancel', function (e) {
  23207. debounceLongpress.cancel();
  23208. if (e.type === 'touchcancel') {
  23209. return;
  23210. }
  23211. startData.get().filter(function (data) {
  23212. return data.target.isEqualNode(e.target);
  23213. }).each(function () {
  23214. if (longpressFired.get()) {
  23215. e.preventDefault();
  23216. } else {
  23217. editor.fire('tap', __assign(__assign({}, e), { type: 'tap' }));
  23218. }
  23219. });
  23220. }, true);
  23221. };
  23222. var isBlockElement = function (blockElements, node) {
  23223. return has$2(blockElements, node.nodeName);
  23224. };
  23225. var isValidTarget = function (blockElements, node) {
  23226. if (isText$7(node)) {
  23227. return true;
  23228. } else if (isElement$5(node)) {
  23229. return !isBlockElement(blockElements, node) && !isBookmarkNode$1(node);
  23230. } else {
  23231. return false;
  23232. }
  23233. };
  23234. var hasBlockParent = function (blockElements, root, node) {
  23235. return exists(parents(SugarElement.fromDom(node), SugarElement.fromDom(root)), function (elm) {
  23236. return isBlockElement(blockElements, elm.dom);
  23237. });
  23238. };
  23239. var shouldRemoveTextNode = function (blockElements, node) {
  23240. if (isText$7(node)) {
  23241. if (node.nodeValue.length === 0) {
  23242. return true;
  23243. } else if (/^\s+$/.test(node.nodeValue) && (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
  23244. return true;
  23245. }
  23246. }
  23247. return false;
  23248. };
  23249. var addRootBlocks = function (editor) {
  23250. var dom = editor.dom, selection = editor.selection;
  23251. var schema = editor.schema, blockElements = schema.getBlockElements();
  23252. var node = selection.getStart();
  23253. var rootNode = editor.getBody();
  23254. var rootBlockNode, tempNode, wrapped;
  23255. var forcedRootBlock = getForcedRootBlock(editor);
  23256. if (!node || !isElement$5(node) || !forcedRootBlock) {
  23257. return;
  23258. }
  23259. var rootNodeName = rootNode.nodeName.toLowerCase();
  23260. if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, node)) {
  23261. return;
  23262. }
  23263. var rng = selection.getRng();
  23264. var startContainer = rng.startContainer;
  23265. var startOffset = rng.startOffset;
  23266. var endContainer = rng.endContainer;
  23267. var endOffset = rng.endOffset;
  23268. var restoreSelection = hasFocus(editor);
  23269. node = rootNode.firstChild;
  23270. while (node) {
  23271. if (isValidTarget(blockElements, node)) {
  23272. if (shouldRemoveTextNode(blockElements, node)) {
  23273. tempNode = node;
  23274. node = node.nextSibling;
  23275. dom.remove(tempNode);
  23276. continue;
  23277. }
  23278. if (!rootBlockNode) {
  23279. rootBlockNode = dom.create(forcedRootBlock, getForcedRootBlockAttrs(editor));
  23280. node.parentNode.insertBefore(rootBlockNode, node);
  23281. wrapped = true;
  23282. }
  23283. tempNode = node;
  23284. node = node.nextSibling;
  23285. rootBlockNode.appendChild(tempNode);
  23286. } else {
  23287. rootBlockNode = null;
  23288. node = node.nextSibling;
  23289. }
  23290. }
  23291. if (wrapped && restoreSelection) {
  23292. rng.setStart(startContainer, startOffset);
  23293. rng.setEnd(endContainer, endOffset);
  23294. selection.setRng(rng);
  23295. editor.nodeChanged();
  23296. }
  23297. };
  23298. var setup$d = function (editor) {
  23299. if (getForcedRootBlock(editor)) {
  23300. editor.on('NodeChange', curry(addRootBlocks, editor));
  23301. }
  23302. };
  23303. var findBlockCaretContainer = function (editor) {
  23304. return descendant(SugarElement.fromDom(editor.getBody()), '*[data-mce-caret]').map(function (elm) {
  23305. return elm.dom;
  23306. }).getOrNull();
  23307. };
  23308. var removeIeControlRect = function (editor) {
  23309. editor.selection.setRng(editor.selection.getRng());
  23310. };
  23311. var showBlockCaretContainer = function (editor, blockCaretContainer) {
  23312. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  23313. showCaretContainerBlock(blockCaretContainer);
  23314. removeIeControlRect(editor);
  23315. editor.selection.scrollIntoView(blockCaretContainer);
  23316. }
  23317. };
  23318. var handleBlockContainer = function (editor, e) {
  23319. var blockCaretContainer = findBlockCaretContainer(editor);
  23320. if (!blockCaretContainer) {
  23321. return;
  23322. }
  23323. if (e.type === 'compositionstart') {
  23324. e.preventDefault();
  23325. e.stopPropagation();
  23326. showBlockCaretContainer(editor, blockCaretContainer);
  23327. return;
  23328. }
  23329. if (hasContent(blockCaretContainer)) {
  23330. showBlockCaretContainer(editor, blockCaretContainer);
  23331. editor.undoManager.add();
  23332. }
  23333. };
  23334. var setup$c = function (editor) {
  23335. editor.on('keyup compositionstart', curry(handleBlockContainer, editor));
  23336. };
  23337. var isContentEditableFalse$2 = isContentEditableFalse$b;
  23338. var moveToCeFalseHorizontally = function (direction, editor, range) {
  23339. return moveHorizontally(editor, direction, range, isBeforeContentEditableFalse, isAfterContentEditableFalse, isContentEditableFalse$2);
  23340. };
  23341. var moveToCeFalseVertically = function (direction, editor, range) {
  23342. var isBefore = function (caretPosition) {
  23343. return isBeforeContentEditableFalse(caretPosition) || isBeforeTable(caretPosition);
  23344. };
  23345. var isAfter = function (caretPosition) {
  23346. return isAfterContentEditableFalse(caretPosition) || isAfterTable(caretPosition);
  23347. };
  23348. return moveVertically(editor, direction, range, isBefore, isAfter, isContentEditableFalse$2);
  23349. };
  23350. var createTextBlock = function (editor) {
  23351. var textBlock = editor.dom.create(getForcedRootBlock(editor));
  23352. if (!Env.ie || Env.ie >= 11) {
  23353. textBlock.innerHTML = '<br data-mce-bogus="1">';
  23354. }
  23355. return textBlock;
  23356. };
  23357. var exitPreBlock = function (editor, direction, range) {
  23358. var caretWalker = CaretWalker(editor.getBody());
  23359. var getVisualCaretPosition$1 = curry(getVisualCaretPosition, direction === 1 ? caretWalker.next : caretWalker.prev);
  23360. if (range.collapsed && hasForcedRootBlock(editor)) {
  23361. var pre = editor.dom.getParent(range.startContainer, 'PRE');
  23362. if (!pre) {
  23363. return;
  23364. }
  23365. var caretPos = getVisualCaretPosition$1(CaretPosition.fromRangeStart(range));
  23366. if (!caretPos) {
  23367. var newBlock = createTextBlock(editor);
  23368. if (direction === 1) {
  23369. editor.$(pre).after(newBlock);
  23370. } else {
  23371. editor.$(pre).before(newBlock);
  23372. }
  23373. editor.selection.select(newBlock, true);
  23374. editor.selection.collapse();
  23375. }
  23376. }
  23377. };
  23378. var getHorizontalRange = function (editor, forward) {
  23379. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23380. var range = editor.selection.getRng();
  23381. return moveToCeFalseHorizontally(direction, editor, range).orThunk(function () {
  23382. exitPreBlock(editor, direction, range);
  23383. return Optional.none();
  23384. });
  23385. };
  23386. var getVerticalRange = function (editor, down) {
  23387. var direction = down ? 1 : -1;
  23388. var range = editor.selection.getRng();
  23389. return moveToCeFalseVertically(direction, editor, range).orThunk(function () {
  23390. exitPreBlock(editor, direction, range);
  23391. return Optional.none();
  23392. });
  23393. };
  23394. var moveH$2 = function (editor, forward) {
  23395. return getHorizontalRange(editor, forward).exists(function (newRange) {
  23396. moveToRange(editor, newRange);
  23397. return true;
  23398. });
  23399. };
  23400. var moveV$3 = function (editor, down) {
  23401. return getVerticalRange(editor, down).exists(function (newRange) {
  23402. moveToRange(editor, newRange);
  23403. return true;
  23404. });
  23405. };
  23406. var moveToLineEndPoint$1 = function (editor, forward) {
  23407. var isCefPosition = forward ? isAfterContentEditableFalse : isBeforeContentEditableFalse;
  23408. return moveToLineEndPoint$3(editor, forward, isCefPosition);
  23409. };
  23410. var isTarget = function (node) {
  23411. return contains$3(['figcaption'], name(node));
  23412. };
  23413. var rangeBefore = function (target) {
  23414. var rng = document.createRange();
  23415. rng.setStartBefore(target.dom);
  23416. rng.setEndBefore(target.dom);
  23417. return rng;
  23418. };
  23419. var insertElement = function (root, elm, forward) {
  23420. if (forward) {
  23421. append$1(root, elm);
  23422. } else {
  23423. prepend(root, elm);
  23424. }
  23425. };
  23426. var insertBr = function (root, forward) {
  23427. var br = SugarElement.fromTag('br');
  23428. insertElement(root, br, forward);
  23429. return rangeBefore(br);
  23430. };
  23431. var insertBlock = function (root, forward, blockName, attrs) {
  23432. var block = SugarElement.fromTag(blockName);
  23433. var br = SugarElement.fromTag('br');
  23434. setAll$1(block, attrs);
  23435. append$1(block, br);
  23436. insertElement(root, block, forward);
  23437. return rangeBefore(br);
  23438. };
  23439. var insertEmptyLine = function (root, rootBlockName, attrs, forward) {
  23440. if (rootBlockName === '') {
  23441. return insertBr(root, forward);
  23442. } else {
  23443. return insertBlock(root, forward, rootBlockName, attrs);
  23444. }
  23445. };
  23446. var getClosestTargetBlock = function (pos, root) {
  23447. var isRoot = curry(eq, root);
  23448. return closest$3(SugarElement.fromDom(pos.container()), isBlock$2, isRoot).filter(isTarget);
  23449. };
  23450. var isAtFirstOrLastLine = function (root, forward, pos) {
  23451. return forward ? isAtLastLine(root.dom, pos) : isAtFirstLine(root.dom, pos);
  23452. };
  23453. var moveCaretToNewEmptyLine = function (editor, forward) {
  23454. var root = SugarElement.fromDom(editor.getBody());
  23455. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23456. var rootBlock = getForcedRootBlock(editor);
  23457. var rootBlockAttrs = getForcedRootBlockAttrs(editor);
  23458. return getClosestTargetBlock(pos, root).exists(function () {
  23459. if (isAtFirstOrLastLine(root, forward, pos)) {
  23460. var rng = insertEmptyLine(root, rootBlock, rootBlockAttrs, forward);
  23461. editor.selection.setRng(rng);
  23462. return true;
  23463. } else {
  23464. return false;
  23465. }
  23466. });
  23467. };
  23468. var moveV$2 = function (editor, forward) {
  23469. if (editor.selection.isCollapsed()) {
  23470. return moveCaretToNewEmptyLine(editor, forward);
  23471. } else {
  23472. return false;
  23473. }
  23474. };
  23475. var defaultPatterns = function (patterns) {
  23476. return map$3(patterns, function (pattern) {
  23477. return __assign({
  23478. shiftKey: false,
  23479. altKey: false,
  23480. ctrlKey: false,
  23481. metaKey: false,
  23482. keyCode: 0,
  23483. action: noop
  23484. }, pattern);
  23485. });
  23486. };
  23487. var matchesEvent = function (pattern, evt) {
  23488. return evt.keyCode === pattern.keyCode && evt.shiftKey === pattern.shiftKey && evt.altKey === pattern.altKey && evt.ctrlKey === pattern.ctrlKey && evt.metaKey === pattern.metaKey;
  23489. };
  23490. var match$1 = function (patterns, evt) {
  23491. return bind(defaultPatterns(patterns), function (pattern) {
  23492. return matchesEvent(pattern, evt) ? [pattern] : [];
  23493. });
  23494. };
  23495. var action = function (f) {
  23496. var x = [];
  23497. for (var _i = 1; _i < arguments.length; _i++) {
  23498. x[_i - 1] = arguments[_i];
  23499. }
  23500. return function () {
  23501. return f.apply(null, x);
  23502. };
  23503. };
  23504. var execute = function (patterns, evt) {
  23505. return find$3(match$1(patterns, evt), function (pattern) {
  23506. return pattern.action();
  23507. });
  23508. };
  23509. var moveH$1 = function (editor, forward) {
  23510. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23511. var range = editor.selection.getRng();
  23512. return moveHorizontally(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(function (newRange) {
  23513. moveToRange(editor, newRange);
  23514. return true;
  23515. });
  23516. };
  23517. var moveV$1 = function (editor, down) {
  23518. var direction = down ? 1 : -1;
  23519. var range = editor.selection.getRng();
  23520. return moveVertically(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(function (newRange) {
  23521. moveToRange(editor, newRange);
  23522. return true;
  23523. });
  23524. };
  23525. var moveToLineEndPoint = function (editor, forward) {
  23526. var isNearMedia = forward ? isAfterMedia : isBeforeMedia;
  23527. return moveToLineEndPoint$3(editor, forward, isNearMedia);
  23528. };
  23529. var deflate = function (rect, delta) {
  23530. return {
  23531. left: rect.left - delta,
  23532. top: rect.top - delta,
  23533. right: rect.right + delta * 2,
  23534. bottom: rect.bottom + delta * 2,
  23535. width: rect.width + delta,
  23536. height: rect.height + delta
  23537. };
  23538. };
  23539. var getCorners = function (getYAxisValue, tds) {
  23540. return bind(tds, function (td) {
  23541. var rect = deflate(clone(td.getBoundingClientRect()), -1);
  23542. return [
  23543. {
  23544. x: rect.left,
  23545. y: getYAxisValue(rect),
  23546. cell: td
  23547. },
  23548. {
  23549. x: rect.right,
  23550. y: getYAxisValue(rect),
  23551. cell: td
  23552. }
  23553. ];
  23554. });
  23555. };
  23556. var findClosestCorner = function (corners, x, y) {
  23557. return foldl(corners, function (acc, newCorner) {
  23558. return acc.fold(function () {
  23559. return Optional.some(newCorner);
  23560. }, function (oldCorner) {
  23561. var oldDist = Math.sqrt(Math.abs(oldCorner.x - x) + Math.abs(oldCorner.y - y));
  23562. var newDist = Math.sqrt(Math.abs(newCorner.x - x) + Math.abs(newCorner.y - y));
  23563. return Optional.some(newDist < oldDist ? newCorner : oldCorner);
  23564. });
  23565. }, Optional.none());
  23566. };
  23567. var getClosestCell = function (getYAxisValue, isTargetCorner, table, x, y) {
  23568. var cells = descendants(SugarElement.fromDom(table), 'td,th,caption').map(function (e) {
  23569. return e.dom;
  23570. });
  23571. var corners = filter$4(getCorners(getYAxisValue, cells), function (corner) {
  23572. return isTargetCorner(corner, y);
  23573. });
  23574. return findClosestCorner(corners, x, y).map(function (corner) {
  23575. return corner.cell;
  23576. });
  23577. };
  23578. var getBottomValue = function (rect) {
  23579. return rect.bottom;
  23580. };
  23581. var getTopValue = function (rect) {
  23582. return rect.top;
  23583. };
  23584. var isAbove = function (corner, y) {
  23585. return corner.y < y;
  23586. };
  23587. var isBelow = function (corner, y) {
  23588. return corner.y > y;
  23589. };
  23590. var getClosestCellAbove = curry(getClosestCell, getBottomValue, isAbove);
  23591. var getClosestCellBelow = curry(getClosestCell, getTopValue, isBelow);
  23592. var findClosestPositionInAboveCell = function (table, pos) {
  23593. return head(pos.getClientRects()).bind(function (rect) {
  23594. return getClosestCellAbove(table, rect.left, rect.top);
  23595. }).bind(function (cell) {
  23596. return findClosestHorizontalPosition(getLastLinePositions(cell), pos);
  23597. });
  23598. };
  23599. var findClosestPositionInBelowCell = function (table, pos) {
  23600. return last$2(pos.getClientRects()).bind(function (rect) {
  23601. return getClosestCellBelow(table, rect.left, rect.top);
  23602. }).bind(function (cell) {
  23603. return findClosestHorizontalPosition(getFirstLinePositions(cell), pos);
  23604. });
  23605. };
  23606. var hasNextBreak = function (getPositionsUntil, scope, lineInfo) {
  23607. return lineInfo.breakAt.exists(function (breakPos) {
  23608. return getPositionsUntil(scope, breakPos).breakAt.isSome();
  23609. });
  23610. };
  23611. var startsWithWrapBreak = function (lineInfo) {
  23612. return lineInfo.breakType === BreakType.Wrap && lineInfo.positions.length === 0;
  23613. };
  23614. var startsWithBrBreak = function (lineInfo) {
  23615. return lineInfo.breakType === BreakType.Br && lineInfo.positions.length === 1;
  23616. };
  23617. var isAtTableCellLine = function (getPositionsUntil, scope, pos) {
  23618. var lineInfo = getPositionsUntil(scope, pos);
  23619. if (startsWithWrapBreak(lineInfo) || !isBr$5(pos.getNode()) && startsWithBrBreak(lineInfo)) {
  23620. return !hasNextBreak(getPositionsUntil, scope, lineInfo);
  23621. } else {
  23622. return lineInfo.breakAt.isNone();
  23623. }
  23624. };
  23625. var isAtFirstTableCellLine = curry(isAtTableCellLine, getPositionsUntilPreviousLine);
  23626. var isAtLastTableCellLine = curry(isAtTableCellLine, getPositionsUntilNextLine);
  23627. var isCaretAtStartOrEndOfTable = function (forward, rng, table) {
  23628. var caretPos = CaretPosition.fromRangeStart(rng);
  23629. return positionIn(!forward, table).exists(function (pos) {
  23630. return pos.isEqual(caretPos);
  23631. });
  23632. };
  23633. var navigateHorizontally = function (editor, forward, table, _td) {
  23634. var rng = editor.selection.getRng();
  23635. var direction = forward ? 1 : -1;
  23636. if (isFakeCaretTableBrowser() && isCaretAtStartOrEndOfTable(forward, rng, table)) {
  23637. showCaret(direction, editor, table, !forward, false).each(function (newRng) {
  23638. moveToRange(editor, newRng);
  23639. });
  23640. return true;
  23641. }
  23642. return false;
  23643. };
  23644. var getClosestAbovePosition = function (root, table, start) {
  23645. return findClosestPositionInAboveCell(table, start).orThunk(function () {
  23646. return head(start.getClientRects()).bind(function (rect) {
  23647. return findClosestHorizontalPositionFromPoint(getPositionsAbove(root, CaretPosition.before(table)), rect.left);
  23648. });
  23649. }).getOr(CaretPosition.before(table));
  23650. };
  23651. var getClosestBelowPosition = function (root, table, start) {
  23652. return findClosestPositionInBelowCell(table, start).orThunk(function () {
  23653. return head(start.getClientRects()).bind(function (rect) {
  23654. return findClosestHorizontalPositionFromPoint(getPositionsBelow(root, CaretPosition.after(table)), rect.left);
  23655. });
  23656. }).getOr(CaretPosition.after(table));
  23657. };
  23658. var getTable = function (previous, pos) {
  23659. var node = pos.getNode(previous);
  23660. return isElement$5(node) && node.nodeName === 'TABLE' ? Optional.some(node) : Optional.none();
  23661. };
  23662. var renderBlock = function (down, editor, table, pos) {
  23663. var forcedRootBlock = getForcedRootBlock(editor);
  23664. if (forcedRootBlock) {
  23665. editor.undoManager.transact(function () {
  23666. var element = SugarElement.fromTag(forcedRootBlock);
  23667. setAll$1(element, getForcedRootBlockAttrs(editor));
  23668. append$1(element, SugarElement.fromTag('br'));
  23669. if (down) {
  23670. after$3(SugarElement.fromDom(table), element);
  23671. } else {
  23672. before$4(SugarElement.fromDom(table), element);
  23673. }
  23674. var rng = editor.dom.createRng();
  23675. rng.setStart(element.dom, 0);
  23676. rng.setEnd(element.dom, 0);
  23677. moveToRange(editor, rng);
  23678. });
  23679. } else {
  23680. moveToRange(editor, pos.toRange());
  23681. }
  23682. };
  23683. var moveCaret = function (editor, down, pos) {
  23684. var table = down ? getTable(true, pos) : getTable(false, pos);
  23685. var last = down === false;
  23686. table.fold(function () {
  23687. return moveToRange(editor, pos.toRange());
  23688. }, function (table) {
  23689. return positionIn(last, editor.getBody()).filter(function (lastPos) {
  23690. return lastPos.isEqual(pos);
  23691. }).fold(function () {
  23692. return moveToRange(editor, pos.toRange());
  23693. }, function (_) {
  23694. return renderBlock(down, editor, table, pos);
  23695. });
  23696. });
  23697. };
  23698. var navigateVertically = function (editor, down, table, td) {
  23699. var rng = editor.selection.getRng();
  23700. var pos = CaretPosition.fromRangeStart(rng);
  23701. var root = editor.getBody();
  23702. if (!down && isAtFirstTableCellLine(td, pos)) {
  23703. var newPos = getClosestAbovePosition(root, table, pos);
  23704. moveCaret(editor, down, newPos);
  23705. return true;
  23706. } else if (down && isAtLastTableCellLine(td, pos)) {
  23707. var newPos = getClosestBelowPosition(root, table, pos);
  23708. moveCaret(editor, down, newPos);
  23709. return true;
  23710. } else {
  23711. return false;
  23712. }
  23713. };
  23714. var move$1 = function (editor, forward, mover) {
  23715. return Optional.from(editor.dom.getParent(editor.selection.getNode(), 'td,th')).bind(function (td) {
  23716. return Optional.from(editor.dom.getParent(td, 'table')).map(function (table) {
  23717. return mover(editor, forward, table, td);
  23718. });
  23719. }).getOr(false);
  23720. };
  23721. var moveH = function (editor, forward) {
  23722. return move$1(editor, forward, navigateHorizontally);
  23723. };
  23724. var moveV = function (editor, forward) {
  23725. return move$1(editor, forward, navigateVertically);
  23726. };
  23727. var executeKeydownOverride$3 = function (editor, caret, evt) {
  23728. var os = detect().os;
  23729. execute([
  23730. {
  23731. keyCode: VK.RIGHT,
  23732. action: action(moveH$2, editor, true)
  23733. },
  23734. {
  23735. keyCode: VK.LEFT,
  23736. action: action(moveH$2, editor, false)
  23737. },
  23738. {
  23739. keyCode: VK.UP,
  23740. action: action(moveV$3, editor, false)
  23741. },
  23742. {
  23743. keyCode: VK.DOWN,
  23744. action: action(moveV$3, editor, true)
  23745. },
  23746. {
  23747. keyCode: VK.RIGHT,
  23748. action: action(moveH, editor, true)
  23749. },
  23750. {
  23751. keyCode: VK.LEFT,
  23752. action: action(moveH, editor, false)
  23753. },
  23754. {
  23755. keyCode: VK.UP,
  23756. action: action(moveV, editor, false)
  23757. },
  23758. {
  23759. keyCode: VK.DOWN,
  23760. action: action(moveV, editor, true)
  23761. },
  23762. {
  23763. keyCode: VK.RIGHT,
  23764. action: action(moveH$1, editor, true)
  23765. },
  23766. {
  23767. keyCode: VK.LEFT,
  23768. action: action(moveH$1, editor, false)
  23769. },
  23770. {
  23771. keyCode: VK.UP,
  23772. action: action(moveV$1, editor, false)
  23773. },
  23774. {
  23775. keyCode: VK.DOWN,
  23776. action: action(moveV$1, editor, true)
  23777. },
  23778. {
  23779. keyCode: VK.RIGHT,
  23780. action: action(move$2, editor, caret, true)
  23781. },
  23782. {
  23783. keyCode: VK.LEFT,
  23784. action: action(move$2, editor, caret, false)
  23785. },
  23786. {
  23787. keyCode: VK.RIGHT,
  23788. ctrlKey: !os.isOSX(),
  23789. altKey: os.isOSX(),
  23790. action: action(moveNextWord, editor, caret)
  23791. },
  23792. {
  23793. keyCode: VK.LEFT,
  23794. ctrlKey: !os.isOSX(),
  23795. altKey: os.isOSX(),
  23796. action: action(movePrevWord, editor, caret)
  23797. },
  23798. {
  23799. keyCode: VK.UP,
  23800. action: action(moveV$2, editor, false)
  23801. },
  23802. {
  23803. keyCode: VK.DOWN,
  23804. action: action(moveV$2, editor, true)
  23805. }
  23806. ], evt).each(function (_) {
  23807. evt.preventDefault();
  23808. });
  23809. };
  23810. var setup$b = function (editor, caret) {
  23811. editor.on('keydown', function (evt) {
  23812. if (evt.isDefaultPrevented() === false) {
  23813. executeKeydownOverride$3(editor, caret, evt);
  23814. }
  23815. });
  23816. };
  23817. var executeKeydownOverride$2 = function (editor, caret, evt) {
  23818. execute([
  23819. {
  23820. keyCode: VK.BACKSPACE,
  23821. action: action(backspaceDelete, editor, false)
  23822. },
  23823. {
  23824. keyCode: VK.BACKSPACE,
  23825. action: action(backspaceDelete$5, editor, false)
  23826. },
  23827. {
  23828. keyCode: VK.DELETE,
  23829. action: action(backspaceDelete$5, editor, true)
  23830. },
  23831. {
  23832. keyCode: VK.BACKSPACE,
  23833. action: action(backspaceDelete$6, editor, false)
  23834. },
  23835. {
  23836. keyCode: VK.DELETE,
  23837. action: action(backspaceDelete$6, editor, true)
  23838. },
  23839. {
  23840. keyCode: VK.BACKSPACE,
  23841. action: action(backspaceDelete$3, editor, caret, false)
  23842. },
  23843. {
  23844. keyCode: VK.DELETE,
  23845. action: action(backspaceDelete$3, editor, caret, true)
  23846. },
  23847. {
  23848. keyCode: VK.BACKSPACE,
  23849. action: action(backspaceDelete$9, editor, false)
  23850. },
  23851. {
  23852. keyCode: VK.DELETE,
  23853. action: action(backspaceDelete$9, editor, true)
  23854. },
  23855. {
  23856. keyCode: VK.BACKSPACE,
  23857. action: action(backspaceDelete$4, editor, false)
  23858. },
  23859. {
  23860. keyCode: VK.DELETE,
  23861. action: action(backspaceDelete$4, editor, true)
  23862. },
  23863. {
  23864. keyCode: VK.BACKSPACE,
  23865. action: action(backspaceDelete$1, editor, false)
  23866. },
  23867. {
  23868. keyCode: VK.DELETE,
  23869. action: action(backspaceDelete$1, editor, true)
  23870. },
  23871. {
  23872. keyCode: VK.BACKSPACE,
  23873. action: action(backspaceDelete$7, editor, false)
  23874. },
  23875. {
  23876. keyCode: VK.DELETE,
  23877. action: action(backspaceDelete$7, editor, true)
  23878. },
  23879. {
  23880. keyCode: VK.BACKSPACE,
  23881. action: action(backspaceDelete$8, editor, false)
  23882. },
  23883. {
  23884. keyCode: VK.DELETE,
  23885. action: action(backspaceDelete$8, editor, true)
  23886. },
  23887. {
  23888. keyCode: VK.BACKSPACE,
  23889. action: action(backspaceDelete$2, editor, false)
  23890. },
  23891. {
  23892. keyCode: VK.DELETE,
  23893. action: action(backspaceDelete$2, editor, true)
  23894. }
  23895. ], evt).each(function (_) {
  23896. evt.preventDefault();
  23897. });
  23898. };
  23899. var executeKeyupOverride = function (editor, evt) {
  23900. execute([
  23901. {
  23902. keyCode: VK.BACKSPACE,
  23903. action: action(paddEmptyElement, editor)
  23904. },
  23905. {
  23906. keyCode: VK.DELETE,
  23907. action: action(paddEmptyElement, editor)
  23908. }
  23909. ], evt);
  23910. };
  23911. var setup$a = function (editor, caret) {
  23912. editor.on('keydown', function (evt) {
  23913. if (evt.isDefaultPrevented() === false) {
  23914. executeKeydownOverride$2(editor, caret, evt);
  23915. }
  23916. });
  23917. editor.on('keyup', function (evt) {
  23918. if (evt.isDefaultPrevented() === false) {
  23919. executeKeyupOverride(editor, evt);
  23920. }
  23921. });
  23922. };
  23923. var firstNonWhiteSpaceNodeSibling = function (node) {
  23924. while (node) {
  23925. if (node.nodeType === 1 || node.nodeType === 3 && node.data && /[\r\n\s]/.test(node.data)) {
  23926. return node;
  23927. }
  23928. node = node.nextSibling;
  23929. }
  23930. };
  23931. var moveToCaretPosition = function (editor, root) {
  23932. var node, lastNode = root;
  23933. var dom = editor.dom;
  23934. var moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
  23935. if (!root) {
  23936. return;
  23937. }
  23938. if (/^(LI|DT|DD)$/.test(root.nodeName)) {
  23939. var firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild);
  23940. if (firstChild && /^(UL|OL|DL)$/.test(firstChild.nodeName)) {
  23941. root.insertBefore(dom.doc.createTextNode(nbsp), root.firstChild);
  23942. }
  23943. }
  23944. var rng = dom.createRng();
  23945. root.normalize();
  23946. if (root.hasChildNodes()) {
  23947. var walker = new DomTreeWalker(root, root);
  23948. while (node = walker.current()) {
  23949. if (isText$7(node)) {
  23950. rng.setStart(node, 0);
  23951. rng.setEnd(node, 0);
  23952. break;
  23953. }
  23954. if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) {
  23955. rng.setStartBefore(node);
  23956. rng.setEndBefore(node);
  23957. break;
  23958. }
  23959. lastNode = node;
  23960. node = walker.next();
  23961. }
  23962. if (!node) {
  23963. rng.setStart(lastNode, 0);
  23964. rng.setEnd(lastNode, 0);
  23965. }
  23966. } else {
  23967. if (isBr$5(root)) {
  23968. if (root.nextSibling && dom.isBlock(root.nextSibling)) {
  23969. rng.setStartBefore(root);
  23970. rng.setEndBefore(root);
  23971. } else {
  23972. rng.setStartAfter(root);
  23973. rng.setEndAfter(root);
  23974. }
  23975. } else {
  23976. rng.setStart(root, 0);
  23977. rng.setEnd(root, 0);
  23978. }
  23979. }
  23980. editor.selection.setRng(rng);
  23981. scrollRangeIntoView(editor, rng);
  23982. };
  23983. var getEditableRoot$1 = function (dom, node) {
  23984. var root = dom.getRoot();
  23985. var parent, editableRoot;
  23986. parent = node;
  23987. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  23988. if (dom.getContentEditable(parent) === 'true') {
  23989. editableRoot = parent;
  23990. }
  23991. parent = parent.parentNode;
  23992. }
  23993. return parent !== root ? editableRoot : root;
  23994. };
  23995. var getParentBlock = function (editor) {
  23996. return Optional.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
  23997. };
  23998. var getParentBlockName = function (editor) {
  23999. return getParentBlock(editor).fold(constant(''), function (parentBlock) {
  24000. return parentBlock.nodeName.toUpperCase();
  24001. });
  24002. };
  24003. var isListItemParentBlock = function (editor) {
  24004. return getParentBlock(editor).filter(function (elm) {
  24005. return isListItem(SugarElement.fromDom(elm));
  24006. }).isSome();
  24007. };
  24008. var hasFirstChild = function (elm, name) {
  24009. return elm.firstChild && elm.firstChild.nodeName === name;
  24010. };
  24011. var isFirstChild = function (elm) {
  24012. var _a;
  24013. return ((_a = elm.parentNode) === null || _a === void 0 ? void 0 : _a.firstChild) === elm;
  24014. };
  24015. var hasParent = function (elm, parentName) {
  24016. return elm && elm.parentNode && elm.parentNode.nodeName === parentName;
  24017. };
  24018. var isListBlock = function (elm) {
  24019. return elm && /^(OL|UL|LI)$/.test(elm.nodeName);
  24020. };
  24021. var isNestedList = function (elm) {
  24022. return isListBlock(elm) && isListBlock(elm.parentNode);
  24023. };
  24024. var getContainerBlock = function (containerBlock) {
  24025. var containerBlockParent = containerBlock.parentNode;
  24026. if (/^(LI|DT|DD)$/.test(containerBlockParent.nodeName)) {
  24027. return containerBlockParent;
  24028. }
  24029. return containerBlock;
  24030. };
  24031. var isFirstOrLastLi = function (containerBlock, parentBlock, first) {
  24032. var node = containerBlock[first ? 'firstChild' : 'lastChild'];
  24033. while (node) {
  24034. if (isElement$5(node)) {
  24035. break;
  24036. }
  24037. node = node[first ? 'nextSibling' : 'previousSibling'];
  24038. }
  24039. return node === parentBlock;
  24040. };
  24041. var insert$3 = function (editor, createNewBlock, containerBlock, parentBlock, newBlockName) {
  24042. var dom = editor.dom;
  24043. var rng = editor.selection.getRng();
  24044. if (containerBlock === editor.getBody()) {
  24045. return;
  24046. }
  24047. if (isNestedList(containerBlock)) {
  24048. newBlockName = 'LI';
  24049. }
  24050. var newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR');
  24051. if (isFirstOrLastLi(containerBlock, parentBlock, true) && isFirstOrLastLi(containerBlock, parentBlock, false)) {
  24052. if (hasParent(containerBlock, 'LI')) {
  24053. var containerBlockParent = getContainerBlock(containerBlock);
  24054. dom.insertAfter(newBlock, containerBlockParent);
  24055. if (isFirstChild(containerBlock)) {
  24056. dom.remove(containerBlockParent);
  24057. } else {
  24058. dom.remove(containerBlock);
  24059. }
  24060. } else {
  24061. dom.replace(newBlock, containerBlock);
  24062. }
  24063. } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
  24064. if (hasParent(containerBlock, 'LI')) {
  24065. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  24066. newBlock.appendChild(dom.doc.createTextNode(' '));
  24067. newBlock.appendChild(containerBlock);
  24068. } else {
  24069. containerBlock.parentNode.insertBefore(newBlock, containerBlock);
  24070. }
  24071. dom.remove(parentBlock);
  24072. } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
  24073. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  24074. dom.remove(parentBlock);
  24075. } else {
  24076. containerBlock = getContainerBlock(containerBlock);
  24077. var tmpRng = rng.cloneRange();
  24078. tmpRng.setStartAfter(parentBlock);
  24079. tmpRng.setEndAfter(containerBlock);
  24080. var fragment = tmpRng.extractContents();
  24081. if (newBlockName === 'LI' && hasFirstChild(fragment, 'LI')) {
  24082. newBlock = fragment.firstChild;
  24083. dom.insertAfter(fragment, containerBlock);
  24084. } else {
  24085. dom.insertAfter(fragment, containerBlock);
  24086. dom.insertAfter(newBlock, containerBlock);
  24087. }
  24088. dom.remove(parentBlock);
  24089. }
  24090. moveToCaretPosition(editor, newBlock);
  24091. };
  24092. var trimZwsp = function (fragment) {
  24093. each$k(descendants$1(SugarElement.fromDom(fragment), isText$8), function (text) {
  24094. var rawNode = text.dom;
  24095. rawNode.nodeValue = trim$2(rawNode.nodeValue);
  24096. });
  24097. };
  24098. var isEmptyAnchor = function (dom, elm) {
  24099. return elm && elm.nodeName === 'A' && dom.isEmpty(elm);
  24100. };
  24101. var isTableCell = function (node) {
  24102. return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  24103. };
  24104. var emptyBlock = function (elm) {
  24105. elm.innerHTML = '<br data-mce-bogus="1">';
  24106. };
  24107. var containerAndSiblingName = function (container, nodeName) {
  24108. return container.nodeName === nodeName || container.previousSibling && container.previousSibling.nodeName === nodeName;
  24109. };
  24110. var canSplitBlock = function (dom, node) {
  24111. return node && dom.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.getContentEditable(node) !== 'true';
  24112. };
  24113. var trimInlineElementsOnLeftSideOfBlock = function (dom, nonEmptyElementsMap, block) {
  24114. var node = block;
  24115. var firstChilds = [];
  24116. var i;
  24117. if (!node) {
  24118. return;
  24119. }
  24120. while (node = node.firstChild) {
  24121. if (dom.isBlock(node)) {
  24122. return;
  24123. }
  24124. if (isElement$5(node) && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  24125. firstChilds.push(node);
  24126. }
  24127. }
  24128. i = firstChilds.length;
  24129. while (i--) {
  24130. node = firstChilds[i];
  24131. if (!node.hasChildNodes() || node.firstChild === node.lastChild && node.firstChild.nodeValue === '') {
  24132. dom.remove(node);
  24133. } else {
  24134. if (isEmptyAnchor(dom, node)) {
  24135. dom.remove(node);
  24136. }
  24137. }
  24138. }
  24139. };
  24140. var normalizeZwspOffset = function (start, container, offset) {
  24141. if (isText$7(container) === false) {
  24142. return offset;
  24143. } else if (start) {
  24144. return offset === 1 && container.data.charAt(offset - 1) === ZWSP$1 ? 0 : offset;
  24145. } else {
  24146. return offset === container.data.length - 1 && container.data.charAt(offset) === ZWSP$1 ? container.data.length : offset;
  24147. }
  24148. };
  24149. var includeZwspInRange = function (rng) {
  24150. var newRng = rng.cloneRange();
  24151. newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
  24152. newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
  24153. return newRng;
  24154. };
  24155. var trimLeadingLineBreaks = function (node) {
  24156. do {
  24157. if (isText$7(node)) {
  24158. node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
  24159. }
  24160. node = node.firstChild;
  24161. } while (node);
  24162. };
  24163. var getEditableRoot = function (dom, node) {
  24164. var root = dom.getRoot();
  24165. var parent, editableRoot;
  24166. parent = node;
  24167. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  24168. if (dom.getContentEditable(parent) === 'true') {
  24169. editableRoot = parent;
  24170. }
  24171. parent = parent.parentNode;
  24172. }
  24173. return parent !== root ? editableRoot : root;
  24174. };
  24175. var applyAttributes = function (editor, node, forcedRootBlockAttrs) {
  24176. var dom = editor.dom;
  24177. Optional.from(forcedRootBlockAttrs.style).map(dom.parseStyle).each(function (attrStyles) {
  24178. var currentStyles = getAllRaw(SugarElement.fromDom(node));
  24179. var newStyles = __assign(__assign({}, currentStyles), attrStyles);
  24180. dom.setStyles(node, newStyles);
  24181. });
  24182. var attrClassesOpt = Optional.from(forcedRootBlockAttrs.class).map(function (attrClasses) {
  24183. return attrClasses.split(/\s+/);
  24184. });
  24185. var currentClassesOpt = Optional.from(node.className).map(function (currentClasses) {
  24186. return filter$4(currentClasses.split(/\s+/), function (clazz) {
  24187. return clazz !== '';
  24188. });
  24189. });
  24190. lift2(attrClassesOpt, currentClassesOpt, function (attrClasses, currentClasses) {
  24191. var filteredClasses = filter$4(currentClasses, function (clazz) {
  24192. return !contains$3(attrClasses, clazz);
  24193. });
  24194. var newClasses = __spreadArray(__spreadArray([], attrClasses, true), filteredClasses, true);
  24195. dom.setAttrib(node, 'class', newClasses.join(' '));
  24196. });
  24197. var appliedAttrs = [
  24198. 'style',
  24199. 'class'
  24200. ];
  24201. var remainingAttrs = filter$3(forcedRootBlockAttrs, function (_, attrs) {
  24202. return !contains$3(appliedAttrs, attrs);
  24203. });
  24204. dom.setAttribs(node, remainingAttrs);
  24205. };
  24206. var setForcedBlockAttrs = function (editor, node) {
  24207. var forcedRootBlockName = getForcedRootBlock(editor);
  24208. if (forcedRootBlockName && forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
  24209. var forcedRootBlockAttrs = getForcedRootBlockAttrs(editor);
  24210. applyAttributes(editor, node, forcedRootBlockAttrs);
  24211. }
  24212. };
  24213. var wrapSelfAndSiblingsInDefaultBlock = function (editor, newBlockName, rng, container, offset) {
  24214. var newBlock, parentBlock, startNode, node, next, rootBlockName;
  24215. var blockName = newBlockName || 'P';
  24216. var dom = editor.dom, editableRoot = getEditableRoot(dom, container);
  24217. parentBlock = dom.getParent(container, dom.isBlock);
  24218. if (!parentBlock || !canSplitBlock(dom, parentBlock)) {
  24219. parentBlock = parentBlock || editableRoot;
  24220. if (parentBlock === editor.getBody() || isTableCell(parentBlock)) {
  24221. rootBlockName = parentBlock.nodeName.toLowerCase();
  24222. } else {
  24223. rootBlockName = parentBlock.parentNode.nodeName.toLowerCase();
  24224. }
  24225. if (!parentBlock.hasChildNodes()) {
  24226. newBlock = dom.create(blockName);
  24227. setForcedBlockAttrs(editor, newBlock);
  24228. parentBlock.appendChild(newBlock);
  24229. rng.setStart(newBlock, 0);
  24230. rng.setEnd(newBlock, 0);
  24231. return newBlock;
  24232. }
  24233. node = container;
  24234. while (node.parentNode !== parentBlock) {
  24235. node = node.parentNode;
  24236. }
  24237. while (node && !dom.isBlock(node)) {
  24238. startNode = node;
  24239. node = node.previousSibling;
  24240. }
  24241. if (startNode && editor.schema.isValidChild(rootBlockName, blockName.toLowerCase())) {
  24242. newBlock = dom.create(blockName);
  24243. setForcedBlockAttrs(editor, newBlock);
  24244. startNode.parentNode.insertBefore(newBlock, startNode);
  24245. node = startNode;
  24246. while (node && !dom.isBlock(node)) {
  24247. next = node.nextSibling;
  24248. newBlock.appendChild(node);
  24249. node = next;
  24250. }
  24251. rng.setStart(container, offset);
  24252. rng.setEnd(container, offset);
  24253. }
  24254. }
  24255. return container;
  24256. };
  24257. var addBrToBlockIfNeeded = function (dom, block) {
  24258. block.normalize();
  24259. var lastChild = block.lastChild;
  24260. if (!lastChild || /^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true))) {
  24261. dom.add(block, 'br');
  24262. }
  24263. };
  24264. var insert$2 = function (editor, evt) {
  24265. var tmpRng, container, offset, parentBlock;
  24266. var newBlock, fragment, containerBlock, parentBlockName, newBlockName, isAfterLastNodeInContainer;
  24267. var dom = editor.dom;
  24268. var schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
  24269. var rng = editor.selection.getRng();
  24270. var createNewBlock = function (name) {
  24271. var node = container, block, clonedNode, caretNode;
  24272. var textInlineElements = schema.getTextInlineElements();
  24273. if (name || parentBlockName === 'TABLE' || parentBlockName === 'HR') {
  24274. block = dom.create(name || newBlockName);
  24275. } else {
  24276. block = parentBlock.cloneNode(false);
  24277. }
  24278. caretNode = block;
  24279. if (shouldKeepStyles(editor) === false) {
  24280. dom.setAttrib(block, 'style', null);
  24281. dom.setAttrib(block, 'class', null);
  24282. } else {
  24283. do {
  24284. if (textInlineElements[node.nodeName]) {
  24285. if (isCaretNode(node) || isBookmarkNode$1(node)) {
  24286. continue;
  24287. }
  24288. clonedNode = node.cloneNode(false);
  24289. dom.setAttrib(clonedNode, 'id', '');
  24290. if (block.hasChildNodes()) {
  24291. clonedNode.appendChild(block.firstChild);
  24292. block.appendChild(clonedNode);
  24293. } else {
  24294. caretNode = clonedNode;
  24295. block.appendChild(clonedNode);
  24296. }
  24297. }
  24298. } while ((node = node.parentNode) && node !== editableRoot);
  24299. }
  24300. setForcedBlockAttrs(editor, block);
  24301. emptyBlock(caretNode);
  24302. return block;
  24303. };
  24304. var isCaretAtStartOrEndOfBlock = function (start) {
  24305. var node, name;
  24306. var normalizedOffset = normalizeZwspOffset(start, container, offset);
  24307. if (isText$7(container) && (start ? normalizedOffset > 0 : normalizedOffset < container.nodeValue.length)) {
  24308. return false;
  24309. }
  24310. if (container.parentNode === parentBlock && isAfterLastNodeInContainer && !start) {
  24311. return true;
  24312. }
  24313. if (start && isElement$5(container) && container === parentBlock.firstChild) {
  24314. return true;
  24315. }
  24316. if (containerAndSiblingName(container, 'TABLE') || containerAndSiblingName(container, 'HR')) {
  24317. return isAfterLastNodeInContainer && !start || !isAfterLastNodeInContainer && start;
  24318. }
  24319. var walker = new DomTreeWalker(container, parentBlock);
  24320. if (isText$7(container)) {
  24321. if (start && normalizedOffset === 0) {
  24322. walker.prev();
  24323. } else if (!start && normalizedOffset === container.nodeValue.length) {
  24324. walker.next();
  24325. }
  24326. }
  24327. while (node = walker.current()) {
  24328. if (isElement$5(node)) {
  24329. if (!node.getAttribute('data-mce-bogus')) {
  24330. name = node.nodeName.toLowerCase();
  24331. if (nonEmptyElementsMap[name] && name !== 'br') {
  24332. return false;
  24333. }
  24334. }
  24335. } else if (isText$7(node) && !isWhitespaceText(node.nodeValue)) {
  24336. return false;
  24337. }
  24338. if (start) {
  24339. walker.prev();
  24340. } else {
  24341. walker.next();
  24342. }
  24343. }
  24344. return true;
  24345. };
  24346. var insertNewBlockAfter = function () {
  24347. if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName !== 'HGROUP') {
  24348. newBlock = createNewBlock(newBlockName);
  24349. } else {
  24350. newBlock = createNewBlock();
  24351. }
  24352. if (shouldEndContainerOnEmptyBlock(editor) && canSplitBlock(dom, containerBlock) && dom.isEmpty(parentBlock)) {
  24353. newBlock = dom.split(containerBlock, parentBlock);
  24354. } else {
  24355. dom.insertAfter(newBlock, parentBlock);
  24356. }
  24357. moveToCaretPosition(editor, newBlock);
  24358. };
  24359. normalize$2(dom, rng).each(function (normRng) {
  24360. rng.setStart(normRng.startContainer, normRng.startOffset);
  24361. rng.setEnd(normRng.endContainer, normRng.endOffset);
  24362. });
  24363. container = rng.startContainer;
  24364. offset = rng.startOffset;
  24365. newBlockName = getForcedRootBlock(editor);
  24366. var shiftKey = !!(evt && evt.shiftKey);
  24367. var ctrlKey = !!(evt && evt.ctrlKey);
  24368. if (isElement$5(container) && container.hasChildNodes()) {
  24369. isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  24370. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  24371. if (isAfterLastNodeInContainer && isText$7(container)) {
  24372. offset = container.nodeValue.length;
  24373. } else {
  24374. offset = 0;
  24375. }
  24376. }
  24377. var editableRoot = getEditableRoot(dom, container);
  24378. if (!editableRoot) {
  24379. return;
  24380. }
  24381. if (newBlockName && !shiftKey || !newBlockName && shiftKey) {
  24382. container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset);
  24383. }
  24384. parentBlock = dom.getParent(container, dom.isBlock);
  24385. containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  24386. parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : '';
  24387. var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  24388. if (containerBlockName === 'LI' && !ctrlKey) {
  24389. parentBlock = containerBlock;
  24390. containerBlock = containerBlock.parentNode;
  24391. parentBlockName = containerBlockName;
  24392. }
  24393. if (/^(LI|DT|DD)$/.test(parentBlockName)) {
  24394. if (dom.isEmpty(parentBlock)) {
  24395. insert$3(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
  24396. return;
  24397. }
  24398. }
  24399. if (newBlockName && parentBlock === editor.getBody()) {
  24400. return;
  24401. }
  24402. newBlockName = newBlockName || 'P';
  24403. if (isCaretContainerBlock$1(parentBlock)) {
  24404. newBlock = showCaretContainerBlock(parentBlock);
  24405. if (dom.isEmpty(parentBlock)) {
  24406. emptyBlock(parentBlock);
  24407. }
  24408. setForcedBlockAttrs(editor, newBlock);
  24409. moveToCaretPosition(editor, newBlock);
  24410. } else if (isCaretAtStartOrEndOfBlock()) {
  24411. insertNewBlockAfter();
  24412. } else if (isCaretAtStartOrEndOfBlock(true)) {
  24413. newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
  24414. moveToCaretPosition(editor, containerAndSiblingName(parentBlock, 'HR') ? newBlock : parentBlock);
  24415. } else {
  24416. tmpRng = includeZwspInRange(rng).cloneRange();
  24417. tmpRng.setEndAfter(parentBlock);
  24418. fragment = tmpRng.extractContents();
  24419. trimZwsp(fragment);
  24420. trimLeadingLineBreaks(fragment);
  24421. newBlock = fragment.firstChild;
  24422. dom.insertAfter(fragment, parentBlock);
  24423. trimInlineElementsOnLeftSideOfBlock(dom, nonEmptyElementsMap, newBlock);
  24424. addBrToBlockIfNeeded(dom, parentBlock);
  24425. if (dom.isEmpty(parentBlock)) {
  24426. emptyBlock(parentBlock);
  24427. }
  24428. newBlock.normalize();
  24429. if (dom.isEmpty(newBlock)) {
  24430. dom.remove(newBlock);
  24431. insertNewBlockAfter();
  24432. } else {
  24433. setForcedBlockAttrs(editor, newBlock);
  24434. moveToCaretPosition(editor, newBlock);
  24435. }
  24436. }
  24437. dom.setAttrib(newBlock, 'id', '');
  24438. editor.fire('NewBlock', { newBlock: newBlock });
  24439. };
  24440. var hasRightSideContent = function (schema, container, parentBlock) {
  24441. var walker = new DomTreeWalker(container, parentBlock);
  24442. var node;
  24443. var nonEmptyElementsMap = schema.getNonEmptyElements();
  24444. while (node = walker.next()) {
  24445. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
  24446. return true;
  24447. }
  24448. }
  24449. };
  24450. var moveSelectionToBr = function (editor, brElm, extraBr) {
  24451. var rng = editor.dom.createRng();
  24452. if (!extraBr) {
  24453. rng.setStartAfter(brElm);
  24454. rng.setEndAfter(brElm);
  24455. } else {
  24456. rng.setStartBefore(brElm);
  24457. rng.setEndBefore(brElm);
  24458. }
  24459. editor.selection.setRng(rng);
  24460. scrollRangeIntoView(editor, rng);
  24461. };
  24462. var insertBrAtCaret = function (editor, evt) {
  24463. var selection = editor.selection;
  24464. var dom = editor.dom;
  24465. var rng = selection.getRng();
  24466. var brElm;
  24467. var extraBr;
  24468. normalize$2(dom, rng).each(function (normRng) {
  24469. rng.setStart(normRng.startContainer, normRng.startOffset);
  24470. rng.setEnd(normRng.endContainer, normRng.endOffset);
  24471. });
  24472. var offset = rng.startOffset;
  24473. var container = rng.startContainer;
  24474. if (container.nodeType === 1 && container.hasChildNodes()) {
  24475. var isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  24476. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  24477. if (isAfterLastNodeInContainer && container.nodeType === 3) {
  24478. offset = container.nodeValue.length;
  24479. } else {
  24480. offset = 0;
  24481. }
  24482. }
  24483. var parentBlock = dom.getParent(container, dom.isBlock);
  24484. var containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  24485. var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  24486. var isControlKey = !!(evt && evt.ctrlKey);
  24487. if (containerBlockName === 'LI' && !isControlKey) {
  24488. parentBlock = containerBlock;
  24489. }
  24490. if (container && container.nodeType === 3 && offset >= container.nodeValue.length) {
  24491. if (!hasRightSideContent(editor.schema, container, parentBlock)) {
  24492. brElm = dom.create('br');
  24493. rng.insertNode(brElm);
  24494. rng.setStartAfter(brElm);
  24495. rng.setEndAfter(brElm);
  24496. extraBr = true;
  24497. }
  24498. }
  24499. brElm = dom.create('br');
  24500. rangeInsertNode(dom, rng, brElm);
  24501. moveSelectionToBr(editor, brElm, extraBr);
  24502. editor.undoManager.add();
  24503. };
  24504. var insertBrBefore = function (editor, inline) {
  24505. var br = SugarElement.fromTag('br');
  24506. before$4(SugarElement.fromDom(inline), br);
  24507. editor.undoManager.add();
  24508. };
  24509. var insertBrAfter = function (editor, inline) {
  24510. if (!hasBrAfter(editor.getBody(), inline)) {
  24511. after$3(SugarElement.fromDom(inline), SugarElement.fromTag('br'));
  24512. }
  24513. var br = SugarElement.fromTag('br');
  24514. after$3(SugarElement.fromDom(inline), br);
  24515. moveSelectionToBr(editor, br.dom, false);
  24516. editor.undoManager.add();
  24517. };
  24518. var isBeforeBr = function (pos) {
  24519. return isBr$5(pos.getNode());
  24520. };
  24521. var hasBrAfter = function (rootNode, startNode) {
  24522. if (isBeforeBr(CaretPosition.after(startNode))) {
  24523. return true;
  24524. } else {
  24525. return nextPosition(rootNode, CaretPosition.after(startNode)).map(function (pos) {
  24526. return isBr$5(pos.getNode());
  24527. }).getOr(false);
  24528. }
  24529. };
  24530. var isAnchorLink = function (elm) {
  24531. return elm && elm.nodeName === 'A' && 'href' in elm;
  24532. };
  24533. var isInsideAnchor = function (location) {
  24534. return location.fold(never, isAnchorLink, isAnchorLink, never);
  24535. };
  24536. var readInlineAnchorLocation = function (editor) {
  24537. var isInlineTarget$1 = curry(isInlineTarget, editor);
  24538. var position = CaretPosition.fromRangeStart(editor.selection.getRng());
  24539. return readLocation(isInlineTarget$1, editor.getBody(), position).filter(isInsideAnchor);
  24540. };
  24541. var insertBrOutsideAnchor = function (editor, location) {
  24542. location.fold(noop, curry(insertBrBefore, editor), curry(insertBrAfter, editor), noop);
  24543. };
  24544. var insert$1 = function (editor, evt) {
  24545. var anchorLocation = readInlineAnchorLocation(editor);
  24546. if (anchorLocation.isSome()) {
  24547. anchorLocation.each(curry(insertBrOutsideAnchor, editor));
  24548. } else {
  24549. insertBrAtCaret(editor, evt);
  24550. }
  24551. };
  24552. var matchesSelector = function (editor, selector) {
  24553. return getParentBlock(editor).filter(function (parentBlock) {
  24554. return selector.length > 0 && is$2(SugarElement.fromDom(parentBlock), selector);
  24555. }).isSome();
  24556. };
  24557. var shouldInsertBr = function (editor) {
  24558. return matchesSelector(editor, getBrNewLineSelector(editor));
  24559. };
  24560. var shouldBlockNewLine$1 = function (editor) {
  24561. return matchesSelector(editor, getNoNewLineSelector(editor));
  24562. };
  24563. var newLineAction = Adt.generate([
  24564. { br: [] },
  24565. { block: [] },
  24566. { none: [] }
  24567. ]);
  24568. var shouldBlockNewLine = function (editor, _shiftKey) {
  24569. return shouldBlockNewLine$1(editor);
  24570. };
  24571. var isBrMode = function (requiredState) {
  24572. return function (editor, _shiftKey) {
  24573. var brMode = getForcedRootBlock(editor) === '';
  24574. return brMode === requiredState;
  24575. };
  24576. };
  24577. var inListBlock = function (requiredState) {
  24578. return function (editor, _shiftKey) {
  24579. return isListItemParentBlock(editor) === requiredState;
  24580. };
  24581. };
  24582. var inBlock = function (blockName, requiredState) {
  24583. return function (editor, _shiftKey) {
  24584. var state = getParentBlockName(editor) === blockName.toUpperCase();
  24585. return state === requiredState;
  24586. };
  24587. };
  24588. var inPreBlock = function (requiredState) {
  24589. return inBlock('pre', requiredState);
  24590. };
  24591. var inSummaryBlock = function () {
  24592. return inBlock('summary', true);
  24593. };
  24594. var shouldPutBrInPre = function (requiredState) {
  24595. return function (editor, _shiftKey) {
  24596. return shouldPutBrInPre$1(editor) === requiredState;
  24597. };
  24598. };
  24599. var inBrContext = function (editor, _shiftKey) {
  24600. return shouldInsertBr(editor);
  24601. };
  24602. var hasShiftKey = function (_editor, shiftKey) {
  24603. return shiftKey;
  24604. };
  24605. var canInsertIntoEditableRoot = function (editor) {
  24606. var forcedRootBlock = getForcedRootBlock(editor);
  24607. var rootEditable = getEditableRoot$1(editor.dom, editor.selection.getStart());
  24608. return rootEditable && editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock ? forcedRootBlock : 'P');
  24609. };
  24610. var match = function (predicates, action) {
  24611. return function (editor, shiftKey) {
  24612. var isMatch = foldl(predicates, function (res, p) {
  24613. return res && p(editor, shiftKey);
  24614. }, true);
  24615. return isMatch ? Optional.some(action) : Optional.none();
  24616. };
  24617. };
  24618. var getAction = function (editor, evt) {
  24619. return evaluateUntil([
  24620. match([shouldBlockNewLine], newLineAction.none()),
  24621. match([inSummaryBlock()], newLineAction.br()),
  24622. match([
  24623. inPreBlock(true),
  24624. shouldPutBrInPre(false),
  24625. hasShiftKey
  24626. ], newLineAction.br()),
  24627. match([
  24628. inPreBlock(true),
  24629. shouldPutBrInPre(false)
  24630. ], newLineAction.block()),
  24631. match([
  24632. inPreBlock(true),
  24633. shouldPutBrInPre(true),
  24634. hasShiftKey
  24635. ], newLineAction.block()),
  24636. match([
  24637. inPreBlock(true),
  24638. shouldPutBrInPre(true)
  24639. ], newLineAction.br()),
  24640. match([
  24641. inListBlock(true),
  24642. hasShiftKey
  24643. ], newLineAction.br()),
  24644. match([inListBlock(true)], newLineAction.block()),
  24645. match([
  24646. isBrMode(true),
  24647. hasShiftKey,
  24648. canInsertIntoEditableRoot
  24649. ], newLineAction.block()),
  24650. match([isBrMode(true)], newLineAction.br()),
  24651. match([inBrContext], newLineAction.br()),
  24652. match([
  24653. isBrMode(false),
  24654. hasShiftKey
  24655. ], newLineAction.br()),
  24656. match([canInsertIntoEditableRoot], newLineAction.block())
  24657. ], [
  24658. editor,
  24659. !!(evt && evt.shiftKey)
  24660. ]).getOr(newLineAction.none());
  24661. };
  24662. var insert = function (editor, evt) {
  24663. getAction(editor, evt).fold(function () {
  24664. insert$1(editor, evt);
  24665. }, function () {
  24666. insert$2(editor, evt);
  24667. }, noop);
  24668. };
  24669. var handleEnterKeyEvent = function (editor, event) {
  24670. if (event.isDefaultPrevented()) {
  24671. return;
  24672. }
  24673. event.preventDefault();
  24674. endTypingLevelIgnoreLocks(editor.undoManager);
  24675. editor.undoManager.transact(function () {
  24676. if (editor.selection.isCollapsed() === false) {
  24677. editor.execCommand('Delete');
  24678. }
  24679. insert(editor, event);
  24680. });
  24681. };
  24682. var setup$9 = function (editor) {
  24683. editor.on('keydown', function (event) {
  24684. if (event.keyCode === VK.ENTER) {
  24685. handleEnterKeyEvent(editor, event);
  24686. }
  24687. });
  24688. };
  24689. var executeKeydownOverride$1 = function (editor, caret, evt) {
  24690. execute([
  24691. {
  24692. keyCode: VK.END,
  24693. action: action(moveToLineEndPoint$1, editor, true)
  24694. },
  24695. {
  24696. keyCode: VK.HOME,
  24697. action: action(moveToLineEndPoint$1, editor, false)
  24698. },
  24699. {
  24700. keyCode: VK.END,
  24701. action: action(moveToLineEndPoint, editor, true)
  24702. },
  24703. {
  24704. keyCode: VK.HOME,
  24705. action: action(moveToLineEndPoint, editor, false)
  24706. },
  24707. {
  24708. keyCode: VK.END,
  24709. action: action(moveToLineEndPoint$2, editor, true, caret)
  24710. },
  24711. {
  24712. keyCode: VK.HOME,
  24713. action: action(moveToLineEndPoint$2, editor, false, caret)
  24714. }
  24715. ], evt).each(function (_) {
  24716. evt.preventDefault();
  24717. });
  24718. };
  24719. var setup$8 = function (editor, caret) {
  24720. editor.on('keydown', function (evt) {
  24721. if (evt.isDefaultPrevented() === false) {
  24722. executeKeydownOverride$1(editor, caret, evt);
  24723. }
  24724. });
  24725. };
  24726. var browser = detect().browser;
  24727. var setupIeInput = function (editor) {
  24728. var keypressThrotter = first(function () {
  24729. if (!editor.composing) {
  24730. normalizeNbspsInEditor(editor);
  24731. }
  24732. }, 0);
  24733. if (browser.isIE()) {
  24734. editor.on('keypress', function (_e) {
  24735. keypressThrotter.throttle();
  24736. });
  24737. editor.on('remove', function (_e) {
  24738. keypressThrotter.cancel();
  24739. });
  24740. }
  24741. };
  24742. var setup$7 = function (editor) {
  24743. setupIeInput(editor);
  24744. editor.on('input', function (e) {
  24745. if (e.isComposing === false) {
  24746. normalizeNbspsInEditor(editor);
  24747. }
  24748. });
  24749. };
  24750. var platform = detect();
  24751. var executeKeyupAction = function (editor, caret, evt) {
  24752. execute([
  24753. {
  24754. keyCode: VK.PAGE_UP,
  24755. action: action(moveToLineEndPoint$2, editor, false, caret)
  24756. },
  24757. {
  24758. keyCode: VK.PAGE_DOWN,
  24759. action: action(moveToLineEndPoint$2, editor, true, caret)
  24760. }
  24761. ], evt);
  24762. };
  24763. var stopImmediatePropagation = function (e) {
  24764. return e.stopImmediatePropagation();
  24765. };
  24766. var isPageUpDown = function (evt) {
  24767. return evt.keyCode === VK.PAGE_UP || evt.keyCode === VK.PAGE_DOWN;
  24768. };
  24769. var setNodeChangeBlocker = function (blocked, editor, block) {
  24770. if (block && !blocked.get()) {
  24771. editor.on('NodeChange', stopImmediatePropagation, true);
  24772. } else if (!block && blocked.get()) {
  24773. editor.off('NodeChange', stopImmediatePropagation);
  24774. }
  24775. blocked.set(block);
  24776. };
  24777. var setup$6 = function (editor, caret) {
  24778. if (platform.os.isOSX()) {
  24779. return;
  24780. }
  24781. var blocked = Cell(false);
  24782. editor.on('keydown', function (evt) {
  24783. if (isPageUpDown(evt)) {
  24784. setNodeChangeBlocker(blocked, editor, true);
  24785. }
  24786. });
  24787. editor.on('keyup', function (evt) {
  24788. if (evt.isDefaultPrevented() === false) {
  24789. executeKeyupAction(editor, caret, evt);
  24790. }
  24791. if (isPageUpDown(evt) && blocked.get()) {
  24792. setNodeChangeBlocker(blocked, editor, false);
  24793. editor.nodeChanged();
  24794. }
  24795. });
  24796. };
  24797. var insertTextAtPosition = function (text, pos) {
  24798. var container = pos.container();
  24799. var offset = pos.offset();
  24800. if (isText$7(container)) {
  24801. container.insertData(offset, text);
  24802. return Optional.some(CaretPosition(container, offset + text.length));
  24803. } else {
  24804. return getElementFromPosition(pos).map(function (elm) {
  24805. var textNode = SugarElement.fromText(text);
  24806. if (pos.isAtEnd()) {
  24807. after$3(elm, textNode);
  24808. } else {
  24809. before$4(elm, textNode);
  24810. }
  24811. return CaretPosition(textNode.dom, text.length);
  24812. });
  24813. }
  24814. };
  24815. var insertNbspAtPosition = curry(insertTextAtPosition, nbsp);
  24816. var insertSpaceAtPosition = curry(insertTextAtPosition, ' ');
  24817. var locationToCaretPosition = function (root) {
  24818. return function (location) {
  24819. return location.fold(function (element) {
  24820. return prevPosition(root.dom, CaretPosition.before(element));
  24821. }, function (element) {
  24822. return firstPositionIn(element);
  24823. }, function (element) {
  24824. return lastPositionIn(element);
  24825. }, function (element) {
  24826. return nextPosition(root.dom, CaretPosition.after(element));
  24827. });
  24828. };
  24829. };
  24830. var insertInlineBoundarySpaceOrNbsp = function (root, pos) {
  24831. return function (checkPos) {
  24832. return needsToHaveNbsp(root, checkPos) ? insertNbspAtPosition(pos) : insertSpaceAtPosition(pos);
  24833. };
  24834. };
  24835. var setSelection = function (editor) {
  24836. return function (pos) {
  24837. editor.selection.setRng(pos.toRange());
  24838. editor.nodeChanged();
  24839. return true;
  24840. };
  24841. };
  24842. var insertSpaceOrNbspAtSelection = function (editor) {
  24843. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  24844. var root = SugarElement.fromDom(editor.getBody());
  24845. if (editor.selection.isCollapsed()) {
  24846. var isInlineTarget$1 = curry(isInlineTarget, editor);
  24847. var caretPosition = CaretPosition.fromRangeStart(editor.selection.getRng());
  24848. return readLocation(isInlineTarget$1, editor.getBody(), caretPosition).bind(locationToCaretPosition(root)).bind(insertInlineBoundarySpaceOrNbsp(root, pos)).exists(setSelection(editor));
  24849. } else {
  24850. return false;
  24851. }
  24852. };
  24853. var executeKeydownOverride = function (editor, evt) {
  24854. execute([{
  24855. keyCode: VK.SPACEBAR,
  24856. action: action(insertSpaceOrNbspAtSelection, editor)
  24857. }], evt).each(function (_) {
  24858. evt.preventDefault();
  24859. });
  24860. };
  24861. var setup$5 = function (editor) {
  24862. editor.on('keydown', function (evt) {
  24863. if (evt.isDefaultPrevented() === false) {
  24864. executeKeydownOverride(editor, evt);
  24865. }
  24866. });
  24867. };
  24868. var registerKeyboardOverrides = function (editor) {
  24869. var caret = setupSelectedState(editor);
  24870. setup$c(editor);
  24871. setup$b(editor, caret);
  24872. setup$a(editor, caret);
  24873. setup$9(editor);
  24874. setup$5(editor);
  24875. setup$7(editor);
  24876. setup$8(editor, caret);
  24877. setup$6(editor, caret);
  24878. return caret;
  24879. };
  24880. var setup$4 = function (editor) {
  24881. if (!isRtc(editor)) {
  24882. return registerKeyboardOverrides(editor);
  24883. } else {
  24884. return Cell(null);
  24885. }
  24886. };
  24887. var NodeChange = function () {
  24888. function NodeChange(editor) {
  24889. this.lastPath = [];
  24890. this.editor = editor;
  24891. var lastRng;
  24892. var self = this;
  24893. if (!('onselectionchange' in editor.getDoc())) {
  24894. editor.on('NodeChange click mouseup keyup focus', function (e) {
  24895. var nativeRng = editor.selection.getRng();
  24896. var fakeRng = {
  24897. startContainer: nativeRng.startContainer,
  24898. startOffset: nativeRng.startOffset,
  24899. endContainer: nativeRng.endContainer,
  24900. endOffset: nativeRng.endOffset
  24901. };
  24902. if (e.type === 'nodechange' || !isEq$4(fakeRng, lastRng)) {
  24903. editor.fire('SelectionChange');
  24904. }
  24905. lastRng = fakeRng;
  24906. });
  24907. }
  24908. editor.on('contextmenu', function () {
  24909. editor.fire('SelectionChange');
  24910. });
  24911. editor.on('SelectionChange', function () {
  24912. var startElm = editor.selection.getStart(true);
  24913. if (!startElm || !Env.range && editor.selection.isCollapsed()) {
  24914. return;
  24915. }
  24916. if (hasAnyRanges(editor) && !self.isSameElementPath(startElm) && editor.dom.isChildOf(startElm, editor.getBody())) {
  24917. editor.nodeChanged({ selectionChange: true });
  24918. }
  24919. });
  24920. editor.on('mouseup', function (e) {
  24921. if (!e.isDefaultPrevented() && hasAnyRanges(editor)) {
  24922. if (editor.selection.getNode().nodeName === 'IMG') {
  24923. Delay.setEditorTimeout(editor, function () {
  24924. editor.nodeChanged();
  24925. });
  24926. } else {
  24927. editor.nodeChanged();
  24928. }
  24929. }
  24930. });
  24931. }
  24932. NodeChange.prototype.nodeChanged = function (args) {
  24933. var selection = this.editor.selection;
  24934. var node, parents, root;
  24935. if (this.editor.initialized && selection && !shouldDisableNodeChange(this.editor) && !this.editor.mode.isReadOnly()) {
  24936. root = this.editor.getBody();
  24937. node = selection.getStart(true) || root;
  24938. if (node.ownerDocument !== this.editor.getDoc() || !this.editor.dom.isChildOf(node, root)) {
  24939. node = root;
  24940. }
  24941. parents = [];
  24942. this.editor.dom.getParent(node, function (node) {
  24943. if (node === root) {
  24944. return true;
  24945. }
  24946. parents.push(node);
  24947. });
  24948. args = args || {};
  24949. args.element = node;
  24950. args.parents = parents;
  24951. this.editor.fire('NodeChange', args);
  24952. }
  24953. };
  24954. NodeChange.prototype.isSameElementPath = function (startElm) {
  24955. var i;
  24956. var currentPath = this.editor.$(startElm).parentsUntil(this.editor.getBody()).add(startElm);
  24957. if (currentPath.length === this.lastPath.length) {
  24958. for (i = currentPath.length; i >= 0; i--) {
  24959. if (currentPath[i] !== this.lastPath[i]) {
  24960. break;
  24961. }
  24962. }
  24963. if (i === -1) {
  24964. this.lastPath = currentPath;
  24965. return true;
  24966. }
  24967. }
  24968. this.lastPath = currentPath;
  24969. return false;
  24970. };
  24971. return NodeChange;
  24972. }();
  24973. var preventSummaryToggle = function (editor) {
  24974. editor.on('click', function (e) {
  24975. if (editor.dom.getParent(e.target, 'details')) {
  24976. e.preventDefault();
  24977. }
  24978. });
  24979. };
  24980. var filterDetails = function (editor) {
  24981. editor.parser.addNodeFilter('details', function (elms) {
  24982. each$k(elms, function (details) {
  24983. details.attr('data-mce-open', details.attr('open'));
  24984. details.attr('open', 'open');
  24985. });
  24986. });
  24987. editor.serializer.addNodeFilter('details', function (elms) {
  24988. each$k(elms, function (details) {
  24989. var open = details.attr('data-mce-open');
  24990. details.attr('open', isString$1(open) ? open : null);
  24991. details.attr('data-mce-open', null);
  24992. });
  24993. });
  24994. };
  24995. var setup$3 = function (editor) {
  24996. preventSummaryToggle(editor);
  24997. filterDetails(editor);
  24998. };
  24999. var isTextBlockNode = function (node) {
  25000. return isElement$5(node) && isTextBlock$2(SugarElement.fromDom(node));
  25001. };
  25002. var normalizeSelection = function (editor) {
  25003. var rng = editor.selection.getRng();
  25004. var startPos = CaretPosition.fromRangeStart(rng);
  25005. var endPos = CaretPosition.fromRangeEnd(rng);
  25006. if (CaretPosition.isElementPosition(startPos)) {
  25007. var container = startPos.container();
  25008. if (isTextBlockNode(container)) {
  25009. firstPositionIn(container).each(function (pos) {
  25010. return rng.setStart(pos.container(), pos.offset());
  25011. });
  25012. }
  25013. }
  25014. if (CaretPosition.isElementPosition(endPos)) {
  25015. var container = startPos.container();
  25016. if (isTextBlockNode(container)) {
  25017. lastPositionIn(container).each(function (pos) {
  25018. return rng.setEnd(pos.container(), pos.offset());
  25019. });
  25020. }
  25021. }
  25022. editor.selection.setRng(normalize(rng));
  25023. };
  25024. var setup$2 = function (editor) {
  25025. editor.on('click', function (e) {
  25026. if (e.detail >= 3) {
  25027. normalizeSelection(editor);
  25028. }
  25029. });
  25030. };
  25031. var getAbsolutePosition = function (elm) {
  25032. var clientRect = elm.getBoundingClientRect();
  25033. var doc = elm.ownerDocument;
  25034. var docElem = doc.documentElement;
  25035. var win = doc.defaultView;
  25036. return {
  25037. top: clientRect.top + win.pageYOffset - docElem.clientTop,
  25038. left: clientRect.left + win.pageXOffset - docElem.clientLeft
  25039. };
  25040. };
  25041. var getBodyPosition = function (editor) {
  25042. return editor.inline ? getAbsolutePosition(editor.getBody()) : {
  25043. left: 0,
  25044. top: 0
  25045. };
  25046. };
  25047. var getScrollPosition = function (editor) {
  25048. var body = editor.getBody();
  25049. return editor.inline ? {
  25050. left: body.scrollLeft,
  25051. top: body.scrollTop
  25052. } : {
  25053. left: 0,
  25054. top: 0
  25055. };
  25056. };
  25057. var getBodyScroll = function (editor) {
  25058. var body = editor.getBody(), docElm = editor.getDoc().documentElement;
  25059. var inlineScroll = {
  25060. left: body.scrollLeft,
  25061. top: body.scrollTop
  25062. };
  25063. var iframeScroll = {
  25064. left: body.scrollLeft || docElm.scrollLeft,
  25065. top: body.scrollTop || docElm.scrollTop
  25066. };
  25067. return editor.inline ? inlineScroll : iframeScroll;
  25068. };
  25069. var getMousePosition = function (editor, event) {
  25070. if (event.target.ownerDocument !== editor.getDoc()) {
  25071. var iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
  25072. var scrollPosition = getBodyScroll(editor);
  25073. return {
  25074. left: event.pageX - iframePosition.left + scrollPosition.left,
  25075. top: event.pageY - iframePosition.top + scrollPosition.top
  25076. };
  25077. }
  25078. return {
  25079. left: event.pageX,
  25080. top: event.pageY
  25081. };
  25082. };
  25083. var calculatePosition = function (bodyPosition, scrollPosition, mousePosition) {
  25084. return {
  25085. pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
  25086. pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
  25087. };
  25088. };
  25089. var calc = function (editor, event) {
  25090. return calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
  25091. };
  25092. var isContentEditableFalse$1 = isContentEditableFalse$b, isContentEditableTrue$1 = isContentEditableTrue$4;
  25093. var isDraggable = function (rootElm, elm) {
  25094. return isContentEditableFalse$1(elm) && elm !== rootElm;
  25095. };
  25096. var isValidDropTarget = function (editor, targetElement, dragElement) {
  25097. if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
  25098. return false;
  25099. }
  25100. return !isContentEditableFalse$1(targetElement);
  25101. };
  25102. var cloneElement = function (elm) {
  25103. var cloneElm = elm.cloneNode(true);
  25104. cloneElm.removeAttribute('data-mce-selected');
  25105. return cloneElm;
  25106. };
  25107. var createGhost = function (editor, elm, width, height) {
  25108. var dom = editor.dom;
  25109. var clonedElm = elm.cloneNode(true);
  25110. dom.setStyles(clonedElm, {
  25111. width: width,
  25112. height: height
  25113. });
  25114. dom.setAttrib(clonedElm, 'data-mce-selected', null);
  25115. var ghostElm = dom.create('div', {
  25116. 'class': 'mce-drag-container',
  25117. 'data-mce-bogus': 'all',
  25118. 'unselectable': 'on',
  25119. 'contenteditable': 'false'
  25120. });
  25121. dom.setStyles(ghostElm, {
  25122. position: 'absolute',
  25123. opacity: 0.5,
  25124. overflow: 'hidden',
  25125. border: 0,
  25126. padding: 0,
  25127. margin: 0,
  25128. width: width,
  25129. height: height
  25130. });
  25131. dom.setStyles(clonedElm, {
  25132. margin: 0,
  25133. boxSizing: 'border-box'
  25134. });
  25135. ghostElm.appendChild(clonedElm);
  25136. return ghostElm;
  25137. };
  25138. var appendGhostToBody = function (ghostElm, bodyElm) {
  25139. if (ghostElm.parentNode !== bodyElm) {
  25140. bodyElm.appendChild(ghostElm);
  25141. }
  25142. };
  25143. var moveGhost = function (ghostElm, position, width, height, maxX, maxY) {
  25144. var overflowX = 0, overflowY = 0;
  25145. ghostElm.style.left = position.pageX + 'px';
  25146. ghostElm.style.top = position.pageY + 'px';
  25147. if (position.pageX + width > maxX) {
  25148. overflowX = position.pageX + width - maxX;
  25149. }
  25150. if (position.pageY + height > maxY) {
  25151. overflowY = position.pageY + height - maxY;
  25152. }
  25153. ghostElm.style.width = width - overflowX + 'px';
  25154. ghostElm.style.height = height - overflowY + 'px';
  25155. };
  25156. var removeElement = function (elm) {
  25157. if (elm && elm.parentNode) {
  25158. elm.parentNode.removeChild(elm);
  25159. }
  25160. };
  25161. var isLeftMouseButtonPressed = function (e) {
  25162. return e.button === 0;
  25163. };
  25164. var applyRelPos = function (state, position) {
  25165. return {
  25166. pageX: position.pageX - state.relX,
  25167. pageY: position.pageY + 5
  25168. };
  25169. };
  25170. var start = function (state, editor) {
  25171. return function (e) {
  25172. if (isLeftMouseButtonPressed(e)) {
  25173. var ceElm = find$3(editor.dom.getParents(e.target), or(isContentEditableFalse$1, isContentEditableTrue$1)).getOr(null);
  25174. if (isDraggable(editor.getBody(), ceElm)) {
  25175. var elmPos = editor.dom.getPos(ceElm);
  25176. var bodyElm = editor.getBody();
  25177. var docElm = editor.getDoc().documentElement;
  25178. state.set({
  25179. element: ceElm,
  25180. dragging: false,
  25181. screenX: e.screenX,
  25182. screenY: e.screenY,
  25183. maxX: (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2,
  25184. maxY: (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2,
  25185. relX: e.pageX - elmPos.x,
  25186. relY: e.pageY - elmPos.y,
  25187. width: ceElm.offsetWidth,
  25188. height: ceElm.offsetHeight,
  25189. ghost: createGhost(editor, ceElm, ceElm.offsetWidth, ceElm.offsetHeight)
  25190. });
  25191. }
  25192. }
  25193. };
  25194. };
  25195. var move = function (state, editor) {
  25196. var throttledPlaceCaretAt = Delay.throttle(function (clientX, clientY) {
  25197. editor._selectionOverrides.hideFakeCaret();
  25198. editor.selection.placeCaretAt(clientX, clientY);
  25199. }, 0);
  25200. editor.on('remove', throttledPlaceCaretAt.stop);
  25201. return function (e) {
  25202. return state.on(function (state) {
  25203. var movement = Math.max(Math.abs(e.screenX - state.screenX), Math.abs(e.screenY - state.screenY));
  25204. if (!state.dragging && movement > 10) {
  25205. var args = editor.fire('dragstart', { target: state.element });
  25206. if (args.isDefaultPrevented()) {
  25207. return;
  25208. }
  25209. state.dragging = true;
  25210. editor.focus();
  25211. }
  25212. if (state.dragging) {
  25213. var targetPos = applyRelPos(state, calc(editor, e));
  25214. appendGhostToBody(state.ghost, editor.getBody());
  25215. moveGhost(state.ghost, targetPos, state.width, state.height, state.maxX, state.maxY);
  25216. throttledPlaceCaretAt(e.clientX, e.clientY);
  25217. }
  25218. });
  25219. };
  25220. };
  25221. var getRawTarget = function (selection) {
  25222. var rng = selection.getSel().getRangeAt(0);
  25223. var startContainer = rng.startContainer;
  25224. return startContainer.nodeType === 3 ? startContainer.parentNode : startContainer;
  25225. };
  25226. var drop = function (state, editor) {
  25227. return function (e) {
  25228. state.on(function (state) {
  25229. if (state.dragging) {
  25230. if (isValidDropTarget(editor, getRawTarget(editor.selection), state.element)) {
  25231. var targetClone_1 = cloneElement(state.element);
  25232. var args = editor.fire('drop', {
  25233. clientX: e.clientX,
  25234. clientY: e.clientY
  25235. });
  25236. if (!args.isDefaultPrevented()) {
  25237. editor.undoManager.transact(function () {
  25238. removeElement(state.element);
  25239. editor.insertContent(editor.dom.getOuterHTML(targetClone_1));
  25240. editor._selectionOverrides.hideFakeCaret();
  25241. });
  25242. }
  25243. }
  25244. editor.fire('dragend');
  25245. }
  25246. });
  25247. removeDragState(state);
  25248. };
  25249. };
  25250. var stop = function (state, editor) {
  25251. return function () {
  25252. state.on(function (state) {
  25253. if (state.dragging) {
  25254. editor.fire('dragend');
  25255. }
  25256. });
  25257. removeDragState(state);
  25258. };
  25259. };
  25260. var removeDragState = function (state) {
  25261. state.on(function (state) {
  25262. removeElement(state.ghost);
  25263. });
  25264. state.clear();
  25265. };
  25266. var bindFakeDragEvents = function (editor) {
  25267. var state = value();
  25268. var pageDom = DOMUtils.DOM;
  25269. var rootDocument = document;
  25270. var dragStartHandler = start(state, editor);
  25271. var dragHandler = move(state, editor);
  25272. var dropHandler = drop(state, editor);
  25273. var dragEndHandler = stop(state, editor);
  25274. editor.on('mousedown', dragStartHandler);
  25275. editor.on('mousemove', dragHandler);
  25276. editor.on('mouseup', dropHandler);
  25277. pageDom.bind(rootDocument, 'mousemove', dragHandler);
  25278. pageDom.bind(rootDocument, 'mouseup', dragEndHandler);
  25279. editor.on('remove', function () {
  25280. pageDom.unbind(rootDocument, 'mousemove', dragHandler);
  25281. pageDom.unbind(rootDocument, 'mouseup', dragEndHandler);
  25282. });
  25283. editor.on('keydown', function (e) {
  25284. if (e.keyCode === VK.ESC) {
  25285. dragEndHandler();
  25286. }
  25287. });
  25288. };
  25289. var blockIeDrop = function (editor) {
  25290. editor.on('drop', function (e) {
  25291. var realTarget = typeof e.clientX !== 'undefined' ? editor.getDoc().elementFromPoint(e.clientX, e.clientY) : null;
  25292. if (isContentEditableFalse$1(realTarget) || editor.dom.getContentEditableParent(realTarget) === 'false') {
  25293. e.preventDefault();
  25294. }
  25295. });
  25296. };
  25297. var blockUnsupportedFileDrop = function (editor) {
  25298. var preventFileDrop = function (e) {
  25299. if (!e.isDefaultPrevented()) {
  25300. var dataTransfer = e.dataTransfer;
  25301. if (dataTransfer && (contains$3(dataTransfer.types, 'Files') || dataTransfer.files.length > 0)) {
  25302. e.preventDefault();
  25303. if (e.type === 'drop') {
  25304. displayError(editor, 'Dropped file type is not supported');
  25305. }
  25306. }
  25307. }
  25308. };
  25309. var preventFileDropIfUIElement = function (e) {
  25310. if (isUIElement(editor, e.target)) {
  25311. preventFileDrop(e);
  25312. }
  25313. };
  25314. var setup = function () {
  25315. var pageDom = DOMUtils.DOM;
  25316. var dom = editor.dom;
  25317. var doc = document;
  25318. var editorRoot = editor.inline ? editor.getBody() : editor.getDoc();
  25319. var eventNames = [
  25320. 'drop',
  25321. 'dragover'
  25322. ];
  25323. each$k(eventNames, function (name) {
  25324. pageDom.bind(doc, name, preventFileDropIfUIElement);
  25325. dom.bind(editorRoot, name, preventFileDrop);
  25326. });
  25327. editor.on('remove', function () {
  25328. each$k(eventNames, function (name) {
  25329. pageDom.unbind(doc, name, preventFileDropIfUIElement);
  25330. dom.unbind(editorRoot, name, preventFileDrop);
  25331. });
  25332. });
  25333. };
  25334. editor.on('init', function () {
  25335. Delay.setEditorTimeout(editor, setup, 0);
  25336. });
  25337. };
  25338. var init$2 = function (editor) {
  25339. bindFakeDragEvents(editor);
  25340. blockIeDrop(editor);
  25341. if (shouldBlockUnsupportedDrop(editor)) {
  25342. blockUnsupportedFileDrop(editor);
  25343. }
  25344. };
  25345. var setup$1 = function (editor) {
  25346. var renderFocusCaret = first(function () {
  25347. if (!editor.removed && editor.getBody().contains(document.activeElement)) {
  25348. var rng = editor.selection.getRng();
  25349. if (rng.collapsed) {
  25350. var caretRange = renderRangeCaret(editor, rng, false);
  25351. editor.selection.setRng(caretRange);
  25352. }
  25353. }
  25354. }, 0);
  25355. editor.on('focus', function () {
  25356. renderFocusCaret.throttle();
  25357. });
  25358. editor.on('blur', function () {
  25359. renderFocusCaret.cancel();
  25360. });
  25361. };
  25362. var setup = function (editor) {
  25363. editor.on('init', function () {
  25364. editor.on('focusin', function (e) {
  25365. var target = e.target;
  25366. if (isMedia$2(target)) {
  25367. var ceRoot = getContentEditableRoot$1(editor.getBody(), target);
  25368. var node = isContentEditableFalse$b(ceRoot) ? ceRoot : target;
  25369. if (editor.selection.getNode() !== node) {
  25370. selectNode(editor, node).each(function (rng) {
  25371. return editor.selection.setRng(rng);
  25372. });
  25373. }
  25374. }
  25375. });
  25376. });
  25377. };
  25378. var isContentEditableTrue = isContentEditableTrue$4;
  25379. var isContentEditableFalse = isContentEditableFalse$b;
  25380. var getContentEditableRoot = function (editor, node) {
  25381. return getContentEditableRoot$1(editor.getBody(), node);
  25382. };
  25383. var SelectionOverrides = function (editor) {
  25384. var selection = editor.selection, dom = editor.dom;
  25385. var isBlock = dom.isBlock;
  25386. var rootNode = editor.getBody();
  25387. var fakeCaret = FakeCaret(editor, rootNode, isBlock, function () {
  25388. return hasFocus(editor);
  25389. });
  25390. var realSelectionId = 'sel-' + dom.uniqueId();
  25391. var elementSelectionAttr = 'data-mce-selected';
  25392. var selectedElement;
  25393. var isFakeSelectionElement = function (node) {
  25394. return dom.hasClass(node, 'mce-offscreen-selection');
  25395. };
  25396. var isFakeSelectionTargetElement = function (node) {
  25397. return node !== rootNode && (isContentEditableFalse(node) || isMedia$2(node)) && dom.isChildOf(node, rootNode);
  25398. };
  25399. var isNearFakeSelectionElement = function (pos) {
  25400. return isBeforeContentEditableFalse(pos) || isAfterContentEditableFalse(pos) || isBeforeMedia(pos) || isAfterMedia(pos);
  25401. };
  25402. var getRealSelectionElement = function () {
  25403. var container = dom.get(realSelectionId);
  25404. return container ? container.getElementsByTagName('*')[0] : container;
  25405. };
  25406. var setRange = function (range) {
  25407. if (range) {
  25408. selection.setRng(range);
  25409. }
  25410. };
  25411. var getRange = selection.getRng;
  25412. var showCaret = function (direction, node, before, scrollIntoView) {
  25413. if (scrollIntoView === void 0) {
  25414. scrollIntoView = true;
  25415. }
  25416. var e = editor.fire('ShowCaret', {
  25417. target: node,
  25418. direction: direction,
  25419. before: before
  25420. });
  25421. if (e.isDefaultPrevented()) {
  25422. return null;
  25423. }
  25424. if (scrollIntoView) {
  25425. selection.scrollIntoView(node, direction === -1);
  25426. }
  25427. return fakeCaret.show(before, node);
  25428. };
  25429. var showBlockCaretContainer = function (blockCaretContainer) {
  25430. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  25431. showCaretContainerBlock(blockCaretContainer);
  25432. setRange(getRange());
  25433. selection.scrollIntoView(blockCaretContainer);
  25434. }
  25435. };
  25436. var registerEvents = function () {
  25437. editor.on('mouseup', function (e) {
  25438. var range = getRange();
  25439. if (range.collapsed && isXYInContentArea(editor, e.clientX, e.clientY)) {
  25440. renderCaretAtRange(editor, range, false).each(setRange);
  25441. }
  25442. });
  25443. editor.on('click', function (e) {
  25444. var contentEditableRoot = getContentEditableRoot(editor, e.target);
  25445. if (contentEditableRoot) {
  25446. if (isContentEditableFalse(contentEditableRoot)) {
  25447. e.preventDefault();
  25448. editor.focus();
  25449. }
  25450. if (isContentEditableTrue(contentEditableRoot)) {
  25451. if (dom.isChildOf(contentEditableRoot, selection.getNode())) {
  25452. removeElementSelection();
  25453. }
  25454. }
  25455. }
  25456. });
  25457. editor.on('blur NewBlock', removeElementSelection);
  25458. editor.on('ResizeWindow FullscreenStateChanged', fakeCaret.reposition);
  25459. var hasNormalCaretPosition = function (elm) {
  25460. var start = elm.firstChild;
  25461. if (isNullable(start)) {
  25462. return false;
  25463. }
  25464. var startPos = CaretPosition.before(start);
  25465. if (isBr$5(startPos.getNode()) && elm.childNodes.length === 1) {
  25466. return !isNearFakeSelectionElement(startPos);
  25467. } else {
  25468. var caretWalker = CaretWalker(elm);
  25469. var newPos = caretWalker.next(startPos);
  25470. return newPos && !isNearFakeSelectionElement(newPos);
  25471. }
  25472. };
  25473. var isInSameBlock = function (node1, node2) {
  25474. var block1 = dom.getParent(node1, isBlock);
  25475. var block2 = dom.getParent(node2, isBlock);
  25476. return block1 === block2;
  25477. };
  25478. var hasBetterMouseTarget = function (targetNode, caretNode) {
  25479. var targetBlock = dom.getParent(targetNode, isBlock);
  25480. var caretBlock = dom.getParent(caretNode, isBlock);
  25481. if (isNullable(targetBlock)) {
  25482. return false;
  25483. }
  25484. if (targetNode !== caretBlock && dom.isChildOf(targetBlock, caretBlock) && isContentEditableFalse(getContentEditableRoot(editor, targetBlock)) === false) {
  25485. return true;
  25486. }
  25487. return !dom.isChildOf(caretBlock, targetBlock) && !isInSameBlock(targetBlock, caretBlock) && hasNormalCaretPosition(targetBlock);
  25488. };
  25489. editor.on('tap', function (e) {
  25490. var targetElm = e.target;
  25491. var contentEditableRoot = getContentEditableRoot(editor, targetElm);
  25492. if (isContentEditableFalse(contentEditableRoot)) {
  25493. e.preventDefault();
  25494. selectNode(editor, contentEditableRoot).each(setElementSelection);
  25495. } else if (isFakeSelectionTargetElement(targetElm)) {
  25496. selectNode(editor, targetElm).each(setElementSelection);
  25497. }
  25498. }, true);
  25499. editor.on('mousedown', function (e) {
  25500. var targetElm = e.target;
  25501. if (targetElm !== rootNode && targetElm.nodeName !== 'HTML' && !dom.isChildOf(targetElm, rootNode)) {
  25502. return;
  25503. }
  25504. if (isXYInContentArea(editor, e.clientX, e.clientY) === false) {
  25505. return;
  25506. }
  25507. var contentEditableRoot = getContentEditableRoot(editor, targetElm);
  25508. if (contentEditableRoot) {
  25509. if (isContentEditableFalse(contentEditableRoot)) {
  25510. e.preventDefault();
  25511. selectNode(editor, contentEditableRoot).each(setElementSelection);
  25512. } else {
  25513. removeElementSelection();
  25514. if (!(isContentEditableTrue(contentEditableRoot) && e.shiftKey) && !isXYWithinRange(e.clientX, e.clientY, selection.getRng())) {
  25515. hideFakeCaret();
  25516. selection.placeCaretAt(e.clientX, e.clientY);
  25517. }
  25518. }
  25519. } else if (isFakeSelectionTargetElement(targetElm)) {
  25520. selectNode(editor, targetElm).each(setElementSelection);
  25521. } else if (isFakeCaretTarget(targetElm) === false) {
  25522. removeElementSelection();
  25523. hideFakeCaret();
  25524. var fakeCaretInfo = closestFakeCaret(rootNode, e.clientX, e.clientY);
  25525. if (fakeCaretInfo) {
  25526. if (!hasBetterMouseTarget(targetElm, fakeCaretInfo.node)) {
  25527. e.preventDefault();
  25528. var range = showCaret(1, fakeCaretInfo.node, fakeCaretInfo.before, false);
  25529. setRange(range);
  25530. editor.getBody().focus();
  25531. }
  25532. }
  25533. }
  25534. });
  25535. editor.on('keypress', function (e) {
  25536. if (VK.modifierPressed(e)) {
  25537. return;
  25538. }
  25539. if (isContentEditableFalse(selection.getNode())) {
  25540. e.preventDefault();
  25541. }
  25542. });
  25543. editor.on('GetSelectionRange', function (e) {
  25544. var rng = e.range;
  25545. if (selectedElement) {
  25546. if (!selectedElement.parentNode) {
  25547. selectedElement = null;
  25548. return;
  25549. }
  25550. rng = rng.cloneRange();
  25551. rng.selectNode(selectedElement);
  25552. e.range = rng;
  25553. }
  25554. });
  25555. editor.on('SetSelectionRange', function (e) {
  25556. e.range = normalizeShortEndedElementSelection(e.range);
  25557. var rng = setElementSelection(e.range, e.forward);
  25558. if (rng) {
  25559. e.range = rng;
  25560. }
  25561. });
  25562. var isPasteBin = function (node) {
  25563. return node.id === 'mcepastebin';
  25564. };
  25565. editor.on('AfterSetSelectionRange', function (e) {
  25566. var rng = e.range;
  25567. var parentNode = rng.startContainer.parentNode;
  25568. if (!isRangeInCaretContainer(rng) && !isPasteBin(parentNode)) {
  25569. hideFakeCaret();
  25570. }
  25571. if (!isFakeSelectionElement(parentNode)) {
  25572. removeElementSelection();
  25573. }
  25574. });
  25575. editor.on('copy', function (e) {
  25576. var clipboardData = e.clipboardData;
  25577. if (!e.isDefaultPrevented() && e.clipboardData && !Env.ie) {
  25578. var realSelectionElement = getRealSelectionElement();
  25579. if (realSelectionElement) {
  25580. e.preventDefault();
  25581. clipboardData.clearData();
  25582. clipboardData.setData('text/html', realSelectionElement.outerHTML);
  25583. clipboardData.setData('text/plain', realSelectionElement.outerText || realSelectionElement.innerText);
  25584. }
  25585. }
  25586. });
  25587. init$2(editor);
  25588. setup$1(editor);
  25589. setup(editor);
  25590. };
  25591. var isWithinCaretContainer = function (node) {
  25592. return isCaretContainer$2(node) || startsWithCaretContainer$1(node) || endsWithCaretContainer$1(node);
  25593. };
  25594. var isRangeInCaretContainer = function (rng) {
  25595. return isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
  25596. };
  25597. var normalizeShortEndedElementSelection = function (rng) {
  25598. var shortEndedElements = editor.schema.getShortEndedElements();
  25599. var newRng = dom.createRng();
  25600. var startContainer = rng.startContainer;
  25601. var startOffset = rng.startOffset;
  25602. var endContainer = rng.endContainer;
  25603. var endOffset = rng.endOffset;
  25604. if (has$2(shortEndedElements, startContainer.nodeName.toLowerCase())) {
  25605. if (startOffset === 0) {
  25606. newRng.setStartBefore(startContainer);
  25607. } else {
  25608. newRng.setStartAfter(startContainer);
  25609. }
  25610. } else {
  25611. newRng.setStart(startContainer, startOffset);
  25612. }
  25613. if (has$2(shortEndedElements, endContainer.nodeName.toLowerCase())) {
  25614. if (endOffset === 0) {
  25615. newRng.setEndBefore(endContainer);
  25616. } else {
  25617. newRng.setEndAfter(endContainer);
  25618. }
  25619. } else {
  25620. newRng.setEnd(endContainer, endOffset);
  25621. }
  25622. return newRng;
  25623. };
  25624. var setupOffscreenSelection = function (node, targetClone, origTargetClone) {
  25625. var $ = editor.$;
  25626. var $realSelectionContainer = descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).fold(function () {
  25627. return $([]);
  25628. }, function (elm) {
  25629. return $([elm.dom]);
  25630. });
  25631. if ($realSelectionContainer.length === 0) {
  25632. $realSelectionContainer = $('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>').attr('id', realSelectionId);
  25633. $realSelectionContainer.appendTo(editor.getBody());
  25634. }
  25635. var newRange = dom.createRng();
  25636. if (targetClone === origTargetClone && Env.ie) {
  25637. $realSelectionContainer.empty().append('<p style="font-size: 0" data-mce-bogus="all">\xA0</p>').append(targetClone);
  25638. newRange.setStartAfter($realSelectionContainer[0].firstChild.firstChild);
  25639. newRange.setEndAfter(targetClone);
  25640. } else {
  25641. $realSelectionContainer.empty().append(nbsp).append(targetClone).append(nbsp);
  25642. newRange.setStart($realSelectionContainer[0].firstChild, 1);
  25643. newRange.setEnd($realSelectionContainer[0].lastChild, 0);
  25644. }
  25645. $realSelectionContainer.css({ top: dom.getPos(node, editor.getBody()).y });
  25646. $realSelectionContainer[0].focus();
  25647. var sel = selection.getSel();
  25648. sel.removeAllRanges();
  25649. sel.addRange(newRange);
  25650. return newRange;
  25651. };
  25652. var selectElement = function (elm) {
  25653. var targetClone = elm.cloneNode(true);
  25654. var e = editor.fire('ObjectSelected', {
  25655. target: elm,
  25656. targetClone: targetClone
  25657. });
  25658. if (e.isDefaultPrevented()) {
  25659. return null;
  25660. }
  25661. var range = setupOffscreenSelection(elm, e.targetClone, targetClone);
  25662. var nodeElm = SugarElement.fromDom(elm);
  25663. each$k(descendants(SugarElement.fromDom(editor.getBody()), '*[data-mce-selected]'), function (elm) {
  25664. if (!eq(nodeElm, elm)) {
  25665. remove$6(elm, elementSelectionAttr);
  25666. }
  25667. });
  25668. if (!dom.getAttrib(elm, elementSelectionAttr)) {
  25669. elm.setAttribute(elementSelectionAttr, '1');
  25670. }
  25671. selectedElement = elm;
  25672. hideFakeCaret();
  25673. return range;
  25674. };
  25675. var setElementSelection = function (range, forward) {
  25676. if (!range) {
  25677. return null;
  25678. }
  25679. if (range.collapsed) {
  25680. if (!isRangeInCaretContainer(range)) {
  25681. var dir = forward ? 1 : -1;
  25682. var caretPosition = getNormalizedRangeEndPoint(dir, rootNode, range);
  25683. var beforeNode = caretPosition.getNode(!forward);
  25684. if (isFakeCaretTarget(beforeNode)) {
  25685. return showCaret(dir, beforeNode, forward ? !caretPosition.isAtEnd() : false, false);
  25686. }
  25687. var afterNode = caretPosition.getNode(forward);
  25688. if (isFakeCaretTarget(afterNode)) {
  25689. return showCaret(dir, afterNode, forward ? false : !caretPosition.isAtEnd(), false);
  25690. }
  25691. }
  25692. return null;
  25693. }
  25694. var startContainer = range.startContainer;
  25695. var startOffset = range.startOffset;
  25696. var endOffset = range.endOffset;
  25697. if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse(startContainer.parentNode)) {
  25698. startContainer = startContainer.parentNode;
  25699. startOffset = dom.nodeIndex(startContainer);
  25700. startContainer = startContainer.parentNode;
  25701. }
  25702. if (startContainer.nodeType !== 1) {
  25703. return null;
  25704. }
  25705. if (endOffset === startOffset + 1 && startContainer === range.endContainer) {
  25706. var node = startContainer.childNodes[startOffset];
  25707. if (isFakeSelectionTargetElement(node)) {
  25708. return selectElement(node);
  25709. }
  25710. }
  25711. return null;
  25712. };
  25713. var removeElementSelection = function () {
  25714. if (selectedElement) {
  25715. selectedElement.removeAttribute(elementSelectionAttr);
  25716. }
  25717. descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).each(remove$7);
  25718. selectedElement = null;
  25719. };
  25720. var destroy = function () {
  25721. fakeCaret.destroy();
  25722. selectedElement = null;
  25723. };
  25724. var hideFakeCaret = function () {
  25725. fakeCaret.hide();
  25726. };
  25727. if (Env.ceFalse && !isRtc(editor)) {
  25728. registerEvents();
  25729. }
  25730. return {
  25731. showCaret: showCaret,
  25732. showBlockCaretContainer: showBlockCaretContainer,
  25733. hideFakeCaret: hideFakeCaret,
  25734. destroy: destroy
  25735. };
  25736. };
  25737. var Quirks = function (editor) {
  25738. var each = Tools.each;
  25739. var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, parser = editor.parser;
  25740. var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit;
  25741. var mceInternalUrlPrefix = 'data:text/mce-internal,';
  25742. var mceInternalDataType = isIE ? 'Text' : 'URL';
  25743. var setEditorCommandState = function (cmd, state) {
  25744. try {
  25745. editor.getDoc().execCommand(cmd, false, state);
  25746. } catch (ex) {
  25747. }
  25748. };
  25749. var isDefaultPrevented = function (e) {
  25750. return e.isDefaultPrevented();
  25751. };
  25752. var setMceInternalContent = function (e) {
  25753. var selectionHtml, internalContent;
  25754. if (e.dataTransfer) {
  25755. if (editor.selection.isCollapsed() && e.target.tagName === 'IMG') {
  25756. selection.select(e.target);
  25757. }
  25758. selectionHtml = editor.selection.getContent();
  25759. if (selectionHtml.length > 0) {
  25760. internalContent = mceInternalUrlPrefix + escape(editor.id) + ',' + escape(selectionHtml);
  25761. e.dataTransfer.setData(mceInternalDataType, internalContent);
  25762. }
  25763. }
  25764. };
  25765. var getMceInternalContent = function (e) {
  25766. var internalContent;
  25767. if (e.dataTransfer) {
  25768. internalContent = e.dataTransfer.getData(mceInternalDataType);
  25769. if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) {
  25770. internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(',');
  25771. return {
  25772. id: unescape(internalContent[0]),
  25773. html: unescape(internalContent[1])
  25774. };
  25775. }
  25776. }
  25777. return null;
  25778. };
  25779. var insertClipboardContents = function (content, internal) {
  25780. if (editor.queryCommandSupported('mceInsertClipboardContent')) {
  25781. editor.execCommand('mceInsertClipboardContent', false, {
  25782. content: content,
  25783. internal: internal
  25784. });
  25785. } else {
  25786. editor.execCommand('mceInsertContent', false, content);
  25787. }
  25788. };
  25789. var emptyEditorWhenDeleting = function () {
  25790. var serializeRng = function (rng) {
  25791. var body = dom.create('body');
  25792. var contents = rng.cloneContents();
  25793. body.appendChild(contents);
  25794. return selection.serializer.serialize(body, { format: 'html' });
  25795. };
  25796. var allContentsSelected = function (rng) {
  25797. var selection = serializeRng(rng);
  25798. var allRng = dom.createRng();
  25799. allRng.selectNode(editor.getBody());
  25800. var allSelection = serializeRng(allRng);
  25801. return selection === allSelection;
  25802. };
  25803. editor.on('keydown', function (e) {
  25804. var keyCode = e.keyCode;
  25805. var isCollapsed, body;
  25806. if (!isDefaultPrevented(e) && (keyCode === DELETE || keyCode === BACKSPACE)) {
  25807. isCollapsed = editor.selection.isCollapsed();
  25808. body = editor.getBody();
  25809. if (isCollapsed && !dom.isEmpty(body)) {
  25810. return;
  25811. }
  25812. if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
  25813. return;
  25814. }
  25815. e.preventDefault();
  25816. editor.setContent('');
  25817. if (body.firstChild && dom.isBlock(body.firstChild)) {
  25818. editor.selection.setCursorLocation(body.firstChild, 0);
  25819. } else {
  25820. editor.selection.setCursorLocation(body, 0);
  25821. }
  25822. editor.nodeChanged();
  25823. }
  25824. });
  25825. };
  25826. var selectAll = function () {
  25827. editor.shortcuts.add('meta+a', null, 'SelectAll');
  25828. };
  25829. var documentElementEditingFocus = function () {
  25830. if (!editor.inline) {
  25831. dom.bind(editor.getDoc(), 'mousedown mouseup', function (e) {
  25832. var rng;
  25833. if (e.target === editor.getDoc().documentElement) {
  25834. rng = selection.getRng();
  25835. editor.getBody().focus();
  25836. if (e.type === 'mousedown') {
  25837. if (isCaretContainer$2(rng.startContainer)) {
  25838. return;
  25839. }
  25840. selection.placeCaretAt(e.clientX, e.clientY);
  25841. } else {
  25842. selection.setRng(rng);
  25843. }
  25844. }
  25845. });
  25846. }
  25847. };
  25848. var removeHrOnBackspace = function () {
  25849. editor.on('keydown', function (e) {
  25850. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25851. if (!editor.getBody().getElementsByTagName('hr').length) {
  25852. return;
  25853. }
  25854. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25855. var node = selection.getNode();
  25856. var previousSibling = node.previousSibling;
  25857. if (node.nodeName === 'HR') {
  25858. dom.remove(node);
  25859. e.preventDefault();
  25860. return;
  25861. }
  25862. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'hr') {
  25863. dom.remove(previousSibling);
  25864. e.preventDefault();
  25865. }
  25866. }
  25867. }
  25868. });
  25869. };
  25870. var focusBody = function () {
  25871. if (!Range.prototype.getClientRects) {
  25872. editor.on('mousedown', function (e) {
  25873. if (!isDefaultPrevented(e) && e.target.nodeName === 'HTML') {
  25874. var body_1 = editor.getBody();
  25875. body_1.blur();
  25876. Delay.setEditorTimeout(editor, function () {
  25877. body_1.focus();
  25878. });
  25879. }
  25880. });
  25881. }
  25882. };
  25883. var selectControlElements = function () {
  25884. editor.on('click', function (e) {
  25885. var target = e.target;
  25886. if (/^(IMG|HR)$/.test(target.nodeName) && dom.getContentEditableParent(target) !== 'false') {
  25887. e.preventDefault();
  25888. editor.selection.select(target);
  25889. editor.nodeChanged();
  25890. }
  25891. if (target.nodeName === 'A' && dom.hasClass(target, 'mce-item-anchor')) {
  25892. e.preventDefault();
  25893. selection.select(target);
  25894. }
  25895. });
  25896. };
  25897. var removeStylesWhenDeletingAcrossBlockElements = function () {
  25898. var getAttributeApplyFunction = function () {
  25899. var template = dom.getAttribs(selection.getStart().cloneNode(false));
  25900. return function () {
  25901. var target = selection.getStart();
  25902. if (target !== editor.getBody()) {
  25903. dom.setAttrib(target, 'style', null);
  25904. each(template, function (attr) {
  25905. target.setAttributeNode(attr.cloneNode(true));
  25906. });
  25907. }
  25908. };
  25909. };
  25910. var isSelectionAcrossElements = function () {
  25911. return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock);
  25912. };
  25913. editor.on('keypress', function (e) {
  25914. var applyAttributes;
  25915. if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) {
  25916. applyAttributes = getAttributeApplyFunction();
  25917. editor.getDoc().execCommand('delete', false, null);
  25918. applyAttributes();
  25919. e.preventDefault();
  25920. return false;
  25921. }
  25922. });
  25923. dom.bind(editor.getDoc(), 'cut', function (e) {
  25924. var applyAttributes;
  25925. if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
  25926. applyAttributes = getAttributeApplyFunction();
  25927. Delay.setEditorTimeout(editor, function () {
  25928. applyAttributes();
  25929. });
  25930. }
  25931. });
  25932. };
  25933. var disableBackspaceIntoATable = function () {
  25934. editor.on('keydown', function (e) {
  25935. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25936. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25937. var previousSibling = selection.getNode().previousSibling;
  25938. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'table') {
  25939. e.preventDefault();
  25940. return false;
  25941. }
  25942. }
  25943. }
  25944. });
  25945. };
  25946. var removeBlockQuoteOnBackSpace = function () {
  25947. editor.on('keydown', function (e) {
  25948. var rng, parent;
  25949. if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) {
  25950. return;
  25951. }
  25952. rng = selection.getRng();
  25953. var container = rng.startContainer;
  25954. var offset = rng.startOffset;
  25955. var root = dom.getRoot();
  25956. parent = container;
  25957. if (!rng.collapsed || offset !== 0) {
  25958. return;
  25959. }
  25960. while (parent && parent.parentNode && parent.parentNode.firstChild === parent && parent.parentNode !== root) {
  25961. parent = parent.parentNode;
  25962. }
  25963. if (parent.tagName === 'BLOCKQUOTE') {
  25964. editor.formatter.toggle('blockquote', null, parent);
  25965. rng = dom.createRng();
  25966. rng.setStart(container, 0);
  25967. rng.setEnd(container, 0);
  25968. selection.setRng(rng);
  25969. }
  25970. });
  25971. };
  25972. var setGeckoEditingOptions = function () {
  25973. var setOpts = function () {
  25974. setEditorCommandState('StyleWithCSS', false);
  25975. setEditorCommandState('enableInlineTableEditing', false);
  25976. if (!getObjectResizing(editor)) {
  25977. setEditorCommandState('enableObjectResizing', false);
  25978. }
  25979. };
  25980. if (!isReadOnly$1(editor)) {
  25981. editor.on('BeforeExecCommand mousedown', setOpts);
  25982. }
  25983. };
  25984. var addBrAfterLastLinks = function () {
  25985. var fixLinks = function () {
  25986. each(dom.select('a'), function (node) {
  25987. var parentNode = node.parentNode;
  25988. var root = dom.getRoot();
  25989. if (parentNode.lastChild === node) {
  25990. while (parentNode && !dom.isBlock(parentNode)) {
  25991. if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
  25992. return;
  25993. }
  25994. parentNode = parentNode.parentNode;
  25995. }
  25996. dom.add(parentNode, 'br', { 'data-mce-bogus': 1 });
  25997. }
  25998. });
  25999. };
  26000. editor.on('SetContent ExecCommand', function (e) {
  26001. if (e.type === 'setcontent' || e.command === 'mceInsertLink') {
  26002. fixLinks();
  26003. }
  26004. });
  26005. };
  26006. var setDefaultBlockType = function () {
  26007. if (getForcedRootBlock(editor)) {
  26008. editor.on('init', function () {
  26009. setEditorCommandState('DefaultParagraphSeparator', getForcedRootBlock(editor));
  26010. });
  26011. }
  26012. };
  26013. var normalizeSelection = function () {
  26014. editor.on('keyup focusin mouseup', function (e) {
  26015. if (!VK.modifierPressed(e)) {
  26016. selection.normalize();
  26017. }
  26018. }, true);
  26019. };
  26020. var showBrokenImageIcon = function () {
  26021. editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}');
  26022. };
  26023. var restoreFocusOnKeyDown = function () {
  26024. if (!editor.inline) {
  26025. editor.on('keydown', function () {
  26026. if (document.activeElement === document.body) {
  26027. editor.getWin().focus();
  26028. }
  26029. });
  26030. }
  26031. };
  26032. var bodyHeight = function () {
  26033. if (!editor.inline) {
  26034. editor.contentStyles.push('body {min-height: 150px}');
  26035. editor.on('click', function (e) {
  26036. var rng;
  26037. if (e.target.nodeName === 'HTML') {
  26038. if (Env.ie > 11) {
  26039. editor.getBody().focus();
  26040. return;
  26041. }
  26042. rng = editor.selection.getRng();
  26043. editor.getBody().focus();
  26044. editor.selection.setRng(rng);
  26045. editor.selection.normalize();
  26046. editor.nodeChanged();
  26047. }
  26048. });
  26049. }
  26050. };
  26051. var blockCmdArrowNavigation = function () {
  26052. if (Env.mac) {
  26053. editor.on('keydown', function (e) {
  26054. if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) {
  26055. e.preventDefault();
  26056. var selection_1 = editor.selection.getSel();
  26057. selection_1.modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary');
  26058. }
  26059. });
  26060. }
  26061. };
  26062. var disableAutoUrlDetect = function () {
  26063. setEditorCommandState('AutoUrlDetect', false);
  26064. };
  26065. var tapLinksAndImages = function () {
  26066. editor.on('click', function (e) {
  26067. var elm = e.target;
  26068. do {
  26069. if (elm.tagName === 'A') {
  26070. e.preventDefault();
  26071. return;
  26072. }
  26073. } while (elm = elm.parentNode);
  26074. });
  26075. editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
  26076. };
  26077. var blockFormSubmitInsideEditor = function () {
  26078. editor.on('init', function () {
  26079. editor.dom.bind(editor.getBody(), 'submit', function (e) {
  26080. e.preventDefault();
  26081. });
  26082. });
  26083. };
  26084. var removeAppleInterchangeBrs = function () {
  26085. parser.addNodeFilter('br', function (nodes) {
  26086. var i = nodes.length;
  26087. while (i--) {
  26088. if (nodes[i].attr('class') === 'Apple-interchange-newline') {
  26089. nodes[i].remove();
  26090. }
  26091. }
  26092. });
  26093. };
  26094. var ieInternalDragAndDrop = function () {
  26095. editor.on('dragstart', function (e) {
  26096. setMceInternalContent(e);
  26097. });
  26098. editor.on('drop', function (e) {
  26099. if (!isDefaultPrevented(e)) {
  26100. var internalContent = getMceInternalContent(e);
  26101. if (internalContent && internalContent.id !== editor.id) {
  26102. e.preventDefault();
  26103. var rng = fromPoint(e.x, e.y, editor.getDoc());
  26104. selection.setRng(rng);
  26105. insertClipboardContents(internalContent.html, true);
  26106. }
  26107. }
  26108. });
  26109. };
  26110. var refreshContentEditable = noop;
  26111. var isHidden = function () {
  26112. if (!isGecko || editor.removed) {
  26113. return false;
  26114. }
  26115. var sel = editor.selection.getSel();
  26116. return !sel || !sel.rangeCount || sel.rangeCount === 0;
  26117. };
  26118. var setupRtc = function () {
  26119. if (isWebKit) {
  26120. documentElementEditingFocus();
  26121. selectControlElements();
  26122. blockFormSubmitInsideEditor();
  26123. selectAll();
  26124. if (Env.iOS) {
  26125. restoreFocusOnKeyDown();
  26126. bodyHeight();
  26127. tapLinksAndImages();
  26128. }
  26129. }
  26130. if (isGecko) {
  26131. focusBody();
  26132. setGeckoEditingOptions();
  26133. showBrokenImageIcon();
  26134. blockCmdArrowNavigation();
  26135. }
  26136. };
  26137. var setup = function () {
  26138. removeBlockQuoteOnBackSpace();
  26139. emptyEditorWhenDeleting();
  26140. if (!Env.windowsPhone) {
  26141. normalizeSelection();
  26142. }
  26143. if (isWebKit) {
  26144. documentElementEditingFocus();
  26145. selectControlElements();
  26146. setDefaultBlockType();
  26147. blockFormSubmitInsideEditor();
  26148. disableBackspaceIntoATable();
  26149. removeAppleInterchangeBrs();
  26150. if (Env.iOS) {
  26151. restoreFocusOnKeyDown();
  26152. bodyHeight();
  26153. tapLinksAndImages();
  26154. } else {
  26155. selectAll();
  26156. }
  26157. }
  26158. if (Env.ie >= 11) {
  26159. bodyHeight();
  26160. disableBackspaceIntoATable();
  26161. }
  26162. if (Env.ie) {
  26163. selectAll();
  26164. disableAutoUrlDetect();
  26165. ieInternalDragAndDrop();
  26166. }
  26167. if (isGecko) {
  26168. removeHrOnBackspace();
  26169. focusBody();
  26170. removeStylesWhenDeletingAcrossBlockElements();
  26171. setGeckoEditingOptions();
  26172. addBrAfterLastLinks();
  26173. showBrokenImageIcon();
  26174. blockCmdArrowNavigation();
  26175. disableBackspaceIntoATable();
  26176. }
  26177. };
  26178. if (isRtc(editor)) {
  26179. setupRtc();
  26180. } else {
  26181. setup();
  26182. }
  26183. return {
  26184. refreshContentEditable: refreshContentEditable,
  26185. isHidden: isHidden
  26186. };
  26187. };
  26188. var DOM$6 = DOMUtils.DOM;
  26189. var appendStyle = function (editor, text) {
  26190. var body = SugarElement.fromDom(editor.getBody());
  26191. var container = getStyleContainer(getRootNode(body));
  26192. var style = SugarElement.fromTag('style');
  26193. set$1(style, 'type', 'text/css');
  26194. append$1(style, SugarElement.fromText(text));
  26195. append$1(container, style);
  26196. editor.on('remove', function () {
  26197. remove$7(style);
  26198. });
  26199. };
  26200. var getRootName = function (editor) {
  26201. return editor.inline ? editor.getElement().nodeName.toLowerCase() : undefined;
  26202. };
  26203. var removeUndefined = function (obj) {
  26204. return filter$3(obj, function (v) {
  26205. return isUndefined(v) === false;
  26206. });
  26207. };
  26208. var mkParserSettings = function (editor) {
  26209. var settings = editor.settings;
  26210. var blobCache = editor.editorUpload.blobCache;
  26211. return removeUndefined({
  26212. allow_conditional_comments: settings.allow_conditional_comments,
  26213. allow_html_data_urls: settings.allow_html_data_urls,
  26214. allow_svg_data_urls: settings.allow_svg_data_urls,
  26215. allow_html_in_named_anchor: settings.allow_html_in_named_anchor,
  26216. allow_script_urls: settings.allow_script_urls,
  26217. allow_unsafe_link_target: settings.allow_unsafe_link_target,
  26218. convert_fonts_to_spans: settings.convert_fonts_to_spans,
  26219. fix_list_elements: settings.fix_list_elements,
  26220. font_size_legacy_values: settings.font_size_legacy_values,
  26221. forced_root_block: settings.forced_root_block,
  26222. forced_root_block_attrs: settings.forced_root_block_attrs,
  26223. padd_empty_with_br: settings.padd_empty_with_br,
  26224. preserve_cdata: settings.preserve_cdata,
  26225. remove_trailing_brs: settings.remove_trailing_brs,
  26226. inline_styles: settings.inline_styles,
  26227. root_name: getRootName(editor),
  26228. validate: true,
  26229. blob_cache: blobCache,
  26230. document: editor.getDoc(),
  26231. images_dataimg_filter: settings.images_dataimg_filter
  26232. });
  26233. };
  26234. var mkSerializerSettings = function (editor) {
  26235. var settings = editor.settings;
  26236. return __assign(__assign({}, mkParserSettings(editor)), removeUndefined({
  26237. url_converter: settings.url_converter,
  26238. url_converter_scope: settings.url_converter_scope,
  26239. element_format: settings.element_format,
  26240. entities: settings.entities,
  26241. entity_encoding: settings.entity_encoding,
  26242. indent: settings.indent,
  26243. indent_after: settings.indent_after,
  26244. indent_before: settings.indent_before,
  26245. block_elements: settings.block_elements,
  26246. boolean_attributes: settings.boolean_attributes,
  26247. custom_elements: settings.custom_elements,
  26248. extended_valid_elements: settings.extended_valid_elements,
  26249. invalid_elements: settings.invalid_elements,
  26250. invalid_styles: settings.invalid_styles,
  26251. move_caret_before_on_enter_elements: settings.move_caret_before_on_enter_elements,
  26252. non_empty_elements: settings.non_empty_elements,
  26253. schema: settings.schema,
  26254. self_closing_elements: settings.self_closing_elements,
  26255. short_ended_elements: settings.short_ended_elements,
  26256. special: settings.special,
  26257. text_block_elements: settings.text_block_elements,
  26258. text_inline_elements: settings.text_inline_elements,
  26259. valid_children: settings.valid_children,
  26260. valid_classes: settings.valid_classes,
  26261. valid_elements: settings.valid_elements,
  26262. valid_styles: settings.valid_styles,
  26263. verify_html: settings.verify_html,
  26264. whitespace_elements: settings.whitespace_elements
  26265. }));
  26266. };
  26267. var createParser = function (editor) {
  26268. var parser = DomParser(mkParserSettings(editor), editor.schema);
  26269. parser.addAttributeFilter('src,href,style,tabindex', function (nodes, name) {
  26270. var i = nodes.length, node, value;
  26271. var dom = editor.dom;
  26272. var internalName = 'data-mce-' + name;
  26273. while (i--) {
  26274. node = nodes[i];
  26275. value = node.attr(name);
  26276. if (value && !node.attr(internalName)) {
  26277. if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) {
  26278. continue;
  26279. }
  26280. if (name === 'style') {
  26281. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  26282. if (!value.length) {
  26283. value = null;
  26284. }
  26285. node.attr(internalName, value);
  26286. node.attr(name, value);
  26287. } else if (name === 'tabindex') {
  26288. node.attr(internalName, value);
  26289. node.attr(name, null);
  26290. } else {
  26291. node.attr(internalName, editor.convertURL(value, name, node.name));
  26292. }
  26293. }
  26294. }
  26295. });
  26296. parser.addNodeFilter('script', function (nodes) {
  26297. var i = nodes.length;
  26298. while (i--) {
  26299. var node = nodes[i];
  26300. var type = node.attr('type') || 'no/type';
  26301. if (type.indexOf('mce-') !== 0) {
  26302. node.attr('type', 'mce-' + type);
  26303. }
  26304. }
  26305. });
  26306. if (editor.settings.preserve_cdata) {
  26307. parser.addNodeFilter('#cdata', function (nodes) {
  26308. var i = nodes.length;
  26309. while (i--) {
  26310. var node = nodes[i];
  26311. node.type = 8;
  26312. node.name = '#comment';
  26313. node.value = '[CDATA[' + editor.dom.encode(node.value) + ']]';
  26314. }
  26315. });
  26316. }
  26317. parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function (nodes) {
  26318. var i = nodes.length;
  26319. var nonEmptyElements = editor.schema.getNonEmptyElements();
  26320. while (i--) {
  26321. var node = nodes[i];
  26322. if (node.isEmpty(nonEmptyElements) && node.getAll('br').length === 0) {
  26323. node.append(new AstNode('br', 1)).shortEnded = true;
  26324. }
  26325. }
  26326. });
  26327. return parser;
  26328. };
  26329. var autoFocus = function (editor) {
  26330. if (editor.settings.auto_focus) {
  26331. Delay.setEditorTimeout(editor, function () {
  26332. var focusEditor;
  26333. if (editor.settings.auto_focus === true) {
  26334. focusEditor = editor;
  26335. } else {
  26336. focusEditor = editor.editorManager.get(editor.settings.auto_focus);
  26337. }
  26338. if (!focusEditor.destroyed) {
  26339. focusEditor.focus();
  26340. }
  26341. }, 100);
  26342. }
  26343. };
  26344. var moveSelectionToFirstCaretPosition = function (editor) {
  26345. var root = editor.dom.getRoot();
  26346. if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) {
  26347. firstPositionIn(root).each(function (pos) {
  26348. var node = pos.getNode();
  26349. var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  26350. if (Env.browser.isIE()) {
  26351. storeNative(editor, caretPos.toRange());
  26352. } else {
  26353. editor.selection.setRng(caretPos.toRange());
  26354. }
  26355. });
  26356. }
  26357. };
  26358. var initEditor = function (editor) {
  26359. editor.bindPendingEventDelegates();
  26360. editor.initialized = true;
  26361. fireInit(editor);
  26362. editor.focus(true);
  26363. moveSelectionToFirstCaretPosition(editor);
  26364. editor.nodeChanged({ initial: true });
  26365. editor.execCallback('init_instance_callback', editor);
  26366. autoFocus(editor);
  26367. };
  26368. var getStyleSheetLoader$1 = function (editor) {
  26369. return editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader;
  26370. };
  26371. var makeStylesheetLoadingPromises = function (editor, css, framedFonts) {
  26372. var promises = [new promiseObj(function (resolve, reject) {
  26373. return getStyleSheetLoader$1(editor).loadAll(css, resolve, reject);
  26374. })];
  26375. if (editor.inline) {
  26376. return promises;
  26377. } else {
  26378. return promises.concat([new promiseObj(function (resolve, reject) {
  26379. return editor.ui.styleSheetLoader.loadAll(framedFonts, resolve, reject);
  26380. })]);
  26381. }
  26382. };
  26383. var loadContentCss = function (editor) {
  26384. var styleSheetLoader = getStyleSheetLoader$1(editor);
  26385. var fontCss = getFontCss(editor);
  26386. var css = editor.contentCSS;
  26387. var removeCss = function () {
  26388. styleSheetLoader.unloadAll(css);
  26389. if (!editor.inline) {
  26390. editor.ui.styleSheetLoader.unloadAll(fontCss);
  26391. }
  26392. };
  26393. var loaded = function () {
  26394. if (editor.removed) {
  26395. removeCss();
  26396. } else {
  26397. editor.on('remove', removeCss);
  26398. }
  26399. };
  26400. if (editor.contentStyles.length > 0) {
  26401. var contentCssText_1 = '';
  26402. Tools.each(editor.contentStyles, function (style) {
  26403. contentCssText_1 += style + '\r\n';
  26404. });
  26405. editor.dom.addStyle(contentCssText_1);
  26406. }
  26407. var allStylesheets = promiseObj.all(makeStylesheetLoadingPromises(editor, css, fontCss)).then(loaded).catch(loaded);
  26408. if (editor.settings.content_style) {
  26409. appendStyle(editor, editor.settings.content_style);
  26410. }
  26411. return allStylesheets;
  26412. };
  26413. var preInit = function (editor) {
  26414. var settings = editor.settings, doc = editor.getDoc(), body = editor.getBody();
  26415. firePreInit(editor);
  26416. if (!settings.browser_spellcheck && !settings.gecko_spellcheck) {
  26417. doc.body.spellcheck = false;
  26418. DOM$6.setAttrib(body, 'spellcheck', 'false');
  26419. }
  26420. editor.quirks = Quirks(editor);
  26421. firePostRender(editor);
  26422. var directionality = getDirectionality(editor);
  26423. if (directionality !== undefined) {
  26424. body.dir = directionality;
  26425. }
  26426. if (settings.protect) {
  26427. editor.on('BeforeSetContent', function (e) {
  26428. Tools.each(settings.protect, function (pattern) {
  26429. e.content = e.content.replace(pattern, function (str) {
  26430. return '<!--mce:protected ' + escape(str) + '-->';
  26431. });
  26432. });
  26433. });
  26434. }
  26435. editor.on('SetContent', function () {
  26436. editor.addVisual(editor.getBody());
  26437. });
  26438. editor.on('compositionstart compositionend', function (e) {
  26439. editor.composing = e.type === 'compositionstart';
  26440. });
  26441. };
  26442. var loadInitialContent = function (editor) {
  26443. if (!isRtc(editor)) {
  26444. editor.load({
  26445. initial: true,
  26446. format: 'html'
  26447. });
  26448. }
  26449. editor.startContent = editor.getContent({ format: 'raw' });
  26450. };
  26451. var initEditorWithInitialContent = function (editor) {
  26452. if (editor.removed !== true) {
  26453. loadInitialContent(editor);
  26454. initEditor(editor);
  26455. }
  26456. };
  26457. var initContentBody = function (editor, skipWrite) {
  26458. var settings = editor.settings;
  26459. var targetElm = editor.getElement();
  26460. var doc = editor.getDoc();
  26461. if (!settings.inline) {
  26462. editor.getElement().style.visibility = editor.orgVisibility;
  26463. }
  26464. if (!skipWrite && !editor.inline) {
  26465. doc.open();
  26466. doc.write(editor.iframeHTML);
  26467. doc.close();
  26468. }
  26469. if (editor.inline) {
  26470. DOM$6.addClass(targetElm, 'mce-content-body');
  26471. editor.contentDocument = doc = document;
  26472. editor.contentWindow = window;
  26473. editor.bodyElement = targetElm;
  26474. editor.contentAreaContainer = targetElm;
  26475. }
  26476. var body = editor.getBody();
  26477. body.disabled = true;
  26478. editor.readonly = !!settings.readonly;
  26479. if (!editor.readonly) {
  26480. if (editor.inline && DOM$6.getStyle(body, 'position', true) === 'static') {
  26481. body.style.position = 'relative';
  26482. }
  26483. body.contentEditable = editor.getParam('content_editable_state', true);
  26484. }
  26485. body.disabled = false;
  26486. editor.editorUpload = EditorUpload(editor);
  26487. editor.schema = Schema(settings);
  26488. editor.dom = DOMUtils(doc, {
  26489. keep_values: true,
  26490. url_converter: editor.convertURL,
  26491. url_converter_scope: editor,
  26492. hex_colors: settings.force_hex_style_colors,
  26493. update_styles: true,
  26494. root_element: editor.inline ? editor.getBody() : null,
  26495. collect: function () {
  26496. return editor.inline;
  26497. },
  26498. schema: editor.schema,
  26499. contentCssCors: shouldUseContentCssCors(editor),
  26500. referrerPolicy: getReferrerPolicy(editor),
  26501. onSetAttrib: function (e) {
  26502. editor.fire('SetAttrib', e);
  26503. }
  26504. });
  26505. editor.parser = createParser(editor);
  26506. editor.serializer = DomSerializer(mkSerializerSettings(editor), editor);
  26507. editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor);
  26508. editor.annotator = Annotator(editor);
  26509. editor.formatter = Formatter(editor);
  26510. editor.undoManager = UndoManager(editor);
  26511. editor._nodeChangeDispatcher = new NodeChange(editor);
  26512. editor._selectionOverrides = SelectionOverrides(editor);
  26513. setup$e(editor);
  26514. setup$3(editor);
  26515. if (!isRtc(editor)) {
  26516. setup$2(editor);
  26517. }
  26518. var caret = setup$4(editor);
  26519. setup$f(editor, caret);
  26520. setup$d(editor);
  26521. setup$g(editor);
  26522. var setupRtcThunk = setup$i(editor);
  26523. preInit(editor);
  26524. setupRtcThunk.fold(function () {
  26525. loadContentCss(editor).then(function () {
  26526. return initEditorWithInitialContent(editor);
  26527. });
  26528. }, function (setupRtc) {
  26529. editor.setProgressState(true);
  26530. loadContentCss(editor).then(function () {
  26531. setupRtc().then(function (_rtcMode) {
  26532. editor.setProgressState(false);
  26533. initEditorWithInitialContent(editor);
  26534. }, function (err) {
  26535. editor.notificationManager.open({
  26536. type: 'error',
  26537. text: String(err)
  26538. });
  26539. initEditorWithInitialContent(editor);
  26540. });
  26541. });
  26542. });
  26543. };
  26544. var DOM$5 = DOMUtils.DOM;
  26545. var relaxDomain = function (editor, ifr) {
  26546. if (document.domain !== window.location.hostname && Env.browser.isIE()) {
  26547. var bodyUuid = uuid('mce');
  26548. editor[bodyUuid] = function () {
  26549. initContentBody(editor);
  26550. };
  26551. var domainRelaxUrl = 'javascript:(function(){' + 'document.open();document.domain="' + document.domain + '";' + 'var ed = window.parent.tinymce.get("' + editor.id + '");document.write(ed.iframeHTML);' + 'document.close();ed.' + bodyUuid + '(true);})()';
  26552. DOM$5.setAttrib(ifr, 'src', domainRelaxUrl);
  26553. return true;
  26554. }
  26555. return false;
  26556. };
  26557. var createIframeElement = function (id, title, height, customAttrs) {
  26558. var iframe = SugarElement.fromTag('iframe');
  26559. setAll$1(iframe, customAttrs);
  26560. setAll$1(iframe, {
  26561. id: id + '_ifr',
  26562. frameBorder: '0',
  26563. allowTransparency: 'true',
  26564. title: title
  26565. });
  26566. add$1(iframe, 'tox-edit-area__iframe');
  26567. return iframe;
  26568. };
  26569. var getIframeHtml = function (editor) {
  26570. var iframeHTML = getDocType(editor) + '<html><head>';
  26571. if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
  26572. iframeHTML += '<base href="' + editor.documentBaseURI.getURI() + '" />';
  26573. }
  26574. iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
  26575. var bodyId = getBodyId(editor);
  26576. var bodyClass = getBodyClass(editor);
  26577. if (getContentSecurityPolicy(editor)) {
  26578. iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + getContentSecurityPolicy(editor) + '" />';
  26579. }
  26580. iframeHTML += '</head><body id="' + bodyId + '" class="mce-content-body ' + bodyClass + '" data-id="' + editor.id + '"><br></body></html>';
  26581. return iframeHTML;
  26582. };
  26583. var createIframe = function (editor, o) {
  26584. var iframeTranslatedTitle = editor.translate(getIframeTitle(editor));
  26585. var ifr = createIframeElement(editor.id, iframeTranslatedTitle, o.height, getIframeAttrs(editor)).dom;
  26586. ifr.onload = function () {
  26587. ifr.onload = null;
  26588. editor.fire('load');
  26589. };
  26590. var isDomainRelaxed = relaxDomain(editor, ifr);
  26591. editor.contentAreaContainer = o.iframeContainer;
  26592. editor.iframeElement = ifr;
  26593. editor.iframeHTML = getIframeHtml(editor);
  26594. DOM$5.add(o.iframeContainer, ifr);
  26595. return isDomainRelaxed;
  26596. };
  26597. var init$1 = function (editor, boxInfo) {
  26598. var isDomainRelaxed = createIframe(editor, boxInfo);
  26599. if (boxInfo.editorContainer) {
  26600. DOM$5.get(boxInfo.editorContainer).style.display = editor.orgDisplay;
  26601. editor.hidden = DOM$5.isHidden(boxInfo.editorContainer);
  26602. }
  26603. editor.getElement().style.display = 'none';
  26604. DOM$5.setAttrib(editor.id, 'aria-hidden', 'true');
  26605. if (!isDomainRelaxed) {
  26606. initContentBody(editor);
  26607. }
  26608. };
  26609. var DOM$4 = DOMUtils.DOM;
  26610. var initPlugin = function (editor, initializedPlugins, plugin) {
  26611. var Plugin = PluginManager.get(plugin);
  26612. var pluginUrl = PluginManager.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, '');
  26613. plugin = Tools.trim(plugin);
  26614. if (Plugin && Tools.inArray(initializedPlugins, plugin) === -1) {
  26615. Tools.each(PluginManager.dependencies(plugin), function (dep) {
  26616. initPlugin(editor, initializedPlugins, dep);
  26617. });
  26618. if (editor.plugins[plugin]) {
  26619. return;
  26620. }
  26621. try {
  26622. var pluginInstance = new Plugin(editor, pluginUrl, editor.$);
  26623. editor.plugins[plugin] = pluginInstance;
  26624. if (pluginInstance.init) {
  26625. pluginInstance.init(editor, pluginUrl);
  26626. initializedPlugins.push(plugin);
  26627. }
  26628. } catch (e) {
  26629. pluginInitError(editor, plugin, e);
  26630. }
  26631. }
  26632. };
  26633. var trimLegacyPrefix = function (name) {
  26634. return name.replace(/^\-/, '');
  26635. };
  26636. var initPlugins = function (editor) {
  26637. var initializedPlugins = [];
  26638. Tools.each(getPlugins(editor).split(/[ ,]/), function (name) {
  26639. initPlugin(editor, initializedPlugins, trimLegacyPrefix(name));
  26640. });
  26641. };
  26642. var initIcons = function (editor) {
  26643. var iconPackName = Tools.trim(getIconPackName(editor));
  26644. var currentIcons = editor.ui.registry.getAll().icons;
  26645. var loadIcons = __assign(__assign({}, IconManager.get('default').icons), IconManager.get(iconPackName).icons);
  26646. each$j(loadIcons, function (svgData, icon) {
  26647. if (!has$2(currentIcons, icon)) {
  26648. editor.ui.registry.addIcon(icon, svgData);
  26649. }
  26650. });
  26651. };
  26652. var initTheme = function (editor) {
  26653. var theme = getTheme(editor);
  26654. if (isString$1(theme)) {
  26655. editor.settings.theme = trimLegacyPrefix(theme);
  26656. var Theme = ThemeManager.get(theme);
  26657. editor.theme = new Theme(editor, ThemeManager.urls[theme]);
  26658. if (editor.theme.init) {
  26659. editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ''), editor.$);
  26660. }
  26661. } else {
  26662. editor.theme = {};
  26663. }
  26664. };
  26665. var renderFromLoadedTheme = function (editor) {
  26666. return editor.theme.renderUI();
  26667. };
  26668. var renderFromThemeFunc = function (editor) {
  26669. var elm = editor.getElement();
  26670. var theme = getTheme(editor);
  26671. var info = theme(editor, elm);
  26672. if (info.editorContainer.nodeType) {
  26673. info.editorContainer.id = info.editorContainer.id || editor.id + '_parent';
  26674. }
  26675. if (info.iframeContainer && info.iframeContainer.nodeType) {
  26676. info.iframeContainer.id = info.iframeContainer.id || editor.id + '_iframecontainer';
  26677. }
  26678. info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
  26679. return info;
  26680. };
  26681. var createThemeFalseResult = function (element) {
  26682. return {
  26683. editorContainer: element,
  26684. iframeContainer: element,
  26685. api: {}
  26686. };
  26687. };
  26688. var renderThemeFalseIframe = function (targetElement) {
  26689. var iframeContainer = DOM$4.create('div');
  26690. DOM$4.insertAfter(iframeContainer, targetElement);
  26691. return createThemeFalseResult(iframeContainer);
  26692. };
  26693. var renderThemeFalse = function (editor) {
  26694. var targetElement = editor.getElement();
  26695. return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
  26696. };
  26697. var renderThemeUi = function (editor) {
  26698. var elm = editor.getElement();
  26699. editor.orgDisplay = elm.style.display;
  26700. if (isString$1(getTheme(editor))) {
  26701. return renderFromLoadedTheme(editor);
  26702. } else if (isFunction(getTheme(editor))) {
  26703. return renderFromThemeFunc(editor);
  26704. } else {
  26705. return renderThemeFalse(editor);
  26706. }
  26707. };
  26708. var augmentEditorUiApi = function (editor, api) {
  26709. var uiApiFacade = {
  26710. show: Optional.from(api.show).getOr(noop),
  26711. hide: Optional.from(api.hide).getOr(noop),
  26712. disable: Optional.from(api.disable).getOr(noop),
  26713. isDisabled: Optional.from(api.isDisabled).getOr(never),
  26714. enable: function () {
  26715. if (!editor.mode.isReadOnly()) {
  26716. Optional.from(api.enable).map(call);
  26717. }
  26718. }
  26719. };
  26720. editor.ui = __assign(__assign({}, editor.ui), uiApiFacade);
  26721. };
  26722. var init = function (editor) {
  26723. editor.fire('ScriptsLoaded');
  26724. initIcons(editor);
  26725. initTheme(editor);
  26726. initPlugins(editor);
  26727. var renderInfo = renderThemeUi(editor);
  26728. augmentEditorUiApi(editor, Optional.from(renderInfo.api).getOr({}));
  26729. var boxInfo = {
  26730. editorContainer: renderInfo.editorContainer,
  26731. iframeContainer: renderInfo.iframeContainer
  26732. };
  26733. editor.editorContainer = boxInfo.editorContainer ? boxInfo.editorContainer : null;
  26734. appendContentCssFromSettings(editor);
  26735. if (editor.inline) {
  26736. return initContentBody(editor);
  26737. } else {
  26738. return init$1(editor, boxInfo);
  26739. }
  26740. };
  26741. var DOM$3 = DOMUtils.DOM;
  26742. var hasSkipLoadPrefix = function (name) {
  26743. return name.charAt(0) === '-';
  26744. };
  26745. var loadLanguage = function (scriptLoader, editor) {
  26746. var languageCode = getLanguageCode(editor);
  26747. var languageUrl = getLanguageUrl(editor);
  26748. if (I18n.hasCode(languageCode) === false && languageCode !== 'en') {
  26749. var url_1 = languageUrl !== '' ? languageUrl : editor.editorManager.baseURL + '/langs/' + languageCode + '.js';
  26750. scriptLoader.add(url_1, noop, undefined, function () {
  26751. languageLoadError(editor, url_1, languageCode);
  26752. });
  26753. }
  26754. };
  26755. var loadTheme = function (scriptLoader, editor, suffix, callback) {
  26756. var theme = getTheme(editor);
  26757. if (isString$1(theme)) {
  26758. if (!hasSkipLoadPrefix(theme) && !has$2(ThemeManager.urls, theme)) {
  26759. var themeUrl = getThemeUrl(editor);
  26760. if (themeUrl) {
  26761. ThemeManager.load(theme, editor.documentBaseURI.toAbsolute(themeUrl));
  26762. } else {
  26763. ThemeManager.load(theme, 'themes/' + theme + '/theme' + suffix + '.js');
  26764. }
  26765. }
  26766. scriptLoader.loadQueue(function () {
  26767. ThemeManager.waitFor(theme, callback);
  26768. });
  26769. } else {
  26770. callback();
  26771. }
  26772. };
  26773. var getIconsUrlMetaFromUrl = function (editor) {
  26774. return Optional.from(getIconsUrl(editor)).filter(function (url) {
  26775. return url.length > 0;
  26776. }).map(function (url) {
  26777. return {
  26778. url: url,
  26779. name: Optional.none()
  26780. };
  26781. });
  26782. };
  26783. var getIconsUrlMetaFromName = function (editor, name, suffix) {
  26784. return Optional.from(name).filter(function (name) {
  26785. return name.length > 0 && !IconManager.has(name);
  26786. }).map(function (name) {
  26787. return {
  26788. url: editor.editorManager.baseURL + '/icons/' + name + '/icons' + suffix + '.js',
  26789. name: Optional.some(name)
  26790. };
  26791. });
  26792. };
  26793. var loadIcons = function (scriptLoader, editor, suffix) {
  26794. var defaultIconsUrl = getIconsUrlMetaFromName(editor, 'default', suffix);
  26795. var customIconsUrl = getIconsUrlMetaFromUrl(editor).orThunk(function () {
  26796. return getIconsUrlMetaFromName(editor, getIconPackName(editor), '');
  26797. });
  26798. each$k(cat([
  26799. defaultIconsUrl,
  26800. customIconsUrl
  26801. ]), function (urlMeta) {
  26802. scriptLoader.add(urlMeta.url, noop, undefined, function () {
  26803. iconsLoadError(editor, urlMeta.url, urlMeta.name.getOrUndefined());
  26804. });
  26805. });
  26806. };
  26807. var loadPlugins = function (editor, suffix) {
  26808. Tools.each(getExternalPlugins$1(editor), function (url, name) {
  26809. PluginManager.load(name, url, noop, undefined, function () {
  26810. pluginLoadError(editor, url, name);
  26811. });
  26812. editor.settings.plugins += ' ' + name;
  26813. });
  26814. Tools.each(getPlugins(editor).split(/[ ,]/), function (plugin) {
  26815. plugin = Tools.trim(plugin);
  26816. if (plugin && !PluginManager.urls[plugin]) {
  26817. if (hasSkipLoadPrefix(plugin)) {
  26818. plugin = plugin.substr(1, plugin.length);
  26819. var dependencies = PluginManager.dependencies(plugin);
  26820. Tools.each(dependencies, function (depPlugin) {
  26821. var defaultSettings = {
  26822. prefix: 'plugins/',
  26823. resource: depPlugin,
  26824. suffix: '/plugin' + suffix + '.js'
  26825. };
  26826. var dep = PluginManager.createUrl(defaultSettings, depPlugin);
  26827. PluginManager.load(dep.resource, dep, noop, undefined, function () {
  26828. pluginLoadError(editor, dep.prefix + dep.resource + dep.suffix, dep.resource);
  26829. });
  26830. });
  26831. } else {
  26832. var url_2 = {
  26833. prefix: 'plugins/',
  26834. resource: plugin,
  26835. suffix: '/plugin' + suffix + '.js'
  26836. };
  26837. PluginManager.load(plugin, url_2, noop, undefined, function () {
  26838. pluginLoadError(editor, url_2.prefix + url_2.resource + url_2.suffix, plugin);
  26839. });
  26840. }
  26841. }
  26842. });
  26843. };
  26844. var loadScripts = function (editor, suffix) {
  26845. var scriptLoader = ScriptLoader.ScriptLoader;
  26846. loadTheme(scriptLoader, editor, suffix, function () {
  26847. loadLanguage(scriptLoader, editor);
  26848. loadIcons(scriptLoader, editor, suffix);
  26849. loadPlugins(editor, suffix);
  26850. scriptLoader.loadQueue(function () {
  26851. if (!editor.removed) {
  26852. init(editor);
  26853. }
  26854. }, editor, function () {
  26855. if (!editor.removed) {
  26856. init(editor);
  26857. }
  26858. });
  26859. });
  26860. };
  26861. var getStyleSheetLoader = function (element, editor) {
  26862. return instance.forElement(element, {
  26863. contentCssCors: hasContentCssCors(editor),
  26864. referrerPolicy: getReferrerPolicy(editor)
  26865. });
  26866. };
  26867. var render = function (editor) {
  26868. var id = editor.id;
  26869. I18n.setCode(getLanguageCode(editor));
  26870. var readyHandler = function () {
  26871. DOM$3.unbind(window, 'ready', readyHandler);
  26872. editor.render();
  26873. };
  26874. if (!EventUtils.Event.domLoaded) {
  26875. DOM$3.bind(window, 'ready', readyHandler);
  26876. return;
  26877. }
  26878. if (!editor.getElement()) {
  26879. return;
  26880. }
  26881. if (!Env.contentEditable) {
  26882. return;
  26883. }
  26884. var element = SugarElement.fromDom(editor.getElement());
  26885. var snapshot = clone$3(element);
  26886. editor.on('remove', function () {
  26887. eachr(element.dom.attributes, function (attr) {
  26888. return remove$6(element, attr.name);
  26889. });
  26890. setAll$1(element, snapshot);
  26891. });
  26892. editor.ui.styleSheetLoader = getStyleSheetLoader(element, editor);
  26893. if (!isInline(editor)) {
  26894. editor.orgVisibility = editor.getElement().style.visibility;
  26895. editor.getElement().style.visibility = 'hidden';
  26896. } else {
  26897. editor.inline = true;
  26898. }
  26899. var form = editor.getElement().form || DOM$3.getParent(id, 'form');
  26900. if (form) {
  26901. editor.formElement = form;
  26902. if (hasHiddenInput(editor) && !isTextareaOrInput(editor.getElement())) {
  26903. DOM$3.insertAfter(DOM$3.create('input', {
  26904. type: 'hidden',
  26905. name: id
  26906. }), id);
  26907. editor.hasHiddenInput = true;
  26908. }
  26909. editor.formEventDelegate = function (e) {
  26910. editor.fire(e.type, e);
  26911. };
  26912. DOM$3.bind(form, 'submit reset', editor.formEventDelegate);
  26913. editor.on('reset', function () {
  26914. editor.resetContent();
  26915. });
  26916. if (shouldPatchSubmit(editor) && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
  26917. form._mceOldSubmit = form.submit;
  26918. form.submit = function () {
  26919. editor.editorManager.triggerSave();
  26920. editor.setDirty(false);
  26921. return form._mceOldSubmit(form);
  26922. };
  26923. }
  26924. }
  26925. editor.windowManager = WindowManager(editor);
  26926. editor.notificationManager = NotificationManager(editor);
  26927. if (isEncodingXml(editor)) {
  26928. editor.on('GetContent', function (e) {
  26929. if (e.save) {
  26930. e.content = DOM$3.encode(e.content);
  26931. }
  26932. });
  26933. }
  26934. if (shouldAddFormSubmitTrigger(editor)) {
  26935. editor.on('submit', function () {
  26936. if (editor.initialized) {
  26937. editor.save();
  26938. }
  26939. });
  26940. }
  26941. if (shouldAddUnloadTrigger(editor)) {
  26942. editor._beforeUnload = function () {
  26943. if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
  26944. editor.save({
  26945. format: 'raw',
  26946. no_events: true,
  26947. set_dirty: false
  26948. });
  26949. }
  26950. };
  26951. editor.editorManager.on('BeforeUnload', editor._beforeUnload);
  26952. }
  26953. editor.editorManager.add(editor);
  26954. loadScripts(editor, editor.suffix);
  26955. };
  26956. var addVisual = function (editor, elm) {
  26957. return addVisual$1(editor, elm);
  26958. };
  26959. var legacyPropNames = {
  26960. 'font-size': 'size',
  26961. 'font-family': 'face'
  26962. };
  26963. var getSpecifiedFontProp = function (propName, rootElm, elm) {
  26964. var getProperty = function (elm) {
  26965. return getRaw(elm, propName).orThunk(function () {
  26966. if (name(elm) === 'font') {
  26967. return get$9(legacyPropNames, propName).bind(function (legacyPropName) {
  26968. return getOpt(elm, legacyPropName);
  26969. });
  26970. } else {
  26971. return Optional.none();
  26972. }
  26973. });
  26974. };
  26975. var isRoot = function (elm) {
  26976. return eq(SugarElement.fromDom(rootElm), elm);
  26977. };
  26978. return closest$1(SugarElement.fromDom(elm), function (elm) {
  26979. return getProperty(elm);
  26980. }, isRoot);
  26981. };
  26982. var normalizeFontFamily = function (fontFamily) {
  26983. return fontFamily.replace(/[\'\"\\]/g, '').replace(/,\s+/g, ',');
  26984. };
  26985. var getComputedFontProp = function (propName, elm) {
  26986. return Optional.from(DOMUtils.DOM.getStyle(elm, propName, true));
  26987. };
  26988. var getFontProp = function (propName) {
  26989. return function (rootElm, elm) {
  26990. return Optional.from(elm).map(SugarElement.fromDom).filter(isElement$6).bind(function (element) {
  26991. return getSpecifiedFontProp(propName, rootElm, element.dom).or(getComputedFontProp(propName, element.dom));
  26992. }).getOr('');
  26993. };
  26994. };
  26995. var getFontSize = getFontProp('font-size');
  26996. var getFontFamily = compose(normalizeFontFamily, getFontProp('font-family'));
  26997. var findFirstCaretElement = function (editor) {
  26998. return firstPositionIn(editor.getBody()).map(function (caret) {
  26999. var container = caret.container();
  27000. return isText$7(container) ? container.parentNode : container;
  27001. });
  27002. };
  27003. var getCaretElement = function (editor) {
  27004. return Optional.from(editor.selection.getRng()).bind(function (rng) {
  27005. var root = editor.getBody();
  27006. var atStartOfNode = rng.startContainer === root && rng.startOffset === 0;
  27007. return atStartOfNode ? Optional.none() : Optional.from(editor.selection.getStart(true));
  27008. });
  27009. };
  27010. var bindRange = function (editor, binder) {
  27011. return getCaretElement(editor).orThunk(curry(findFirstCaretElement, editor)).map(SugarElement.fromDom).filter(isElement$6).bind(binder);
  27012. };
  27013. var mapRange = function (editor, mapper) {
  27014. return bindRange(editor, compose1(Optional.some, mapper));
  27015. };
  27016. var fromFontSizeNumber = function (editor, value) {
  27017. if (/^[0-9.]+$/.test(value)) {
  27018. var fontSizeNumber = parseInt(value, 10);
  27019. if (fontSizeNumber >= 1 && fontSizeNumber <= 7) {
  27020. var fontSizes = getFontStyleValues(editor);
  27021. var fontClasses = getFontSizeClasses(editor);
  27022. if (fontClasses) {
  27023. return fontClasses[fontSizeNumber - 1] || value;
  27024. } else {
  27025. return fontSizes[fontSizeNumber - 1] || value;
  27026. }
  27027. } else {
  27028. return value;
  27029. }
  27030. } else {
  27031. return value;
  27032. }
  27033. };
  27034. var normalizeFontNames = function (font) {
  27035. var fonts = font.split(/\s*,\s*/);
  27036. return map$3(fonts, function (font) {
  27037. if (font.indexOf(' ') !== -1 && !(startsWith(font, '"') || startsWith(font, '\''))) {
  27038. return '\'' + font + '\'';
  27039. } else {
  27040. return font;
  27041. }
  27042. }).join(',');
  27043. };
  27044. var fontNameAction = function (editor, value) {
  27045. var font = fromFontSizeNumber(editor, value);
  27046. editor.formatter.toggle('fontname', { value: normalizeFontNames(font) });
  27047. editor.nodeChanged();
  27048. };
  27049. var fontNameQuery = function (editor) {
  27050. return mapRange(editor, function (elm) {
  27051. return getFontFamily(editor.getBody(), elm.dom);
  27052. }).getOr('');
  27053. };
  27054. var fontSizeAction = function (editor, value) {
  27055. editor.formatter.toggle('fontsize', { value: fromFontSizeNumber(editor, value) });
  27056. editor.nodeChanged();
  27057. };
  27058. var fontSizeQuery = function (editor) {
  27059. return mapRange(editor, function (elm) {
  27060. return getFontSize(editor.getBody(), elm.dom);
  27061. }).getOr('');
  27062. };
  27063. var lineHeightQuery = function (editor) {
  27064. return mapRange(editor, function (elm) {
  27065. var root = SugarElement.fromDom(editor.getBody());
  27066. var specifiedStyle = closest$1(elm, function (elm) {
  27067. return getRaw(elm, 'line-height');
  27068. }, curry(eq, root));
  27069. var computedStyle = function () {
  27070. var lineHeight = parseFloat(get$5(elm, 'line-height'));
  27071. var fontSize = parseFloat(get$5(elm, 'font-size'));
  27072. return String(lineHeight / fontSize);
  27073. };
  27074. return specifiedStyle.getOrThunk(computedStyle);
  27075. }).getOr('');
  27076. };
  27077. var lineHeightAction = function (editor, lineHeight) {
  27078. editor.formatter.toggle('lineheight', { value: String(lineHeight) });
  27079. editor.nodeChanged();
  27080. };
  27081. var processValue = function (value) {
  27082. if (typeof value !== 'string') {
  27083. var details = Tools.extend({
  27084. paste: value.paste,
  27085. data: { paste: value.paste }
  27086. }, value);
  27087. return {
  27088. content: value.content,
  27089. details: details
  27090. };
  27091. }
  27092. return {
  27093. content: value,
  27094. details: {}
  27095. };
  27096. };
  27097. var insertAtCaret = function (editor, value) {
  27098. var result = processValue(value);
  27099. insertContent(editor, result.content, result.details);
  27100. };
  27101. var each$4 = Tools.each;
  27102. var map = Tools.map, inArray = Tools.inArray;
  27103. var EditorCommands = function () {
  27104. function EditorCommands(editor) {
  27105. this.commands = {
  27106. state: {},
  27107. exec: {},
  27108. value: {}
  27109. };
  27110. this.editor = editor;
  27111. this.setupCommands(editor);
  27112. }
  27113. EditorCommands.prototype.execCommand = function (command, ui, value, args) {
  27114. var func, state = false;
  27115. var self = this;
  27116. if (self.editor.removed) {
  27117. return;
  27118. }
  27119. if (command.toLowerCase() !== 'mcefocus') {
  27120. if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) {
  27121. self.editor.focus();
  27122. } else {
  27123. restore(self.editor);
  27124. }
  27125. }
  27126. args = self.editor.fire('BeforeExecCommand', {
  27127. command: command,
  27128. ui: ui,
  27129. value: value
  27130. });
  27131. if (args.isDefaultPrevented()) {
  27132. return false;
  27133. }
  27134. var customCommand = command.toLowerCase();
  27135. if (func = self.commands.exec[customCommand]) {
  27136. func(customCommand, ui, value);
  27137. self.editor.fire('ExecCommand', {
  27138. command: command,
  27139. ui: ui,
  27140. value: value
  27141. });
  27142. return true;
  27143. }
  27144. each$4(this.editor.plugins, function (p) {
  27145. if (p.execCommand && p.execCommand(command, ui, value)) {
  27146. self.editor.fire('ExecCommand', {
  27147. command: command,
  27148. ui: ui,
  27149. value: value
  27150. });
  27151. state = true;
  27152. return false;
  27153. }
  27154. });
  27155. if (state) {
  27156. return state;
  27157. }
  27158. if (self.editor.theme && self.editor.theme.execCommand && self.editor.theme.execCommand(command, ui, value)) {
  27159. self.editor.fire('ExecCommand', {
  27160. command: command,
  27161. ui: ui,
  27162. value: value
  27163. });
  27164. return true;
  27165. }
  27166. try {
  27167. state = self.editor.getDoc().execCommand(command, ui, value);
  27168. } catch (ex) {
  27169. }
  27170. if (state) {
  27171. self.editor.fire('ExecCommand', {
  27172. command: command,
  27173. ui: ui,
  27174. value: value
  27175. });
  27176. return true;
  27177. }
  27178. return false;
  27179. };
  27180. EditorCommands.prototype.queryCommandState = function (command) {
  27181. var func;
  27182. if (this.editor.quirks.isHidden() || this.editor.removed) {
  27183. return;
  27184. }
  27185. command = command.toLowerCase();
  27186. if (func = this.commands.state[command]) {
  27187. return func(command);
  27188. }
  27189. try {
  27190. return this.editor.getDoc().queryCommandState(command);
  27191. } catch (ex) {
  27192. }
  27193. return false;
  27194. };
  27195. EditorCommands.prototype.queryCommandValue = function (command) {
  27196. var func;
  27197. if (this.editor.quirks.isHidden() || this.editor.removed) {
  27198. return;
  27199. }
  27200. command = command.toLowerCase();
  27201. if (func = this.commands.value[command]) {
  27202. return func(command);
  27203. }
  27204. try {
  27205. return this.editor.getDoc().queryCommandValue(command);
  27206. } catch (ex) {
  27207. }
  27208. };
  27209. EditorCommands.prototype.addCommands = function (commandList, type) {
  27210. if (type === void 0) {
  27211. type = 'exec';
  27212. }
  27213. var self = this;
  27214. each$4(commandList, function (callback, command) {
  27215. each$4(command.toLowerCase().split(','), function (command) {
  27216. self.commands[type][command] = callback;
  27217. });
  27218. });
  27219. };
  27220. EditorCommands.prototype.addCommand = function (command, callback, scope) {
  27221. var _this = this;
  27222. command = command.toLowerCase();
  27223. this.commands.exec[command] = function (command, ui, value, args) {
  27224. return callback.call(scope || _this.editor, ui, value, args);
  27225. };
  27226. };
  27227. EditorCommands.prototype.queryCommandSupported = function (command) {
  27228. command = command.toLowerCase();
  27229. if (this.commands.exec[command]) {
  27230. return true;
  27231. }
  27232. try {
  27233. return this.editor.getDoc().queryCommandSupported(command);
  27234. } catch (ex) {
  27235. }
  27236. return false;
  27237. };
  27238. EditorCommands.prototype.addQueryStateHandler = function (command, callback, scope) {
  27239. var _this = this;
  27240. command = command.toLowerCase();
  27241. this.commands.state[command] = function () {
  27242. return callback.call(scope || _this.editor);
  27243. };
  27244. };
  27245. EditorCommands.prototype.addQueryValueHandler = function (command, callback, scope) {
  27246. var _this = this;
  27247. command = command.toLowerCase();
  27248. this.commands.value[command] = function () {
  27249. return callback.call(scope || _this.editor);
  27250. };
  27251. };
  27252. EditorCommands.prototype.hasCustomCommand = function (command) {
  27253. command = command.toLowerCase();
  27254. return !!this.commands.exec[command];
  27255. };
  27256. EditorCommands.prototype.execNativeCommand = function (command, ui, value) {
  27257. if (ui === undefined) {
  27258. ui = false;
  27259. }
  27260. if (value === undefined) {
  27261. value = null;
  27262. }
  27263. return this.editor.getDoc().execCommand(command, ui, value);
  27264. };
  27265. EditorCommands.prototype.isFormatMatch = function (name) {
  27266. return this.editor.formatter.match(name);
  27267. };
  27268. EditorCommands.prototype.toggleFormat = function (name, value) {
  27269. this.editor.formatter.toggle(name, value);
  27270. this.editor.nodeChanged();
  27271. };
  27272. EditorCommands.prototype.storeSelection = function (type) {
  27273. this.selectionBookmark = this.editor.selection.getBookmark(type);
  27274. };
  27275. EditorCommands.prototype.restoreSelection = function () {
  27276. this.editor.selection.moveToBookmark(this.selectionBookmark);
  27277. };
  27278. EditorCommands.prototype.setupCommands = function (editor) {
  27279. var self = this;
  27280. this.addCommands({
  27281. 'mceResetDesignMode,mceBeginUndoLevel': noop,
  27282. 'mceEndUndoLevel,mceAddUndoLevel': function () {
  27283. editor.undoManager.add();
  27284. },
  27285. 'mceFocus': function (_command, _ui, value) {
  27286. focus(editor, value);
  27287. },
  27288. 'Cut,Copy,Paste': function (command) {
  27289. var doc = editor.getDoc();
  27290. var failed;
  27291. try {
  27292. self.execNativeCommand(command);
  27293. } catch (ex) {
  27294. failed = true;
  27295. }
  27296. if (command === 'paste' && !doc.queryCommandEnabled(command)) {
  27297. failed = true;
  27298. }
  27299. if (failed || !doc.queryCommandSupported(command)) {
  27300. var msg = editor.translate('Your browser doesn\'t support direct access to the clipboard. ' + 'Please use the Ctrl+X/C/V keyboard shortcuts instead.');
  27301. if (Env.mac) {
  27302. msg = msg.replace(/Ctrl\+/g, '\u2318+');
  27303. }
  27304. editor.notificationManager.open({
  27305. text: msg,
  27306. type: 'error'
  27307. });
  27308. }
  27309. },
  27310. 'unlink': function () {
  27311. if (editor.selection.isCollapsed()) {
  27312. var elm = editor.dom.getParent(editor.selection.getStart(), 'a');
  27313. if (elm) {
  27314. editor.dom.remove(elm, true);
  27315. }
  27316. return;
  27317. }
  27318. editor.formatter.remove('link');
  27319. },
  27320. 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone': function (command) {
  27321. var align = command.substring(7);
  27322. if (align === 'full') {
  27323. align = 'justify';
  27324. }
  27325. each$4('left,center,right,justify'.split(','), function (name) {
  27326. if (align !== name) {
  27327. editor.formatter.remove('align' + name);
  27328. }
  27329. });
  27330. if (align !== 'none') {
  27331. self.toggleFormat('align' + align);
  27332. }
  27333. },
  27334. 'InsertUnorderedList,InsertOrderedList': function (command) {
  27335. var listParent;
  27336. self.execNativeCommand(command);
  27337. var listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
  27338. if (listElm) {
  27339. listParent = listElm.parentNode;
  27340. if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
  27341. self.storeSelection();
  27342. editor.dom.split(listParent, listElm);
  27343. self.restoreSelection();
  27344. }
  27345. }
  27346. },
  27347. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  27348. self.toggleFormat(command);
  27349. },
  27350. 'ForeColor,HiliteColor': function (command, ui, value) {
  27351. self.toggleFormat(command, { value: value });
  27352. },
  27353. 'FontName': function (command, ui, value) {
  27354. fontNameAction(editor, value);
  27355. },
  27356. 'FontSize': function (command, ui, value) {
  27357. fontSizeAction(editor, value);
  27358. },
  27359. 'LineHeight': function (command, ui, value) {
  27360. lineHeightAction(editor, value);
  27361. },
  27362. 'Lang': function (command, ui, lang) {
  27363. self.toggleFormat(command, {
  27364. value: lang.code,
  27365. customValue: lang.customCode
  27366. });
  27367. },
  27368. 'RemoveFormat': function (command) {
  27369. editor.formatter.remove(command);
  27370. },
  27371. 'mceBlockQuote': function () {
  27372. self.toggleFormat('blockquote');
  27373. },
  27374. 'FormatBlock': function (command, ui, value) {
  27375. return self.toggleFormat(value || 'p');
  27376. },
  27377. 'mceCleanup': function () {
  27378. var bookmark = editor.selection.getBookmark();
  27379. editor.setContent(editor.getContent());
  27380. editor.selection.moveToBookmark(bookmark);
  27381. },
  27382. 'mceRemoveNode': function (command, ui, value) {
  27383. var node = value || editor.selection.getNode();
  27384. if (node !== editor.getBody()) {
  27385. self.storeSelection();
  27386. editor.dom.remove(node, true);
  27387. self.restoreSelection();
  27388. }
  27389. },
  27390. 'mceSelectNodeDepth': function (command, ui, value) {
  27391. var counter = 0;
  27392. editor.dom.getParent(editor.selection.getNode(), function (node) {
  27393. if (node.nodeType === 1 && counter++ === value) {
  27394. editor.selection.select(node);
  27395. return false;
  27396. }
  27397. }, editor.getBody());
  27398. },
  27399. 'mceSelectNode': function (command, ui, value) {
  27400. editor.selection.select(value);
  27401. },
  27402. 'mceInsertContent': function (command, ui, value) {
  27403. insertAtCaret(editor, value);
  27404. },
  27405. 'mceInsertRawHTML': function (command, ui, value) {
  27406. editor.selection.setContent('tiny_mce_marker');
  27407. var content = editor.getContent();
  27408. editor.setContent(content.replace(/tiny_mce_marker/g, function () {
  27409. return value;
  27410. }));
  27411. },
  27412. 'mceInsertNewLine': function (command, ui, value) {
  27413. insert(editor, value);
  27414. },
  27415. 'mceToggleFormat': function (command, ui, value) {
  27416. self.toggleFormat(value);
  27417. },
  27418. 'mceSetContent': function (command, ui, value) {
  27419. editor.setContent(value);
  27420. },
  27421. 'Indent,Outdent': function (command) {
  27422. handle(editor, command);
  27423. },
  27424. 'mceRepaint': noop,
  27425. 'InsertHorizontalRule': function () {
  27426. editor.execCommand('mceInsertContent', false, '<hr />');
  27427. },
  27428. 'mceToggleVisualAid': function () {
  27429. editor.hasVisual = !editor.hasVisual;
  27430. editor.addVisual();
  27431. },
  27432. 'mceReplaceContent': function (command, ui, value) {
  27433. editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, editor.selection.getContent({ format: 'text' })));
  27434. },
  27435. 'mceInsertLink': function (command, ui, value) {
  27436. if (typeof value === 'string') {
  27437. value = { href: value };
  27438. }
  27439. var anchor = editor.dom.getParent(editor.selection.getNode(), 'a');
  27440. value.href = value.href.replace(/ /g, '%20');
  27441. if (!anchor || !value.href) {
  27442. editor.formatter.remove('link');
  27443. }
  27444. if (value.href) {
  27445. editor.formatter.apply('link', value, anchor);
  27446. }
  27447. },
  27448. 'selectAll': function () {
  27449. var editingHost = editor.dom.getParent(editor.selection.getStart(), isContentEditableTrue$4);
  27450. if (editingHost) {
  27451. var rng = editor.dom.createRng();
  27452. rng.selectNodeContents(editingHost);
  27453. editor.selection.setRng(rng);
  27454. }
  27455. },
  27456. 'mceNewDocument': function () {
  27457. editor.setContent('');
  27458. },
  27459. 'InsertLineBreak': function (command, ui, value) {
  27460. insert$1(editor, value);
  27461. return true;
  27462. }
  27463. });
  27464. var alignStates = function (name) {
  27465. return function () {
  27466. var selection = editor.selection;
  27467. var nodes = selection.isCollapsed() ? [editor.dom.getParent(selection.getNode(), editor.dom.isBlock)] : selection.getSelectedBlocks();
  27468. var matches = map(nodes, function (node) {
  27469. return !!editor.formatter.matchNode(node, name);
  27470. });
  27471. return inArray(matches, true) !== -1;
  27472. };
  27473. };
  27474. self.addCommands({
  27475. 'JustifyLeft': alignStates('alignleft'),
  27476. 'JustifyCenter': alignStates('aligncenter'),
  27477. 'JustifyRight': alignStates('alignright'),
  27478. 'JustifyFull': alignStates('alignjustify'),
  27479. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  27480. return self.isFormatMatch(command);
  27481. },
  27482. 'mceBlockQuote': function () {
  27483. return self.isFormatMatch('blockquote');
  27484. },
  27485. 'Outdent': function () {
  27486. return canOutdent(editor);
  27487. },
  27488. 'InsertUnorderedList,InsertOrderedList': function (command) {
  27489. var list = editor.dom.getParent(editor.selection.getNode(), 'ul,ol');
  27490. return list && (command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL');
  27491. }
  27492. }, 'state');
  27493. self.addCommands({
  27494. Undo: function () {
  27495. editor.undoManager.undo();
  27496. },
  27497. Redo: function () {
  27498. editor.undoManager.redo();
  27499. }
  27500. });
  27501. self.addQueryValueHandler('FontName', function () {
  27502. return fontNameQuery(editor);
  27503. }, this);
  27504. self.addQueryValueHandler('FontSize', function () {
  27505. return fontSizeQuery(editor);
  27506. }, this);
  27507. self.addQueryValueHandler('LineHeight', function () {
  27508. return lineHeightQuery(editor);
  27509. }, this);
  27510. };
  27511. return EditorCommands;
  27512. }();
  27513. var internalContentEditableAttr = 'data-mce-contenteditable';
  27514. var toggleClass = function (elm, cls, state) {
  27515. if (has(elm, cls) && state === false) {
  27516. remove$3(elm, cls);
  27517. } else if (state) {
  27518. add$1(elm, cls);
  27519. }
  27520. };
  27521. var setEditorCommandState = function (editor, cmd, state) {
  27522. try {
  27523. editor.getDoc().execCommand(cmd, false, String(state));
  27524. } catch (ex) {
  27525. }
  27526. };
  27527. var setContentEditable = function (elm, state) {
  27528. elm.dom.contentEditable = state ? 'true' : 'false';
  27529. };
  27530. var switchOffContentEditableTrue = function (elm) {
  27531. each$k(descendants(elm, '*[contenteditable="true"]'), function (elm) {
  27532. set$1(elm, internalContentEditableAttr, 'true');
  27533. setContentEditable(elm, false);
  27534. });
  27535. };
  27536. var switchOnContentEditableTrue = function (elm) {
  27537. each$k(descendants(elm, '*[' + internalContentEditableAttr + '="true"]'), function (elm) {
  27538. remove$6(elm, internalContentEditableAttr);
  27539. setContentEditable(elm, true);
  27540. });
  27541. };
  27542. var removeFakeSelection = function (editor) {
  27543. Optional.from(editor.selection.getNode()).each(function (elm) {
  27544. elm.removeAttribute('data-mce-selected');
  27545. });
  27546. };
  27547. var restoreFakeSelection = function (editor) {
  27548. editor.selection.setRng(editor.selection.getRng());
  27549. };
  27550. var toggleReadOnly = function (editor, state) {
  27551. var body = SugarElement.fromDom(editor.getBody());
  27552. toggleClass(body, 'mce-content-readonly', state);
  27553. if (state) {
  27554. editor.selection.controlSelection.hideResizeRect();
  27555. editor._selectionOverrides.hideFakeCaret();
  27556. removeFakeSelection(editor);
  27557. editor.readonly = true;
  27558. setContentEditable(body, false);
  27559. switchOffContentEditableTrue(body);
  27560. } else {
  27561. editor.readonly = false;
  27562. setContentEditable(body, true);
  27563. switchOnContentEditableTrue(body);
  27564. setEditorCommandState(editor, 'StyleWithCSS', false);
  27565. setEditorCommandState(editor, 'enableInlineTableEditing', false);
  27566. setEditorCommandState(editor, 'enableObjectResizing', false);
  27567. if (hasEditorOrUiFocus(editor)) {
  27568. editor.focus();
  27569. }
  27570. restoreFakeSelection(editor);
  27571. editor.nodeChanged();
  27572. }
  27573. };
  27574. var isReadOnly = function (editor) {
  27575. return editor.readonly;
  27576. };
  27577. var registerFilters = function (editor) {
  27578. editor.parser.addAttributeFilter('contenteditable', function (nodes) {
  27579. if (isReadOnly(editor)) {
  27580. each$k(nodes, function (node) {
  27581. node.attr(internalContentEditableAttr, node.attr('contenteditable'));
  27582. node.attr('contenteditable', 'false');
  27583. });
  27584. }
  27585. });
  27586. editor.serializer.addAttributeFilter(internalContentEditableAttr, function (nodes) {
  27587. if (isReadOnly(editor)) {
  27588. each$k(nodes, function (node) {
  27589. node.attr('contenteditable', node.attr(internalContentEditableAttr));
  27590. });
  27591. }
  27592. });
  27593. editor.serializer.addTempAttr(internalContentEditableAttr);
  27594. };
  27595. var registerReadOnlyContentFilters = function (editor) {
  27596. if (editor.serializer) {
  27597. registerFilters(editor);
  27598. } else {
  27599. editor.on('PreInit', function () {
  27600. registerFilters(editor);
  27601. });
  27602. }
  27603. };
  27604. var isClickEvent = function (e) {
  27605. return e.type === 'click';
  27606. };
  27607. var getAnchorHrefOpt = function (editor, elm) {
  27608. var isRoot = function (elm) {
  27609. return eq(elm, SugarElement.fromDom(editor.getBody()));
  27610. };
  27611. return closest$2(elm, 'a', isRoot).bind(function (a) {
  27612. return getOpt(a, 'href');
  27613. });
  27614. };
  27615. var processReadonlyEvents = function (editor, e) {
  27616. if (isClickEvent(e) && !VK.metaKeyPressed(e)) {
  27617. var elm = SugarElement.fromDom(e.target);
  27618. getAnchorHrefOpt(editor, elm).each(function (href) {
  27619. e.preventDefault();
  27620. if (/^#/.test(href)) {
  27621. var targetEl = editor.dom.select(href + ',[name="' + removeLeading(href, '#') + '"]');
  27622. if (targetEl.length) {
  27623. editor.selection.scrollIntoView(targetEl[0], true);
  27624. }
  27625. } else {
  27626. window.open(href, '_blank', 'rel=noopener noreferrer,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes,scrollbars=yes');
  27627. }
  27628. });
  27629. }
  27630. };
  27631. var registerReadOnlySelectionBlockers = function (editor) {
  27632. editor.on('ShowCaret', function (e) {
  27633. if (isReadOnly(editor)) {
  27634. e.preventDefault();
  27635. }
  27636. });
  27637. editor.on('ObjectSelected', function (e) {
  27638. if (isReadOnly(editor)) {
  27639. e.preventDefault();
  27640. }
  27641. });
  27642. };
  27643. 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', ' ');
  27644. var EventDispatcher = function () {
  27645. function EventDispatcher(settings) {
  27646. this.bindings = {};
  27647. this.settings = settings || {};
  27648. this.scope = this.settings.scope || this;
  27649. this.toggleEvent = this.settings.toggleEvent || never;
  27650. }
  27651. EventDispatcher.isNative = function (name) {
  27652. return !!nativeEvents[name.toLowerCase()];
  27653. };
  27654. EventDispatcher.prototype.fire = function (name, args) {
  27655. var lcName = name.toLowerCase();
  27656. var event = normalize$3(lcName, args || {}, this.scope);
  27657. if (this.settings.beforeFire) {
  27658. this.settings.beforeFire(event);
  27659. }
  27660. var handlers = this.bindings[lcName];
  27661. if (handlers) {
  27662. for (var i = 0, l = handlers.length; i < l; i++) {
  27663. var callback = handlers[i];
  27664. if (callback.removed) {
  27665. continue;
  27666. }
  27667. if (callback.once) {
  27668. this.off(lcName, callback.func);
  27669. }
  27670. if (event.isImmediatePropagationStopped()) {
  27671. return event;
  27672. }
  27673. if (callback.func.call(this.scope, event) === false) {
  27674. event.preventDefault();
  27675. return event;
  27676. }
  27677. }
  27678. }
  27679. return event;
  27680. };
  27681. EventDispatcher.prototype.on = function (name, callback, prepend, extra) {
  27682. if (callback === false) {
  27683. callback = never;
  27684. }
  27685. if (callback) {
  27686. var wrappedCallback = {
  27687. func: callback,
  27688. removed: false
  27689. };
  27690. if (extra) {
  27691. Tools.extend(wrappedCallback, extra);
  27692. }
  27693. var names = name.toLowerCase().split(' ');
  27694. var i = names.length;
  27695. while (i--) {
  27696. var currentName = names[i];
  27697. var handlers = this.bindings[currentName];
  27698. if (!handlers) {
  27699. handlers = [];
  27700. this.toggleEvent(currentName, true);
  27701. }
  27702. if (prepend) {
  27703. handlers = __spreadArray([wrappedCallback], handlers, true);
  27704. } else {
  27705. handlers = __spreadArray(__spreadArray([], handlers, true), [wrappedCallback], false);
  27706. }
  27707. this.bindings[currentName] = handlers;
  27708. }
  27709. }
  27710. return this;
  27711. };
  27712. EventDispatcher.prototype.off = function (name, callback) {
  27713. var _this = this;
  27714. if (name) {
  27715. var names = name.toLowerCase().split(' ');
  27716. var i = names.length;
  27717. while (i--) {
  27718. var currentName = names[i];
  27719. var handlers = this.bindings[currentName];
  27720. if (!currentName) {
  27721. each$j(this.bindings, function (_value, bindingName) {
  27722. _this.toggleEvent(bindingName, false);
  27723. delete _this.bindings[bindingName];
  27724. });
  27725. return this;
  27726. }
  27727. if (handlers) {
  27728. if (!callback) {
  27729. handlers.length = 0;
  27730. } else {
  27731. var filteredHandlers = partition(handlers, function (handler) {
  27732. return handler.func === callback;
  27733. });
  27734. handlers = filteredHandlers.fail;
  27735. this.bindings[currentName] = handlers;
  27736. each$k(filteredHandlers.pass, function (handler) {
  27737. handler.removed = true;
  27738. });
  27739. }
  27740. if (!handlers.length) {
  27741. this.toggleEvent(name, false);
  27742. delete this.bindings[currentName];
  27743. }
  27744. }
  27745. }
  27746. } else {
  27747. each$j(this.bindings, function (_value, name) {
  27748. _this.toggleEvent(name, false);
  27749. });
  27750. this.bindings = {};
  27751. }
  27752. return this;
  27753. };
  27754. EventDispatcher.prototype.once = function (name, callback, prepend) {
  27755. return this.on(name, callback, prepend, { once: true });
  27756. };
  27757. EventDispatcher.prototype.has = function (name) {
  27758. name = name.toLowerCase();
  27759. return !(!this.bindings[name] || this.bindings[name].length === 0);
  27760. };
  27761. return EventDispatcher;
  27762. }();
  27763. var getEventDispatcher = function (obj) {
  27764. if (!obj._eventDispatcher) {
  27765. obj._eventDispatcher = new EventDispatcher({
  27766. scope: obj,
  27767. toggleEvent: function (name, state) {
  27768. if (EventDispatcher.isNative(name) && obj.toggleNativeEvent) {
  27769. obj.toggleNativeEvent(name, state);
  27770. }
  27771. }
  27772. });
  27773. }
  27774. return obj._eventDispatcher;
  27775. };
  27776. var Observable = {
  27777. fire: function (name, args, bubble) {
  27778. var self = this;
  27779. if (self.removed && name !== 'remove' && name !== 'detach') {
  27780. return args;
  27781. }
  27782. var dispatcherArgs = getEventDispatcher(self).fire(name, args);
  27783. if (bubble !== false && self.parent) {
  27784. var parent_1 = self.parent();
  27785. while (parent_1 && !dispatcherArgs.isPropagationStopped()) {
  27786. parent_1.fire(name, dispatcherArgs, false);
  27787. parent_1 = parent_1.parent();
  27788. }
  27789. }
  27790. return dispatcherArgs;
  27791. },
  27792. on: function (name, callback, prepend) {
  27793. return getEventDispatcher(this).on(name, callback, prepend);
  27794. },
  27795. off: function (name, callback) {
  27796. return getEventDispatcher(this).off(name, callback);
  27797. },
  27798. once: function (name, callback) {
  27799. return getEventDispatcher(this).once(name, callback);
  27800. },
  27801. hasEventListeners: function (name) {
  27802. return getEventDispatcher(this).has(name);
  27803. }
  27804. };
  27805. var DOM$2 = DOMUtils.DOM;
  27806. var customEventRootDelegates;
  27807. var getEventTarget = function (editor, eventName) {
  27808. if (eventName === 'selectionchange') {
  27809. return editor.getDoc();
  27810. }
  27811. if (!editor.inline && /^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(eventName)) {
  27812. return editor.getDoc().documentElement;
  27813. }
  27814. var eventRoot = getEventRoot(editor);
  27815. if (eventRoot) {
  27816. if (!editor.eventRoot) {
  27817. editor.eventRoot = DOM$2.select(eventRoot)[0];
  27818. }
  27819. return editor.eventRoot;
  27820. }
  27821. return editor.getBody();
  27822. };
  27823. var isListening = function (editor) {
  27824. return !editor.hidden && !isReadOnly(editor);
  27825. };
  27826. var fireEvent = function (editor, eventName, e) {
  27827. if (isListening(editor)) {
  27828. editor.fire(eventName, e);
  27829. } else if (isReadOnly(editor)) {
  27830. processReadonlyEvents(editor, e);
  27831. }
  27832. };
  27833. var bindEventDelegate = function (editor, eventName) {
  27834. var delegate;
  27835. if (!editor.delegates) {
  27836. editor.delegates = {};
  27837. }
  27838. if (editor.delegates[eventName] || editor.removed) {
  27839. return;
  27840. }
  27841. var eventRootElm = getEventTarget(editor, eventName);
  27842. if (getEventRoot(editor)) {
  27843. if (!customEventRootDelegates) {
  27844. customEventRootDelegates = {};
  27845. editor.editorManager.on('removeEditor', function () {
  27846. if (!editor.editorManager.activeEditor) {
  27847. if (customEventRootDelegates) {
  27848. each$j(customEventRootDelegates, function (_value, name) {
  27849. editor.dom.unbind(getEventTarget(editor, name));
  27850. });
  27851. customEventRootDelegates = null;
  27852. }
  27853. }
  27854. });
  27855. }
  27856. if (customEventRootDelegates[eventName]) {
  27857. return;
  27858. }
  27859. delegate = function (e) {
  27860. var target = e.target;
  27861. var editors = editor.editorManager.get();
  27862. var i = editors.length;
  27863. while (i--) {
  27864. var body = editors[i].getBody();
  27865. if (body === target || DOM$2.isChildOf(target, body)) {
  27866. fireEvent(editors[i], eventName, e);
  27867. }
  27868. }
  27869. };
  27870. customEventRootDelegates[eventName] = delegate;
  27871. DOM$2.bind(eventRootElm, eventName, delegate);
  27872. } else {
  27873. delegate = function (e) {
  27874. fireEvent(editor, eventName, e);
  27875. };
  27876. DOM$2.bind(eventRootElm, eventName, delegate);
  27877. editor.delegates[eventName] = delegate;
  27878. }
  27879. };
  27880. var EditorObservable = __assign(__assign({}, Observable), {
  27881. bindPendingEventDelegates: function () {
  27882. var self = this;
  27883. Tools.each(self._pendingNativeEvents, function (name) {
  27884. bindEventDelegate(self, name);
  27885. });
  27886. },
  27887. toggleNativeEvent: function (name, state) {
  27888. var self = this;
  27889. if (name === 'focus' || name === 'blur') {
  27890. return;
  27891. }
  27892. if (self.removed) {
  27893. return;
  27894. }
  27895. if (state) {
  27896. if (self.initialized) {
  27897. bindEventDelegate(self, name);
  27898. } else {
  27899. if (!self._pendingNativeEvents) {
  27900. self._pendingNativeEvents = [name];
  27901. } else {
  27902. self._pendingNativeEvents.push(name);
  27903. }
  27904. }
  27905. } else if (self.initialized) {
  27906. self.dom.unbind(getEventTarget(self, name), name, self.delegates[name]);
  27907. delete self.delegates[name];
  27908. }
  27909. },
  27910. unbindAllNativeEvents: function () {
  27911. var self = this;
  27912. var body = self.getBody();
  27913. var dom = self.dom;
  27914. if (self.delegates) {
  27915. each$j(self.delegates, function (value, name) {
  27916. self.dom.unbind(getEventTarget(self, name), name, value);
  27917. });
  27918. delete self.delegates;
  27919. }
  27920. if (!self.inline && body && dom) {
  27921. body.onload = null;
  27922. dom.unbind(self.getWin());
  27923. dom.unbind(self.getDoc());
  27924. }
  27925. if (dom) {
  27926. dom.unbind(body);
  27927. dom.unbind(self.getContainer());
  27928. }
  27929. }
  27930. });
  27931. var defaultModes = [
  27932. 'design',
  27933. 'readonly'
  27934. ];
  27935. var switchToMode = function (editor, activeMode, availableModes, mode) {
  27936. var oldMode = availableModes[activeMode.get()];
  27937. var newMode = availableModes[mode];
  27938. try {
  27939. newMode.activate();
  27940. } catch (e) {
  27941. console.error('problem while activating editor mode ' + mode + ':', e);
  27942. return;
  27943. }
  27944. oldMode.deactivate();
  27945. if (oldMode.editorReadOnly !== newMode.editorReadOnly) {
  27946. toggleReadOnly(editor, newMode.editorReadOnly);
  27947. }
  27948. activeMode.set(mode);
  27949. fireSwitchMode(editor, mode);
  27950. };
  27951. var setMode = function (editor, availableModes, activeMode, mode) {
  27952. if (mode === activeMode.get()) {
  27953. return;
  27954. } else if (!has$2(availableModes, mode)) {
  27955. throw new Error('Editor mode \'' + mode + '\' is invalid');
  27956. }
  27957. if (editor.initialized) {
  27958. switchToMode(editor, activeMode, availableModes, mode);
  27959. } else {
  27960. editor.on('init', function () {
  27961. return switchToMode(editor, activeMode, availableModes, mode);
  27962. });
  27963. }
  27964. };
  27965. var registerMode = function (availableModes, mode, api) {
  27966. var _a;
  27967. if (contains$3(defaultModes, mode)) {
  27968. throw new Error('Cannot override default mode ' + mode);
  27969. }
  27970. return __assign(__assign({}, availableModes), (_a = {}, _a[mode] = __assign(__assign({}, api), {
  27971. deactivate: function () {
  27972. try {
  27973. api.deactivate();
  27974. } catch (e) {
  27975. console.error('problem while deactivating editor mode ' + mode + ':', e);
  27976. }
  27977. }
  27978. }), _a));
  27979. };
  27980. var create$4 = function (editor) {
  27981. var activeMode = Cell('design');
  27982. var availableModes = Cell({
  27983. design: {
  27984. activate: noop,
  27985. deactivate: noop,
  27986. editorReadOnly: false
  27987. },
  27988. readonly: {
  27989. activate: noop,
  27990. deactivate: noop,
  27991. editorReadOnly: true
  27992. }
  27993. });
  27994. registerReadOnlyContentFilters(editor);
  27995. registerReadOnlySelectionBlockers(editor);
  27996. return {
  27997. isReadOnly: function () {
  27998. return isReadOnly(editor);
  27999. },
  28000. set: function (mode) {
  28001. return setMode(editor, availableModes.get(), activeMode, mode);
  28002. },
  28003. get: function () {
  28004. return activeMode.get();
  28005. },
  28006. register: function (mode, api) {
  28007. availableModes.set(registerMode(availableModes.get(), mode, api));
  28008. }
  28009. };
  28010. };
  28011. var each$3 = Tools.each, explode$1 = Tools.explode;
  28012. var keyCodeLookup = {
  28013. f1: 112,
  28014. f2: 113,
  28015. f3: 114,
  28016. f4: 115,
  28017. f5: 116,
  28018. f6: 117,
  28019. f7: 118,
  28020. f8: 119,
  28021. f9: 120,
  28022. f10: 121,
  28023. f11: 122,
  28024. f12: 123
  28025. };
  28026. var modifierNames = Tools.makeMap('alt,ctrl,shift,meta,access');
  28027. var parseShortcut = function (pattern) {
  28028. var key;
  28029. var shortcut = {};
  28030. each$3(explode$1(pattern.toLowerCase(), '+'), function (value) {
  28031. if (value in modifierNames) {
  28032. shortcut[value] = true;
  28033. } else {
  28034. if (/^[0-9]{2,}$/.test(value)) {
  28035. shortcut.keyCode = parseInt(value, 10);
  28036. } else {
  28037. shortcut.charCode = value.charCodeAt(0);
  28038. shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);
  28039. }
  28040. }
  28041. });
  28042. var id = [shortcut.keyCode];
  28043. for (key in modifierNames) {
  28044. if (shortcut[key]) {
  28045. id.push(key);
  28046. } else {
  28047. shortcut[key] = false;
  28048. }
  28049. }
  28050. shortcut.id = id.join(',');
  28051. if (shortcut.access) {
  28052. shortcut.alt = true;
  28053. if (Env.mac) {
  28054. shortcut.ctrl = true;
  28055. } else {
  28056. shortcut.shift = true;
  28057. }
  28058. }
  28059. if (shortcut.meta) {
  28060. if (Env.mac) {
  28061. shortcut.meta = true;
  28062. } else {
  28063. shortcut.ctrl = true;
  28064. shortcut.meta = false;
  28065. }
  28066. }
  28067. return shortcut;
  28068. };
  28069. var Shortcuts = function () {
  28070. function Shortcuts(editor) {
  28071. this.shortcuts = {};
  28072. this.pendingPatterns = [];
  28073. this.editor = editor;
  28074. var self = this;
  28075. editor.on('keyup keypress keydown', function (e) {
  28076. if ((self.hasModifier(e) || self.isFunctionKey(e)) && !e.isDefaultPrevented()) {
  28077. each$3(self.shortcuts, function (shortcut) {
  28078. if (self.matchShortcut(e, shortcut)) {
  28079. self.pendingPatterns = shortcut.subpatterns.slice(0);
  28080. if (e.type === 'keydown') {
  28081. self.executeShortcutAction(shortcut);
  28082. }
  28083. return true;
  28084. }
  28085. });
  28086. if (self.matchShortcut(e, self.pendingPatterns[0])) {
  28087. if (self.pendingPatterns.length === 1) {
  28088. if (e.type === 'keydown') {
  28089. self.executeShortcutAction(self.pendingPatterns[0]);
  28090. }
  28091. }
  28092. self.pendingPatterns.shift();
  28093. }
  28094. }
  28095. });
  28096. }
  28097. Shortcuts.prototype.add = function (pattern, desc, cmdFunc, scope) {
  28098. var self = this;
  28099. var func = self.normalizeCommandFunc(cmdFunc);
  28100. each$3(explode$1(Tools.trim(pattern)), function (pattern) {
  28101. var shortcut = self.createShortcut(pattern, desc, func, scope);
  28102. self.shortcuts[shortcut.id] = shortcut;
  28103. });
  28104. return true;
  28105. };
  28106. Shortcuts.prototype.remove = function (pattern) {
  28107. var shortcut = this.createShortcut(pattern);
  28108. if (this.shortcuts[shortcut.id]) {
  28109. delete this.shortcuts[shortcut.id];
  28110. return true;
  28111. }
  28112. return false;
  28113. };
  28114. Shortcuts.prototype.normalizeCommandFunc = function (cmdFunc) {
  28115. var self = this;
  28116. var cmd = cmdFunc;
  28117. if (typeof cmd === 'string') {
  28118. return function () {
  28119. self.editor.execCommand(cmd, false, null);
  28120. };
  28121. } else if (Tools.isArray(cmd)) {
  28122. return function () {
  28123. self.editor.execCommand(cmd[0], cmd[1], cmd[2]);
  28124. };
  28125. } else {
  28126. return cmd;
  28127. }
  28128. };
  28129. Shortcuts.prototype.createShortcut = function (pattern, desc, cmdFunc, scope) {
  28130. var shortcuts = Tools.map(explode$1(pattern, '>'), parseShortcut);
  28131. shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {
  28132. func: cmdFunc,
  28133. scope: scope || this.editor
  28134. });
  28135. return Tools.extend(shortcuts[0], {
  28136. desc: this.editor.translate(desc),
  28137. subpatterns: shortcuts.slice(1)
  28138. });
  28139. };
  28140. Shortcuts.prototype.hasModifier = function (e) {
  28141. return e.altKey || e.ctrlKey || e.metaKey;
  28142. };
  28143. Shortcuts.prototype.isFunctionKey = function (e) {
  28144. return e.type === 'keydown' && e.keyCode >= 112 && e.keyCode <= 123;
  28145. };
  28146. Shortcuts.prototype.matchShortcut = function (e, shortcut) {
  28147. if (!shortcut) {
  28148. return false;
  28149. }
  28150. if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
  28151. return false;
  28152. }
  28153. if (shortcut.alt !== e.altKey || shortcut.shift !== e.shiftKey) {
  28154. return false;
  28155. }
  28156. if (e.keyCode === shortcut.keyCode || e.charCode && e.charCode === shortcut.charCode) {
  28157. e.preventDefault();
  28158. return true;
  28159. }
  28160. return false;
  28161. };
  28162. Shortcuts.prototype.executeShortcutAction = function (shortcut) {
  28163. return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
  28164. };
  28165. return Shortcuts;
  28166. }();
  28167. var create$3 = function () {
  28168. var buttons = {};
  28169. var menuItems = {};
  28170. var popups = {};
  28171. var icons = {};
  28172. var contextMenus = {};
  28173. var contextToolbars = {};
  28174. var sidebars = {};
  28175. var add = function (collection, type) {
  28176. return function (name, spec) {
  28177. return collection[name.toLowerCase()] = __assign(__assign({}, spec), { type: type });
  28178. };
  28179. };
  28180. var addIcon = function (name, svgData) {
  28181. return icons[name.toLowerCase()] = svgData;
  28182. };
  28183. return {
  28184. addButton: add(buttons, 'button'),
  28185. addGroupToolbarButton: add(buttons, 'grouptoolbarbutton'),
  28186. addToggleButton: add(buttons, 'togglebutton'),
  28187. addMenuButton: add(buttons, 'menubutton'),
  28188. addSplitButton: add(buttons, 'splitbutton'),
  28189. addMenuItem: add(menuItems, 'menuitem'),
  28190. addNestedMenuItem: add(menuItems, 'nestedmenuitem'),
  28191. addToggleMenuItem: add(menuItems, 'togglemenuitem'),
  28192. addAutocompleter: add(popups, 'autocompleter'),
  28193. addContextMenu: add(contextMenus, 'contextmenu'),
  28194. addContextToolbar: add(contextToolbars, 'contexttoolbar'),
  28195. addContextForm: add(contextToolbars, 'contextform'),
  28196. addSidebar: add(sidebars, 'sidebar'),
  28197. addIcon: addIcon,
  28198. getAll: function () {
  28199. return {
  28200. buttons: buttons,
  28201. menuItems: menuItems,
  28202. icons: icons,
  28203. popups: popups,
  28204. contextMenus: contextMenus,
  28205. contextToolbars: contextToolbars,
  28206. sidebars: sidebars
  28207. };
  28208. }
  28209. };
  28210. };
  28211. var registry = function () {
  28212. var bridge = create$3();
  28213. return {
  28214. addAutocompleter: bridge.addAutocompleter,
  28215. addButton: bridge.addButton,
  28216. addContextForm: bridge.addContextForm,
  28217. addContextMenu: bridge.addContextMenu,
  28218. addContextToolbar: bridge.addContextToolbar,
  28219. addIcon: bridge.addIcon,
  28220. addMenuButton: bridge.addMenuButton,
  28221. addMenuItem: bridge.addMenuItem,
  28222. addNestedMenuItem: bridge.addNestedMenuItem,
  28223. addSidebar: bridge.addSidebar,
  28224. addSplitButton: bridge.addSplitButton,
  28225. addToggleButton: bridge.addToggleButton,
  28226. addGroupToolbarButton: bridge.addGroupToolbarButton,
  28227. addToggleMenuItem: bridge.addToggleMenuItem,
  28228. getAll: bridge.getAll
  28229. };
  28230. };
  28231. var DOM$1 = DOMUtils.DOM;
  28232. var extend$3 = Tools.extend, each$2 = Tools.each;
  28233. var resolve = Tools.resolve;
  28234. var ie = Env.ie;
  28235. var Editor = function () {
  28236. function Editor(id, settings, editorManager) {
  28237. var _this = this;
  28238. this.plugins = {};
  28239. this.contentCSS = [];
  28240. this.contentStyles = [];
  28241. this.loadedCSS = {};
  28242. this.isNotDirty = false;
  28243. this.editorManager = editorManager;
  28244. this.documentBaseUrl = editorManager.documentBaseURL;
  28245. extend$3(this, EditorObservable);
  28246. this.settings = getEditorSettings(this, id, this.documentBaseUrl, editorManager.defaultSettings, settings);
  28247. if (this.settings.suffix) {
  28248. editorManager.suffix = this.settings.suffix;
  28249. }
  28250. this.suffix = editorManager.suffix;
  28251. if (this.settings.base_url) {
  28252. editorManager._setBaseUrl(this.settings.base_url);
  28253. }
  28254. this.baseUri = editorManager.baseURI;
  28255. if (this.settings.referrer_policy) {
  28256. ScriptLoader.ScriptLoader._setReferrerPolicy(this.settings.referrer_policy);
  28257. DOMUtils.DOM.styleSheetLoader._setReferrerPolicy(this.settings.referrer_policy);
  28258. }
  28259. AddOnManager.languageLoad = this.settings.language_load;
  28260. AddOnManager.baseURL = editorManager.baseURL;
  28261. this.id = id;
  28262. this.setDirty(false);
  28263. this.documentBaseURI = new URI(this.settings.document_base_url, { base_uri: this.baseUri });
  28264. this.baseURI = this.baseUri;
  28265. this.inline = !!this.settings.inline;
  28266. this.shortcuts = new Shortcuts(this);
  28267. this.editorCommands = new EditorCommands(this);
  28268. if (this.settings.cache_suffix) {
  28269. Env.cacheSuffix = this.settings.cache_suffix.replace(/^[\?\&]+/, '');
  28270. }
  28271. this.ui = {
  28272. registry: registry(),
  28273. styleSheetLoader: undefined,
  28274. show: noop,
  28275. hide: noop,
  28276. enable: noop,
  28277. disable: noop,
  28278. isDisabled: never
  28279. };
  28280. var self = this;
  28281. var modeInstance = create$4(self);
  28282. this.mode = modeInstance;
  28283. this.setMode = modeInstance.set;
  28284. editorManager.fire('SetupEditor', { editor: this });
  28285. this.execCallback('setup', this);
  28286. this.$ = DomQuery.overrideDefaults(function () {
  28287. return {
  28288. context: _this.inline ? _this.getBody() : _this.getDoc(),
  28289. element: _this.getBody()
  28290. };
  28291. });
  28292. }
  28293. Editor.prototype.render = function () {
  28294. render(this);
  28295. };
  28296. Editor.prototype.focus = function (skipFocus) {
  28297. this.execCommand('mceFocus', false, skipFocus);
  28298. };
  28299. Editor.prototype.hasFocus = function () {
  28300. return hasFocus(this);
  28301. };
  28302. Editor.prototype.execCallback = function (name) {
  28303. var x = [];
  28304. for (var _i = 1; _i < arguments.length; _i++) {
  28305. x[_i - 1] = arguments[_i];
  28306. }
  28307. var self = this;
  28308. var callback = self.settings[name], scope;
  28309. if (!callback) {
  28310. return;
  28311. }
  28312. if (self.callbackLookup && (scope = self.callbackLookup[name])) {
  28313. callback = scope.func;
  28314. scope = scope.scope;
  28315. }
  28316. if (typeof callback === 'string') {
  28317. scope = callback.replace(/\.\w+$/, '');
  28318. scope = scope ? resolve(scope) : 0;
  28319. callback = resolve(callback);
  28320. self.callbackLookup = self.callbackLookup || {};
  28321. self.callbackLookup[name] = {
  28322. func: callback,
  28323. scope: scope
  28324. };
  28325. }
  28326. return callback.apply(scope || self, x);
  28327. };
  28328. Editor.prototype.translate = function (text) {
  28329. return I18n.translate(text);
  28330. };
  28331. Editor.prototype.getParam = function (name, defaultVal, type) {
  28332. return getParam(this, name, defaultVal, type);
  28333. };
  28334. Editor.prototype.hasPlugin = function (name, loaded) {
  28335. var hasPlugin = contains$3(getPlugins(this).split(/[ ,]/), name);
  28336. if (hasPlugin) {
  28337. return loaded ? PluginManager.get(name) !== undefined : true;
  28338. } else {
  28339. return false;
  28340. }
  28341. };
  28342. Editor.prototype.nodeChanged = function (args) {
  28343. this._nodeChangeDispatcher.nodeChanged(args);
  28344. };
  28345. Editor.prototype.addCommand = function (name, callback, scope) {
  28346. this.editorCommands.addCommand(name, callback, scope);
  28347. };
  28348. Editor.prototype.addQueryStateHandler = function (name, callback, scope) {
  28349. this.editorCommands.addQueryStateHandler(name, callback, scope);
  28350. };
  28351. Editor.prototype.addQueryValueHandler = function (name, callback, scope) {
  28352. this.editorCommands.addQueryValueHandler(name, callback, scope);
  28353. };
  28354. Editor.prototype.addShortcut = function (pattern, desc, cmdFunc, scope) {
  28355. this.shortcuts.add(pattern, desc, cmdFunc, scope);
  28356. };
  28357. Editor.prototype.execCommand = function (cmd, ui, value, args) {
  28358. return this.editorCommands.execCommand(cmd, ui, value, args);
  28359. };
  28360. Editor.prototype.queryCommandState = function (cmd) {
  28361. return this.editorCommands.queryCommandState(cmd);
  28362. };
  28363. Editor.prototype.queryCommandValue = function (cmd) {
  28364. return this.editorCommands.queryCommandValue(cmd);
  28365. };
  28366. Editor.prototype.queryCommandSupported = function (cmd) {
  28367. return this.editorCommands.queryCommandSupported(cmd);
  28368. };
  28369. Editor.prototype.show = function () {
  28370. var self = this;
  28371. if (self.hidden) {
  28372. self.hidden = false;
  28373. if (self.inline) {
  28374. self.getBody().contentEditable = 'true';
  28375. } else {
  28376. DOM$1.show(self.getContainer());
  28377. DOM$1.hide(self.id);
  28378. }
  28379. self.load();
  28380. self.fire('show');
  28381. }
  28382. };
  28383. Editor.prototype.hide = function () {
  28384. var self = this, doc = self.getDoc();
  28385. if (!self.hidden) {
  28386. if (ie && doc && !self.inline) {
  28387. doc.execCommand('SelectAll');
  28388. }
  28389. self.save();
  28390. if (self.inline) {
  28391. self.getBody().contentEditable = 'false';
  28392. if (self === self.editorManager.focusedEditor) {
  28393. self.editorManager.focusedEditor = null;
  28394. }
  28395. } else {
  28396. DOM$1.hide(self.getContainer());
  28397. DOM$1.setStyle(self.id, 'display', self.orgDisplay);
  28398. }
  28399. self.hidden = true;
  28400. self.fire('hide');
  28401. }
  28402. };
  28403. Editor.prototype.isHidden = function () {
  28404. return !!this.hidden;
  28405. };
  28406. Editor.prototype.setProgressState = function (state, time) {
  28407. this.fire('ProgressState', {
  28408. state: state,
  28409. time: time
  28410. });
  28411. };
  28412. Editor.prototype.load = function (args) {
  28413. var self = this;
  28414. var elm = self.getElement(), html;
  28415. if (self.removed) {
  28416. return '';
  28417. }
  28418. if (elm) {
  28419. args = args || {};
  28420. args.load = true;
  28421. var value = isTextareaOrInput(elm) ? elm.value : elm.innerHTML;
  28422. html = self.setContent(value, args);
  28423. args.element = elm;
  28424. if (!args.no_events) {
  28425. self.fire('LoadContent', args);
  28426. }
  28427. args.element = elm = null;
  28428. return html;
  28429. }
  28430. };
  28431. Editor.prototype.save = function (args) {
  28432. var self = this;
  28433. var elm = self.getElement(), html, form;
  28434. if (!elm || !self.initialized || self.removed) {
  28435. return;
  28436. }
  28437. args = args || {};
  28438. args.save = true;
  28439. args.element = elm;
  28440. html = args.content = self.getContent(args);
  28441. if (!args.no_events) {
  28442. self.fire('SaveContent', args);
  28443. }
  28444. if (args.format === 'raw') {
  28445. self.fire('RawSaveContent', args);
  28446. }
  28447. html = args.content;
  28448. if (!isTextareaOrInput(elm)) {
  28449. if (args.is_removing || !self.inline) {
  28450. elm.innerHTML = html;
  28451. }
  28452. if (form = DOM$1.getParent(self.id, 'form')) {
  28453. each$2(form.elements, function (elm) {
  28454. if (elm.name === self.id) {
  28455. elm.value = html;
  28456. return false;
  28457. }
  28458. });
  28459. }
  28460. } else {
  28461. elm.value = html;
  28462. }
  28463. args.element = elm = null;
  28464. if (args.set_dirty !== false) {
  28465. self.setDirty(false);
  28466. }
  28467. return html;
  28468. };
  28469. Editor.prototype.setContent = function (content, args) {
  28470. return setContent(this, content, args);
  28471. };
  28472. Editor.prototype.getContent = function (args) {
  28473. return getContent(this, args);
  28474. };
  28475. Editor.prototype.insertContent = function (content, args) {
  28476. if (args) {
  28477. content = extend$3({ content: content }, args);
  28478. }
  28479. this.execCommand('mceInsertContent', false, content);
  28480. };
  28481. Editor.prototype.resetContent = function (initialContent) {
  28482. if (initialContent === undefined) {
  28483. setContent(this, this.startContent, { format: 'raw' });
  28484. } else {
  28485. setContent(this, initialContent);
  28486. }
  28487. this.undoManager.reset();
  28488. this.setDirty(false);
  28489. this.nodeChanged();
  28490. };
  28491. Editor.prototype.isDirty = function () {
  28492. return !this.isNotDirty;
  28493. };
  28494. Editor.prototype.setDirty = function (state) {
  28495. var oldState = !this.isNotDirty;
  28496. this.isNotDirty = !state;
  28497. if (state && state !== oldState) {
  28498. this.fire('dirty');
  28499. }
  28500. };
  28501. Editor.prototype.getContainer = function () {
  28502. var self = this;
  28503. if (!self.container) {
  28504. self.container = DOM$1.get(self.editorContainer || self.id + '_parent');
  28505. }
  28506. return self.container;
  28507. };
  28508. Editor.prototype.getContentAreaContainer = function () {
  28509. return this.contentAreaContainer;
  28510. };
  28511. Editor.prototype.getElement = function () {
  28512. if (!this.targetElm) {
  28513. this.targetElm = DOM$1.get(this.id);
  28514. }
  28515. return this.targetElm;
  28516. };
  28517. Editor.prototype.getWin = function () {
  28518. var self = this;
  28519. var elm;
  28520. if (!self.contentWindow) {
  28521. elm = self.iframeElement;
  28522. if (elm) {
  28523. self.contentWindow = elm.contentWindow;
  28524. }
  28525. }
  28526. return self.contentWindow;
  28527. };
  28528. Editor.prototype.getDoc = function () {
  28529. var self = this;
  28530. var win;
  28531. if (!self.contentDocument) {
  28532. win = self.getWin();
  28533. if (win) {
  28534. self.contentDocument = win.document;
  28535. }
  28536. }
  28537. return self.contentDocument;
  28538. };
  28539. Editor.prototype.getBody = function () {
  28540. var doc = this.getDoc();
  28541. return this.bodyElement || (doc ? doc.body : null);
  28542. };
  28543. Editor.prototype.convertURL = function (url, name, elm) {
  28544. var self = this, settings = self.settings;
  28545. if (settings.urlconverter_callback) {
  28546. return self.execCallback('urlconverter_callback', url, elm, true, name);
  28547. }
  28548. if (!settings.convert_urls || elm && elm.nodeName === 'LINK' || url.indexOf('file:') === 0 || url.length === 0) {
  28549. return url;
  28550. }
  28551. if (settings.relative_urls) {
  28552. return self.documentBaseURI.toRelative(url);
  28553. }
  28554. url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host);
  28555. return url;
  28556. };
  28557. Editor.prototype.addVisual = function (elm) {
  28558. addVisual(this, elm);
  28559. };
  28560. Editor.prototype.remove = function () {
  28561. remove(this);
  28562. };
  28563. Editor.prototype.destroy = function (automatic) {
  28564. destroy(this, automatic);
  28565. };
  28566. Editor.prototype.uploadImages = function (callback) {
  28567. return this.editorUpload.uploadImages(callback);
  28568. };
  28569. Editor.prototype._scanForImages = function () {
  28570. return this.editorUpload.scanForImages();
  28571. };
  28572. Editor.prototype.addButton = function () {
  28573. 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');
  28574. };
  28575. Editor.prototype.addSidebar = function () {
  28576. throw new Error('editor.addSidebar has been removed in tinymce 5x, use editor.ui.registry.addSidebar instead');
  28577. };
  28578. Editor.prototype.addMenuItem = function () {
  28579. throw new Error('editor.addMenuItem has been removed in tinymce 5x, use editor.ui.registry.addMenuItem instead');
  28580. };
  28581. Editor.prototype.addContextToolbar = function () {
  28582. throw new Error('editor.addContextToolbar has been removed in tinymce 5x, use editor.ui.registry.addContextToolbar instead');
  28583. };
  28584. return Editor;
  28585. }();
  28586. var DOM = DOMUtils.DOM;
  28587. var explode = Tools.explode, each$1 = Tools.each, extend$2 = Tools.extend;
  28588. var instanceCounter = 0, boundGlobalEvents = false;
  28589. var beforeUnloadDelegate;
  28590. var legacyEditors = [];
  28591. var editors = [];
  28592. var isValidLegacyKey = function (id) {
  28593. return id !== 'length';
  28594. };
  28595. var globalEventDelegate = function (e) {
  28596. var type = e.type;
  28597. each$1(EditorManager.get(), function (editor) {
  28598. switch (type) {
  28599. case 'scroll':
  28600. editor.fire('ScrollWindow', e);
  28601. break;
  28602. case 'resize':
  28603. editor.fire('ResizeWindow', e);
  28604. break;
  28605. }
  28606. });
  28607. };
  28608. var toggleGlobalEvents = function (state) {
  28609. if (state !== boundGlobalEvents) {
  28610. if (state) {
  28611. DomQuery(window).on('resize scroll', globalEventDelegate);
  28612. } else {
  28613. DomQuery(window).off('resize scroll', globalEventDelegate);
  28614. }
  28615. boundGlobalEvents = state;
  28616. }
  28617. };
  28618. var removeEditorFromList = function (targetEditor) {
  28619. var oldEditors = editors;
  28620. delete legacyEditors[targetEditor.id];
  28621. for (var i = 0; i < legacyEditors.length; i++) {
  28622. if (legacyEditors[i] === targetEditor) {
  28623. legacyEditors.splice(i, 1);
  28624. break;
  28625. }
  28626. }
  28627. editors = filter$4(editors, function (editor) {
  28628. return targetEditor !== editor;
  28629. });
  28630. if (EditorManager.activeEditor === targetEditor) {
  28631. EditorManager.activeEditor = editors.length > 0 ? editors[0] : null;
  28632. }
  28633. if (EditorManager.focusedEditor === targetEditor) {
  28634. EditorManager.focusedEditor = null;
  28635. }
  28636. return oldEditors.length !== editors.length;
  28637. };
  28638. var purgeDestroyedEditor = function (editor) {
  28639. if (editor && editor.initialized && !(editor.getContainer() || editor.getBody()).parentNode) {
  28640. removeEditorFromList(editor);
  28641. editor.unbindAllNativeEvents();
  28642. editor.destroy(true);
  28643. editor.removed = true;
  28644. editor = null;
  28645. }
  28646. return editor;
  28647. };
  28648. var isQuirksMode = document.compatMode !== 'CSS1Compat';
  28649. var EditorManager = __assign(__assign({}, Observable), {
  28650. baseURI: null,
  28651. baseURL: null,
  28652. defaultSettings: {},
  28653. documentBaseURL: null,
  28654. suffix: null,
  28655. $: DomQuery,
  28656. majorVersion: '5',
  28657. minorVersion: '10.0',
  28658. releaseDate: '2021-10-11',
  28659. editors: legacyEditors,
  28660. i18n: I18n,
  28661. activeEditor: null,
  28662. focusedEditor: null,
  28663. settings: {},
  28664. setup: function () {
  28665. var self = this;
  28666. var baseURL, documentBaseURL, suffix = '';
  28667. documentBaseURL = URI.getDocumentBaseUrl(document.location);
  28668. if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
  28669. documentBaseURL = documentBaseURL.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  28670. if (!/[\/\\]$/.test(documentBaseURL)) {
  28671. documentBaseURL += '/';
  28672. }
  28673. }
  28674. var preInit = window.tinymce || window.tinyMCEPreInit;
  28675. if (preInit) {
  28676. baseURL = preInit.base || preInit.baseURL;
  28677. suffix = preInit.suffix;
  28678. } else {
  28679. var scripts = document.getElementsByTagName('script');
  28680. for (var i = 0; i < scripts.length; i++) {
  28681. var src = scripts[i].src || '';
  28682. if (src === '') {
  28683. continue;
  28684. }
  28685. var srcScript = src.substring(src.lastIndexOf('/'));
  28686. if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
  28687. if (srcScript.indexOf('.min') !== -1) {
  28688. suffix = '.min';
  28689. }
  28690. baseURL = src.substring(0, src.lastIndexOf('/'));
  28691. break;
  28692. }
  28693. }
  28694. if (!baseURL && document.currentScript) {
  28695. var src = document.currentScript.src;
  28696. if (src.indexOf('.min') !== -1) {
  28697. suffix = '.min';
  28698. }
  28699. baseURL = src.substring(0, src.lastIndexOf('/'));
  28700. }
  28701. }
  28702. self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
  28703. self.documentBaseURL = documentBaseURL;
  28704. self.baseURI = new URI(self.baseURL);
  28705. self.suffix = suffix;
  28706. setup$l(self);
  28707. },
  28708. overrideDefaults: function (defaultSettings) {
  28709. var baseUrl = defaultSettings.base_url;
  28710. if (baseUrl) {
  28711. this._setBaseUrl(baseUrl);
  28712. }
  28713. var suffix = defaultSettings.suffix;
  28714. if (defaultSettings.suffix) {
  28715. this.suffix = suffix;
  28716. }
  28717. this.defaultSettings = defaultSettings;
  28718. var pluginBaseUrls = defaultSettings.plugin_base_urls;
  28719. if (pluginBaseUrls !== undefined) {
  28720. each$j(pluginBaseUrls, function (pluginBaseUrl, pluginName) {
  28721. AddOnManager.PluginManager.urls[pluginName] = pluginBaseUrl;
  28722. });
  28723. }
  28724. },
  28725. init: function (settings) {
  28726. var self = this;
  28727. var result;
  28728. 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', ' ');
  28729. var isInvalidInlineTarget = function (settings, elm) {
  28730. return settings.inline && elm.tagName.toLowerCase() in invalidInlineTargets;
  28731. };
  28732. var createId = function (elm) {
  28733. var id = elm.id;
  28734. if (!id) {
  28735. id = get$9(elm, 'name').filter(function (name) {
  28736. return !DOM.get(name);
  28737. }).getOrThunk(DOM.uniqueId);
  28738. elm.setAttribute('id', id);
  28739. }
  28740. return id;
  28741. };
  28742. var execCallback = function (name) {
  28743. var callback = settings[name];
  28744. if (!callback) {
  28745. return;
  28746. }
  28747. return callback.apply(self, []);
  28748. };
  28749. var hasClass = function (elm, className) {
  28750. return className.constructor === RegExp ? className.test(elm.className) : DOM.hasClass(elm, className);
  28751. };
  28752. var findTargets = function (settings) {
  28753. var targets = [];
  28754. if (Env.browser.isIE() && Env.browser.version.major < 11) {
  28755. 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/');
  28756. return [];
  28757. } else if (isQuirksMode) {
  28758. initError('Failed to initialize the editor as the document is not in standards mode. ' + 'TinyMCE requires standards mode.');
  28759. return [];
  28760. }
  28761. if (settings.types) {
  28762. each$1(settings.types, function (type) {
  28763. targets = targets.concat(DOM.select(type.selector));
  28764. });
  28765. return targets;
  28766. } else if (settings.selector) {
  28767. return DOM.select(settings.selector);
  28768. } else if (settings.target) {
  28769. return [settings.target];
  28770. }
  28771. switch (settings.mode) {
  28772. case 'exact':
  28773. var l = settings.elements || '';
  28774. if (l.length > 0) {
  28775. each$1(explode(l), function (id) {
  28776. var elm = DOM.get(id);
  28777. if (elm) {
  28778. targets.push(elm);
  28779. } else {
  28780. each$1(document.forms, function (f) {
  28781. each$1(f.elements, function (e) {
  28782. if (e.name === id) {
  28783. id = 'mce_editor_' + instanceCounter++;
  28784. DOM.setAttrib(e, 'id', id);
  28785. targets.push(e);
  28786. }
  28787. });
  28788. });
  28789. }
  28790. });
  28791. }
  28792. break;
  28793. case 'textareas':
  28794. case 'specific_textareas':
  28795. each$1(DOM.select('textarea'), function (elm) {
  28796. if (settings.editor_deselector && hasClass(elm, settings.editor_deselector)) {
  28797. return;
  28798. }
  28799. if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) {
  28800. targets.push(elm);
  28801. }
  28802. });
  28803. break;
  28804. }
  28805. return targets;
  28806. };
  28807. var provideResults = function (editors) {
  28808. result = editors;
  28809. };
  28810. var initEditors = function () {
  28811. var initCount = 0;
  28812. var editors = [];
  28813. var targets;
  28814. var createEditor = function (id, settings, targetElm) {
  28815. var editor = new Editor(id, settings, self);
  28816. editors.push(editor);
  28817. editor.on('init', function () {
  28818. if (++initCount === targets.length) {
  28819. provideResults(editors);
  28820. }
  28821. });
  28822. editor.targetElm = editor.targetElm || targetElm;
  28823. editor.render();
  28824. };
  28825. DOM.unbind(window, 'ready', initEditors);
  28826. execCallback('onpageload');
  28827. targets = DomQuery.unique(findTargets(settings));
  28828. if (settings.types) {
  28829. each$1(settings.types, function (type) {
  28830. Tools.each(targets, function (elm) {
  28831. if (DOM.is(elm, type.selector)) {
  28832. createEditor(createId(elm), extend$2({}, settings, type), elm);
  28833. return false;
  28834. }
  28835. return true;
  28836. });
  28837. });
  28838. return;
  28839. }
  28840. Tools.each(targets, function (elm) {
  28841. purgeDestroyedEditor(self.get(elm.id));
  28842. });
  28843. targets = Tools.grep(targets, function (elm) {
  28844. return !self.get(elm.id);
  28845. });
  28846. if (targets.length === 0) {
  28847. provideResults([]);
  28848. } else {
  28849. each$1(targets, function (elm) {
  28850. if (isInvalidInlineTarget(settings, elm)) {
  28851. initError('Could not initialize inline editor on invalid inline target element', elm);
  28852. } else {
  28853. createEditor(createId(elm), settings, elm);
  28854. }
  28855. });
  28856. }
  28857. };
  28858. self.settings = settings;
  28859. DOM.bind(window, 'ready', initEditors);
  28860. return new promiseObj(function (resolve) {
  28861. if (result) {
  28862. resolve(result);
  28863. } else {
  28864. provideResults = function (editors) {
  28865. resolve(editors);
  28866. };
  28867. }
  28868. });
  28869. },
  28870. get: function (id) {
  28871. if (arguments.length === 0) {
  28872. return editors.slice(0);
  28873. } else if (isString$1(id)) {
  28874. return find$3(editors, function (editor) {
  28875. return editor.id === id;
  28876. }).getOr(null);
  28877. } else if (isNumber(id)) {
  28878. return editors[id] ? editors[id] : null;
  28879. } else {
  28880. return null;
  28881. }
  28882. },
  28883. add: function (editor) {
  28884. var self = this;
  28885. var existingEditor = legacyEditors[editor.id];
  28886. if (existingEditor === editor) {
  28887. return editor;
  28888. }
  28889. if (self.get(editor.id) === null) {
  28890. if (isValidLegacyKey(editor.id)) {
  28891. legacyEditors[editor.id] = editor;
  28892. }
  28893. legacyEditors.push(editor);
  28894. editors.push(editor);
  28895. }
  28896. toggleGlobalEvents(true);
  28897. self.activeEditor = editor;
  28898. self.fire('AddEditor', { editor: editor });
  28899. if (!beforeUnloadDelegate) {
  28900. beforeUnloadDelegate = function (e) {
  28901. var event = self.fire('BeforeUnload');
  28902. if (event.returnValue) {
  28903. e.preventDefault();
  28904. e.returnValue = event.returnValue;
  28905. return event.returnValue;
  28906. }
  28907. };
  28908. window.addEventListener('beforeunload', beforeUnloadDelegate);
  28909. }
  28910. return editor;
  28911. },
  28912. createEditor: function (id, settings) {
  28913. return this.add(new Editor(id, settings, this));
  28914. },
  28915. remove: function (selector) {
  28916. var self = this;
  28917. var i, editor;
  28918. if (!selector) {
  28919. for (i = editors.length - 1; i >= 0; i--) {
  28920. self.remove(editors[i]);
  28921. }
  28922. return;
  28923. }
  28924. if (isString$1(selector)) {
  28925. each$1(DOM.select(selector), function (elm) {
  28926. editor = self.get(elm.id);
  28927. if (editor) {
  28928. self.remove(editor);
  28929. }
  28930. });
  28931. return;
  28932. }
  28933. editor = selector;
  28934. if (isNull(self.get(editor.id))) {
  28935. return null;
  28936. }
  28937. if (removeEditorFromList(editor)) {
  28938. self.fire('RemoveEditor', { editor: editor });
  28939. }
  28940. if (editors.length === 0) {
  28941. window.removeEventListener('beforeunload', beforeUnloadDelegate);
  28942. }
  28943. editor.remove();
  28944. toggleGlobalEvents(editors.length > 0);
  28945. return editor;
  28946. },
  28947. execCommand: function (cmd, ui, value) {
  28948. var self = this, editor = self.get(value);
  28949. switch (cmd) {
  28950. case 'mceAddEditor':
  28951. if (!self.get(value)) {
  28952. new Editor(value, self.settings, self).render();
  28953. }
  28954. return true;
  28955. case 'mceRemoveEditor':
  28956. if (editor) {
  28957. editor.remove();
  28958. }
  28959. return true;
  28960. case 'mceToggleEditor':
  28961. if (!editor) {
  28962. self.execCommand('mceAddEditor', false, value);
  28963. return true;
  28964. }
  28965. if (editor.isHidden()) {
  28966. editor.show();
  28967. } else {
  28968. editor.hide();
  28969. }
  28970. return true;
  28971. }
  28972. if (self.activeEditor) {
  28973. return self.activeEditor.execCommand(cmd, ui, value);
  28974. }
  28975. return false;
  28976. },
  28977. triggerSave: function () {
  28978. each$1(editors, function (editor) {
  28979. editor.save();
  28980. });
  28981. },
  28982. addI18n: function (code, items) {
  28983. I18n.add(code, items);
  28984. },
  28985. translate: function (text) {
  28986. return I18n.translate(text);
  28987. },
  28988. setActive: function (editor) {
  28989. var activeEditor = this.activeEditor;
  28990. if (this.activeEditor !== editor) {
  28991. if (activeEditor) {
  28992. activeEditor.fire('deactivate', { relatedTarget: editor });
  28993. }
  28994. editor.fire('activate', { relatedTarget: activeEditor });
  28995. }
  28996. this.activeEditor = editor;
  28997. },
  28998. _setBaseUrl: function (baseUrl) {
  28999. this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ''));
  29000. this.baseURI = new URI(this.baseURL);
  29001. }
  29002. });
  29003. EditorManager.setup();
  29004. var min$1 = Math.min, max$1 = Math.max, round$1 = Math.round;
  29005. var relativePosition = function (rect, targetRect, rel) {
  29006. var x = targetRect.x;
  29007. var y = targetRect.y;
  29008. var w = rect.w;
  29009. var h = rect.h;
  29010. var targetW = targetRect.w;
  29011. var targetH = targetRect.h;
  29012. var relChars = (rel || '').split('');
  29013. if (relChars[0] === 'b') {
  29014. y += targetH;
  29015. }
  29016. if (relChars[1] === 'r') {
  29017. x += targetW;
  29018. }
  29019. if (relChars[0] === 'c') {
  29020. y += round$1(targetH / 2);
  29021. }
  29022. if (relChars[1] === 'c') {
  29023. x += round$1(targetW / 2);
  29024. }
  29025. if (relChars[3] === 'b') {
  29026. y -= h;
  29027. }
  29028. if (relChars[4] === 'r') {
  29029. x -= w;
  29030. }
  29031. if (relChars[3] === 'c') {
  29032. y -= round$1(h / 2);
  29033. }
  29034. if (relChars[4] === 'c') {
  29035. x -= round$1(w / 2);
  29036. }
  29037. return create$2(x, y, w, h);
  29038. };
  29039. var findBestRelativePosition = function (rect, targetRect, constrainRect, rels) {
  29040. var pos, i;
  29041. for (i = 0; i < rels.length; i++) {
  29042. pos = relativePosition(rect, targetRect, rels[i]);
  29043. 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) {
  29044. return rels[i];
  29045. }
  29046. }
  29047. return null;
  29048. };
  29049. var inflate = function (rect, w, h) {
  29050. return create$2(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2);
  29051. };
  29052. var intersect = function (rect, cropRect) {
  29053. var x1 = max$1(rect.x, cropRect.x);
  29054. var y1 = max$1(rect.y, cropRect.y);
  29055. var x2 = min$1(rect.x + rect.w, cropRect.x + cropRect.w);
  29056. var y2 = min$1(rect.y + rect.h, cropRect.y + cropRect.h);
  29057. if (x2 - x1 < 0 || y2 - y1 < 0) {
  29058. return null;
  29059. }
  29060. return create$2(x1, y1, x2 - x1, y2 - y1);
  29061. };
  29062. var clamp = function (rect, clampRect, fixedSize) {
  29063. var x1 = rect.x;
  29064. var y1 = rect.y;
  29065. var x2 = rect.x + rect.w;
  29066. var y2 = rect.y + rect.h;
  29067. var cx2 = clampRect.x + clampRect.w;
  29068. var cy2 = clampRect.y + clampRect.h;
  29069. var underflowX1 = max$1(0, clampRect.x - x1);
  29070. var underflowY1 = max$1(0, clampRect.y - y1);
  29071. var overflowX2 = max$1(0, x2 - cx2);
  29072. var overflowY2 = max$1(0, y2 - cy2);
  29073. x1 += underflowX1;
  29074. y1 += underflowY1;
  29075. if (fixedSize) {
  29076. x2 += underflowX1;
  29077. y2 += underflowY1;
  29078. x1 -= overflowX2;
  29079. y1 -= overflowY2;
  29080. }
  29081. x2 -= overflowX2;
  29082. y2 -= overflowY2;
  29083. return create$2(x1, y1, x2 - x1, y2 - y1);
  29084. };
  29085. var create$2 = function (x, y, w, h) {
  29086. return {
  29087. x: x,
  29088. y: y,
  29089. w: w,
  29090. h: h
  29091. };
  29092. };
  29093. var fromClientRect = function (clientRect) {
  29094. return create$2(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
  29095. };
  29096. var Rect = {
  29097. inflate: inflate,
  29098. relativePosition: relativePosition,
  29099. findBestRelativePosition: findBestRelativePosition,
  29100. intersect: intersect,
  29101. clamp: clamp,
  29102. create: create$2,
  29103. fromClientRect: fromClientRect
  29104. };
  29105. var awaiter = function (resolveCb, rejectCb, timeout) {
  29106. if (timeout === void 0) {
  29107. timeout = 1000;
  29108. }
  29109. var done = false;
  29110. var timer = null;
  29111. var complete = function (completer) {
  29112. return function () {
  29113. var args = [];
  29114. for (var _i = 0; _i < arguments.length; _i++) {
  29115. args[_i] = arguments[_i];
  29116. }
  29117. if (!done) {
  29118. done = true;
  29119. if (timer !== null) {
  29120. clearTimeout(timer);
  29121. timer = null;
  29122. }
  29123. completer.apply(null, args);
  29124. }
  29125. };
  29126. };
  29127. var resolve = complete(resolveCb);
  29128. var reject = complete(rejectCb);
  29129. var start = function () {
  29130. var args = [];
  29131. for (var _i = 0; _i < arguments.length; _i++) {
  29132. args[_i] = arguments[_i];
  29133. }
  29134. if (!done && timer === null) {
  29135. timer = setTimeout(function () {
  29136. return reject.apply(null, args);
  29137. }, timeout);
  29138. }
  29139. };
  29140. return {
  29141. start: start,
  29142. resolve: resolve,
  29143. reject: reject
  29144. };
  29145. };
  29146. var create$1 = function () {
  29147. var tasks = {};
  29148. var resultFns = {};
  29149. var load = function (id, url) {
  29150. var loadErrMsg = 'Script at URL "' + url + '" failed to load';
  29151. var runErrMsg = 'Script at URL "' + url + '" did not call `tinymce.Resource.add(\'' + id + '\', data)` within 1 second';
  29152. if (tasks[id] !== undefined) {
  29153. return tasks[id];
  29154. } else {
  29155. var task = new promiseObj(function (resolve, reject) {
  29156. var waiter = awaiter(resolve, reject);
  29157. resultFns[id] = waiter.resolve;
  29158. ScriptLoader.ScriptLoader.loadScript(url, function () {
  29159. return waiter.start(runErrMsg);
  29160. }, function () {
  29161. return waiter.reject(loadErrMsg);
  29162. });
  29163. });
  29164. tasks[id] = task;
  29165. return task;
  29166. }
  29167. };
  29168. var add = function (id, data) {
  29169. if (resultFns[id] !== undefined) {
  29170. resultFns[id](data);
  29171. delete resultFns[id];
  29172. }
  29173. tasks[id] = promiseObj.resolve(data);
  29174. };
  29175. return {
  29176. load: load,
  29177. add: add
  29178. };
  29179. };
  29180. var Resource = create$1();
  29181. var each = Tools.each, extend$1 = Tools.extend;
  29182. var extendClass, initializing;
  29183. var Class = function () {
  29184. };
  29185. Class.extend = extendClass = function (props) {
  29186. var self = this;
  29187. var _super = self.prototype;
  29188. var Class = function () {
  29189. var i, mixins, mixin;
  29190. var self = this;
  29191. if (!initializing) {
  29192. if (self.init) {
  29193. self.init.apply(self, arguments);
  29194. }
  29195. mixins = self.Mixins;
  29196. if (mixins) {
  29197. i = mixins.length;
  29198. while (i--) {
  29199. mixin = mixins[i];
  29200. if (mixin.init) {
  29201. mixin.init.apply(self, arguments);
  29202. }
  29203. }
  29204. }
  29205. }
  29206. };
  29207. var dummy = function () {
  29208. return this;
  29209. };
  29210. var createMethod = function (name, fn) {
  29211. return function () {
  29212. var self = this;
  29213. var tmp = self._super;
  29214. self._super = _super[name];
  29215. var ret = fn.apply(self, arguments);
  29216. self._super = tmp;
  29217. return ret;
  29218. };
  29219. };
  29220. initializing = true;
  29221. var prototype = new self();
  29222. initializing = false;
  29223. if (props.Mixins) {
  29224. each(props.Mixins, function (mixin) {
  29225. for (var name_1 in mixin) {
  29226. if (name_1 !== 'init') {
  29227. props[name_1] = mixin[name_1];
  29228. }
  29229. }
  29230. });
  29231. if (_super.Mixins) {
  29232. props.Mixins = _super.Mixins.concat(props.Mixins);
  29233. }
  29234. }
  29235. if (props.Methods) {
  29236. each(props.Methods.split(','), function (name) {
  29237. props[name] = dummy;
  29238. });
  29239. }
  29240. if (props.Properties) {
  29241. each(props.Properties.split(','), function (name) {
  29242. var fieldName = '_' + name;
  29243. props[name] = function (value) {
  29244. var self = this;
  29245. if (value !== undefined) {
  29246. self[fieldName] = value;
  29247. return self;
  29248. }
  29249. return self[fieldName];
  29250. };
  29251. });
  29252. }
  29253. if (props.Statics) {
  29254. each(props.Statics, function (func, name) {
  29255. Class[name] = func;
  29256. });
  29257. }
  29258. if (props.Defaults && _super.Defaults) {
  29259. props.Defaults = extend$1({}, _super.Defaults, props.Defaults);
  29260. }
  29261. each$j(props, function (member, name) {
  29262. if (typeof member === 'function' && _super[name]) {
  29263. prototype[name] = createMethod(name, member);
  29264. } else {
  29265. prototype[name] = member;
  29266. }
  29267. });
  29268. Class.prototype = prototype;
  29269. Class.constructor = Class;
  29270. Class.extend = extendClass;
  29271. return Class;
  29272. };
  29273. var min = Math.min, max = Math.max, round = Math.round;
  29274. var Color = function (value) {
  29275. var self = {};
  29276. var r = 0, g = 0, b = 0;
  29277. var rgb2hsv = function (r, g, b) {
  29278. var h, s, v;
  29279. h = 0;
  29280. s = 0;
  29281. v = 0;
  29282. r = r / 255;
  29283. g = g / 255;
  29284. b = b / 255;
  29285. var minRGB = min(r, min(g, b));
  29286. var maxRGB = max(r, max(g, b));
  29287. if (minRGB === maxRGB) {
  29288. v = minRGB;
  29289. return {
  29290. h: 0,
  29291. s: 0,
  29292. v: v * 100
  29293. };
  29294. }
  29295. var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  29296. h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  29297. h = 60 * (h - d / (maxRGB - minRGB));
  29298. s = (maxRGB - minRGB) / maxRGB;
  29299. v = maxRGB;
  29300. return {
  29301. h: round(h),
  29302. s: round(s * 100),
  29303. v: round(v * 100)
  29304. };
  29305. };
  29306. var hsvToRgb = function (hue, saturation, brightness) {
  29307. hue = (parseInt(hue, 10) || 0) % 360;
  29308. saturation = parseInt(saturation, 10) / 100;
  29309. brightness = parseInt(brightness, 10) / 100;
  29310. saturation = max(0, min(saturation, 1));
  29311. brightness = max(0, min(brightness, 1));
  29312. if (saturation === 0) {
  29313. r = g = b = round(255 * brightness);
  29314. return;
  29315. }
  29316. var side = hue / 60;
  29317. var chroma = brightness * saturation;
  29318. var x = chroma * (1 - Math.abs(side % 2 - 1));
  29319. var match = brightness - chroma;
  29320. switch (Math.floor(side)) {
  29321. case 0:
  29322. r = chroma;
  29323. g = x;
  29324. b = 0;
  29325. break;
  29326. case 1:
  29327. r = x;
  29328. g = chroma;
  29329. b = 0;
  29330. break;
  29331. case 2:
  29332. r = 0;
  29333. g = chroma;
  29334. b = x;
  29335. break;
  29336. case 3:
  29337. r = 0;
  29338. g = x;
  29339. b = chroma;
  29340. break;
  29341. case 4:
  29342. r = x;
  29343. g = 0;
  29344. b = chroma;
  29345. break;
  29346. case 5:
  29347. r = chroma;
  29348. g = 0;
  29349. b = x;
  29350. break;
  29351. default:
  29352. r = g = b = 0;
  29353. }
  29354. r = round(255 * (r + match));
  29355. g = round(255 * (g + match));
  29356. b = round(255 * (b + match));
  29357. };
  29358. var toHex = function () {
  29359. var hex = function (val) {
  29360. val = parseInt(val, 10).toString(16);
  29361. return val.length > 1 ? val : '0' + val;
  29362. };
  29363. return '#' + hex(r) + hex(g) + hex(b);
  29364. };
  29365. var toRgb = function () {
  29366. return {
  29367. r: r,
  29368. g: g,
  29369. b: b
  29370. };
  29371. };
  29372. var toHsv = function () {
  29373. return rgb2hsv(r, g, b);
  29374. };
  29375. var parse = function (value) {
  29376. var matches;
  29377. if (typeof value === 'object') {
  29378. if ('r' in value) {
  29379. r = value.r;
  29380. g = value.g;
  29381. b = value.b;
  29382. } else if ('v' in value) {
  29383. hsvToRgb(value.h, value.s, value.v);
  29384. }
  29385. } else {
  29386. if (matches = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)[^\)]*\)/gi.exec(value)) {
  29387. r = parseInt(matches[1], 10);
  29388. g = parseInt(matches[2], 10);
  29389. b = parseInt(matches[3], 10);
  29390. } else if (matches = /#([0-F]{2})([0-F]{2})([0-F]{2})/gi.exec(value)) {
  29391. r = parseInt(matches[1], 16);
  29392. g = parseInt(matches[2], 16);
  29393. b = parseInt(matches[3], 16);
  29394. } else if (matches = /#([0-F])([0-F])([0-F])/gi.exec(value)) {
  29395. r = parseInt(matches[1] + matches[1], 16);
  29396. g = parseInt(matches[2] + matches[2], 16);
  29397. b = parseInt(matches[3] + matches[3], 16);
  29398. }
  29399. }
  29400. r = r < 0 ? 0 : r > 255 ? 255 : r;
  29401. g = g < 0 ? 0 : g > 255 ? 255 : g;
  29402. b = b < 0 ? 0 : b > 255 ? 255 : b;
  29403. return self;
  29404. };
  29405. if (value) {
  29406. parse(value);
  29407. }
  29408. self.toRgb = toRgb;
  29409. self.toHsv = toHsv;
  29410. self.toHex = toHex;
  29411. self.parse = parse;
  29412. return self;
  29413. };
  29414. var serialize = function (obj) {
  29415. var data = JSON.stringify(obj);
  29416. if (!isString$1(data)) {
  29417. return data;
  29418. }
  29419. return data.replace(/[\u0080-\uFFFF]/g, function (match) {
  29420. var hexCode = match.charCodeAt(0).toString(16);
  29421. return '\\u' + '0000'.substring(hexCode.length) + hexCode;
  29422. });
  29423. };
  29424. var JSONUtils = {
  29425. serialize: serialize,
  29426. parse: function (text) {
  29427. try {
  29428. return JSON.parse(text);
  29429. } catch (ex) {
  29430. }
  29431. }
  29432. };
  29433. var JSONP = {
  29434. callbacks: {},
  29435. count: 0,
  29436. send: function (settings) {
  29437. var self = this, dom = DOMUtils.DOM, count = settings.count !== undefined ? settings.count : self.count;
  29438. var id = 'tinymce_jsonp_' + count;
  29439. self.callbacks[count] = function (json) {
  29440. dom.remove(id);
  29441. delete self.callbacks[count];
  29442. settings.callback(json);
  29443. };
  29444. dom.add(dom.doc.body, 'script', {
  29445. id: id,
  29446. src: settings.url,
  29447. type: 'text/javascript'
  29448. });
  29449. self.count++;
  29450. }
  29451. };
  29452. var XHR = __assign(__assign({}, Observable), {
  29453. send: function (settings) {
  29454. var xhr, count = 0;
  29455. var ready = function () {
  29456. if (!settings.async || xhr.readyState === 4 || count++ > 10000) {
  29457. if (settings.success && count < 10000 && xhr.status === 200) {
  29458. settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings);
  29459. } else if (settings.error) {
  29460. settings.error.call(settings.error_scope, count > 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings);
  29461. }
  29462. xhr = null;
  29463. } else {
  29464. Delay.setTimeout(ready, 10);
  29465. }
  29466. };
  29467. settings.scope = settings.scope || this;
  29468. settings.success_scope = settings.success_scope || settings.scope;
  29469. settings.error_scope = settings.error_scope || settings.scope;
  29470. settings.async = settings.async !== false;
  29471. settings.data = settings.data || '';
  29472. XHR.fire('beforeInitialize', { settings: settings });
  29473. xhr = new XMLHttpRequest();
  29474. if (xhr.overrideMimeType) {
  29475. xhr.overrideMimeType(settings.content_type);
  29476. }
  29477. xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async);
  29478. if (settings.crossDomain) {
  29479. xhr.withCredentials = true;
  29480. }
  29481. if (settings.content_type) {
  29482. xhr.setRequestHeader('Content-Type', settings.content_type);
  29483. }
  29484. if (settings.requestheaders) {
  29485. Tools.each(settings.requestheaders, function (header) {
  29486. xhr.setRequestHeader(header.key, header.value);
  29487. });
  29488. }
  29489. xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  29490. xhr = XHR.fire('beforeSend', {
  29491. xhr: xhr,
  29492. settings: settings
  29493. }).xhr;
  29494. xhr.send(settings.data);
  29495. if (!settings.async) {
  29496. return ready();
  29497. }
  29498. Delay.setTimeout(ready, 10);
  29499. }
  29500. });
  29501. var extend = Tools.extend;
  29502. var JSONRequest = function () {
  29503. function JSONRequest(settings) {
  29504. this.settings = extend({}, settings);
  29505. this.count = 0;
  29506. }
  29507. JSONRequest.sendRPC = function (o) {
  29508. return new JSONRequest().send(o);
  29509. };
  29510. JSONRequest.prototype.send = function (args) {
  29511. var ecb = args.error, scb = args.success;
  29512. var xhrArgs = extend(this.settings, args);
  29513. xhrArgs.success = function (c, x) {
  29514. c = JSONUtils.parse(c);
  29515. if (typeof c === 'undefined') {
  29516. c = { error: 'JSON Parse error.' };
  29517. }
  29518. if (c.error) {
  29519. ecb.call(xhrArgs.error_scope || xhrArgs.scope, c.error, x);
  29520. } else {
  29521. scb.call(xhrArgs.success_scope || xhrArgs.scope, c.result);
  29522. }
  29523. };
  29524. xhrArgs.error = function (ty, x) {
  29525. if (ecb) {
  29526. ecb.call(xhrArgs.error_scope || xhrArgs.scope, ty, x);
  29527. }
  29528. };
  29529. xhrArgs.data = JSONUtils.serialize({
  29530. id: args.id || 'c' + this.count++,
  29531. method: args.method,
  29532. params: args.params
  29533. });
  29534. xhrArgs.content_type = 'application/json';
  29535. XHR.send(xhrArgs);
  29536. };
  29537. return JSONRequest;
  29538. }();
  29539. var create = function () {
  29540. return function () {
  29541. var data = {};
  29542. var keys = [];
  29543. var storage = {
  29544. getItem: function (key) {
  29545. var item = data[key];
  29546. return item ? item : null;
  29547. },
  29548. setItem: function (key, value) {
  29549. keys.push(key);
  29550. data[key] = String(value);
  29551. },
  29552. key: function (index) {
  29553. return keys[index];
  29554. },
  29555. removeItem: function (key) {
  29556. keys = keys.filter(function (k) {
  29557. return k === key;
  29558. });
  29559. delete data[key];
  29560. },
  29561. clear: function () {
  29562. keys = [];
  29563. data = {};
  29564. },
  29565. length: 0
  29566. };
  29567. Object.defineProperty(storage, 'length', {
  29568. get: function () {
  29569. return keys.length;
  29570. },
  29571. configurable: false,
  29572. enumerable: false
  29573. });
  29574. return storage;
  29575. }();
  29576. };
  29577. var localStorage;
  29578. try {
  29579. var test = '__storage_test__';
  29580. localStorage = window.localStorage;
  29581. localStorage.setItem(test, test);
  29582. localStorage.removeItem(test);
  29583. } catch (e) {
  29584. localStorage = create();
  29585. }
  29586. var LocalStorage = localStorage;
  29587. var publicApi = {
  29588. geom: { Rect: Rect },
  29589. util: {
  29590. Promise: promiseObj,
  29591. Delay: Delay,
  29592. Tools: Tools,
  29593. VK: VK,
  29594. URI: URI,
  29595. Class: Class,
  29596. EventDispatcher: EventDispatcher,
  29597. Observable: Observable,
  29598. I18n: I18n,
  29599. XHR: XHR,
  29600. JSON: JSONUtils,
  29601. JSONRequest: JSONRequest,
  29602. JSONP: JSONP,
  29603. LocalStorage: LocalStorage,
  29604. Color: Color,
  29605. ImageUploader: ImageUploader
  29606. },
  29607. dom: {
  29608. EventUtils: EventUtils,
  29609. Sizzle: Sizzle,
  29610. DomQuery: DomQuery,
  29611. TreeWalker: DomTreeWalker,
  29612. TextSeeker: TextSeeker,
  29613. DOMUtils: DOMUtils,
  29614. ScriptLoader: ScriptLoader,
  29615. RangeUtils: RangeUtils,
  29616. Serializer: DomSerializer,
  29617. StyleSheetLoader: StyleSheetLoader,
  29618. ControlSelection: ControlSelection,
  29619. BookmarkManager: BookmarkManager,
  29620. Selection: EditorSelection,
  29621. Event: EventUtils.Event
  29622. },
  29623. html: {
  29624. Styles: Styles,
  29625. Entities: Entities,
  29626. Node: AstNode,
  29627. Schema: Schema,
  29628. SaxParser: SaxParser,
  29629. DomParser: DomParser,
  29630. Writer: Writer,
  29631. Serializer: HtmlSerializer
  29632. },
  29633. Env: Env,
  29634. AddOnManager: AddOnManager,
  29635. Annotator: Annotator,
  29636. Formatter: Formatter,
  29637. UndoManager: UndoManager,
  29638. EditorCommands: EditorCommands,
  29639. WindowManager: WindowManager,
  29640. NotificationManager: NotificationManager,
  29641. EditorObservable: EditorObservable,
  29642. Shortcuts: Shortcuts,
  29643. Editor: Editor,
  29644. FocusManager: FocusManager,
  29645. EditorManager: EditorManager,
  29646. DOM: DOMUtils.DOM,
  29647. ScriptLoader: ScriptLoader.ScriptLoader,
  29648. PluginManager: PluginManager,
  29649. ThemeManager: ThemeManager,
  29650. IconManager: IconManager,
  29651. Resource: Resource,
  29652. trim: Tools.trim,
  29653. isArray: Tools.isArray,
  29654. is: Tools.is,
  29655. toArray: Tools.toArray,
  29656. makeMap: Tools.makeMap,
  29657. each: Tools.each,
  29658. map: Tools.map,
  29659. grep: Tools.grep,
  29660. inArray: Tools.inArray,
  29661. extend: Tools.extend,
  29662. create: Tools.create,
  29663. walk: Tools.walk,
  29664. createNS: Tools.createNS,
  29665. resolve: Tools.resolve,
  29666. explode: Tools.explode,
  29667. _addCacheSuffix: Tools._addCacheSuffix,
  29668. isOpera: Env.opera,
  29669. isWebKit: Env.webkit,
  29670. isIE: Env.ie,
  29671. isGecko: Env.gecko,
  29672. isMac: Env.mac
  29673. };
  29674. var tinymce = Tools.extend(EditorManager, publicApi);
  29675. var exportToModuleLoaders = function (tinymce) {
  29676. if (typeof module === 'object') {
  29677. try {
  29678. module.exports = tinymce;
  29679. } catch (_) {
  29680. }
  29681. }
  29682. };
  29683. var exportToWindowGlobal = function (tinymce) {
  29684. window.tinymce = tinymce;
  29685. window.tinyMCE = tinymce;
  29686. };
  29687. exportToWindowGlobal(tinymce);
  29688. exportToModuleLoaders(tinymce);
  29689. }());