tinymce.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375
  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.9.1 (2021-08-27)
  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. return Optional.from(win['visualViewport']);
  1642. };
  1643. var bounds = function (x, y, width, height) {
  1644. return {
  1645. x: x,
  1646. y: y,
  1647. width: width,
  1648. height: height,
  1649. right: x + width,
  1650. bottom: y + height
  1651. };
  1652. };
  1653. var getBounds = function (_win) {
  1654. var win = _win === undefined ? window : _win;
  1655. var doc = win.document;
  1656. var scroll = get$8(SugarElement.fromDom(doc));
  1657. return get$7(win).fold(function () {
  1658. var html = win.document.documentElement;
  1659. var width = html.clientWidth;
  1660. var height = html.clientHeight;
  1661. return bounds(scroll.left, scroll.top, width, height);
  1662. }, function (visualViewport) {
  1663. return bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
  1664. });
  1665. };
  1666. var isNodeType = function (type) {
  1667. return function (node) {
  1668. return !!node && node.nodeType === type;
  1669. };
  1670. };
  1671. var isRestrictedNode = function (node) {
  1672. return !!node && !Object.getPrototypeOf(node);
  1673. };
  1674. var isElement$5 = isNodeType(1);
  1675. var matchNodeNames = function (names) {
  1676. var lowercasedNames = names.map(function (s) {
  1677. return s.toLowerCase();
  1678. });
  1679. return function (node) {
  1680. if (node && node.nodeName) {
  1681. var nodeName = node.nodeName.toLowerCase();
  1682. return contains$3(lowercasedNames, nodeName);
  1683. }
  1684. return false;
  1685. };
  1686. };
  1687. var matchStyleValues = function (name, values) {
  1688. var items = values.toLowerCase().split(' ');
  1689. return function (node) {
  1690. if (isElement$5(node)) {
  1691. for (var i = 0; i < items.length; i++) {
  1692. var computed = node.ownerDocument.defaultView.getComputedStyle(node, null);
  1693. var cssValue = computed ? computed.getPropertyValue(name) : null;
  1694. if (cssValue === items[i]) {
  1695. return true;
  1696. }
  1697. }
  1698. }
  1699. return false;
  1700. };
  1701. };
  1702. var hasAttribute = function (attrName) {
  1703. return function (node) {
  1704. return isElement$5(node) && node.hasAttribute(attrName);
  1705. };
  1706. };
  1707. var hasAttributeValue = function (attrName, attrValue) {
  1708. return function (node) {
  1709. return isElement$5(node) && node.getAttribute(attrName) === attrValue;
  1710. };
  1711. };
  1712. var isBogus$2 = function (node) {
  1713. return isElement$5(node) && node.hasAttribute('data-mce-bogus');
  1714. };
  1715. var isBogusAll$1 = function (node) {
  1716. return isElement$5(node) && node.getAttribute('data-mce-bogus') === 'all';
  1717. };
  1718. var isTable$3 = function (node) {
  1719. return isElement$5(node) && node.tagName === 'TABLE';
  1720. };
  1721. var hasContentEditableState = function (value) {
  1722. return function (node) {
  1723. if (isElement$5(node)) {
  1724. if (node.contentEditable === value) {
  1725. return true;
  1726. }
  1727. if (node.getAttribute('data-mce-contenteditable') === value) {
  1728. return true;
  1729. }
  1730. }
  1731. return false;
  1732. };
  1733. };
  1734. var isTextareaOrInput = matchNodeNames([
  1735. 'textarea',
  1736. 'input'
  1737. ]);
  1738. var isText$7 = isNodeType(3);
  1739. var isComment = isNodeType(8);
  1740. var isDocument$1 = isNodeType(9);
  1741. var isDocumentFragment = isNodeType(11);
  1742. var isBr$5 = matchNodeNames(['br']);
  1743. var isImg = matchNodeNames(['img']);
  1744. var isContentEditableTrue$4 = hasContentEditableState('true');
  1745. var isContentEditableFalse$b = hasContentEditableState('false');
  1746. var isTableCell$5 = matchNodeNames([
  1747. 'td',
  1748. 'th'
  1749. ]);
  1750. var isMedia$2 = matchNodeNames([
  1751. 'video',
  1752. 'audio',
  1753. 'object',
  1754. 'embed'
  1755. ]);
  1756. var is$1 = function (lhs, rhs, comparator) {
  1757. if (comparator === void 0) {
  1758. comparator = tripleEquals;
  1759. }
  1760. return lhs.exists(function (left) {
  1761. return comparator(left, rhs);
  1762. });
  1763. };
  1764. var cat = function (arr) {
  1765. var r = [];
  1766. var push = function (x) {
  1767. r.push(x);
  1768. };
  1769. for (var i = 0; i < arr.length; i++) {
  1770. arr[i].each(push);
  1771. }
  1772. return r;
  1773. };
  1774. var lift2 = function (oa, ob, f) {
  1775. return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  1776. };
  1777. var lift3 = function (oa, ob, oc, f) {
  1778. return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
  1779. };
  1780. var someIf = function (b, a) {
  1781. return b ? Optional.some(a) : Optional.none();
  1782. };
  1783. var isSupported = function (dom) {
  1784. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  1785. };
  1786. var rawSet = function (dom, key, value) {
  1787. if (isString$1(value) || isBoolean(value) || isNumber(value)) {
  1788. dom.setAttribute(key, value + '');
  1789. } else {
  1790. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1791. throw new Error('Attribute value was not simple');
  1792. }
  1793. };
  1794. var set$1 = function (element, key, value) {
  1795. rawSet(element.dom, key, value);
  1796. };
  1797. var setAll$1 = function (element, attrs) {
  1798. var dom = element.dom;
  1799. each$j(attrs, function (v, k) {
  1800. rawSet(dom, k, v);
  1801. });
  1802. };
  1803. var get$6 = function (element, key) {
  1804. var v = element.dom.getAttribute(key);
  1805. return v === null ? undefined : v;
  1806. };
  1807. var getOpt = function (element, key) {
  1808. return Optional.from(get$6(element, key));
  1809. };
  1810. var has$1 = function (element, key) {
  1811. var dom = element.dom;
  1812. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  1813. };
  1814. var remove$6 = function (element, key) {
  1815. element.dom.removeAttribute(key);
  1816. };
  1817. var clone$3 = function (element) {
  1818. return foldl(element.dom.attributes, function (acc, attr) {
  1819. acc[attr.name] = attr.value;
  1820. return acc;
  1821. }, {});
  1822. };
  1823. var internalSet = function (dom, property, value) {
  1824. if (!isString$1(value)) {
  1825. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  1826. throw new Error('CSS value must be a string: ' + value);
  1827. }
  1828. if (isSupported(dom)) {
  1829. dom.style.setProperty(property, value);
  1830. }
  1831. };
  1832. var setAll = function (element, css) {
  1833. var dom = element.dom;
  1834. each$j(css, function (v, k) {
  1835. internalSet(dom, k, v);
  1836. });
  1837. };
  1838. var get$5 = function (element, property) {
  1839. var dom = element.dom;
  1840. var styles = window.getComputedStyle(dom);
  1841. var r = styles.getPropertyValue(property);
  1842. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  1843. };
  1844. var getUnsafeProperty = function (dom, property) {
  1845. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  1846. };
  1847. var getRaw = function (element, property) {
  1848. var dom = element.dom;
  1849. var raw = getUnsafeProperty(dom, property);
  1850. return Optional.from(raw).filter(function (r) {
  1851. return r.length > 0;
  1852. });
  1853. };
  1854. var getAllRaw = function (element) {
  1855. var css = {};
  1856. var dom = element.dom;
  1857. if (isSupported(dom)) {
  1858. for (var i = 0; i < dom.style.length; i++) {
  1859. var ruleName = dom.style.item(i);
  1860. css[ruleName] = dom.style[ruleName];
  1861. }
  1862. }
  1863. return css;
  1864. };
  1865. var reflow = function (e) {
  1866. return e.dom.offsetWidth;
  1867. };
  1868. var browser$3 = detect().browser;
  1869. var firstElement = function (nodes) {
  1870. return find$3(nodes, isElement$6);
  1871. };
  1872. var getTableCaptionDeltaY = function (elm) {
  1873. if (browser$3.isFirefox() && name(elm) === 'table') {
  1874. return firstElement(children(elm)).filter(function (elm) {
  1875. return name(elm) === 'caption';
  1876. }).bind(function (caption) {
  1877. return firstElement(nextSiblings(caption)).map(function (body) {
  1878. var bodyTop = body.dom.offsetTop;
  1879. var captionTop = caption.dom.offsetTop;
  1880. var captionHeight = caption.dom.offsetHeight;
  1881. return bodyTop <= captionTop ? -captionHeight : 0;
  1882. });
  1883. }).getOr(0);
  1884. } else {
  1885. return 0;
  1886. }
  1887. };
  1888. var hasChild = function (elm, child) {
  1889. return elm.children && contains$3(elm.children, child);
  1890. };
  1891. var getPos = function (body, elm, rootElm) {
  1892. var x = 0, y = 0;
  1893. var doc = body.ownerDocument;
  1894. rootElm = rootElm ? rootElm : body;
  1895. if (elm) {
  1896. if (rootElm === body && elm.getBoundingClientRect && get$5(SugarElement.fromDom(body), 'position') === 'static') {
  1897. var pos = elm.getBoundingClientRect();
  1898. x = pos.left + (doc.documentElement.scrollLeft || body.scrollLeft) - doc.documentElement.clientLeft;
  1899. y = pos.top + (doc.documentElement.scrollTop || body.scrollTop) - doc.documentElement.clientTop;
  1900. return {
  1901. x: x,
  1902. y: y
  1903. };
  1904. }
  1905. var offsetParent = elm;
  1906. while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  1907. var castOffsetParent = offsetParent;
  1908. x += castOffsetParent.offsetLeft || 0;
  1909. y += castOffsetParent.offsetTop || 0;
  1910. offsetParent = castOffsetParent.offsetParent;
  1911. }
  1912. offsetParent = elm.parentNode;
  1913. while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  1914. x -= offsetParent.scrollLeft || 0;
  1915. y -= offsetParent.scrollTop || 0;
  1916. offsetParent = offsetParent.parentNode;
  1917. }
  1918. y += getTableCaptionDeltaY(SugarElement.fromDom(elm));
  1919. }
  1920. return {
  1921. x: x,
  1922. y: y
  1923. };
  1924. };
  1925. var exports$1 = {}, module$1 = { exports: exports$1 };
  1926. (function (define, exports, module, require) {
  1927. (function (f) {
  1928. if (typeof exports === 'object' && typeof module !== 'undefined') {
  1929. module.exports = f();
  1930. } else if (typeof define === 'function' && define.amd) {
  1931. define([], f);
  1932. } else {
  1933. var g;
  1934. if (typeof window !== 'undefined') {
  1935. g = window;
  1936. } else if (typeof global !== 'undefined') {
  1937. g = global;
  1938. } else if (typeof self !== 'undefined') {
  1939. g = self;
  1940. } else {
  1941. g = this;
  1942. }
  1943. g.EphoxContactWrapper = f();
  1944. }
  1945. }(function () {
  1946. return function () {
  1947. function r(e, n, t) {
  1948. function o(i, f) {
  1949. if (!n[i]) {
  1950. if (!e[i]) {
  1951. var c = 'function' == typeof require && require;
  1952. if (!f && c)
  1953. return c(i, !0);
  1954. if (u)
  1955. return u(i, !0);
  1956. var a = new Error('Cannot find module \'' + i + '\'');
  1957. throw a.code = 'MODULE_NOT_FOUND', a;
  1958. }
  1959. var p = n[i] = { exports: {} };
  1960. e[i][0].call(p.exports, function (r) {
  1961. var n = e[i][1][r];
  1962. return o(n || r);
  1963. }, p, p.exports, r, e, n, t);
  1964. }
  1965. return n[i].exports;
  1966. }
  1967. for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++)
  1968. o(t[i]);
  1969. return o;
  1970. }
  1971. return r;
  1972. }()({
  1973. 1: [
  1974. function (require, module, exports) {
  1975. var process = module.exports = {};
  1976. var cachedSetTimeout;
  1977. var cachedClearTimeout;
  1978. function defaultSetTimout() {
  1979. throw new Error('setTimeout has not been defined');
  1980. }
  1981. function defaultClearTimeout() {
  1982. throw new Error('clearTimeout has not been defined');
  1983. }
  1984. (function () {
  1985. try {
  1986. if (typeof setTimeout === 'function') {
  1987. cachedSetTimeout = setTimeout;
  1988. } else {
  1989. cachedSetTimeout = defaultSetTimout;
  1990. }
  1991. } catch (e) {
  1992. cachedSetTimeout = defaultSetTimout;
  1993. }
  1994. try {
  1995. if (typeof clearTimeout === 'function') {
  1996. cachedClearTimeout = clearTimeout;
  1997. } else {
  1998. cachedClearTimeout = defaultClearTimeout;
  1999. }
  2000. } catch (e) {
  2001. cachedClearTimeout = defaultClearTimeout;
  2002. }
  2003. }());
  2004. function runTimeout(fun) {
  2005. if (cachedSetTimeout === setTimeout) {
  2006. return setTimeout(fun, 0);
  2007. }
  2008. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  2009. cachedSetTimeout = setTimeout;
  2010. return setTimeout(fun, 0);
  2011. }
  2012. try {
  2013. return cachedSetTimeout(fun, 0);
  2014. } catch (e) {
  2015. try {
  2016. return cachedSetTimeout.call(null, fun, 0);
  2017. } catch (e) {
  2018. return cachedSetTimeout.call(this, fun, 0);
  2019. }
  2020. }
  2021. }
  2022. function runClearTimeout(marker) {
  2023. if (cachedClearTimeout === clearTimeout) {
  2024. return clearTimeout(marker);
  2025. }
  2026. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  2027. cachedClearTimeout = clearTimeout;
  2028. return clearTimeout(marker);
  2029. }
  2030. try {
  2031. return cachedClearTimeout(marker);
  2032. } catch (e) {
  2033. try {
  2034. return cachedClearTimeout.call(null, marker);
  2035. } catch (e) {
  2036. return cachedClearTimeout.call(this, marker);
  2037. }
  2038. }
  2039. }
  2040. var queue = [];
  2041. var draining = false;
  2042. var currentQueue;
  2043. var queueIndex = -1;
  2044. function cleanUpNextTick() {
  2045. if (!draining || !currentQueue) {
  2046. return;
  2047. }
  2048. draining = false;
  2049. if (currentQueue.length) {
  2050. queue = currentQueue.concat(queue);
  2051. } else {
  2052. queueIndex = -1;
  2053. }
  2054. if (queue.length) {
  2055. drainQueue();
  2056. }
  2057. }
  2058. function drainQueue() {
  2059. if (draining) {
  2060. return;
  2061. }
  2062. var timeout = runTimeout(cleanUpNextTick);
  2063. draining = true;
  2064. var len = queue.length;
  2065. while (len) {
  2066. currentQueue = queue;
  2067. queue = [];
  2068. while (++queueIndex < len) {
  2069. if (currentQueue) {
  2070. currentQueue[queueIndex].run();
  2071. }
  2072. }
  2073. queueIndex = -1;
  2074. len = queue.length;
  2075. }
  2076. currentQueue = null;
  2077. draining = false;
  2078. runClearTimeout(timeout);
  2079. }
  2080. process.nextTick = function (fun) {
  2081. var args = new Array(arguments.length - 1);
  2082. if (arguments.length > 1) {
  2083. for (var i = 1; i < arguments.length; i++) {
  2084. args[i - 1] = arguments[i];
  2085. }
  2086. }
  2087. queue.push(new Item(fun, args));
  2088. if (queue.length === 1 && !draining) {
  2089. runTimeout(drainQueue);
  2090. }
  2091. };
  2092. function Item(fun, array) {
  2093. this.fun = fun;
  2094. this.array = array;
  2095. }
  2096. Item.prototype.run = function () {
  2097. this.fun.apply(null, this.array);
  2098. };
  2099. process.title = 'browser';
  2100. process.browser = true;
  2101. process.env = {};
  2102. process.argv = [];
  2103. process.version = '';
  2104. process.versions = {};
  2105. function noop() {
  2106. }
  2107. process.on = noop;
  2108. process.addListener = noop;
  2109. process.once = noop;
  2110. process.off = noop;
  2111. process.removeListener = noop;
  2112. process.removeAllListeners = noop;
  2113. process.emit = noop;
  2114. process.prependListener = noop;
  2115. process.prependOnceListener = noop;
  2116. process.listeners = function (name) {
  2117. return [];
  2118. };
  2119. process.binding = function (name) {
  2120. throw new Error('process.binding is not supported');
  2121. };
  2122. process.cwd = function () {
  2123. return '/';
  2124. };
  2125. process.chdir = function (dir) {
  2126. throw new Error('process.chdir is not supported');
  2127. };
  2128. process.umask = function () {
  2129. return 0;
  2130. };
  2131. },
  2132. {}
  2133. ],
  2134. 2: [
  2135. function (require, module, exports) {
  2136. (function (setImmediate) {
  2137. (function (root) {
  2138. var setTimeoutFunc = setTimeout;
  2139. function noop() {
  2140. }
  2141. function bind(fn, thisArg) {
  2142. return function () {
  2143. fn.apply(thisArg, arguments);
  2144. };
  2145. }
  2146. function Promise(fn) {
  2147. if (typeof this !== 'object')
  2148. throw new TypeError('Promises must be constructed via new');
  2149. if (typeof fn !== 'function')
  2150. throw new TypeError('not a function');
  2151. this._state = 0;
  2152. this._handled = false;
  2153. this._value = undefined;
  2154. this._deferreds = [];
  2155. doResolve(fn, this);
  2156. }
  2157. function handle(self, deferred) {
  2158. while (self._state === 3) {
  2159. self = self._value;
  2160. }
  2161. if (self._state === 0) {
  2162. self._deferreds.push(deferred);
  2163. return;
  2164. }
  2165. self._handled = true;
  2166. Promise._immediateFn(function () {
  2167. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  2168. if (cb === null) {
  2169. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  2170. return;
  2171. }
  2172. var ret;
  2173. try {
  2174. ret = cb(self._value);
  2175. } catch (e) {
  2176. reject(deferred.promise, e);
  2177. return;
  2178. }
  2179. resolve(deferred.promise, ret);
  2180. });
  2181. }
  2182. function resolve(self, newValue) {
  2183. try {
  2184. if (newValue === self)
  2185. throw new TypeError('A promise cannot be resolved with itself.');
  2186. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  2187. var then = newValue.then;
  2188. if (newValue instanceof Promise) {
  2189. self._state = 3;
  2190. self._value = newValue;
  2191. finale(self);
  2192. return;
  2193. } else if (typeof then === 'function') {
  2194. doResolve(bind(then, newValue), self);
  2195. return;
  2196. }
  2197. }
  2198. self._state = 1;
  2199. self._value = newValue;
  2200. finale(self);
  2201. } catch (e) {
  2202. reject(self, e);
  2203. }
  2204. }
  2205. function reject(self, newValue) {
  2206. self._state = 2;
  2207. self._value = newValue;
  2208. finale(self);
  2209. }
  2210. function finale(self) {
  2211. if (self._state === 2 && self._deferreds.length === 0) {
  2212. Promise._immediateFn(function () {
  2213. if (!self._handled) {
  2214. Promise._unhandledRejectionFn(self._value);
  2215. }
  2216. });
  2217. }
  2218. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  2219. handle(self, self._deferreds[i]);
  2220. }
  2221. self._deferreds = null;
  2222. }
  2223. function Handler(onFulfilled, onRejected, promise) {
  2224. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  2225. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  2226. this.promise = promise;
  2227. }
  2228. function doResolve(fn, self) {
  2229. var done = false;
  2230. try {
  2231. fn(function (value) {
  2232. if (done)
  2233. return;
  2234. done = true;
  2235. resolve(self, value);
  2236. }, function (reason) {
  2237. if (done)
  2238. return;
  2239. done = true;
  2240. reject(self, reason);
  2241. });
  2242. } catch (ex) {
  2243. if (done)
  2244. return;
  2245. done = true;
  2246. reject(self, ex);
  2247. }
  2248. }
  2249. Promise.prototype['catch'] = function (onRejected) {
  2250. return this.then(null, onRejected);
  2251. };
  2252. Promise.prototype.then = function (onFulfilled, onRejected) {
  2253. var prom = new this.constructor(noop);
  2254. handle(this, new Handler(onFulfilled, onRejected, prom));
  2255. return prom;
  2256. };
  2257. Promise.all = function (arr) {
  2258. var args = Array.prototype.slice.call(arr);
  2259. return new Promise(function (resolve, reject) {
  2260. if (args.length === 0)
  2261. return resolve([]);
  2262. var remaining = args.length;
  2263. function res(i, val) {
  2264. try {
  2265. if (val && (typeof val === 'object' || typeof val === 'function')) {
  2266. var then = val.then;
  2267. if (typeof then === 'function') {
  2268. then.call(val, function (val) {
  2269. res(i, val);
  2270. }, reject);
  2271. return;
  2272. }
  2273. }
  2274. args[i] = val;
  2275. if (--remaining === 0) {
  2276. resolve(args);
  2277. }
  2278. } catch (ex) {
  2279. reject(ex);
  2280. }
  2281. }
  2282. for (var i = 0; i < args.length; i++) {
  2283. res(i, args[i]);
  2284. }
  2285. });
  2286. };
  2287. Promise.resolve = function (value) {
  2288. if (value && typeof value === 'object' && value.constructor === Promise) {
  2289. return value;
  2290. }
  2291. return new Promise(function (resolve) {
  2292. resolve(value);
  2293. });
  2294. };
  2295. Promise.reject = function (value) {
  2296. return new Promise(function (resolve, reject) {
  2297. reject(value);
  2298. });
  2299. };
  2300. Promise.race = function (values) {
  2301. return new Promise(function (resolve, reject) {
  2302. for (var i = 0, len = values.length; i < len; i++) {
  2303. values[i].then(resolve, reject);
  2304. }
  2305. });
  2306. };
  2307. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  2308. setImmediate(fn);
  2309. } : function (fn) {
  2310. setTimeoutFunc(fn, 0);
  2311. };
  2312. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  2313. if (typeof console !== 'undefined' && console) {
  2314. console.warn('Possible Unhandled Promise Rejection:', err);
  2315. }
  2316. };
  2317. Promise._setImmediateFn = function _setImmediateFn(fn) {
  2318. Promise._immediateFn = fn;
  2319. };
  2320. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  2321. Promise._unhandledRejectionFn = fn;
  2322. };
  2323. if (typeof module !== 'undefined' && module.exports) {
  2324. module.exports = Promise;
  2325. } else if (!root.Promise) {
  2326. root.Promise = Promise;
  2327. }
  2328. }(this));
  2329. }.call(this, require('timers').setImmediate));
  2330. },
  2331. { 'timers': 3 }
  2332. ],
  2333. 3: [
  2334. function (require, module, exports) {
  2335. (function (setImmediate, clearImmediate) {
  2336. var nextTick = require('process/browser.js').nextTick;
  2337. var apply = Function.prototype.apply;
  2338. var slice = Array.prototype.slice;
  2339. var immediateIds = {};
  2340. var nextImmediateId = 0;
  2341. exports.setTimeout = function () {
  2342. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  2343. };
  2344. exports.setInterval = function () {
  2345. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  2346. };
  2347. exports.clearTimeout = exports.clearInterval = function (timeout) {
  2348. timeout.close();
  2349. };
  2350. function Timeout(id, clearFn) {
  2351. this._id = id;
  2352. this._clearFn = clearFn;
  2353. }
  2354. Timeout.prototype.unref = Timeout.prototype.ref = function () {
  2355. };
  2356. Timeout.prototype.close = function () {
  2357. this._clearFn.call(window, this._id);
  2358. };
  2359. exports.enroll = function (item, msecs) {
  2360. clearTimeout(item._idleTimeoutId);
  2361. item._idleTimeout = msecs;
  2362. };
  2363. exports.unenroll = function (item) {
  2364. clearTimeout(item._idleTimeoutId);
  2365. item._idleTimeout = -1;
  2366. };
  2367. exports._unrefActive = exports.active = function (item) {
  2368. clearTimeout(item._idleTimeoutId);
  2369. var msecs = item._idleTimeout;
  2370. if (msecs >= 0) {
  2371. item._idleTimeoutId = setTimeout(function onTimeout() {
  2372. if (item._onTimeout)
  2373. item._onTimeout();
  2374. }, msecs);
  2375. }
  2376. };
  2377. exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) {
  2378. var id = nextImmediateId++;
  2379. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  2380. immediateIds[id] = true;
  2381. nextTick(function onNextTick() {
  2382. if (immediateIds[id]) {
  2383. if (args) {
  2384. fn.apply(null, args);
  2385. } else {
  2386. fn.call(null);
  2387. }
  2388. exports.clearImmediate(id);
  2389. }
  2390. });
  2391. return id;
  2392. };
  2393. exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) {
  2394. delete immediateIds[id];
  2395. };
  2396. }.call(this, require('timers').setImmediate, require('timers').clearImmediate));
  2397. },
  2398. {
  2399. 'process/browser.js': 1,
  2400. 'timers': 3
  2401. }
  2402. ],
  2403. 4: [
  2404. function (require, module, exports) {
  2405. var promisePolyfill = require('promise-polyfill');
  2406. var Global = function () {
  2407. if (typeof window !== 'undefined') {
  2408. return window;
  2409. } else {
  2410. return Function('return this;')();
  2411. }
  2412. }();
  2413. module.exports = { boltExport: Global.Promise || promisePolyfill };
  2414. },
  2415. { 'promise-polyfill': 2 }
  2416. ]
  2417. }, {}, [4])(4);
  2418. }));
  2419. }(undefined, exports$1, module$1, undefined));
  2420. var Promise$1 = module$1.exports.boltExport;
  2421. var nu$1 = function (baseFn) {
  2422. var data = Optional.none();
  2423. var callbacks = [];
  2424. var map = function (f) {
  2425. return nu$1(function (nCallback) {
  2426. get(function (data) {
  2427. nCallback(f(data));
  2428. });
  2429. });
  2430. };
  2431. var get = function (nCallback) {
  2432. if (isReady()) {
  2433. call(nCallback);
  2434. } else {
  2435. callbacks.push(nCallback);
  2436. }
  2437. };
  2438. var set = function (x) {
  2439. if (!isReady()) {
  2440. data = Optional.some(x);
  2441. run(callbacks);
  2442. callbacks = [];
  2443. }
  2444. };
  2445. var isReady = function () {
  2446. return data.isSome();
  2447. };
  2448. var run = function (cbs) {
  2449. each$k(cbs, call);
  2450. };
  2451. var call = function (cb) {
  2452. data.each(function (x) {
  2453. setTimeout(function () {
  2454. cb(x);
  2455. }, 0);
  2456. });
  2457. };
  2458. baseFn(set);
  2459. return {
  2460. get: get,
  2461. map: map,
  2462. isReady: isReady
  2463. };
  2464. };
  2465. var pure$1 = function (a) {
  2466. return nu$1(function (callback) {
  2467. callback(a);
  2468. });
  2469. };
  2470. var LazyValue = {
  2471. nu: nu$1,
  2472. pure: pure$1
  2473. };
  2474. var errorReporter = function (err) {
  2475. setTimeout(function () {
  2476. throw err;
  2477. }, 0);
  2478. };
  2479. var make = function (run) {
  2480. var get = function (callback) {
  2481. run().then(callback, errorReporter);
  2482. };
  2483. var map = function (fab) {
  2484. return make(function () {
  2485. return run().then(fab);
  2486. });
  2487. };
  2488. var bind = function (aFutureB) {
  2489. return make(function () {
  2490. return run().then(function (v) {
  2491. return aFutureB(v).toPromise();
  2492. });
  2493. });
  2494. };
  2495. var anonBind = function (futureB) {
  2496. return make(function () {
  2497. return run().then(function () {
  2498. return futureB.toPromise();
  2499. });
  2500. });
  2501. };
  2502. var toLazy = function () {
  2503. return LazyValue.nu(get);
  2504. };
  2505. var toCached = function () {
  2506. var cache = null;
  2507. return make(function () {
  2508. if (cache === null) {
  2509. cache = run();
  2510. }
  2511. return cache;
  2512. });
  2513. };
  2514. var toPromise = run;
  2515. return {
  2516. map: map,
  2517. bind: bind,
  2518. anonBind: anonBind,
  2519. toLazy: toLazy,
  2520. toCached: toCached,
  2521. toPromise: toPromise,
  2522. get: get
  2523. };
  2524. };
  2525. var nu = function (baseFn) {
  2526. return make(function () {
  2527. return new Promise$1(baseFn);
  2528. });
  2529. };
  2530. var pure = function (a) {
  2531. return make(function () {
  2532. return Promise$1.resolve(a);
  2533. });
  2534. };
  2535. var Future = {
  2536. nu: nu,
  2537. pure: pure
  2538. };
  2539. var par$1 = function (asyncValues, nu) {
  2540. return nu(function (callback) {
  2541. var r = [];
  2542. var count = 0;
  2543. var cb = function (i) {
  2544. return function (value) {
  2545. r[i] = value;
  2546. count++;
  2547. if (count >= asyncValues.length) {
  2548. callback(r);
  2549. }
  2550. };
  2551. };
  2552. if (asyncValues.length === 0) {
  2553. callback([]);
  2554. } else {
  2555. each$k(asyncValues, function (asyncValue, i) {
  2556. asyncValue.get(cb(i));
  2557. });
  2558. }
  2559. });
  2560. };
  2561. var par = function (futures) {
  2562. return par$1(futures, Future.nu);
  2563. };
  2564. var value$1 = function (o) {
  2565. var or = function (_opt) {
  2566. return value$1(o);
  2567. };
  2568. var orThunk = function (_f) {
  2569. return value$1(o);
  2570. };
  2571. var map = function (f) {
  2572. return value$1(f(o));
  2573. };
  2574. var mapError = function (_f) {
  2575. return value$1(o);
  2576. };
  2577. var each = function (f) {
  2578. f(o);
  2579. };
  2580. var bind = function (f) {
  2581. return f(o);
  2582. };
  2583. var fold = function (_, onValue) {
  2584. return onValue(o);
  2585. };
  2586. var exists = function (f) {
  2587. return f(o);
  2588. };
  2589. var forall = function (f) {
  2590. return f(o);
  2591. };
  2592. var toOptional = function () {
  2593. return Optional.some(o);
  2594. };
  2595. return {
  2596. isValue: always,
  2597. isError: never,
  2598. getOr: constant(o),
  2599. getOrThunk: constant(o),
  2600. getOrDie: constant(o),
  2601. or: or,
  2602. orThunk: orThunk,
  2603. fold: fold,
  2604. map: map,
  2605. mapError: mapError,
  2606. each: each,
  2607. bind: bind,
  2608. exists: exists,
  2609. forall: forall,
  2610. toOptional: toOptional
  2611. };
  2612. };
  2613. var error = function (message) {
  2614. var getOrThunk = function (f) {
  2615. return f();
  2616. };
  2617. var getOrDie = function () {
  2618. return die(String(message))();
  2619. };
  2620. var or = identity;
  2621. var orThunk = function (f) {
  2622. return f();
  2623. };
  2624. var map = function (_f) {
  2625. return error(message);
  2626. };
  2627. var mapError = function (f) {
  2628. return error(f(message));
  2629. };
  2630. var bind = function (_f) {
  2631. return error(message);
  2632. };
  2633. var fold = function (onError, _) {
  2634. return onError(message);
  2635. };
  2636. return {
  2637. isValue: never,
  2638. isError: always,
  2639. getOr: identity,
  2640. getOrThunk: getOrThunk,
  2641. getOrDie: getOrDie,
  2642. or: or,
  2643. orThunk: orThunk,
  2644. fold: fold,
  2645. map: map,
  2646. mapError: mapError,
  2647. each: noop,
  2648. bind: bind,
  2649. exists: never,
  2650. forall: always,
  2651. toOptional: Optional.none
  2652. };
  2653. };
  2654. var fromOption = function (opt, err) {
  2655. return opt.fold(function () {
  2656. return error(err);
  2657. }, value$1);
  2658. };
  2659. var Result = {
  2660. value: value$1,
  2661. error: error,
  2662. fromOption: fromOption
  2663. };
  2664. var generate$1 = function (cases) {
  2665. if (!isArray$1(cases)) {
  2666. throw new Error('cases must be an array');
  2667. }
  2668. if (cases.length === 0) {
  2669. throw new Error('there must be at least one case');
  2670. }
  2671. var constructors = [];
  2672. var adt = {};
  2673. each$k(cases, function (acase, count) {
  2674. var keys$1 = keys(acase);
  2675. if (keys$1.length !== 1) {
  2676. throw new Error('one and only one name per case');
  2677. }
  2678. var key = keys$1[0];
  2679. var value = acase[key];
  2680. if (adt[key] !== undefined) {
  2681. throw new Error('duplicate key detected:' + key);
  2682. } else if (key === 'cata') {
  2683. throw new Error('cannot have a case named cata (sorry)');
  2684. } else if (!isArray$1(value)) {
  2685. throw new Error('case arguments must be an array');
  2686. }
  2687. constructors.push(key);
  2688. adt[key] = function () {
  2689. var args = [];
  2690. for (var _i = 0; _i < arguments.length; _i++) {
  2691. args[_i] = arguments[_i];
  2692. }
  2693. var argLength = args.length;
  2694. if (argLength !== value.length) {
  2695. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  2696. }
  2697. var match = function (branches) {
  2698. var branchKeys = keys(branches);
  2699. if (constructors.length !== branchKeys.length) {
  2700. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  2701. }
  2702. var allReqd = forall(constructors, function (reqKey) {
  2703. return contains$3(branchKeys, reqKey);
  2704. });
  2705. if (!allReqd) {
  2706. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  2707. }
  2708. return branches[key].apply(null, args);
  2709. };
  2710. return {
  2711. fold: function () {
  2712. var foldArgs = [];
  2713. for (var _i = 0; _i < arguments.length; _i++) {
  2714. foldArgs[_i] = arguments[_i];
  2715. }
  2716. if (foldArgs.length !== cases.length) {
  2717. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  2718. }
  2719. var target = foldArgs[count];
  2720. return target.apply(null, args);
  2721. },
  2722. match: match,
  2723. log: function (label) {
  2724. console.log(label, {
  2725. constructors: constructors,
  2726. constructor: key,
  2727. params: args
  2728. });
  2729. }
  2730. };
  2731. };
  2732. });
  2733. return adt;
  2734. };
  2735. var Adt = { generate: generate$1 };
  2736. Adt.generate([
  2737. {
  2738. bothErrors: [
  2739. 'error1',
  2740. 'error2'
  2741. ]
  2742. },
  2743. {
  2744. firstError: [
  2745. 'error1',
  2746. 'value2'
  2747. ]
  2748. },
  2749. {
  2750. secondError: [
  2751. 'value1',
  2752. 'error2'
  2753. ]
  2754. },
  2755. {
  2756. bothValues: [
  2757. 'value1',
  2758. 'value2'
  2759. ]
  2760. }
  2761. ]);
  2762. var unite = function (result) {
  2763. return result.fold(identity, identity);
  2764. };
  2765. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  2766. if (is(scope, a)) {
  2767. return Optional.some(scope);
  2768. } else if (isFunction(isRoot) && isRoot(scope)) {
  2769. return Optional.none();
  2770. } else {
  2771. return ancestor(scope, a, isRoot);
  2772. }
  2773. }
  2774. var ancestor$3 = function (scope, predicate, isRoot) {
  2775. var element = scope.dom;
  2776. var stop = isFunction(isRoot) ? isRoot : never;
  2777. while (element.parentNode) {
  2778. element = element.parentNode;
  2779. var el = SugarElement.fromDom(element);
  2780. if (predicate(el)) {
  2781. return Optional.some(el);
  2782. } else if (stop(el)) {
  2783. break;
  2784. }
  2785. }
  2786. return Optional.none();
  2787. };
  2788. var closest$3 = function (scope, predicate, isRoot) {
  2789. var is = function (s, test) {
  2790. return test(s);
  2791. };
  2792. return ClosestOrAncestor(is, ancestor$3, scope, predicate, isRoot);
  2793. };
  2794. var sibling$2 = function (scope, predicate) {
  2795. var element = scope.dom;
  2796. if (!element.parentNode) {
  2797. return Optional.none();
  2798. }
  2799. return child(SugarElement.fromDom(element.parentNode), function (x) {
  2800. return !eq(scope, x) && predicate(x);
  2801. });
  2802. };
  2803. var child = function (scope, predicate) {
  2804. var pred = function (node) {
  2805. return predicate(SugarElement.fromDom(node));
  2806. };
  2807. var result = find$3(scope.dom.childNodes, pred);
  2808. return result.map(SugarElement.fromDom);
  2809. };
  2810. var ancestor$2 = function (scope, selector, isRoot) {
  2811. return ancestor$3(scope, function (e) {
  2812. return is$2(e, selector);
  2813. }, isRoot);
  2814. };
  2815. var descendant = function (scope, selector) {
  2816. return one(selector, scope);
  2817. };
  2818. var closest$2 = function (scope, selector, isRoot) {
  2819. var is = function (element, selector) {
  2820. return is$2(element, selector);
  2821. };
  2822. return ClosestOrAncestor(is, ancestor$2, scope, selector, isRoot);
  2823. };
  2824. var promise = function () {
  2825. var bind = function (fn, thisArg) {
  2826. return function () {
  2827. var args = [];
  2828. for (var _i = 0; _i < arguments.length; _i++) {
  2829. args[_i] = arguments[_i];
  2830. }
  2831. fn.apply(thisArg, args);
  2832. };
  2833. };
  2834. var isArray = Array.isArray || function (value) {
  2835. return Object.prototype.toString.call(value) === '[object Array]';
  2836. };
  2837. var Promise = function (fn) {
  2838. if (typeof this !== 'object') {
  2839. throw new TypeError('Promises must be constructed via new');
  2840. }
  2841. if (typeof fn !== 'function') {
  2842. throw new TypeError('not a function');
  2843. }
  2844. this._state = null;
  2845. this._value = null;
  2846. this._deferreds = [];
  2847. doResolve(fn, bind(resolve, this), bind(reject, this));
  2848. };
  2849. var asap = Promise.immediateFn || typeof setImmediate === 'function' && setImmediate || function (fn) {
  2850. return setTimeout(fn, 1);
  2851. };
  2852. function handle(deferred) {
  2853. var me = this;
  2854. if (this._state === null) {
  2855. this._deferreds.push(deferred);
  2856. return;
  2857. }
  2858. asap(function () {
  2859. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  2860. if (cb === null) {
  2861. (me._state ? deferred.resolve : deferred.reject)(me._value);
  2862. return;
  2863. }
  2864. var ret;
  2865. try {
  2866. ret = cb(me._value);
  2867. } catch (e) {
  2868. deferred.reject(e);
  2869. return;
  2870. }
  2871. deferred.resolve(ret);
  2872. });
  2873. }
  2874. function resolve(newValue) {
  2875. try {
  2876. if (newValue === this) {
  2877. throw new TypeError('A promise cannot be resolved with itself.');
  2878. }
  2879. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  2880. var then = newValue.then;
  2881. if (typeof then === 'function') {
  2882. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  2883. return;
  2884. }
  2885. }
  2886. this._state = true;
  2887. this._value = newValue;
  2888. finale.call(this);
  2889. } catch (e) {
  2890. reject.call(this, e);
  2891. }
  2892. }
  2893. function reject(newValue) {
  2894. this._state = false;
  2895. this._value = newValue;
  2896. finale.call(this);
  2897. }
  2898. function finale() {
  2899. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  2900. handle.call(this, this._deferreds[i]);
  2901. }
  2902. this._deferreds = null;
  2903. }
  2904. function Handler(onFulfilled, onRejected, resolve, reject) {
  2905. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  2906. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  2907. this.resolve = resolve;
  2908. this.reject = reject;
  2909. }
  2910. var doResolve = function (fn, onFulfilled, onRejected) {
  2911. var done = false;
  2912. try {
  2913. fn(function (value) {
  2914. if (done) {
  2915. return;
  2916. }
  2917. done = true;
  2918. onFulfilled(value);
  2919. }, function (reason) {
  2920. if (done) {
  2921. return;
  2922. }
  2923. done = true;
  2924. onRejected(reason);
  2925. });
  2926. } catch (ex) {
  2927. if (done) {
  2928. return;
  2929. }
  2930. done = true;
  2931. onRejected(ex);
  2932. }
  2933. };
  2934. Promise.prototype.catch = function (onRejected) {
  2935. return this.then(null, onRejected);
  2936. };
  2937. Promise.prototype.then = function (onFulfilled, onRejected) {
  2938. var me = this;
  2939. return new Promise(function (resolve, reject) {
  2940. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  2941. });
  2942. };
  2943. Promise.all = function () {
  2944. var values = [];
  2945. for (var _i = 0; _i < arguments.length; _i++) {
  2946. values[_i] = arguments[_i];
  2947. }
  2948. var args = Array.prototype.slice.call(values.length === 1 && isArray(values[0]) ? values[0] : values);
  2949. return new Promise(function (resolve, reject) {
  2950. if (args.length === 0) {
  2951. return resolve([]);
  2952. }
  2953. var remaining = args.length;
  2954. var res = function (i, val) {
  2955. try {
  2956. if (val && (typeof val === 'object' || typeof val === 'function')) {
  2957. var then = val.then;
  2958. if (typeof then === 'function') {
  2959. then.call(val, function (val) {
  2960. res(i, val);
  2961. }, reject);
  2962. return;
  2963. }
  2964. }
  2965. args[i] = val;
  2966. if (--remaining === 0) {
  2967. resolve(args);
  2968. }
  2969. } catch (ex) {
  2970. reject(ex);
  2971. }
  2972. };
  2973. for (var i = 0; i < args.length; i++) {
  2974. res(i, args[i]);
  2975. }
  2976. });
  2977. };
  2978. Promise.resolve = function (value) {
  2979. if (value && typeof value === 'object' && value.constructor === Promise) {
  2980. return value;
  2981. }
  2982. return new Promise(function (resolve) {
  2983. resolve(value);
  2984. });
  2985. };
  2986. Promise.reject = function (value) {
  2987. return new Promise(function (resolve, reject) {
  2988. reject(value);
  2989. });
  2990. };
  2991. Promise.race = function (values) {
  2992. return new Promise(function (resolve, reject) {
  2993. for (var i = 0, len = values.length; i < len; i++) {
  2994. values[i].then(resolve, reject);
  2995. }
  2996. });
  2997. };
  2998. return Promise;
  2999. };
  3000. var promiseObj = window.Promise ? window.Promise : promise();
  3001. var requestAnimationFramePromise;
  3002. var requestAnimationFrame = function (callback, element) {
  3003. var requestAnimationFrameFunc = window.requestAnimationFrame;
  3004. var vendors = [
  3005. 'ms',
  3006. 'moz',
  3007. 'webkit'
  3008. ];
  3009. var featurefill = function (cb) {
  3010. window.setTimeout(cb, 0);
  3011. };
  3012. for (var i = 0; i < vendors.length && !requestAnimationFrameFunc; i++) {
  3013. requestAnimationFrameFunc = window[vendors[i] + 'RequestAnimationFrame'];
  3014. }
  3015. if (!requestAnimationFrameFunc) {
  3016. requestAnimationFrameFunc = featurefill;
  3017. }
  3018. requestAnimationFrameFunc(callback, element);
  3019. };
  3020. var wrappedSetTimeout = function (callback, time) {
  3021. if (typeof time !== 'number') {
  3022. time = 0;
  3023. }
  3024. return setTimeout(callback, time);
  3025. };
  3026. var wrappedSetInterval = function (callback, time) {
  3027. if (typeof time !== 'number') {
  3028. time = 1;
  3029. }
  3030. return setInterval(callback, time);
  3031. };
  3032. var wrappedClearTimeout = function (id) {
  3033. return clearTimeout(id);
  3034. };
  3035. var wrappedClearInterval = function (id) {
  3036. return clearInterval(id);
  3037. };
  3038. var debounce = function (callback, time) {
  3039. var timer;
  3040. var func = function () {
  3041. var args = [];
  3042. for (var _i = 0; _i < arguments.length; _i++) {
  3043. args[_i] = arguments[_i];
  3044. }
  3045. clearTimeout(timer);
  3046. timer = wrappedSetTimeout(function () {
  3047. callback.apply(this, args);
  3048. }, time);
  3049. };
  3050. func.stop = function () {
  3051. clearTimeout(timer);
  3052. };
  3053. return func;
  3054. };
  3055. var Delay = {
  3056. requestAnimationFrame: function (callback, element) {
  3057. if (requestAnimationFramePromise) {
  3058. requestAnimationFramePromise.then(callback);
  3059. return;
  3060. }
  3061. requestAnimationFramePromise = new promiseObj(function (resolve) {
  3062. if (!element) {
  3063. element = document.body;
  3064. }
  3065. requestAnimationFrame(resolve, element);
  3066. }).then(callback);
  3067. },
  3068. setTimeout: wrappedSetTimeout,
  3069. setInterval: wrappedSetInterval,
  3070. setEditorTimeout: function (editor, callback, time) {
  3071. return wrappedSetTimeout(function () {
  3072. if (!editor.removed) {
  3073. callback();
  3074. }
  3075. }, time);
  3076. },
  3077. setEditorInterval: function (editor, callback, time) {
  3078. var timer = wrappedSetInterval(function () {
  3079. if (!editor.removed) {
  3080. callback();
  3081. } else {
  3082. clearInterval(timer);
  3083. }
  3084. }, time);
  3085. return timer;
  3086. },
  3087. debounce: debounce,
  3088. throttle: debounce,
  3089. clearInterval: wrappedClearInterval,
  3090. clearTimeout: wrappedClearTimeout
  3091. };
  3092. var StyleSheetLoader = function (documentOrShadowRoot, settings) {
  3093. if (settings === void 0) {
  3094. settings = {};
  3095. }
  3096. var idCount = 0;
  3097. var loadedStates = {};
  3098. var edos = SugarElement.fromDom(documentOrShadowRoot);
  3099. var doc = documentOrOwner(edos);
  3100. var maxLoadTime = settings.maxLoadTime || 5000;
  3101. var _setReferrerPolicy = function (referrerPolicy) {
  3102. settings.referrerPolicy = referrerPolicy;
  3103. };
  3104. var addStyle = function (element) {
  3105. append$1(getStyleContainer(edos), element);
  3106. };
  3107. var removeStyle = function (id) {
  3108. var styleContainer = getStyleContainer(edos);
  3109. descendant(styleContainer, '#' + id).each(remove$7);
  3110. };
  3111. var getOrCreateState = function (url) {
  3112. return get$9(loadedStates, url).getOrThunk(function () {
  3113. return {
  3114. id: 'mce-u' + idCount++,
  3115. passed: [],
  3116. failed: [],
  3117. count: 0
  3118. };
  3119. });
  3120. };
  3121. var load = function (url, success, failure) {
  3122. var link;
  3123. var urlWithSuffix = Tools._addCacheSuffix(url);
  3124. var state = getOrCreateState(urlWithSuffix);
  3125. loadedStates[urlWithSuffix] = state;
  3126. state.count++;
  3127. var resolve = function (callbacks, status) {
  3128. var i = callbacks.length;
  3129. while (i--) {
  3130. callbacks[i]();
  3131. }
  3132. state.status = status;
  3133. state.passed = [];
  3134. state.failed = [];
  3135. if (link) {
  3136. link.onload = null;
  3137. link.onerror = null;
  3138. link = null;
  3139. }
  3140. };
  3141. var passed = function () {
  3142. return resolve(state.passed, 2);
  3143. };
  3144. var failed = function () {
  3145. return resolve(state.failed, 3);
  3146. };
  3147. var wait = function (testCallback, waitCallback) {
  3148. if (!testCallback()) {
  3149. if (Date.now() - startTime < maxLoadTime) {
  3150. Delay.setTimeout(waitCallback);
  3151. } else {
  3152. failed();
  3153. }
  3154. }
  3155. };
  3156. var waitForWebKitLinkLoaded = function () {
  3157. wait(function () {
  3158. var styleSheets = documentOrShadowRoot.styleSheets;
  3159. var i = styleSheets.length;
  3160. while (i--) {
  3161. var styleSheet = styleSheets[i];
  3162. var owner = styleSheet.ownerNode;
  3163. if (owner && owner.id === link.id) {
  3164. passed();
  3165. return true;
  3166. }
  3167. }
  3168. return false;
  3169. }, waitForWebKitLinkLoaded);
  3170. };
  3171. if (success) {
  3172. state.passed.push(success);
  3173. }
  3174. if (failure) {
  3175. state.failed.push(failure);
  3176. }
  3177. if (state.status === 1) {
  3178. return;
  3179. }
  3180. if (state.status === 2) {
  3181. passed();
  3182. return;
  3183. }
  3184. if (state.status === 3) {
  3185. failed();
  3186. return;
  3187. }
  3188. state.status = 1;
  3189. var linkElem = SugarElement.fromTag('link', doc.dom);
  3190. setAll$1(linkElem, {
  3191. rel: 'stylesheet',
  3192. type: 'text/css',
  3193. id: state.id
  3194. });
  3195. var startTime = Date.now();
  3196. if (settings.contentCssCors) {
  3197. set$1(linkElem, 'crossOrigin', 'anonymous');
  3198. }
  3199. if (settings.referrerPolicy) {
  3200. set$1(linkElem, 'referrerpolicy', settings.referrerPolicy);
  3201. }
  3202. link = linkElem.dom;
  3203. link.onload = waitForWebKitLinkLoaded;
  3204. link.onerror = failed;
  3205. addStyle(linkElem);
  3206. set$1(linkElem, 'href', urlWithSuffix);
  3207. };
  3208. var loadF = function (url) {
  3209. return Future.nu(function (resolve) {
  3210. load(url, compose(resolve, constant(Result.value(url))), compose(resolve, constant(Result.error(url))));
  3211. });
  3212. };
  3213. var loadAll = function (urls, success, failure) {
  3214. par(map$3(urls, loadF)).get(function (result) {
  3215. var parts = partition(result, function (r) {
  3216. return r.isValue();
  3217. });
  3218. if (parts.fail.length > 0) {
  3219. failure(parts.fail.map(unite));
  3220. } else {
  3221. success(parts.pass.map(unite));
  3222. }
  3223. });
  3224. };
  3225. var unload = function (url) {
  3226. var urlWithSuffix = Tools._addCacheSuffix(url);
  3227. get$9(loadedStates, urlWithSuffix).each(function (state) {
  3228. var count = --state.count;
  3229. if (count === 0) {
  3230. delete loadedStates[urlWithSuffix];
  3231. removeStyle(state.id);
  3232. }
  3233. });
  3234. };
  3235. var unloadAll = function (urls) {
  3236. each$k(urls, function (url) {
  3237. unload(url);
  3238. });
  3239. };
  3240. return {
  3241. load: load,
  3242. loadAll: loadAll,
  3243. unload: unload,
  3244. unloadAll: unloadAll,
  3245. _setReferrerPolicy: _setReferrerPolicy
  3246. };
  3247. };
  3248. var create$8 = function () {
  3249. var map = new WeakMap();
  3250. var forElement = function (referenceElement, settings) {
  3251. var root = getRootNode(referenceElement);
  3252. var rootDom = root.dom;
  3253. return Optional.from(map.get(rootDom)).getOrThunk(function () {
  3254. var sl = StyleSheetLoader(rootDom, settings);
  3255. map.set(rootDom, sl);
  3256. return sl;
  3257. });
  3258. };
  3259. return { forElement: forElement };
  3260. };
  3261. var instance = create$8();
  3262. var DomTreeWalker = function () {
  3263. function DomTreeWalker(startNode, rootNode) {
  3264. this.node = startNode;
  3265. this.rootNode = rootNode;
  3266. this.current = this.current.bind(this);
  3267. this.next = this.next.bind(this);
  3268. this.prev = this.prev.bind(this);
  3269. this.prev2 = this.prev2.bind(this);
  3270. }
  3271. DomTreeWalker.prototype.current = function () {
  3272. return this.node;
  3273. };
  3274. DomTreeWalker.prototype.next = function (shallow) {
  3275. this.node = this.findSibling(this.node, 'firstChild', 'nextSibling', shallow);
  3276. return this.node;
  3277. };
  3278. DomTreeWalker.prototype.prev = function (shallow) {
  3279. this.node = this.findSibling(this.node, 'lastChild', 'previousSibling', shallow);
  3280. return this.node;
  3281. };
  3282. DomTreeWalker.prototype.prev2 = function (shallow) {
  3283. this.node = this.findPreviousNode(this.node, 'lastChild', 'previousSibling', shallow);
  3284. return this.node;
  3285. };
  3286. DomTreeWalker.prototype.findSibling = function (node, startName, siblingName, shallow) {
  3287. var sibling, parent;
  3288. if (node) {
  3289. if (!shallow && node[startName]) {
  3290. return node[startName];
  3291. }
  3292. if (node !== this.rootNode) {
  3293. sibling = node[siblingName];
  3294. if (sibling) {
  3295. return sibling;
  3296. }
  3297. for (parent = node.parentNode; parent && parent !== this.rootNode; parent = parent.parentNode) {
  3298. sibling = parent[siblingName];
  3299. if (sibling) {
  3300. return sibling;
  3301. }
  3302. }
  3303. }
  3304. }
  3305. };
  3306. DomTreeWalker.prototype.findPreviousNode = function (node, startName, siblingName, shallow) {
  3307. var sibling, parent, child;
  3308. if (node) {
  3309. sibling = node[siblingName];
  3310. if (this.rootNode && sibling === this.rootNode) {
  3311. return;
  3312. }
  3313. if (sibling) {
  3314. if (!shallow) {
  3315. for (child = sibling[startName]; child; child = child[startName]) {
  3316. if (!child[startName]) {
  3317. return child;
  3318. }
  3319. }
  3320. }
  3321. return sibling;
  3322. }
  3323. parent = node.parentNode;
  3324. if (parent && parent !== this.rootNode) {
  3325. return parent;
  3326. }
  3327. }
  3328. };
  3329. return DomTreeWalker;
  3330. }();
  3331. var blocks = [
  3332. 'article',
  3333. 'aside',
  3334. 'details',
  3335. 'div',
  3336. 'dt',
  3337. 'figcaption',
  3338. 'footer',
  3339. 'form',
  3340. 'fieldset',
  3341. 'header',
  3342. 'hgroup',
  3343. 'html',
  3344. 'main',
  3345. 'nav',
  3346. 'section',
  3347. 'summary',
  3348. 'body',
  3349. 'p',
  3350. 'dl',
  3351. 'multicol',
  3352. 'dd',
  3353. 'figure',
  3354. 'address',
  3355. 'center',
  3356. 'blockquote',
  3357. 'h1',
  3358. 'h2',
  3359. 'h3',
  3360. 'h4',
  3361. 'h5',
  3362. 'h6',
  3363. 'listing',
  3364. 'xmp',
  3365. 'pre',
  3366. 'plaintext',
  3367. 'menu',
  3368. 'dir',
  3369. 'ul',
  3370. 'ol',
  3371. 'li',
  3372. 'hr',
  3373. 'table',
  3374. 'tbody',
  3375. 'thead',
  3376. 'tfoot',
  3377. 'th',
  3378. 'tr',
  3379. 'td',
  3380. 'caption'
  3381. ];
  3382. var tableCells = [
  3383. 'td',
  3384. 'th'
  3385. ];
  3386. var tableSections = [
  3387. 'thead',
  3388. 'tbody',
  3389. 'tfoot'
  3390. ];
  3391. var textBlocks = [
  3392. 'h1',
  3393. 'h2',
  3394. 'h3',
  3395. 'h4',
  3396. 'h5',
  3397. 'h6',
  3398. 'p',
  3399. 'div',
  3400. 'address',
  3401. 'pre',
  3402. 'form',
  3403. 'blockquote',
  3404. 'center',
  3405. 'dir',
  3406. 'fieldset',
  3407. 'header',
  3408. 'footer',
  3409. 'article',
  3410. 'section',
  3411. 'hgroup',
  3412. 'aside',
  3413. 'nav',
  3414. 'figure'
  3415. ];
  3416. var headings = [
  3417. 'h1',
  3418. 'h2',
  3419. 'h3',
  3420. 'h4',
  3421. 'h5',
  3422. 'h6'
  3423. ];
  3424. var listItems$1 = [
  3425. 'li',
  3426. 'dd',
  3427. 'dt'
  3428. ];
  3429. var lists = [
  3430. 'ul',
  3431. 'ol',
  3432. 'dl'
  3433. ];
  3434. var wsElements = [
  3435. 'pre',
  3436. 'script',
  3437. 'textarea',
  3438. 'style'
  3439. ];
  3440. var lazyLookup = function (items) {
  3441. var lookup;
  3442. return function (node) {
  3443. lookup = lookup ? lookup : mapToObject(items, always);
  3444. return has$2(lookup, name(node));
  3445. };
  3446. };
  3447. var isHeading = lazyLookup(headings);
  3448. var isBlock$2 = lazyLookup(blocks);
  3449. var isTable$2 = function (node) {
  3450. return name(node) === 'table';
  3451. };
  3452. var isInline$1 = function (node) {
  3453. return isElement$6(node) && !isBlock$2(node);
  3454. };
  3455. var isBr$4 = function (node) {
  3456. return isElement$6(node) && name(node) === 'br';
  3457. };
  3458. var isTextBlock$2 = lazyLookup(textBlocks);
  3459. var isList = lazyLookup(lists);
  3460. var isListItem = lazyLookup(listItems$1);
  3461. var isTableSection = lazyLookup(tableSections);
  3462. var isTableCell$4 = lazyLookup(tableCells);
  3463. var isWsPreserveElement = lazyLookup(wsElements);
  3464. var ancestor$1 = function (scope, selector, isRoot) {
  3465. return ancestor$2(scope, selector, isRoot).isSome();
  3466. };
  3467. var zeroWidth = '\uFEFF';
  3468. var nbsp = '\xA0';
  3469. var isZwsp$1 = function (char) {
  3470. return char === zeroWidth;
  3471. };
  3472. var removeZwsp = function (s) {
  3473. return s.replace(/\uFEFF/g, '');
  3474. };
  3475. var ZWSP$1 = zeroWidth;
  3476. var isZwsp = isZwsp$1;
  3477. var trim$2 = removeZwsp;
  3478. var isElement$4 = isElement$5;
  3479. var isText$6 = isText$7;
  3480. var isCaretContainerBlock$1 = function (node) {
  3481. if (isText$6(node)) {
  3482. node = node.parentNode;
  3483. }
  3484. return isElement$4(node) && node.hasAttribute('data-mce-caret');
  3485. };
  3486. var isCaretContainerInline = function (node) {
  3487. return isText$6(node) && isZwsp(node.data);
  3488. };
  3489. var isCaretContainer$2 = function (node) {
  3490. return isCaretContainerBlock$1(node) || isCaretContainerInline(node);
  3491. };
  3492. var hasContent = function (node) {
  3493. return node.firstChild !== node.lastChild || !isBr$5(node.firstChild);
  3494. };
  3495. var insertInline$1 = function (node, before) {
  3496. var doc = node.ownerDocument;
  3497. var textNode = doc.createTextNode(ZWSP$1);
  3498. var parentNode = node.parentNode;
  3499. if (!before) {
  3500. var sibling = node.nextSibling;
  3501. if (isText$6(sibling)) {
  3502. if (isCaretContainer$2(sibling)) {
  3503. return sibling;
  3504. }
  3505. if (startsWithCaretContainer$1(sibling)) {
  3506. sibling.splitText(1);
  3507. return sibling;
  3508. }
  3509. }
  3510. if (node.nextSibling) {
  3511. parentNode.insertBefore(textNode, node.nextSibling);
  3512. } else {
  3513. parentNode.appendChild(textNode);
  3514. }
  3515. } else {
  3516. var sibling = node.previousSibling;
  3517. if (isText$6(sibling)) {
  3518. if (isCaretContainer$2(sibling)) {
  3519. return sibling;
  3520. }
  3521. if (endsWithCaretContainer$1(sibling)) {
  3522. return sibling.splitText(sibling.data.length - 1);
  3523. }
  3524. }
  3525. parentNode.insertBefore(textNode, node);
  3526. }
  3527. return textNode;
  3528. };
  3529. var isBeforeInline = function (pos) {
  3530. var container = pos.container();
  3531. if (!isText$7(container)) {
  3532. return false;
  3533. }
  3534. return container.data.charAt(pos.offset()) === ZWSP$1 || pos.isAtStart() && isCaretContainerInline(container.previousSibling);
  3535. };
  3536. var isAfterInline = function (pos) {
  3537. var container = pos.container();
  3538. if (!isText$7(container)) {
  3539. return false;
  3540. }
  3541. return container.data.charAt(pos.offset() - 1) === ZWSP$1 || pos.isAtEnd() && isCaretContainerInline(container.nextSibling);
  3542. };
  3543. var createBogusBr = function () {
  3544. var br = document.createElement('br');
  3545. br.setAttribute('data-mce-bogus', '1');
  3546. return br;
  3547. };
  3548. var insertBlock$1 = function (blockName, node, before) {
  3549. var doc = node.ownerDocument;
  3550. var blockNode = doc.createElement(blockName);
  3551. blockNode.setAttribute('data-mce-caret', before ? 'before' : 'after');
  3552. blockNode.setAttribute('data-mce-bogus', 'all');
  3553. blockNode.appendChild(createBogusBr());
  3554. var parentNode = node.parentNode;
  3555. if (!before) {
  3556. if (node.nextSibling) {
  3557. parentNode.insertBefore(blockNode, node.nextSibling);
  3558. } else {
  3559. parentNode.appendChild(blockNode);
  3560. }
  3561. } else {
  3562. parentNode.insertBefore(blockNode, node);
  3563. }
  3564. return blockNode;
  3565. };
  3566. var startsWithCaretContainer$1 = function (node) {
  3567. return isText$6(node) && node.data[0] === ZWSP$1;
  3568. };
  3569. var endsWithCaretContainer$1 = function (node) {
  3570. return isText$6(node) && node.data[node.data.length - 1] === ZWSP$1;
  3571. };
  3572. var trimBogusBr = function (elm) {
  3573. var brs = elm.getElementsByTagName('br');
  3574. var lastBr = brs[brs.length - 1];
  3575. if (isBogus$2(lastBr)) {
  3576. lastBr.parentNode.removeChild(lastBr);
  3577. }
  3578. };
  3579. var showCaretContainerBlock = function (caretContainer) {
  3580. if (caretContainer && caretContainer.hasAttribute('data-mce-caret')) {
  3581. trimBogusBr(caretContainer);
  3582. caretContainer.removeAttribute('data-mce-caret');
  3583. caretContainer.removeAttribute('data-mce-bogus');
  3584. caretContainer.removeAttribute('style');
  3585. caretContainer.removeAttribute('_moz_abspos');
  3586. return caretContainer;
  3587. }
  3588. return null;
  3589. };
  3590. var isRangeInCaretContainerBlock = function (range) {
  3591. return isCaretContainerBlock$1(range.startContainer);
  3592. };
  3593. var isContentEditableTrue$3 = isContentEditableTrue$4;
  3594. var isContentEditableFalse$a = isContentEditableFalse$b;
  3595. var isBr$3 = isBr$5;
  3596. var isText$5 = isText$7;
  3597. var isInvalidTextElement = matchNodeNames([
  3598. 'script',
  3599. 'style',
  3600. 'textarea'
  3601. ]);
  3602. var isAtomicInline = matchNodeNames([
  3603. 'img',
  3604. 'input',
  3605. 'textarea',
  3606. 'hr',
  3607. 'iframe',
  3608. 'video',
  3609. 'audio',
  3610. 'object',
  3611. 'embed'
  3612. ]);
  3613. var isTable$1 = matchNodeNames(['table']);
  3614. var isCaretContainer$1 = isCaretContainer$2;
  3615. var isCaretCandidate$3 = function (node) {
  3616. if (isCaretContainer$1(node)) {
  3617. return false;
  3618. }
  3619. if (isText$5(node)) {
  3620. return !isInvalidTextElement(node.parentNode);
  3621. }
  3622. return isAtomicInline(node) || isBr$3(node) || isTable$1(node) || isNonUiContentEditableFalse(node);
  3623. };
  3624. var isUnselectable = function (node) {
  3625. return isElement$5(node) && node.getAttribute('unselectable') === 'true';
  3626. };
  3627. var isNonUiContentEditableFalse = function (node) {
  3628. return isUnselectable(node) === false && isContentEditableFalse$a(node);
  3629. };
  3630. var isInEditable = function (node, root) {
  3631. for (node = node.parentNode; node && node !== root; node = node.parentNode) {
  3632. if (isNonUiContentEditableFalse(node)) {
  3633. return false;
  3634. }
  3635. if (isContentEditableTrue$3(node)) {
  3636. return true;
  3637. }
  3638. }
  3639. return true;
  3640. };
  3641. var isAtomicContentEditableFalse = function (node) {
  3642. if (!isNonUiContentEditableFalse(node)) {
  3643. return false;
  3644. }
  3645. return foldl(from(node.getElementsByTagName('*')), function (result, elm) {
  3646. return result || isContentEditableTrue$3(elm);
  3647. }, false) !== true;
  3648. };
  3649. var isAtomic$1 = function (node) {
  3650. return isAtomicInline(node) || isAtomicContentEditableFalse(node);
  3651. };
  3652. var isEditableCaretCandidate$1 = function (node, root) {
  3653. return isCaretCandidate$3(node) && isInEditable(node, root);
  3654. };
  3655. var whiteSpaceRegExp$1 = /^[ \t\r\n]*$/;
  3656. var isWhitespaceText = function (text) {
  3657. return whiteSpaceRegExp$1.test(text);
  3658. };
  3659. var hasWhitespacePreserveParent = function (node, rootNode) {
  3660. var rootElement = SugarElement.fromDom(rootNode);
  3661. var startNode = SugarElement.fromDom(node);
  3662. return ancestor$1(startNode, 'pre,code', curry(eq, rootElement));
  3663. };
  3664. var isWhitespace = function (node, rootNode) {
  3665. return isText$7(node) && isWhitespaceText(node.data) && hasWhitespacePreserveParent(node, rootNode) === false;
  3666. };
  3667. var isNamedAnchor = function (node) {
  3668. return isElement$5(node) && node.nodeName === 'A' && !node.hasAttribute('href') && (node.hasAttribute('name') || node.hasAttribute('id'));
  3669. };
  3670. var isContent$1 = function (node, rootNode) {
  3671. return isCaretCandidate$3(node) && isWhitespace(node, rootNode) === false || isNamedAnchor(node) || isBookmark(node);
  3672. };
  3673. var isBookmark = hasAttribute('data-mce-bookmark');
  3674. var isBogus$1 = hasAttribute('data-mce-bogus');
  3675. var isBogusAll = hasAttributeValue('data-mce-bogus', 'all');
  3676. var isEmptyNode = function (targetNode, skipBogus) {
  3677. var brCount = 0;
  3678. if (isContent$1(targetNode, targetNode)) {
  3679. return false;
  3680. } else {
  3681. var node = targetNode.firstChild;
  3682. if (!node) {
  3683. return true;
  3684. }
  3685. var walker = new DomTreeWalker(node, targetNode);
  3686. do {
  3687. if (skipBogus) {
  3688. if (isBogusAll(node)) {
  3689. node = walker.next(true);
  3690. continue;
  3691. }
  3692. if (isBogus$1(node)) {
  3693. node = walker.next();
  3694. continue;
  3695. }
  3696. }
  3697. if (isBr$5(node)) {
  3698. brCount++;
  3699. node = walker.next();
  3700. continue;
  3701. }
  3702. if (isContent$1(node, targetNode)) {
  3703. return false;
  3704. }
  3705. node = walker.next();
  3706. } while (node);
  3707. return brCount <= 1;
  3708. }
  3709. };
  3710. var isEmpty$2 = function (elm, skipBogus) {
  3711. if (skipBogus === void 0) {
  3712. skipBogus = true;
  3713. }
  3714. return isEmptyNode(elm.dom, skipBogus);
  3715. };
  3716. var isSpan = function (node) {
  3717. return node.nodeName.toLowerCase() === 'span';
  3718. };
  3719. var isInlineContent = function (node, root) {
  3720. return isNonNullable(node) && (isContent$1(node, root) || isInline$1(SugarElement.fromDom(node)));
  3721. };
  3722. var surroundedByInlineContent = function (node, root) {
  3723. var prev = new DomTreeWalker(node, root).prev(false);
  3724. var next = new DomTreeWalker(node, root).next(false);
  3725. var prevIsInline = isUndefined(prev) || isInlineContent(prev, root);
  3726. var nextIsInline = isUndefined(next) || isInlineContent(next, root);
  3727. return prevIsInline && nextIsInline;
  3728. };
  3729. var isBookmarkNode$2 = function (node) {
  3730. return isSpan(node) && node.getAttribute('data-mce-type') === 'bookmark';
  3731. };
  3732. var isKeepTextNode = function (node, root) {
  3733. return isText$7(node) && node.data.length > 0 && surroundedByInlineContent(node, root);
  3734. };
  3735. var isKeepElement = function (node) {
  3736. return isElement$5(node) ? node.childNodes.length > 0 : false;
  3737. };
  3738. var isDocument = function (node) {
  3739. return isDocumentFragment(node) || isDocument$1(node);
  3740. };
  3741. var trimNode = function (dom, node, root) {
  3742. var rootNode = root || node;
  3743. if (isElement$5(node) && isBookmarkNode$2(node)) {
  3744. return node;
  3745. }
  3746. var children = node.childNodes;
  3747. for (var i = children.length - 1; i >= 0; i--) {
  3748. trimNode(dom, children[i], rootNode);
  3749. }
  3750. if (isElement$5(node)) {
  3751. var currentChildren = node.childNodes;
  3752. if (currentChildren.length === 1 && isBookmarkNode$2(currentChildren[0])) {
  3753. node.parentNode.insertBefore(currentChildren[0], node);
  3754. }
  3755. }
  3756. if (!isDocument(node) && !isContent$1(node, rootNode) && !isKeepElement(node) && !isKeepTextNode(node, rootNode)) {
  3757. dom.remove(node);
  3758. }
  3759. return node;
  3760. };
  3761. var makeMap$3 = Tools.makeMap;
  3762. var attrsCharsRegExp = /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  3763. var textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  3764. var rawCharsRegExp = /[<>&\"\']/g;
  3765. var entityRegExp = /&#([a-z0-9]+);?|&([a-z0-9]+);/gi;
  3766. var asciiMap = {
  3767. 128: '\u20AC',
  3768. 130: '\u201A',
  3769. 131: '\u0192',
  3770. 132: '\u201E',
  3771. 133: '\u2026',
  3772. 134: '\u2020',
  3773. 135: '\u2021',
  3774. 136: '\u02c6',
  3775. 137: '\u2030',
  3776. 138: '\u0160',
  3777. 139: '\u2039',
  3778. 140: '\u0152',
  3779. 142: '\u017d',
  3780. 145: '\u2018',
  3781. 146: '\u2019',
  3782. 147: '\u201C',
  3783. 148: '\u201D',
  3784. 149: '\u2022',
  3785. 150: '\u2013',
  3786. 151: '\u2014',
  3787. 152: '\u02DC',
  3788. 153: '\u2122',
  3789. 154: '\u0161',
  3790. 155: '\u203A',
  3791. 156: '\u0153',
  3792. 158: '\u017e',
  3793. 159: '\u0178'
  3794. };
  3795. var baseEntities = {
  3796. '"': '&quot;',
  3797. '\'': '&#39;',
  3798. '<': '&lt;',
  3799. '>': '&gt;',
  3800. '&': '&amp;',
  3801. '`': '&#96;'
  3802. };
  3803. var reverseEntities = {
  3804. '&lt;': '<',
  3805. '&gt;': '>',
  3806. '&amp;': '&',
  3807. '&quot;': '"',
  3808. '&apos;': '\''
  3809. };
  3810. var nativeDecode = function (text) {
  3811. var elm = SugarElement.fromTag('div').dom;
  3812. elm.innerHTML = text;
  3813. return elm.textContent || elm.innerText || text;
  3814. };
  3815. var buildEntitiesLookup = function (items, radix) {
  3816. var i, chr, entity;
  3817. var lookup = {};
  3818. if (items) {
  3819. items = items.split(',');
  3820. radix = radix || 10;
  3821. for (i = 0; i < items.length; i += 2) {
  3822. chr = String.fromCharCode(parseInt(items[i], radix));
  3823. if (!baseEntities[chr]) {
  3824. entity = '&' + items[i + 1] + ';';
  3825. lookup[chr] = entity;
  3826. lookup[entity] = chr;
  3827. }
  3828. }
  3829. return lookup;
  3830. }
  3831. };
  3832. 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);
  3833. var encodeRaw = function (text, attr) {
  3834. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3835. return baseEntities[chr] || chr;
  3836. });
  3837. };
  3838. var encodeAllRaw = function (text) {
  3839. return ('' + text).replace(rawCharsRegExp, function (chr) {
  3840. return baseEntities[chr] || chr;
  3841. });
  3842. };
  3843. var encodeNumeric = function (text, attr) {
  3844. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3845. if (chr.length > 1) {
  3846. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  3847. }
  3848. return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
  3849. });
  3850. };
  3851. var encodeNamed = function (text, attr, entities) {
  3852. entities = entities || namedEntities;
  3853. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3854. return baseEntities[chr] || entities[chr] || chr;
  3855. });
  3856. };
  3857. var getEncodeFunc = function (name, entities) {
  3858. var entitiesMap = buildEntitiesLookup(entities) || namedEntities;
  3859. var encodeNamedAndNumeric = function (text, attr) {
  3860. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3861. if (baseEntities[chr] !== undefined) {
  3862. return baseEntities[chr];
  3863. }
  3864. if (entitiesMap[chr] !== undefined) {
  3865. return entitiesMap[chr];
  3866. }
  3867. if (chr.length > 1) {
  3868. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  3869. }
  3870. return '&#' + chr.charCodeAt(0) + ';';
  3871. });
  3872. };
  3873. var encodeCustomNamed = function (text, attr) {
  3874. return encodeNamed(text, attr, entitiesMap);
  3875. };
  3876. var nameMap = makeMap$3(name.replace(/\+/g, ','));
  3877. if (nameMap.named && nameMap.numeric) {
  3878. return encodeNamedAndNumeric;
  3879. }
  3880. if (nameMap.named) {
  3881. if (entities) {
  3882. return encodeCustomNamed;
  3883. }
  3884. return encodeNamed;
  3885. }
  3886. if (nameMap.numeric) {
  3887. return encodeNumeric;
  3888. }
  3889. return encodeRaw;
  3890. };
  3891. var decode = function (text) {
  3892. return text.replace(entityRegExp, function (all, numeric) {
  3893. if (numeric) {
  3894. if (numeric.charAt(0).toLowerCase() === 'x') {
  3895. numeric = parseInt(numeric.substr(1), 16);
  3896. } else {
  3897. numeric = parseInt(numeric, 10);
  3898. }
  3899. if (numeric > 65535) {
  3900. numeric -= 65536;
  3901. return String.fromCharCode(55296 + (numeric >> 10), 56320 + (numeric & 1023));
  3902. }
  3903. return asciiMap[numeric] || String.fromCharCode(numeric);
  3904. }
  3905. return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
  3906. });
  3907. };
  3908. var Entities = {
  3909. encodeRaw: encodeRaw,
  3910. encodeAllRaw: encodeAllRaw,
  3911. encodeNumeric: encodeNumeric,
  3912. encodeNamed: encodeNamed,
  3913. getEncodeFunc: getEncodeFunc,
  3914. decode: decode
  3915. };
  3916. var mapCache = {}, dummyObj = {};
  3917. var makeMap$2 = Tools.makeMap, each$h = Tools.each, extend$5 = Tools.extend, explode$3 = Tools.explode, inArray$2 = Tools.inArray;
  3918. var split$1 = function (items, delim) {
  3919. items = Tools.trim(items);
  3920. return items ? items.split(delim || ' ') : [];
  3921. };
  3922. var compileSchema = function (type) {
  3923. var schema = {};
  3924. var globalAttributes, blockContent;
  3925. var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
  3926. var add = function (name, attributes, children) {
  3927. var ni, attributesOrder, element;
  3928. var arrayToMap = function (array, obj) {
  3929. var map = {};
  3930. var i, l;
  3931. for (i = 0, l = array.length; i < l; i++) {
  3932. map[array[i]] = obj || {};
  3933. }
  3934. return map;
  3935. };
  3936. children = children || [];
  3937. attributes = attributes || '';
  3938. if (typeof children === 'string') {
  3939. children = split$1(children);
  3940. }
  3941. var names = split$1(name);
  3942. ni = names.length;
  3943. while (ni--) {
  3944. attributesOrder = split$1([
  3945. globalAttributes,
  3946. attributes
  3947. ].join(' '));
  3948. element = {
  3949. attributes: arrayToMap(attributesOrder),
  3950. attributesOrder: attributesOrder,
  3951. children: arrayToMap(children, dummyObj)
  3952. };
  3953. schema[names[ni]] = element;
  3954. }
  3955. };
  3956. var addAttrs = function (name, attributes) {
  3957. var ni, schemaItem, i, l;
  3958. var names = split$1(name);
  3959. ni = names.length;
  3960. var attrs = split$1(attributes);
  3961. while (ni--) {
  3962. schemaItem = schema[names[ni]];
  3963. for (i = 0, l = attrs.length; i < l; i++) {
  3964. schemaItem.attributes[attrs[i]] = {};
  3965. schemaItem.attributesOrder.push(attrs[i]);
  3966. }
  3967. }
  3968. };
  3969. if (mapCache[type]) {
  3970. return mapCache[type];
  3971. }
  3972. globalAttributes = 'id accesskey class dir lang style tabindex title role';
  3973. blockContent = 'address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul';
  3974. 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';
  3975. if (type !== 'html4') {
  3976. globalAttributes += ' contenteditable contextmenu draggable dropzone ' + 'hidden spellcheck translate';
  3977. blockContent += ' article aside details dialog figure main header footer hgroup section nav';
  3978. phrasingContent += ' audio canvas command datalist mark meter output picture ' + 'progress time wbr video ruby bdi keygen';
  3979. }
  3980. if (type !== 'html5-strict') {
  3981. globalAttributes += ' xml:lang';
  3982. html4PhrasingContent = 'acronym applet basefont big font strike tt';
  3983. phrasingContent = [
  3984. phrasingContent,
  3985. html4PhrasingContent
  3986. ].join(' ');
  3987. each$h(split$1(html4PhrasingContent), function (name) {
  3988. add(name, '', phrasingContent);
  3989. });
  3990. html4BlockContent = 'center dir isindex noframes';
  3991. blockContent = [
  3992. blockContent,
  3993. html4BlockContent
  3994. ].join(' ');
  3995. flowContent = [
  3996. blockContent,
  3997. phrasingContent
  3998. ].join(' ');
  3999. each$h(split$1(html4BlockContent), function (name) {
  4000. add(name, '', flowContent);
  4001. });
  4002. }
  4003. flowContent = flowContent || [
  4004. blockContent,
  4005. phrasingContent
  4006. ].join(' ');
  4007. add('html', 'manifest', 'head body');
  4008. add('head', '', 'base command link meta noscript script style title');
  4009. add('title hr noscript br');
  4010. add('base', 'href target');
  4011. add('link', 'href rel media hreflang type sizes hreflang');
  4012. add('meta', 'name http-equiv content charset');
  4013. add('style', 'media type scoped');
  4014. add('script', 'src async defer type charset');
  4015. add('body', 'onafterprint onbeforeprint onbeforeunload onblur onerror onfocus ' + 'onhashchange onload onmessage onoffline ononline onpagehide onpageshow ' + 'onpopstate onresize onscroll onstorage onunload', flowContent);
  4016. add('address dt dd div caption', '', flowContent);
  4017. 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);
  4018. add('blockquote', 'cite', flowContent);
  4019. add('ol', 'reversed start type', 'li');
  4020. add('ul', '', 'li');
  4021. add('li', 'value', flowContent);
  4022. add('dl', '', 'dt dd');
  4023. add('a', 'href target rel media hreflang type', phrasingContent);
  4024. add('q', 'cite', phrasingContent);
  4025. add('ins del', 'cite datetime', flowContent);
  4026. add('img', 'src sizes srcset alt usemap ismap width height');
  4027. add('iframe', 'src name width height', flowContent);
  4028. add('embed', 'src type width height');
  4029. add('object', 'data type typemustmatch name usemap form width height', [
  4030. flowContent,
  4031. 'param'
  4032. ].join(' '));
  4033. add('param', 'name value');
  4034. add('map', 'name', [
  4035. flowContent,
  4036. 'area'
  4037. ].join(' '));
  4038. add('area', 'alt coords shape href target rel media hreflang type');
  4039. add('table', 'border', 'caption colgroup thead tfoot tbody tr' + (type === 'html4' ? ' col' : ''));
  4040. add('colgroup', 'span', 'col');
  4041. add('col', 'span');
  4042. add('tbody thead tfoot', '', 'tr');
  4043. add('tr', '', 'td th');
  4044. add('td', 'colspan rowspan headers', flowContent);
  4045. add('th', 'colspan rowspan headers scope abbr', flowContent);
  4046. add('form', 'accept-charset action autocomplete enctype method name novalidate target', flowContent);
  4047. add('fieldset', 'disabled form name', [
  4048. flowContent,
  4049. 'legend'
  4050. ].join(' '));
  4051. add('label', 'form for', phrasingContent);
  4052. 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');
  4053. add('button', 'disabled form formaction formenctype formmethod formnovalidate formtarget name type value', type === 'html4' ? flowContent : phrasingContent);
  4054. add('select', 'disabled form multiple name required size', 'option optgroup');
  4055. add('optgroup', 'disabled label', 'option');
  4056. add('option', 'disabled label selected value');
  4057. add('textarea', 'cols dirname disabled form maxlength name readonly required rows wrap');
  4058. add('menu', 'type label', [
  4059. flowContent,
  4060. 'li'
  4061. ].join(' '));
  4062. add('noscript', '', flowContent);
  4063. if (type !== 'html4') {
  4064. add('wbr');
  4065. add('ruby', '', [
  4066. phrasingContent,
  4067. 'rt rp'
  4068. ].join(' '));
  4069. add('figcaption', '', flowContent);
  4070. add('mark rt rp summary bdi', '', phrasingContent);
  4071. add('canvas', 'width height', flowContent);
  4072. add('video', 'src crossorigin poster preload autoplay mediagroup loop ' + 'muted controls width height buffered', [
  4073. flowContent,
  4074. 'track source'
  4075. ].join(' '));
  4076. add('audio', 'src crossorigin preload autoplay mediagroup loop muted controls ' + 'buffered volume', [
  4077. flowContent,
  4078. 'track source'
  4079. ].join(' '));
  4080. add('picture', '', 'img source');
  4081. add('source', 'src srcset type media sizes');
  4082. add('track', 'kind src srclang label default');
  4083. add('datalist', '', [
  4084. phrasingContent,
  4085. 'option'
  4086. ].join(' '));
  4087. add('article section nav aside main header footer', '', flowContent);
  4088. add('hgroup', '', 'h1 h2 h3 h4 h5 h6');
  4089. add('figure', '', [
  4090. flowContent,
  4091. 'figcaption'
  4092. ].join(' '));
  4093. add('time', 'datetime', phrasingContent);
  4094. add('dialog', 'open', flowContent);
  4095. add('command', 'type label icon disabled checked radiogroup command');
  4096. add('output', 'for form name', phrasingContent);
  4097. add('progress', 'value max', phrasingContent);
  4098. add('meter', 'value min max low high optimum', phrasingContent);
  4099. add('details', 'open', [
  4100. flowContent,
  4101. 'summary'
  4102. ].join(' '));
  4103. add('keygen', 'autofocus challenge disabled form keytype name');
  4104. }
  4105. if (type !== 'html5-strict') {
  4106. addAttrs('script', 'language xml:space');
  4107. addAttrs('style', 'xml:space');
  4108. addAttrs('object', 'declare classid code codebase codetype archive standby align border hspace vspace');
  4109. addAttrs('embed', 'align name hspace vspace');
  4110. addAttrs('param', 'valuetype type');
  4111. addAttrs('a', 'charset name rev shape coords');
  4112. addAttrs('br', 'clear');
  4113. addAttrs('applet', 'codebase archive code object alt name width height align hspace vspace');
  4114. addAttrs('img', 'name longdesc align border hspace vspace');
  4115. addAttrs('iframe', 'longdesc frameborder marginwidth marginheight scrolling align');
  4116. addAttrs('font basefont', 'size color face');
  4117. addAttrs('input', 'usemap align');
  4118. addAttrs('select');
  4119. addAttrs('textarea');
  4120. addAttrs('h1 h2 h3 h4 h5 h6 div p legend caption', 'align');
  4121. addAttrs('ul', 'type compact');
  4122. addAttrs('li', 'type');
  4123. addAttrs('ol dl menu dir', 'compact');
  4124. addAttrs('pre', 'width xml:space');
  4125. addAttrs('hr', 'align noshade size width');
  4126. addAttrs('isindex', 'prompt');
  4127. addAttrs('table', 'summary width frame rules cellspacing cellpadding align bgcolor');
  4128. addAttrs('col', 'width align char charoff valign');
  4129. addAttrs('colgroup', 'width align char charoff valign');
  4130. addAttrs('thead', 'align char charoff valign');
  4131. addAttrs('tr', 'align char charoff valign bgcolor');
  4132. addAttrs('th', 'axis align char charoff valign nowrap bgcolor width height');
  4133. addAttrs('form', 'accept');
  4134. addAttrs('td', 'abbr axis scope align char charoff valign nowrap bgcolor width height');
  4135. addAttrs('tfoot', 'align char charoff valign');
  4136. addAttrs('tbody', 'align char charoff valign');
  4137. addAttrs('area', 'nohref');
  4138. addAttrs('body', 'background bgcolor text link vlink alink');
  4139. }
  4140. if (type !== 'html4') {
  4141. addAttrs('input button select textarea', 'autofocus');
  4142. addAttrs('input textarea', 'placeholder');
  4143. addAttrs('a', 'download');
  4144. addAttrs('link script img', 'crossorigin');
  4145. addAttrs('img', 'loading');
  4146. addAttrs('iframe', 'sandbox seamless allowfullscreen loading');
  4147. }
  4148. each$h(split$1('a form meter progress dfn'), function (name) {
  4149. if (schema[name]) {
  4150. delete schema[name].children[name];
  4151. }
  4152. });
  4153. delete schema.caption.children.table;
  4154. delete schema.script;
  4155. mapCache[type] = schema;
  4156. return schema;
  4157. };
  4158. var compileElementMap = function (value, mode) {
  4159. var styles;
  4160. if (value) {
  4161. styles = {};
  4162. if (typeof value === 'string') {
  4163. value = { '*': value };
  4164. }
  4165. each$h(value, function (value, key) {
  4166. styles[key] = styles[key.toUpperCase()] = mode === 'map' ? makeMap$2(value, /[, ]/) : explode$3(value, /[, ]/);
  4167. });
  4168. }
  4169. return styles;
  4170. };
  4171. var Schema = function (settings) {
  4172. var elements = {};
  4173. var children = {};
  4174. var patternElements = [];
  4175. var customElementsMap = {}, specialElements = {};
  4176. var createLookupTable = function (option, defaultValue, extendWith) {
  4177. var value = settings[option];
  4178. if (!value) {
  4179. value = mapCache[option];
  4180. if (!value) {
  4181. value = makeMap$2(defaultValue, ' ', makeMap$2(defaultValue.toUpperCase(), ' '));
  4182. value = extend$5(value, extendWith);
  4183. mapCache[option] = value;
  4184. }
  4185. } else {
  4186. value = makeMap$2(value, /[, ]/, makeMap$2(value.toUpperCase(), /[, ]/));
  4187. }
  4188. return value;
  4189. };
  4190. settings = settings || {};
  4191. var schemaItems = compileSchema(settings.schema);
  4192. if (settings.verify_html === false) {
  4193. settings.valid_elements = '*[*]';
  4194. }
  4195. var validStyles = compileElementMap(settings.valid_styles);
  4196. var invalidStyles = compileElementMap(settings.invalid_styles, 'map');
  4197. var validClasses = compileElementMap(settings.valid_classes, 'map');
  4198. var whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object code');
  4199. var selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
  4200. var shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link ' + 'meta param embed source wbr track');
  4201. var boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + 'noshade nowrap readonly selected autoplay loop controls');
  4202. var nonEmptyOrMoveCaretBeforeOnEnter = 'td th iframe video audio object script code';
  4203. var nonEmptyElementsMap = createLookupTable('non_empty_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' pre', shortEndedElementsMap);
  4204. var moveCaretBeforeOnEnterElementsMap = createLookupTable('move_caret_before_on_enter_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' table', shortEndedElementsMap);
  4205. 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');
  4206. 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);
  4207. var textInlineElementsMap = createLookupTable('text_inline_elements', 'span strong b em i font strike u var cite ' + 'dfn code mark q sup sub samp');
  4208. each$h((settings.special || 'script noscript iframe noframes noembed title style textarea xmp').split(' '), function (name) {
  4209. specialElements[name] = new RegExp('</' + name + '[^>]*>', 'gi');
  4210. });
  4211. var patternToRegExp = function (str) {
  4212. return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
  4213. };
  4214. var addValidElements = function (validElements) {
  4215. var ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, value;
  4216. var elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/, attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/;
  4217. if (validElements) {
  4218. var validElementsArr = split$1(validElements, ',');
  4219. if (elements['@']) {
  4220. globalAttributes = elements['@'].attributes;
  4221. globalAttributesOrder = elements['@'].attributesOrder;
  4222. }
  4223. for (ei = 0, el = validElementsArr.length; ei < el; ei++) {
  4224. matches = elementRuleRegExp.exec(validElementsArr[ei]);
  4225. if (matches) {
  4226. prefix = matches[1];
  4227. elementName = matches[2];
  4228. outputName = matches[3];
  4229. attrData = matches[5];
  4230. attributes = {};
  4231. attributesOrder = [];
  4232. element = {
  4233. attributes: attributes,
  4234. attributesOrder: attributesOrder
  4235. };
  4236. if (prefix === '#') {
  4237. element.paddEmpty = true;
  4238. }
  4239. if (prefix === '-') {
  4240. element.removeEmpty = true;
  4241. }
  4242. if (matches[4] === '!') {
  4243. element.removeEmptyAttrs = true;
  4244. }
  4245. if (globalAttributes) {
  4246. each$j(globalAttributes, function (value, key) {
  4247. attributes[key] = value;
  4248. });
  4249. attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
  4250. }
  4251. if (attrData) {
  4252. attrData = split$1(attrData, '|');
  4253. for (ai = 0, al = attrData.length; ai < al; ai++) {
  4254. matches = attrRuleRegExp.exec(attrData[ai]);
  4255. if (matches) {
  4256. attr = {};
  4257. attrType = matches[1];
  4258. attrName = matches[2].replace(/[\\:]:/g, ':');
  4259. prefix = matches[3];
  4260. value = matches[4];
  4261. if (attrType === '!') {
  4262. element.attributesRequired = element.attributesRequired || [];
  4263. element.attributesRequired.push(attrName);
  4264. attr.required = true;
  4265. }
  4266. if (attrType === '-') {
  4267. delete attributes[attrName];
  4268. attributesOrder.splice(inArray$2(attributesOrder, attrName), 1);
  4269. continue;
  4270. }
  4271. if (prefix) {
  4272. if (prefix === '=') {
  4273. element.attributesDefault = element.attributesDefault || [];
  4274. element.attributesDefault.push({
  4275. name: attrName,
  4276. value: value
  4277. });
  4278. attr.defaultValue = value;
  4279. }
  4280. if (prefix === ':') {
  4281. element.attributesForced = element.attributesForced || [];
  4282. element.attributesForced.push({
  4283. name: attrName,
  4284. value: value
  4285. });
  4286. attr.forcedValue = value;
  4287. }
  4288. if (prefix === '<') {
  4289. attr.validValues = makeMap$2(value, '?');
  4290. }
  4291. }
  4292. if (hasPatternsRegExp.test(attrName)) {
  4293. element.attributePatterns = element.attributePatterns || [];
  4294. attr.pattern = patternToRegExp(attrName);
  4295. element.attributePatterns.push(attr);
  4296. } else {
  4297. if (!attributes[attrName]) {
  4298. attributesOrder.push(attrName);
  4299. }
  4300. attributes[attrName] = attr;
  4301. }
  4302. }
  4303. }
  4304. }
  4305. if (!globalAttributes && elementName === '@') {
  4306. globalAttributes = attributes;
  4307. globalAttributesOrder = attributesOrder;
  4308. }
  4309. if (outputName) {
  4310. element.outputName = elementName;
  4311. elements[outputName] = element;
  4312. }
  4313. if (hasPatternsRegExp.test(elementName)) {
  4314. element.pattern = patternToRegExp(elementName);
  4315. patternElements.push(element);
  4316. } else {
  4317. elements[elementName] = element;
  4318. }
  4319. }
  4320. }
  4321. }
  4322. };
  4323. var setValidElements = function (validElements) {
  4324. elements = {};
  4325. patternElements = [];
  4326. addValidElements(validElements);
  4327. each$h(schemaItems, function (element, name) {
  4328. children[name] = element.children;
  4329. });
  4330. };
  4331. var addCustomElements = function (customElements) {
  4332. var customElementRegExp = /^(~)?(.+)$/;
  4333. if (customElements) {
  4334. mapCache.text_block_elements = mapCache.block_elements = null;
  4335. each$h(split$1(customElements, ','), function (rule) {
  4336. var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2];
  4337. children[name] = children[cloneName];
  4338. customElementsMap[name] = cloneName;
  4339. if (!inline) {
  4340. blockElementsMap[name.toUpperCase()] = {};
  4341. blockElementsMap[name] = {};
  4342. }
  4343. if (!elements[name]) {
  4344. var customRule = elements[cloneName];
  4345. customRule = extend$5({}, customRule);
  4346. delete customRule.removeEmptyAttrs;
  4347. delete customRule.removeEmpty;
  4348. elements[name] = customRule;
  4349. }
  4350. each$h(children, function (element, elmName) {
  4351. if (element[cloneName]) {
  4352. children[elmName] = element = extend$5({}, children[elmName]);
  4353. element[name] = element[cloneName];
  4354. }
  4355. });
  4356. });
  4357. }
  4358. };
  4359. var addValidChildren = function (validChildren) {
  4360. 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]+)\[([^\]]+)]$/;
  4361. mapCache[settings.schema] = null;
  4362. if (validChildren) {
  4363. each$h(split$1(validChildren, ','), function (rule) {
  4364. var matches = childRuleRegExp.exec(rule);
  4365. var parent, prefix;
  4366. if (matches) {
  4367. prefix = matches[1];
  4368. if (prefix) {
  4369. parent = children[matches[2]];
  4370. } else {
  4371. parent = children[matches[2]] = { '#comment': {} };
  4372. }
  4373. parent = children[matches[2]];
  4374. each$h(split$1(matches[3], '|'), function (child) {
  4375. if (prefix === '-') {
  4376. delete parent[child];
  4377. } else {
  4378. parent[child] = {};
  4379. }
  4380. });
  4381. }
  4382. });
  4383. }
  4384. };
  4385. var getElementRule = function (name) {
  4386. var element = elements[name], i;
  4387. if (element) {
  4388. return element;
  4389. }
  4390. i = patternElements.length;
  4391. while (i--) {
  4392. element = patternElements[i];
  4393. if (element.pattern.test(name)) {
  4394. return element;
  4395. }
  4396. }
  4397. };
  4398. if (!settings.valid_elements) {
  4399. each$h(schemaItems, function (element, name) {
  4400. elements[name] = {
  4401. attributes: element.attributes,
  4402. attributesOrder: element.attributesOrder
  4403. };
  4404. children[name] = element.children;
  4405. });
  4406. if (settings.schema !== 'html5') {
  4407. each$h(split$1('strong/b em/i'), function (item) {
  4408. var items = split$1(item, '/');
  4409. elements[items[1]].outputName = items[0];
  4410. });
  4411. }
  4412. each$h(split$1('ol ul sub sup blockquote span font a table tbody strong em b i'), function (name) {
  4413. if (elements[name]) {
  4414. elements[name].removeEmpty = true;
  4415. }
  4416. });
  4417. each$h(split$1('p h1 h2 h3 h4 h5 h6 th td pre div address caption li'), function (name) {
  4418. elements[name].paddEmpty = true;
  4419. });
  4420. each$h(split$1('span'), function (name) {
  4421. elements[name].removeEmptyAttrs = true;
  4422. });
  4423. } else {
  4424. setValidElements(settings.valid_elements);
  4425. }
  4426. addCustomElements(settings.custom_elements);
  4427. addValidChildren(settings.valid_children);
  4428. addValidElements(settings.extended_valid_elements);
  4429. addValidChildren('+ol[ul|ol],+ul[ul|ol]');
  4430. each$h({
  4431. dd: 'dl',
  4432. dt: 'dl',
  4433. li: 'ul ol',
  4434. td: 'tr',
  4435. th: 'tr',
  4436. tr: 'tbody thead tfoot',
  4437. tbody: 'table',
  4438. thead: 'table',
  4439. tfoot: 'table',
  4440. legend: 'fieldset',
  4441. area: 'map',
  4442. param: 'video audio object'
  4443. }, function (parents, item) {
  4444. if (elements[item]) {
  4445. elements[item].parentsRequired = split$1(parents);
  4446. }
  4447. });
  4448. if (settings.invalid_elements) {
  4449. each$h(explode$3(settings.invalid_elements), function (item) {
  4450. if (elements[item]) {
  4451. delete elements[item];
  4452. }
  4453. });
  4454. }
  4455. if (!getElementRule('span')) {
  4456. addValidElements('span[!data-mce-type|*]');
  4457. }
  4458. var getValidStyles = constant(validStyles);
  4459. var getInvalidStyles = constant(invalidStyles);
  4460. var getValidClasses = constant(validClasses);
  4461. var getBoolAttrs = constant(boolAttrMap);
  4462. var getBlockElements = constant(blockElementsMap);
  4463. var getTextBlockElements = constant(textBlockElementsMap);
  4464. var getTextInlineElements = constant(textInlineElementsMap);
  4465. var getShortEndedElements = constant(shortEndedElementsMap);
  4466. var getSelfClosingElements = constant(selfClosingElementsMap);
  4467. var getNonEmptyElements = constant(nonEmptyElementsMap);
  4468. var getMoveCaretBeforeOnEnterElements = constant(moveCaretBeforeOnEnterElementsMap);
  4469. var getWhiteSpaceElements = constant(whiteSpaceElementsMap);
  4470. var getSpecialElements = constant(specialElements);
  4471. var isValidChild = function (name, child) {
  4472. var parent = children[name.toLowerCase()];
  4473. return !!(parent && parent[child.toLowerCase()]);
  4474. };
  4475. var isValid = function (name, attr) {
  4476. var attrPatterns, i;
  4477. var rule = getElementRule(name);
  4478. if (rule) {
  4479. if (attr) {
  4480. if (rule.attributes[attr]) {
  4481. return true;
  4482. }
  4483. attrPatterns = rule.attributePatterns;
  4484. if (attrPatterns) {
  4485. i = attrPatterns.length;
  4486. while (i--) {
  4487. if (attrPatterns[i].pattern.test(name)) {
  4488. return true;
  4489. }
  4490. }
  4491. }
  4492. } else {
  4493. return true;
  4494. }
  4495. }
  4496. return false;
  4497. };
  4498. var getCustomElements = constant(customElementsMap);
  4499. return {
  4500. children: children,
  4501. elements: elements,
  4502. getValidStyles: getValidStyles,
  4503. getValidClasses: getValidClasses,
  4504. getBlockElements: getBlockElements,
  4505. getInvalidStyles: getInvalidStyles,
  4506. getShortEndedElements: getShortEndedElements,
  4507. getTextBlockElements: getTextBlockElements,
  4508. getTextInlineElements: getTextInlineElements,
  4509. getBoolAttrs: getBoolAttrs,
  4510. getElementRule: getElementRule,
  4511. getSelfClosingElements: getSelfClosingElements,
  4512. getNonEmptyElements: getNonEmptyElements,
  4513. getMoveCaretBeforeOnEnterElements: getMoveCaretBeforeOnEnterElements,
  4514. getWhiteSpaceElements: getWhiteSpaceElements,
  4515. getSpecialElements: getSpecialElements,
  4516. isValidChild: isValidChild,
  4517. isValid: isValid,
  4518. getCustomElements: getCustomElements,
  4519. addValidElements: addValidElements,
  4520. setValidElements: setValidElements,
  4521. addCustomElements: addCustomElements,
  4522. addValidChildren: addValidChildren
  4523. };
  4524. };
  4525. var toHex = function (match, r, g, b) {
  4526. var hex = function (val) {
  4527. val = parseInt(val, 10).toString(16);
  4528. return val.length > 1 ? val : '0' + val;
  4529. };
  4530. return '#' + hex(r) + hex(g) + hex(b);
  4531. };
  4532. var Styles = function (settings, schema) {
  4533. var _this = this;
  4534. var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
  4535. var urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
  4536. var styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
  4537. var trimRightRegExp = /\s+$/;
  4538. var i;
  4539. var encodingLookup = {};
  4540. var validStyles;
  4541. var invalidStyles;
  4542. var invisibleChar = zeroWidth;
  4543. settings = settings || {};
  4544. if (schema) {
  4545. validStyles = schema.getValidStyles();
  4546. invalidStyles = schema.getInvalidStyles();
  4547. }
  4548. var encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' ');
  4549. for (i = 0; i < encodingItems.length; i++) {
  4550. encodingLookup[encodingItems[i]] = invisibleChar + i;
  4551. encodingLookup[invisibleChar + i] = encodingItems[i];
  4552. }
  4553. return {
  4554. toHex: function (color) {
  4555. return color.replace(rgbRegExp, toHex);
  4556. },
  4557. parse: function (css) {
  4558. var styles = {};
  4559. var matches, name, value, isEncoded;
  4560. var urlConverter = settings.url_converter;
  4561. var urlConverterScope = settings.url_converter_scope || _this;
  4562. var compress = function (prefix, suffix, noJoin) {
  4563. var top = styles[prefix + '-top' + suffix];
  4564. if (!top) {
  4565. return;
  4566. }
  4567. var right = styles[prefix + '-right' + suffix];
  4568. if (!right) {
  4569. return;
  4570. }
  4571. var bottom = styles[prefix + '-bottom' + suffix];
  4572. if (!bottom) {
  4573. return;
  4574. }
  4575. var left = styles[prefix + '-left' + suffix];
  4576. if (!left) {
  4577. return;
  4578. }
  4579. var box = [
  4580. top,
  4581. right,
  4582. bottom,
  4583. left
  4584. ];
  4585. i = box.length - 1;
  4586. while (i--) {
  4587. if (box[i] !== box[i + 1]) {
  4588. break;
  4589. }
  4590. }
  4591. if (i > -1 && noJoin) {
  4592. return;
  4593. }
  4594. styles[prefix + suffix] = i === -1 ? box[0] : box.join(' ');
  4595. delete styles[prefix + '-top' + suffix];
  4596. delete styles[prefix + '-right' + suffix];
  4597. delete styles[prefix + '-bottom' + suffix];
  4598. delete styles[prefix + '-left' + suffix];
  4599. };
  4600. var canCompress = function (key) {
  4601. var value = styles[key], i;
  4602. if (!value) {
  4603. return;
  4604. }
  4605. value = value.split(' ');
  4606. i = value.length;
  4607. while (i--) {
  4608. if (value[i] !== value[0]) {
  4609. return false;
  4610. }
  4611. }
  4612. styles[key] = value[0];
  4613. return true;
  4614. };
  4615. var compress2 = function (target, a, b, c) {
  4616. if (!canCompress(a)) {
  4617. return;
  4618. }
  4619. if (!canCompress(b)) {
  4620. return;
  4621. }
  4622. if (!canCompress(c)) {
  4623. return;
  4624. }
  4625. styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
  4626. delete styles[a];
  4627. delete styles[b];
  4628. delete styles[c];
  4629. };
  4630. var encode = function (str) {
  4631. isEncoded = true;
  4632. return encodingLookup[str];
  4633. };
  4634. var decode = function (str, keepSlashes) {
  4635. if (isEncoded) {
  4636. str = str.replace(/\uFEFF[0-9]/g, function (str) {
  4637. return encodingLookup[str];
  4638. });
  4639. }
  4640. if (!keepSlashes) {
  4641. str = str.replace(/\\([\'\";:])/g, '$1');
  4642. }
  4643. return str;
  4644. };
  4645. var decodeSingleHexSequence = function (escSeq) {
  4646. return String.fromCharCode(parseInt(escSeq.slice(1), 16));
  4647. };
  4648. var decodeHexSequences = function (value) {
  4649. return value.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
  4650. };
  4651. var processUrl = function (match, url, url2, url3, str, str2) {
  4652. str = str || str2;
  4653. if (str) {
  4654. str = decode(str);
  4655. return '\'' + str.replace(/\'/g, '\\\'') + '\'';
  4656. }
  4657. url = decode(url || url2 || url3);
  4658. if (!settings.allow_script_urls) {
  4659. var scriptUrl = url.replace(/[\s\r\n]+/g, '');
  4660. if (/(java|vb)script:/i.test(scriptUrl)) {
  4661. return '';
  4662. }
  4663. if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
  4664. return '';
  4665. }
  4666. }
  4667. if (urlConverter) {
  4668. url = urlConverter.call(urlConverterScope, url, 'style');
  4669. }
  4670. return 'url(\'' + url.replace(/\'/g, '\\\'') + '\')';
  4671. };
  4672. if (css) {
  4673. css = css.replace(/[\u0000-\u001F]/g, '');
  4674. css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function (str) {
  4675. return str.replace(/[;:]/g, encode);
  4676. });
  4677. while (matches = styleRegExp.exec(css)) {
  4678. styleRegExp.lastIndex = matches.index + matches[0].length;
  4679. name = matches[1].replace(trimRightRegExp, '').toLowerCase();
  4680. value = matches[2].replace(trimRightRegExp, '');
  4681. if (name && value) {
  4682. name = decodeHexSequences(name);
  4683. value = decodeHexSequences(value);
  4684. if (name.indexOf(invisibleChar) !== -1 || name.indexOf('"') !== -1) {
  4685. continue;
  4686. }
  4687. if (!settings.allow_script_urls && (name === 'behavior' || /expression\s*\(|\/\*|\*\//.test(value))) {
  4688. continue;
  4689. }
  4690. if (name === 'font-weight' && value === '700') {
  4691. value = 'bold';
  4692. } else if (name === 'color' || name === 'background-color') {
  4693. value = value.toLowerCase();
  4694. }
  4695. value = value.replace(rgbRegExp, toHex);
  4696. value = value.replace(urlOrStrRegExp, processUrl);
  4697. styles[name] = isEncoded ? decode(value, true) : value;
  4698. }
  4699. }
  4700. compress('border', '', true);
  4701. compress('border', '-width');
  4702. compress('border', '-color');
  4703. compress('border', '-style');
  4704. compress('padding', '');
  4705. compress('margin', '');
  4706. compress2('border', 'border-width', 'border-style', 'border-color');
  4707. if (styles.border === 'medium none') {
  4708. delete styles.border;
  4709. }
  4710. if (styles['border-image'] === 'none') {
  4711. delete styles['border-image'];
  4712. }
  4713. }
  4714. return styles;
  4715. },
  4716. serialize: function (styles, elementName) {
  4717. var css = '';
  4718. var serializeStyles = function (name) {
  4719. var value;
  4720. var styleList = validStyles[name];
  4721. if (styleList) {
  4722. for (var i_1 = 0, l = styleList.length; i_1 < l; i_1++) {
  4723. name = styleList[i_1];
  4724. value = styles[name];
  4725. if (value) {
  4726. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4727. }
  4728. }
  4729. }
  4730. };
  4731. var isValid = function (name, elementName) {
  4732. var styleMap = invalidStyles['*'];
  4733. if (styleMap && styleMap[name]) {
  4734. return false;
  4735. }
  4736. styleMap = invalidStyles[elementName];
  4737. return !(styleMap && styleMap[name]);
  4738. };
  4739. if (elementName && validStyles) {
  4740. serializeStyles('*');
  4741. serializeStyles(elementName);
  4742. } else {
  4743. each$j(styles, function (value, name) {
  4744. if (value && (!invalidStyles || isValid(name, elementName))) {
  4745. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4746. }
  4747. });
  4748. }
  4749. return css;
  4750. }
  4751. };
  4752. };
  4753. var deprecated = {
  4754. keyLocation: true,
  4755. layerX: true,
  4756. layerY: true,
  4757. returnValue: true,
  4758. webkitMovementX: true,
  4759. webkitMovementY: true,
  4760. keyIdentifier: true,
  4761. mozPressure: true
  4762. };
  4763. var isNativeEvent = function (event) {
  4764. return event instanceof Event || isFunction(event.initEvent);
  4765. };
  4766. var hasIsDefaultPrevented = function (event) {
  4767. return event.isDefaultPrevented === always || event.isDefaultPrevented === never;
  4768. };
  4769. var needsNormalizing = function (event) {
  4770. return isNullable(event.preventDefault) || isNativeEvent(event);
  4771. };
  4772. var clone$2 = function (originalEvent, data) {
  4773. var event = data !== null && data !== void 0 ? data : {};
  4774. for (var name_1 in originalEvent) {
  4775. if (!has$2(deprecated, name_1)) {
  4776. event[name_1] = originalEvent[name_1];
  4777. }
  4778. }
  4779. if (isNonNullable(event.composedPath)) {
  4780. event.composedPath = function () {
  4781. return originalEvent.composedPath();
  4782. };
  4783. }
  4784. return event;
  4785. };
  4786. var normalize$3 = function (type, originalEvent, fallbackTarget, data) {
  4787. var _a;
  4788. var event = clone$2(originalEvent, data);
  4789. event.type = type;
  4790. if (isNullable(event.target)) {
  4791. event.target = (_a = event.srcElement) !== null && _a !== void 0 ? _a : fallbackTarget;
  4792. }
  4793. if (needsNormalizing(originalEvent)) {
  4794. event.preventDefault = function () {
  4795. event.defaultPrevented = true;
  4796. event.isDefaultPrevented = always;
  4797. if (isFunction(originalEvent.preventDefault)) {
  4798. originalEvent.preventDefault();
  4799. } else if (isNativeEvent(originalEvent)) {
  4800. originalEvent.returnValue = false;
  4801. }
  4802. };
  4803. event.stopPropagation = function () {
  4804. event.cancelBubble = true;
  4805. event.isPropagationStopped = always;
  4806. if (isFunction(originalEvent.stopPropagation)) {
  4807. originalEvent.stopPropagation();
  4808. } else if (isNativeEvent(originalEvent)) {
  4809. originalEvent.cancelBubble = true;
  4810. }
  4811. };
  4812. event.stopImmediatePropagation = function () {
  4813. event.isImmediatePropagationStopped = always;
  4814. event.stopPropagation();
  4815. };
  4816. if (!hasIsDefaultPrevented(event)) {
  4817. event.isDefaultPrevented = event.defaultPrevented === true ? always : never;
  4818. event.isPropagationStopped = event.cancelBubble === true ? always : never;
  4819. event.isImmediatePropagationStopped = never;
  4820. }
  4821. }
  4822. return event;
  4823. };
  4824. var eventExpandoPrefix = 'mce-data-';
  4825. var mouseEventRe = /^(?:mouse|contextmenu)|click/;
  4826. var addEvent = function (target, name, callback, capture) {
  4827. if (target.addEventListener) {
  4828. target.addEventListener(name, callback, capture || false);
  4829. } else if (target.attachEvent) {
  4830. target.attachEvent('on' + name, callback);
  4831. }
  4832. };
  4833. var removeEvent = function (target, name, callback, capture) {
  4834. if (target.removeEventListener) {
  4835. target.removeEventListener(name, callback, capture || false);
  4836. } else if (target.detachEvent) {
  4837. target.detachEvent('on' + name, callback);
  4838. }
  4839. };
  4840. var isMouseEvent = function (event) {
  4841. return isNonNullable(event) && mouseEventRe.test(event.type);
  4842. };
  4843. var fix = function (originalEvent, data) {
  4844. var event = normalize$3(originalEvent.type, originalEvent, document, data);
  4845. if (isMouseEvent(originalEvent) && isUndefined(originalEvent.pageX) && !isUndefined(originalEvent.clientX)) {
  4846. var eventDoc = event.target.ownerDocument || document;
  4847. var doc = eventDoc.documentElement;
  4848. var body = eventDoc.body;
  4849. var mouseEvent = event;
  4850. mouseEvent.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  4851. mouseEvent.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  4852. }
  4853. if (isUndefined(event.metaKey)) {
  4854. event.metaKey = false;
  4855. }
  4856. return event;
  4857. };
  4858. var bindOnReady = function (win, callback, eventUtils) {
  4859. var doc = win.document, event = { type: 'ready' };
  4860. if (eventUtils.domLoaded) {
  4861. callback(event);
  4862. return;
  4863. }
  4864. var isDocReady = function () {
  4865. return doc.readyState === 'complete' || doc.readyState === 'interactive' && doc.body;
  4866. };
  4867. var readyHandler = function () {
  4868. removeEvent(win, 'DOMContentLoaded', readyHandler);
  4869. removeEvent(win, 'load', readyHandler);
  4870. if (!eventUtils.domLoaded) {
  4871. eventUtils.domLoaded = true;
  4872. callback(event);
  4873. }
  4874. win = null;
  4875. };
  4876. if (isDocReady()) {
  4877. readyHandler();
  4878. } else {
  4879. addEvent(win, 'DOMContentLoaded', readyHandler);
  4880. }
  4881. if (!eventUtils.domLoaded) {
  4882. addEvent(win, 'load', readyHandler);
  4883. }
  4884. };
  4885. var EventUtils = function () {
  4886. function EventUtils() {
  4887. this.domLoaded = false;
  4888. this.events = {};
  4889. this.count = 1;
  4890. this.expando = eventExpandoPrefix + (+new Date()).toString(32);
  4891. this.hasMouseEnterLeave = 'onmouseenter' in document.documentElement;
  4892. this.hasFocusIn = 'onfocusin' in document.documentElement;
  4893. this.count = 1;
  4894. }
  4895. EventUtils.prototype.bind = function (target, names, callback, scope) {
  4896. var self = this;
  4897. var id, callbackList, i, name, fakeName, nativeHandler, capture;
  4898. var win = window;
  4899. var defaultNativeHandler = function (evt) {
  4900. self.executeHandlers(fix(evt || win.event), id);
  4901. };
  4902. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4903. return;
  4904. }
  4905. if (!target[self.expando]) {
  4906. id = self.count++;
  4907. target[self.expando] = id;
  4908. self.events[id] = {};
  4909. } else {
  4910. id = target[self.expando];
  4911. }
  4912. scope = scope || target;
  4913. var namesList = names.split(' ');
  4914. i = namesList.length;
  4915. while (i--) {
  4916. name = namesList[i];
  4917. nativeHandler = defaultNativeHandler;
  4918. fakeName = capture = false;
  4919. if (name === 'DOMContentLoaded') {
  4920. name = 'ready';
  4921. }
  4922. if (self.domLoaded && name === 'ready' && target.readyState === 'complete') {
  4923. callback.call(scope, fix({ type: name }));
  4924. continue;
  4925. }
  4926. if (!self.hasMouseEnterLeave) {
  4927. fakeName = self.mouseEnterLeave[name];
  4928. if (fakeName) {
  4929. nativeHandler = function (evt) {
  4930. var current = evt.currentTarget;
  4931. var related = evt.relatedTarget;
  4932. if (related && current.contains) {
  4933. related = current.contains(related);
  4934. } else {
  4935. while (related && related !== current) {
  4936. related = related.parentNode;
  4937. }
  4938. }
  4939. if (!related) {
  4940. evt = fix(evt || win.event);
  4941. evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
  4942. evt.target = current;
  4943. self.executeHandlers(evt, id);
  4944. }
  4945. };
  4946. }
  4947. }
  4948. if (!self.hasFocusIn && (name === 'focusin' || name === 'focusout')) {
  4949. capture = true;
  4950. fakeName = name === 'focusin' ? 'focus' : 'blur';
  4951. nativeHandler = function (evt) {
  4952. evt = fix(evt || win.event);
  4953. evt.type = evt.type === 'focus' ? 'focusin' : 'focusout';
  4954. self.executeHandlers(evt, id);
  4955. };
  4956. }
  4957. callbackList = self.events[id][name];
  4958. if (!callbackList) {
  4959. self.events[id][name] = callbackList = [{
  4960. func: callback,
  4961. scope: scope
  4962. }];
  4963. callbackList.fakeName = fakeName;
  4964. callbackList.capture = capture;
  4965. callbackList.nativeHandler = nativeHandler;
  4966. if (name === 'ready') {
  4967. bindOnReady(target, nativeHandler, self);
  4968. } else {
  4969. addEvent(target, fakeName || name, nativeHandler, capture);
  4970. }
  4971. } else {
  4972. if (name === 'ready' && self.domLoaded) {
  4973. callback(fix({ type: name }));
  4974. } else {
  4975. callbackList.push({
  4976. func: callback,
  4977. scope: scope
  4978. });
  4979. }
  4980. }
  4981. }
  4982. target = callbackList = null;
  4983. return callback;
  4984. };
  4985. EventUtils.prototype.unbind = function (target, names, callback) {
  4986. var callbackList, i, ci, name, eventMap;
  4987. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4988. return this;
  4989. }
  4990. var id = target[this.expando];
  4991. if (id) {
  4992. eventMap = this.events[id];
  4993. if (names) {
  4994. var namesList = names.split(' ');
  4995. i = namesList.length;
  4996. while (i--) {
  4997. name = namesList[i];
  4998. callbackList = eventMap[name];
  4999. if (callbackList) {
  5000. if (callback) {
  5001. ci = callbackList.length;
  5002. while (ci--) {
  5003. if (callbackList[ci].func === callback) {
  5004. var nativeHandler = callbackList.nativeHandler;
  5005. var fakeName = callbackList.fakeName, capture = callbackList.capture;
  5006. callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
  5007. callbackList.nativeHandler = nativeHandler;
  5008. callbackList.fakeName = fakeName;
  5009. callbackList.capture = capture;
  5010. eventMap[name] = callbackList;
  5011. }
  5012. }
  5013. }
  5014. if (!callback || callbackList.length === 0) {
  5015. delete eventMap[name];
  5016. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  5017. }
  5018. }
  5019. }
  5020. } else {
  5021. each$j(eventMap, function (callbackList, name) {
  5022. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  5023. });
  5024. eventMap = {};
  5025. }
  5026. for (name in eventMap) {
  5027. if (has$2(eventMap, name)) {
  5028. return this;
  5029. }
  5030. }
  5031. delete this.events[id];
  5032. try {
  5033. delete target[this.expando];
  5034. } catch (ex) {
  5035. target[this.expando] = null;
  5036. }
  5037. }
  5038. return this;
  5039. };
  5040. EventUtils.prototype.fire = function (target, name, args) {
  5041. var id;
  5042. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  5043. return this;
  5044. }
  5045. var event = fix({
  5046. type: name,
  5047. target: target
  5048. }, args);
  5049. do {
  5050. id = target[this.expando];
  5051. if (id) {
  5052. this.executeHandlers(event, id);
  5053. }
  5054. target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
  5055. } while (target && !event.isPropagationStopped());
  5056. return this;
  5057. };
  5058. EventUtils.prototype.clean = function (target) {
  5059. var i, children;
  5060. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  5061. return this;
  5062. }
  5063. if (target[this.expando]) {
  5064. this.unbind(target);
  5065. }
  5066. if (!target.getElementsByTagName) {
  5067. target = target.document;
  5068. }
  5069. if (target && target.getElementsByTagName) {
  5070. this.unbind(target);
  5071. children = target.getElementsByTagName('*');
  5072. i = children.length;
  5073. while (i--) {
  5074. target = children[i];
  5075. if (target[this.expando]) {
  5076. this.unbind(target);
  5077. }
  5078. }
  5079. }
  5080. return this;
  5081. };
  5082. EventUtils.prototype.destroy = function () {
  5083. this.events = {};
  5084. };
  5085. EventUtils.prototype.cancel = function (e) {
  5086. if (e) {
  5087. e.preventDefault();
  5088. e.stopImmediatePropagation();
  5089. }
  5090. return false;
  5091. };
  5092. EventUtils.prototype.executeHandlers = function (evt, id) {
  5093. var container = this.events[id];
  5094. var callbackList = container && container[evt.type];
  5095. if (callbackList) {
  5096. for (var i = 0, l = callbackList.length; i < l; i++) {
  5097. var callback = callbackList[i];
  5098. if (callback && callback.func.call(callback.scope, evt) === false) {
  5099. evt.preventDefault();
  5100. }
  5101. if (evt.isImmediatePropagationStopped()) {
  5102. return;
  5103. }
  5104. }
  5105. }
  5106. };
  5107. EventUtils.Event = new EventUtils();
  5108. return EventUtils;
  5109. }();
  5110. 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) {
  5111. if (a === b) {
  5112. hasDuplicate = true;
  5113. }
  5114. return 0;
  5115. }, 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) {
  5116. var i = 0, len = this.length;
  5117. for (; i < len; i++) {
  5118. if (this[i] === elem) {
  5119. return i;
  5120. }
  5121. }
  5122. return -1;
  5123. }, 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 = {
  5124. ID: new RegExp('^#(' + identifier + ')'),
  5125. CLASS: new RegExp('^\\.(' + identifier + ')'),
  5126. TAG: new RegExp('^(' + identifier + '|[*])'),
  5127. ATTR: new RegExp('^' + attributes),
  5128. PSEUDO: new RegExp('^' + pseudos),
  5129. CHILD: new RegExp('^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(' + whitespace + '*(even|odd|(([+-]|)(\\d*)n|)' + whitespace + '*(?:([+-]|)' + whitespace + '*(\\d+)|))' + whitespace + '*\\)|)', 'i'),
  5130. bool: new RegExp('^(?:' + booleans + ')$', 'i'),
  5131. needsContext: new RegExp('^' + whitespace + '*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(' + whitespace + '*((?:-\\d)?\\d*)' + whitespace + '*\\)|)(?=[^-]|$)', 'i')
  5132. }, 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) {
  5133. var high = '0x' + escaped - 65536;
  5134. return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320);
  5135. };
  5136. try {
  5137. push$1.apply(arr = slice$1.call(preferredDoc.childNodes), preferredDoc.childNodes);
  5138. arr[preferredDoc.childNodes.length].nodeType;
  5139. } catch (e) {
  5140. push$1 = {
  5141. apply: arr.length ? function (target, els) {
  5142. push_native.apply(target, slice$1.call(els));
  5143. } : function (target, els) {
  5144. var j = target.length, i = 0;
  5145. while (target[j++] = els[i++]) {
  5146. }
  5147. target.length = j - 1;
  5148. }
  5149. };
  5150. }
  5151. var Sizzle = function (selector, context, results, seed) {
  5152. var match, elem, m, nodeType, i, groups, old, nid, newContext, newSelector;
  5153. if ((context ? context.ownerDocument || context : preferredDoc) !== document$1) {
  5154. setDocument(context);
  5155. }
  5156. context = context || document$1;
  5157. results = results || [];
  5158. if (!selector || typeof selector !== 'string') {
  5159. return results;
  5160. }
  5161. if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) {
  5162. return [];
  5163. }
  5164. if (documentIsHTML && !seed) {
  5165. if (match = rquickExpr$1.exec(selector)) {
  5166. if (m = match[1]) {
  5167. if (nodeType === 9) {
  5168. elem = context.getElementById(m);
  5169. if (elem && elem.parentNode) {
  5170. if (elem.id === m) {
  5171. results.push(elem);
  5172. return results;
  5173. }
  5174. } else {
  5175. return results;
  5176. }
  5177. } else {
  5178. if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains(context, elem) && elem.id === m) {
  5179. results.push(elem);
  5180. return results;
  5181. }
  5182. }
  5183. } else if (match[2]) {
  5184. push$1.apply(results, context.getElementsByTagName(selector));
  5185. return results;
  5186. } else if ((m = match[3]) && support.getElementsByClassName) {
  5187. push$1.apply(results, context.getElementsByClassName(m));
  5188. return results;
  5189. }
  5190. }
  5191. if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
  5192. nid = old = expando;
  5193. newContext = context;
  5194. newSelector = nodeType === 9 && selector;
  5195. if (nodeType === 1 && context.nodeName.toLowerCase() !== 'object') {
  5196. groups = tokenize(selector);
  5197. if (old = context.getAttribute('id')) {
  5198. nid = old.replace(rescape, '\\$&');
  5199. } else {
  5200. context.setAttribute('id', nid);
  5201. }
  5202. nid = '[id=\'' + nid + '\'] ';
  5203. i = groups.length;
  5204. while (i--) {
  5205. groups[i] = nid + toSelector(groups[i]);
  5206. }
  5207. newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
  5208. newSelector = groups.join(',');
  5209. }
  5210. if (newSelector) {
  5211. try {
  5212. push$1.apply(results, newContext.querySelectorAll(newSelector));
  5213. return results;
  5214. } catch (qsaError) {
  5215. } finally {
  5216. if (!old) {
  5217. context.removeAttribute('id');
  5218. }
  5219. }
  5220. }
  5221. }
  5222. }
  5223. return select$1(selector.replace(rtrim, '$1'), context, results, seed);
  5224. };
  5225. function createCache() {
  5226. var keys = [];
  5227. function cache(key, value) {
  5228. if (keys.push(key + ' ') > Expr.cacheLength) {
  5229. delete cache[keys.shift()];
  5230. }
  5231. return cache[key + ' '] = value;
  5232. }
  5233. return cache;
  5234. }
  5235. function markFunction(fn) {
  5236. fn[expando] = true;
  5237. return fn;
  5238. }
  5239. function siblingCheck(a, b) {
  5240. var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && (~b.sourceIndex || MAX_NEGATIVE) - (~a.sourceIndex || MAX_NEGATIVE);
  5241. if (diff) {
  5242. return diff;
  5243. }
  5244. if (cur) {
  5245. while (cur = cur.nextSibling) {
  5246. if (cur === b) {
  5247. return -1;
  5248. }
  5249. }
  5250. }
  5251. return a ? 1 : -1;
  5252. }
  5253. function createInputPseudo(type) {
  5254. return function (elem) {
  5255. var name = elem.nodeName.toLowerCase();
  5256. return name === 'input' && elem.type === type;
  5257. };
  5258. }
  5259. function createButtonPseudo(type) {
  5260. return function (elem) {
  5261. var name = elem.nodeName.toLowerCase();
  5262. return (name === 'input' || name === 'button') && elem.type === type;
  5263. };
  5264. }
  5265. function createPositionalPseudo(fn) {
  5266. return markFunction(function (argument) {
  5267. argument = +argument;
  5268. return markFunction(function (seed, matches) {
  5269. var j, matchIndexes = fn([], seed.length, argument), i = matchIndexes.length;
  5270. while (i--) {
  5271. if (seed[j = matchIndexes[i]]) {
  5272. seed[j] = !(matches[j] = seed[j]);
  5273. }
  5274. }
  5275. });
  5276. });
  5277. }
  5278. function testContext(context) {
  5279. return context && typeof context.getElementsByTagName !== strundefined && context;
  5280. }
  5281. support = Sizzle.support = {};
  5282. isXML = Sizzle.isXML = function (elem) {
  5283. var documentElement = elem && (elem.ownerDocument || elem).documentElement;
  5284. return documentElement ? documentElement.nodeName !== 'HTML' : false;
  5285. };
  5286. setDocument = Sizzle.setDocument = function (node) {
  5287. var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView;
  5288. function getTop(win) {
  5289. try {
  5290. return win.top;
  5291. } catch (ex) {
  5292. }
  5293. return null;
  5294. }
  5295. if (doc === document$1 || doc.nodeType !== 9 || !doc.documentElement) {
  5296. return document$1;
  5297. }
  5298. document$1 = doc;
  5299. docElem = doc.documentElement;
  5300. documentIsHTML = !isXML(doc);
  5301. if (parent && parent !== getTop(parent)) {
  5302. if (parent.addEventListener) {
  5303. parent.addEventListener('unload', function () {
  5304. setDocument();
  5305. }, false);
  5306. } else if (parent.attachEvent) {
  5307. parent.attachEvent('onunload', function () {
  5308. setDocument();
  5309. });
  5310. }
  5311. }
  5312. support.attributes = true;
  5313. support.getElementsByTagName = true;
  5314. support.getElementsByClassName = rnative.test(doc.getElementsByClassName);
  5315. support.getById = true;
  5316. Expr.find.ID = function (id, context) {
  5317. if (typeof context.getElementById !== strundefined && documentIsHTML) {
  5318. var m = context.getElementById(id);
  5319. return m && m.parentNode ? [m] : [];
  5320. }
  5321. };
  5322. Expr.filter.ID = function (id) {
  5323. var attrId = id.replace(runescape, funescape);
  5324. return function (elem) {
  5325. return elem.getAttribute('id') === attrId;
  5326. };
  5327. };
  5328. Expr.find.TAG = support.getElementsByTagName ? function (tag, context) {
  5329. if (typeof context.getElementsByTagName !== strundefined) {
  5330. return context.getElementsByTagName(tag);
  5331. }
  5332. } : function (tag, context) {
  5333. var elem, tmp = [], i = 0, results = context.getElementsByTagName(tag);
  5334. if (tag === '*') {
  5335. while (elem = results[i++]) {
  5336. if (elem.nodeType === 1) {
  5337. tmp.push(elem);
  5338. }
  5339. }
  5340. return tmp;
  5341. }
  5342. return results;
  5343. };
  5344. Expr.find.CLASS = support.getElementsByClassName && function (className, context) {
  5345. if (documentIsHTML) {
  5346. return context.getElementsByClassName(className);
  5347. }
  5348. };
  5349. rbuggyMatches = [];
  5350. rbuggyQSA = [];
  5351. support.disconnectedMatch = true;
  5352. rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join('|'));
  5353. rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join('|'));
  5354. hasCompare = rnative.test(docElem.compareDocumentPosition);
  5355. contains = hasCompare || rnative.test(docElem.contains) ? function (a, b) {
  5356. var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode;
  5357. return a === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
  5358. } : function (a, b) {
  5359. if (b) {
  5360. while (b = b.parentNode) {
  5361. if (b === a) {
  5362. return true;
  5363. }
  5364. }
  5365. }
  5366. return false;
  5367. };
  5368. sortOrder = hasCompare ? function (a, b) {
  5369. if (a === b) {
  5370. hasDuplicate = true;
  5371. return 0;
  5372. }
  5373. var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
  5374. if (compare) {
  5375. return compare;
  5376. }
  5377. compare = (a.ownerDocument || a) === (b.ownerDocument || b) ? a.compareDocumentPosition(b) : 1;
  5378. if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {
  5379. if (a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a)) {
  5380. return -1;
  5381. }
  5382. if (b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b)) {
  5383. return 1;
  5384. }
  5385. return sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
  5386. }
  5387. return compare & 4 ? -1 : 1;
  5388. } : function (a, b) {
  5389. if (a === b) {
  5390. hasDuplicate = true;
  5391. return 0;
  5392. }
  5393. var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [a], bp = [b];
  5394. if (!aup || !bup) {
  5395. return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
  5396. } else if (aup === bup) {
  5397. return siblingCheck(a, b);
  5398. }
  5399. cur = a;
  5400. while (cur = cur.parentNode) {
  5401. ap.unshift(cur);
  5402. }
  5403. cur = b;
  5404. while (cur = cur.parentNode) {
  5405. bp.unshift(cur);
  5406. }
  5407. while (ap[i] === bp[i]) {
  5408. i++;
  5409. }
  5410. return i ? siblingCheck(ap[i], bp[i]) : ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0;
  5411. };
  5412. return doc;
  5413. };
  5414. Sizzle.matches = function (expr, elements) {
  5415. return Sizzle(expr, null, null, elements);
  5416. };
  5417. Sizzle.matchesSelector = function (elem, expr) {
  5418. if ((elem.ownerDocument || elem) !== document$1) {
  5419. setDocument(elem);
  5420. }
  5421. expr = expr.replace(rattributeQuotes, '=\'$1\']');
  5422. if (support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
  5423. try {
  5424. var ret = matches.call(elem, expr);
  5425. if (ret || support.disconnectedMatch || elem.document && elem.document.nodeType !== 11) {
  5426. return ret;
  5427. }
  5428. } catch (e) {
  5429. }
  5430. }
  5431. return Sizzle(expr, document$1, null, [elem]).length > 0;
  5432. };
  5433. Sizzle.contains = function (context, elem) {
  5434. if ((context.ownerDocument || context) !== document$1) {
  5435. setDocument(context);
  5436. }
  5437. return contains(context, elem);
  5438. };
  5439. Sizzle.attr = function (elem, name) {
  5440. if ((elem.ownerDocument || elem) !== document$1) {
  5441. setDocument(elem);
  5442. }
  5443. var fn = Expr.attrHandle[name.toLowerCase()], val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;
  5444. return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
  5445. };
  5446. Sizzle.error = function (msg) {
  5447. throw new Error('Syntax error, unrecognized expression: ' + msg);
  5448. };
  5449. Sizzle.uniqueSort = function (results) {
  5450. var elem, duplicates = [], j = 0, i = 0;
  5451. hasDuplicate = !support.detectDuplicates;
  5452. sortInput = !support.sortStable && results.slice(0);
  5453. results.sort(sortOrder);
  5454. if (hasDuplicate) {
  5455. while (elem = results[i++]) {
  5456. if (elem === results[i]) {
  5457. j = duplicates.push(i);
  5458. }
  5459. }
  5460. while (j--) {
  5461. results.splice(duplicates[j], 1);
  5462. }
  5463. }
  5464. sortInput = null;
  5465. return results;
  5466. };
  5467. getText = Sizzle.getText = function (elem) {
  5468. var node, ret = '', i = 0, nodeType = elem.nodeType;
  5469. if (!nodeType) {
  5470. while (node = elem[i++]) {
  5471. ret += getText(node);
  5472. }
  5473. } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
  5474. if (typeof elem.textContent === 'string') {
  5475. return elem.textContent;
  5476. } else {
  5477. for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5478. ret += getText(elem);
  5479. }
  5480. }
  5481. } else if (nodeType === 3 || nodeType === 4) {
  5482. return elem.nodeValue;
  5483. }
  5484. return ret;
  5485. };
  5486. Expr = Sizzle.selectors = {
  5487. cacheLength: 50,
  5488. createPseudo: markFunction,
  5489. match: matchExpr,
  5490. attrHandle: {},
  5491. find: {},
  5492. relative: {
  5493. '>': {
  5494. dir: 'parentNode',
  5495. first: true
  5496. },
  5497. ' ': { dir: 'parentNode' },
  5498. '+': {
  5499. dir: 'previousSibling',
  5500. first: true
  5501. },
  5502. '~': { dir: 'previousSibling' }
  5503. },
  5504. preFilter: {
  5505. ATTR: function (match) {
  5506. match[1] = match[1].replace(runescape, funescape);
  5507. match[3] = (match[3] || match[4] || match[5] || '').replace(runescape, funescape);
  5508. if (match[2] === '~=') {
  5509. match[3] = ' ' + match[3] + ' ';
  5510. }
  5511. return match.slice(0, 4);
  5512. },
  5513. CHILD: function (match) {
  5514. match[1] = match[1].toLowerCase();
  5515. if (match[1].slice(0, 3) === 'nth') {
  5516. if (!match[3]) {
  5517. Sizzle.error(match[0]);
  5518. }
  5519. match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === 'even' || match[3] === 'odd'));
  5520. match[5] = +(match[7] + match[8] || match[3] === 'odd');
  5521. } else if (match[3]) {
  5522. Sizzle.error(match[0]);
  5523. }
  5524. return match;
  5525. },
  5526. PSEUDO: function (match) {
  5527. var excess, unquoted = !match[6] && match[2];
  5528. if (matchExpr.CHILD.test(match[0])) {
  5529. return null;
  5530. }
  5531. if (match[3]) {
  5532. match[2] = match[4] || match[5] || '';
  5533. } else if (unquoted && rpseudo.test(unquoted) && (excess = tokenize(unquoted, true)) && (excess = unquoted.indexOf(')', unquoted.length - excess) - unquoted.length)) {
  5534. match[0] = match[0].slice(0, excess);
  5535. match[2] = unquoted.slice(0, excess);
  5536. }
  5537. return match.slice(0, 3);
  5538. }
  5539. },
  5540. filter: {
  5541. TAG: function (nodeNameSelector) {
  5542. var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
  5543. return nodeNameSelector === '*' ? function () {
  5544. return true;
  5545. } : function (elem) {
  5546. return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
  5547. };
  5548. },
  5549. CLASS: function (className) {
  5550. var pattern = classCache[className + ' '];
  5551. return pattern || (pattern = new RegExp('(^|' + whitespace + ')' + className + '(' + whitespace + '|$)')) && classCache(className, function (elem) {
  5552. return pattern.test(typeof elem.className === 'string' && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute('class') || '');
  5553. });
  5554. },
  5555. ATTR: function (name, operator, check) {
  5556. return function (elem) {
  5557. var result = Sizzle.attr(elem, name);
  5558. if (result == null) {
  5559. return operator === '!=';
  5560. }
  5561. if (!operator) {
  5562. return true;
  5563. }
  5564. result += '';
  5565. 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;
  5566. };
  5567. },
  5568. CHILD: function (type, what, argument, first, last) {
  5569. var simple = type.slice(0, 3) !== 'nth', forward = type.slice(-4) !== 'last', ofType = what === 'of-type';
  5570. return first === 1 && last === 0 ? function (elem) {
  5571. return !!elem.parentNode;
  5572. } : function (elem, context, xml) {
  5573. var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? 'nextSibling' : 'previousSibling', parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType;
  5574. if (parent) {
  5575. if (simple) {
  5576. while (dir) {
  5577. node = elem;
  5578. while (node = node[dir]) {
  5579. if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
  5580. return false;
  5581. }
  5582. }
  5583. start = dir = type === 'only' && !start && 'nextSibling';
  5584. }
  5585. return true;
  5586. }
  5587. start = [forward ? parent.firstChild : parent.lastChild];
  5588. if (forward && useCache) {
  5589. outerCache = parent[expando] || (parent[expando] = {});
  5590. cache = outerCache[type] || [];
  5591. nodeIndex = cache[0] === dirruns && cache[1];
  5592. diff = cache[0] === dirruns && cache[2];
  5593. node = nodeIndex && parent.childNodes[nodeIndex];
  5594. while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5595. if (node.nodeType === 1 && ++diff && node === elem) {
  5596. outerCache[type] = [
  5597. dirruns,
  5598. nodeIndex,
  5599. diff
  5600. ];
  5601. break;
  5602. }
  5603. }
  5604. } else if (useCache && (cache = (elem[expando] || (elem[expando] = {}))[type]) && cache[0] === dirruns) {
  5605. diff = cache[1];
  5606. } else {
  5607. while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5608. if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) {
  5609. if (useCache) {
  5610. (node[expando] || (node[expando] = {}))[type] = [
  5611. dirruns,
  5612. diff
  5613. ];
  5614. }
  5615. if (node === elem) {
  5616. break;
  5617. }
  5618. }
  5619. }
  5620. }
  5621. diff -= last;
  5622. return diff === first || diff % first === 0 && diff / first >= 0;
  5623. }
  5624. };
  5625. },
  5626. PSEUDO: function (pseudo, argument) {
  5627. var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error('unsupported pseudo: ' + pseudo);
  5628. if (fn[expando]) {
  5629. return fn(argument);
  5630. }
  5631. if (fn.length > 1) {
  5632. args = [
  5633. pseudo,
  5634. pseudo,
  5635. '',
  5636. argument
  5637. ];
  5638. return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) {
  5639. var idx, matched = fn(seed, argument), i = matched.length;
  5640. while (i--) {
  5641. idx = indexOf.call(seed, matched[i]);
  5642. seed[idx] = !(matches[idx] = matched[i]);
  5643. }
  5644. }) : function (elem) {
  5645. return fn(elem, 0, args);
  5646. };
  5647. }
  5648. return fn;
  5649. }
  5650. },
  5651. pseudos: {
  5652. not: markFunction(function (selector) {
  5653. var input = [], results = [], matcher = compile(selector.replace(rtrim, '$1'));
  5654. return matcher[expando] ? markFunction(function (seed, matches, context, xml) {
  5655. var elem, unmatched = matcher(seed, null, xml, []), i = seed.length;
  5656. while (i--) {
  5657. if (elem = unmatched[i]) {
  5658. seed[i] = !(matches[i] = elem);
  5659. }
  5660. }
  5661. }) : function (elem, context, xml) {
  5662. input[0] = elem;
  5663. matcher(input, null, xml, results);
  5664. input[0] = null;
  5665. return !results.pop();
  5666. };
  5667. }),
  5668. has: markFunction(function (selector) {
  5669. return function (elem) {
  5670. return Sizzle(selector, elem).length > 0;
  5671. };
  5672. }),
  5673. contains: markFunction(function (text) {
  5674. text = text.replace(runescape, funescape);
  5675. return function (elem) {
  5676. return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1;
  5677. };
  5678. }),
  5679. lang: markFunction(function (lang) {
  5680. if (!ridentifier.test(lang || '')) {
  5681. Sizzle.error('unsupported lang: ' + lang);
  5682. }
  5683. lang = lang.replace(runescape, funescape).toLowerCase();
  5684. return function (elem) {
  5685. var elemLang;
  5686. do {
  5687. if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute('xml:lang') || elem.getAttribute('lang')) {
  5688. elemLang = elemLang.toLowerCase();
  5689. return elemLang === lang || elemLang.indexOf(lang + '-') === 0;
  5690. }
  5691. } while ((elem = elem.parentNode) && elem.nodeType === 1);
  5692. return false;
  5693. };
  5694. }),
  5695. target: function (elem) {
  5696. var hash = window.location && window.location.hash;
  5697. return hash && hash.slice(1) === elem.id;
  5698. },
  5699. root: function (elem) {
  5700. return elem === docElem;
  5701. },
  5702. focus: function (elem) {
  5703. return elem === document$1.activeElement && (!document$1.hasFocus || document$1.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
  5704. },
  5705. enabled: function (elem) {
  5706. return elem.disabled === false;
  5707. },
  5708. disabled: function (elem) {
  5709. return elem.disabled === true;
  5710. },
  5711. checked: function (elem) {
  5712. var nodeName = elem.nodeName.toLowerCase();
  5713. return nodeName === 'input' && !!elem.checked || nodeName === 'option' && !!elem.selected;
  5714. },
  5715. selected: function (elem) {
  5716. if (elem.parentNode) {
  5717. elem.parentNode.selectedIndex;
  5718. }
  5719. return elem.selected === true;
  5720. },
  5721. empty: function (elem) {
  5722. for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5723. if (elem.nodeType < 6) {
  5724. return false;
  5725. }
  5726. }
  5727. return true;
  5728. },
  5729. parent: function (elem) {
  5730. return !Expr.pseudos.empty(elem);
  5731. },
  5732. header: function (elem) {
  5733. return rheader.test(elem.nodeName);
  5734. },
  5735. input: function (elem) {
  5736. return rinputs.test(elem.nodeName);
  5737. },
  5738. button: function (elem) {
  5739. var name = elem.nodeName.toLowerCase();
  5740. return name === 'input' && elem.type === 'button' || name === 'button';
  5741. },
  5742. text: function (elem) {
  5743. var attr;
  5744. return elem.nodeName.toLowerCase() === 'input' && elem.type === 'text' && ((attr = elem.getAttribute('type')) == null || attr.toLowerCase() === 'text');
  5745. },
  5746. first: createPositionalPseudo(function () {
  5747. return [0];
  5748. }),
  5749. last: createPositionalPseudo(function (matchIndexes, length) {
  5750. return [length - 1];
  5751. }),
  5752. eq: createPositionalPseudo(function (matchIndexes, length, argument) {
  5753. return [argument < 0 ? argument + length : argument];
  5754. }),
  5755. even: createPositionalPseudo(function (matchIndexes, length) {
  5756. var i = 0;
  5757. for (; i < length; i += 2) {
  5758. matchIndexes.push(i);
  5759. }
  5760. return matchIndexes;
  5761. }),
  5762. odd: createPositionalPseudo(function (matchIndexes, length) {
  5763. var i = 1;
  5764. for (; i < length; i += 2) {
  5765. matchIndexes.push(i);
  5766. }
  5767. return matchIndexes;
  5768. }),
  5769. lt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5770. var i = argument < 0 ? argument + length : argument;
  5771. for (; --i >= 0;) {
  5772. matchIndexes.push(i);
  5773. }
  5774. return matchIndexes;
  5775. }),
  5776. gt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5777. var i = argument < 0 ? argument + length : argument;
  5778. for (; ++i < length;) {
  5779. matchIndexes.push(i);
  5780. }
  5781. return matchIndexes;
  5782. })
  5783. }
  5784. };
  5785. Expr.pseudos.nth = Expr.pseudos.eq;
  5786. each$k([
  5787. 'radio',
  5788. 'checkbox',
  5789. 'file',
  5790. 'password',
  5791. 'image'
  5792. ], function (i) {
  5793. Expr.pseudos[i] = createInputPseudo(i);
  5794. });
  5795. each$k([
  5796. 'submit',
  5797. 'reset'
  5798. ], function (i) {
  5799. Expr.pseudos[i] = createButtonPseudo(i);
  5800. });
  5801. function setFilters() {
  5802. }
  5803. setFilters.prototype = Expr.filters = Expr.pseudos;
  5804. Expr.setFilters = new setFilters();
  5805. tokenize = Sizzle.tokenize = function (selector, parseOnly) {
  5806. var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + ' '];
  5807. if (cached) {
  5808. return parseOnly ? 0 : cached.slice(0);
  5809. }
  5810. soFar = selector;
  5811. groups = [];
  5812. preFilters = Expr.preFilter;
  5813. while (soFar) {
  5814. if (!matched || (match = rcomma.exec(soFar))) {
  5815. if (match) {
  5816. soFar = soFar.slice(match[0].length) || soFar;
  5817. }
  5818. groups.push(tokens = []);
  5819. }
  5820. matched = false;
  5821. if (match = rcombinators.exec(soFar)) {
  5822. matched = match.shift();
  5823. tokens.push({
  5824. value: matched,
  5825. type: match[0].replace(rtrim, ' ')
  5826. });
  5827. soFar = soFar.slice(matched.length);
  5828. }
  5829. for (type in Expr.filter) {
  5830. if (!Expr.filter.hasOwnProperty(type)) {
  5831. continue;
  5832. }
  5833. if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) {
  5834. matched = match.shift();
  5835. tokens.push({
  5836. value: matched,
  5837. type: type,
  5838. matches: match
  5839. });
  5840. soFar = soFar.slice(matched.length);
  5841. }
  5842. }
  5843. if (!matched) {
  5844. break;
  5845. }
  5846. }
  5847. return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : tokenCache(selector, groups).slice(0);
  5848. };
  5849. function toSelector(tokens) {
  5850. var i = 0, len = tokens.length, selector = '';
  5851. for (; i < len; i++) {
  5852. selector += tokens[i].value;
  5853. }
  5854. return selector;
  5855. }
  5856. function addCombinator(matcher, combinator, base) {
  5857. var dir = combinator.dir, checkNonElements = base && dir === 'parentNode', doneName = done++;
  5858. return combinator.first ? function (elem, context, xml) {
  5859. while (elem = elem[dir]) {
  5860. if (elem.nodeType === 1 || checkNonElements) {
  5861. return matcher(elem, context, xml);
  5862. }
  5863. }
  5864. } : function (elem, context, xml) {
  5865. var oldCache, outerCache, newCache = [
  5866. dirruns,
  5867. doneName
  5868. ];
  5869. if (xml) {
  5870. while (elem = elem[dir]) {
  5871. if (elem.nodeType === 1 || checkNonElements) {
  5872. if (matcher(elem, context, xml)) {
  5873. return true;
  5874. }
  5875. }
  5876. }
  5877. } else {
  5878. while (elem = elem[dir]) {
  5879. if (elem.nodeType === 1 || checkNonElements) {
  5880. outerCache = elem[expando] || (elem[expando] = {});
  5881. if ((oldCache = outerCache[dir]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
  5882. return newCache[2] = oldCache[2];
  5883. } else {
  5884. outerCache[dir] = newCache;
  5885. if (newCache[2] = matcher(elem, context, xml)) {
  5886. return true;
  5887. }
  5888. }
  5889. }
  5890. }
  5891. }
  5892. };
  5893. }
  5894. function elementMatcher(matchers) {
  5895. return matchers.length > 1 ? function (elem, context, xml) {
  5896. var i = matchers.length;
  5897. while (i--) {
  5898. if (!matchers[i](elem, context, xml)) {
  5899. return false;
  5900. }
  5901. }
  5902. return true;
  5903. } : matchers[0];
  5904. }
  5905. function multipleContexts(selector, contexts, results) {
  5906. var i = 0, len = contexts.length;
  5907. for (; i < len; i++) {
  5908. Sizzle(selector, contexts[i], results);
  5909. }
  5910. return results;
  5911. }
  5912. function condense(unmatched, map, filter, context, xml) {
  5913. var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null;
  5914. for (; i < len; i++) {
  5915. if (elem = unmatched[i]) {
  5916. if (!filter || filter(elem, context, xml)) {
  5917. newUnmatched.push(elem);
  5918. if (mapped) {
  5919. map.push(i);
  5920. }
  5921. }
  5922. }
  5923. }
  5924. return newUnmatched;
  5925. }
  5926. function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
  5927. if (postFilter && !postFilter[expando]) {
  5928. postFilter = setMatcher(postFilter);
  5929. }
  5930. if (postFinder && !postFinder[expando]) {
  5931. postFinder = setMatcher(postFinder, postSelector);
  5932. }
  5933. return markFunction(function (seed, results, context, xml) {
  5934. 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;
  5935. if (matcher) {
  5936. matcher(matcherIn, matcherOut, context, xml);
  5937. }
  5938. if (postFilter) {
  5939. temp = condense(matcherOut, postMap);
  5940. postFilter(temp, [], context, xml);
  5941. i = temp.length;
  5942. while (i--) {
  5943. if (elem = temp[i]) {
  5944. matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
  5945. }
  5946. }
  5947. }
  5948. if (seed) {
  5949. if (postFinder || preFilter) {
  5950. if (postFinder) {
  5951. temp = [];
  5952. i = matcherOut.length;
  5953. while (i--) {
  5954. if (elem = matcherOut[i]) {
  5955. temp.push(matcherIn[i] = elem);
  5956. }
  5957. }
  5958. postFinder(null, matcherOut = [], temp, xml);
  5959. }
  5960. i = matcherOut.length;
  5961. while (i--) {
  5962. if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf.call(seed, elem) : preMap[i]) > -1) {
  5963. seed[temp] = !(results[temp] = elem);
  5964. }
  5965. }
  5966. }
  5967. } else {
  5968. matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
  5969. if (postFinder) {
  5970. postFinder(null, results, matcherOut, xml);
  5971. } else {
  5972. push$1.apply(results, matcherOut);
  5973. }
  5974. }
  5975. });
  5976. }
  5977. function matcherFromTokens(tokens) {
  5978. 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) {
  5979. return elem === checkContext;
  5980. }, implicitRelative, true), matchAnyContext = addCombinator(function (elem) {
  5981. return indexOf.call(checkContext, elem) > -1;
  5982. }, implicitRelative, true), matchers = [function (elem, context, xml) {
  5983. var ret = !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
  5984. checkContext = null;
  5985. return ret;
  5986. }];
  5987. for (; i < len; i++) {
  5988. if (matcher = Expr.relative[tokens[i].type]) {
  5989. matchers = [addCombinator(elementMatcher(matchers), matcher)];
  5990. } else {
  5991. matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);
  5992. if (matcher[expando]) {
  5993. j = ++i;
  5994. for (; j < len; j++) {
  5995. if (Expr.relative[tokens[j].type]) {
  5996. break;
  5997. }
  5998. }
  5999. 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));
  6000. }
  6001. matchers.push(matcher);
  6002. }
  6003. }
  6004. return elementMatcher(matchers);
  6005. }
  6006. function matcherFromGroupMatchers(elementMatchers, setMatchers) {
  6007. var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function (seed, context, xml, results, outermost) {
  6008. 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;
  6009. if (outermost) {
  6010. outermostContext = context !== document$1 && context;
  6011. }
  6012. for (; i !== len && (elem = elems[i]) != null; i++) {
  6013. if (byElement && elem) {
  6014. j = 0;
  6015. while (matcher = elementMatchers[j++]) {
  6016. if (matcher(elem, context, xml)) {
  6017. results.push(elem);
  6018. break;
  6019. }
  6020. }
  6021. if (outermost) {
  6022. dirruns = dirrunsUnique;
  6023. }
  6024. }
  6025. if (bySet) {
  6026. if (elem = !matcher && elem) {
  6027. matchedCount--;
  6028. }
  6029. if (seed) {
  6030. unmatched.push(elem);
  6031. }
  6032. }
  6033. }
  6034. matchedCount += i;
  6035. if (bySet && i !== matchedCount) {
  6036. j = 0;
  6037. while (matcher = setMatchers[j++]) {
  6038. matcher(unmatched, setMatched, context, xml);
  6039. }
  6040. if (seed) {
  6041. if (matchedCount > 0) {
  6042. while (i--) {
  6043. if (!(unmatched[i] || setMatched[i])) {
  6044. setMatched[i] = pop.call(results);
  6045. }
  6046. }
  6047. }
  6048. setMatched = condense(setMatched);
  6049. }
  6050. push$1.apply(results, setMatched);
  6051. if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
  6052. Sizzle.uniqueSort(results);
  6053. }
  6054. }
  6055. if (outermost) {
  6056. dirruns = dirrunsUnique;
  6057. outermostContext = contextBackup;
  6058. }
  6059. return unmatched;
  6060. };
  6061. return bySet ? markFunction(superMatcher) : superMatcher;
  6062. }
  6063. compile = Sizzle.compile = function (selector, match) {
  6064. var i, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + ' '];
  6065. if (!cached) {
  6066. if (!match) {
  6067. match = tokenize(selector);
  6068. }
  6069. i = match.length;
  6070. while (i--) {
  6071. cached = matcherFromTokens(match[i]);
  6072. if (cached[expando]) {
  6073. setMatchers.push(cached);
  6074. } else {
  6075. elementMatchers.push(cached);
  6076. }
  6077. }
  6078. cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
  6079. cached.selector = selector;
  6080. }
  6081. return cached;
  6082. };
  6083. select$1 = Sizzle.select = function (selector, context, results, seed) {
  6084. var i, tokens, token, type, find, compiled = typeof selector === 'function' && selector, match = !seed && tokenize(selector = compiled.selector || selector);
  6085. results = results || [];
  6086. if (match.length === 1) {
  6087. tokens = match[0] = match[0].slice(0);
  6088. if (tokens.length > 2 && (token = tokens[0]).type === 'ID' && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
  6089. context = (Expr.find.ID(token.matches[0].replace(runescape, funescape), context) || [])[0];
  6090. if (!context) {
  6091. return results;
  6092. } else if (compiled) {
  6093. context = context.parentNode;
  6094. }
  6095. selector = selector.slice(tokens.shift().value.length);
  6096. }
  6097. i = matchExpr.needsContext.test(selector) ? 0 : tokens.length;
  6098. while (i--) {
  6099. token = tokens[i];
  6100. if (Expr.relative[type = token.type]) {
  6101. break;
  6102. }
  6103. if (find = Expr.find[type]) {
  6104. if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {
  6105. tokens.splice(i, 1);
  6106. selector = seed.length && toSelector(tokens);
  6107. if (!selector) {
  6108. push$1.apply(results, seed);
  6109. return results;
  6110. }
  6111. break;
  6112. }
  6113. }
  6114. }
  6115. }
  6116. (compiled || compile(selector, match))(seed, context, !documentIsHTML, results, rsibling.test(selector) && testContext(context.parentNode) || context);
  6117. return results;
  6118. };
  6119. support.sortStable = expando.split('').sort(sortOrder).join('') === expando;
  6120. support.detectDuplicates = !!hasDuplicate;
  6121. setDocument();
  6122. support.sortDetached = true;
  6123. var doc = document;
  6124. var push = Array.prototype.push;
  6125. var slice = Array.prototype.slice;
  6126. var rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
  6127. var Event$1 = EventUtils.Event;
  6128. var skipUniques = Tools.makeMap('children,contents,next,prev');
  6129. var isDefined = function (obj) {
  6130. return typeof obj !== 'undefined';
  6131. };
  6132. var isString = function (obj) {
  6133. return typeof obj === 'string';
  6134. };
  6135. var isWindow = function (obj) {
  6136. return obj && obj === obj.window;
  6137. };
  6138. var createFragment$1 = function (html, fragDoc) {
  6139. fragDoc = fragDoc || doc;
  6140. var container = fragDoc.createElement('div');
  6141. var frag = fragDoc.createDocumentFragment();
  6142. container.innerHTML = html;
  6143. var node;
  6144. while (node = container.firstChild) {
  6145. frag.appendChild(node);
  6146. }
  6147. return frag;
  6148. };
  6149. var domManipulate = function (targetNodes, sourceItem, callback, reverse) {
  6150. var i;
  6151. if (isString(sourceItem)) {
  6152. sourceItem = createFragment$1(sourceItem, getElementDocument(targetNodes[0]));
  6153. } else if (sourceItem.length && !sourceItem.nodeType) {
  6154. sourceItem = DomQuery.makeArray(sourceItem);
  6155. if (reverse) {
  6156. for (i = sourceItem.length - 1; i >= 0; i--) {
  6157. domManipulate(targetNodes, sourceItem[i], callback, reverse);
  6158. }
  6159. } else {
  6160. for (i = 0; i < sourceItem.length; i++) {
  6161. domManipulate(targetNodes, sourceItem[i], callback, reverse);
  6162. }
  6163. }
  6164. return targetNodes;
  6165. }
  6166. if (sourceItem.nodeType) {
  6167. i = targetNodes.length;
  6168. while (i--) {
  6169. callback.call(targetNodes[i], sourceItem);
  6170. }
  6171. }
  6172. return targetNodes;
  6173. };
  6174. var hasClass = function (node, className) {
  6175. return node && className && (' ' + node.className + ' ').indexOf(' ' + className + ' ') !== -1;
  6176. };
  6177. var wrap$2 = function (elements, wrapper, all) {
  6178. var lastParent, newWrapper;
  6179. wrapper = DomQuery(wrapper)[0];
  6180. elements.each(function () {
  6181. var self = this;
  6182. if (!all || lastParent !== self.parentNode) {
  6183. lastParent = self.parentNode;
  6184. newWrapper = wrapper.cloneNode(false);
  6185. self.parentNode.insertBefore(newWrapper, self);
  6186. newWrapper.appendChild(self);
  6187. } else {
  6188. newWrapper.appendChild(self);
  6189. }
  6190. });
  6191. return elements;
  6192. };
  6193. var numericCssMap = Tools.makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom', ' ');
  6194. var booleanMap = Tools.makeMap('checked compact declare defer disabled ismap multiple nohref noshade nowrap readonly selected', ' ');
  6195. var propFix = {
  6196. for: 'htmlFor',
  6197. class: 'className',
  6198. readonly: 'readOnly'
  6199. };
  6200. var cssFix = { float: 'cssFloat' };
  6201. var attrHooks = {}, cssHooks = {};
  6202. var DomQueryConstructor = function (selector, context) {
  6203. return new DomQuery.fn.init(selector, context);
  6204. };
  6205. var inArray$1 = function (item, array) {
  6206. var i;
  6207. if (array.indexOf) {
  6208. return array.indexOf(item);
  6209. }
  6210. i = array.length;
  6211. while (i--) {
  6212. if (array[i] === item) {
  6213. return i;
  6214. }
  6215. }
  6216. return -1;
  6217. };
  6218. var whiteSpaceRegExp = /^\s*|\s*$/g;
  6219. var trim$1 = function (str) {
  6220. return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp, '');
  6221. };
  6222. var each$g = function (obj, callback) {
  6223. var length, key, i, value;
  6224. if (obj) {
  6225. length = obj.length;
  6226. if (length === undefined) {
  6227. for (key in obj) {
  6228. if (obj.hasOwnProperty(key)) {
  6229. value = obj[key];
  6230. if (callback.call(value, key, value) === false) {
  6231. break;
  6232. }
  6233. }
  6234. }
  6235. } else {
  6236. for (i = 0; i < length; i++) {
  6237. value = obj[i];
  6238. if (callback.call(value, i, value) === false) {
  6239. break;
  6240. }
  6241. }
  6242. }
  6243. }
  6244. return obj;
  6245. };
  6246. var grep$2 = function (array, callback) {
  6247. var out = [];
  6248. each$g(array, function (i, item) {
  6249. if (callback(item, i)) {
  6250. out.push(item);
  6251. }
  6252. });
  6253. return out;
  6254. };
  6255. var getElementDocument = function (element) {
  6256. if (!element) {
  6257. return doc;
  6258. }
  6259. if (element.nodeType === 9) {
  6260. return element;
  6261. }
  6262. return element.ownerDocument;
  6263. };
  6264. DomQueryConstructor.fn = DomQueryConstructor.prototype = {
  6265. constructor: DomQueryConstructor,
  6266. selector: '',
  6267. context: null,
  6268. length: 0,
  6269. init: function (selector, context) {
  6270. var self = this;
  6271. var match, node;
  6272. if (!selector) {
  6273. return self;
  6274. }
  6275. if (selector.nodeType) {
  6276. self.context = self[0] = selector;
  6277. self.length = 1;
  6278. return self;
  6279. }
  6280. if (context && context.nodeType) {
  6281. self.context = context;
  6282. } else {
  6283. if (context) {
  6284. return DomQuery(selector).attr(context);
  6285. }
  6286. self.context = context = document;
  6287. }
  6288. if (isString(selector)) {
  6289. self.selector = selector;
  6290. if (selector.charAt(0) === '<' && selector.charAt(selector.length - 1) === '>' && selector.length >= 3) {
  6291. match = [
  6292. null,
  6293. selector,
  6294. null
  6295. ];
  6296. } else {
  6297. match = rquickExpr.exec(selector);
  6298. }
  6299. if (match) {
  6300. if (match[1]) {
  6301. node = createFragment$1(selector, getElementDocument(context)).firstChild;
  6302. while (node) {
  6303. push.call(self, node);
  6304. node = node.nextSibling;
  6305. }
  6306. } else {
  6307. node = getElementDocument(context).getElementById(match[2]);
  6308. if (!node) {
  6309. return self;
  6310. }
  6311. if (node.id !== match[2]) {
  6312. return self.find(selector);
  6313. }
  6314. self.length = 1;
  6315. self[0] = node;
  6316. }
  6317. } else {
  6318. return DomQuery(context).find(selector);
  6319. }
  6320. } else {
  6321. this.add(selector, false);
  6322. }
  6323. return self;
  6324. },
  6325. toArray: function () {
  6326. return Tools.toArray(this);
  6327. },
  6328. add: function (items, sort) {
  6329. var self = this;
  6330. var nodes, i;
  6331. if (isString(items)) {
  6332. return self.add(DomQuery(items));
  6333. }
  6334. if (sort !== false) {
  6335. nodes = DomQuery.unique(self.toArray().concat(DomQuery.makeArray(items)));
  6336. self.length = nodes.length;
  6337. for (i = 0; i < nodes.length; i++) {
  6338. self[i] = nodes[i];
  6339. }
  6340. } else {
  6341. push.apply(self, DomQuery.makeArray(items));
  6342. }
  6343. return self;
  6344. },
  6345. attr: function (name, value) {
  6346. var self = this;
  6347. var hook;
  6348. if (typeof name === 'object') {
  6349. each$g(name, function (name, value) {
  6350. self.attr(name, value);
  6351. });
  6352. } else if (isDefined(value)) {
  6353. this.each(function () {
  6354. var hook;
  6355. if (this.nodeType === 1) {
  6356. hook = attrHooks[name];
  6357. if (hook && hook.set) {
  6358. hook.set(this, value);
  6359. return;
  6360. }
  6361. if (value === null) {
  6362. this.removeAttribute(name, 2);
  6363. } else {
  6364. this.setAttribute(name, value, 2);
  6365. }
  6366. }
  6367. });
  6368. } else {
  6369. if (self[0] && self[0].nodeType === 1) {
  6370. hook = attrHooks[name];
  6371. if (hook && hook.get) {
  6372. return hook.get(self[0], name);
  6373. }
  6374. if (booleanMap[name]) {
  6375. return self.prop(name) ? name : undefined;
  6376. }
  6377. value = self[0].getAttribute(name, 2);
  6378. if (value === null) {
  6379. value = undefined;
  6380. }
  6381. }
  6382. return value;
  6383. }
  6384. return self;
  6385. },
  6386. removeAttr: function (name) {
  6387. return this.attr(name, null);
  6388. },
  6389. prop: function (name, value) {
  6390. var self = this;
  6391. name = propFix[name] || name;
  6392. if (typeof name === 'object') {
  6393. each$g(name, function (name, value) {
  6394. self.prop(name, value);
  6395. });
  6396. } else if (isDefined(value)) {
  6397. this.each(function () {
  6398. if (this.nodeType === 1) {
  6399. this[name] = value;
  6400. }
  6401. });
  6402. } else {
  6403. if (self[0] && self[0].nodeType && name in self[0]) {
  6404. return self[0][name];
  6405. }
  6406. return value;
  6407. }
  6408. return self;
  6409. },
  6410. css: function (name, value) {
  6411. var self = this;
  6412. var elm, hook;
  6413. var camel = function (name) {
  6414. return name.replace(/-(\D)/g, function (a, b) {
  6415. return b.toUpperCase();
  6416. });
  6417. };
  6418. var dashed = function (name) {
  6419. return name.replace(/[A-Z]/g, function (a) {
  6420. return '-' + a;
  6421. });
  6422. };
  6423. if (typeof name === 'object') {
  6424. each$g(name, function (name, value) {
  6425. self.css(name, value);
  6426. });
  6427. } else {
  6428. if (isDefined(value)) {
  6429. name = camel(name);
  6430. if (typeof value === 'number' && !numericCssMap[name]) {
  6431. value = value.toString() + 'px';
  6432. }
  6433. self.each(function () {
  6434. var style = this.style;
  6435. hook = cssHooks[name];
  6436. if (hook && hook.set) {
  6437. hook.set(this, value);
  6438. return;
  6439. }
  6440. try {
  6441. this.style[cssFix[name] || name] = value;
  6442. } catch (ex) {
  6443. }
  6444. if (value === null || value === '') {
  6445. if (style.removeProperty) {
  6446. style.removeProperty(dashed(name));
  6447. } else {
  6448. style.removeAttribute(name);
  6449. }
  6450. }
  6451. });
  6452. } else {
  6453. elm = self[0];
  6454. hook = cssHooks[name];
  6455. if (hook && hook.get) {
  6456. return hook.get(elm);
  6457. }
  6458. if (elm.ownerDocument.defaultView) {
  6459. try {
  6460. return elm.ownerDocument.defaultView.getComputedStyle(elm, null).getPropertyValue(dashed(name));
  6461. } catch (ex) {
  6462. return undefined;
  6463. }
  6464. } else if (elm.currentStyle) {
  6465. return elm.currentStyle[camel(name)];
  6466. } else {
  6467. return '';
  6468. }
  6469. }
  6470. }
  6471. return self;
  6472. },
  6473. remove: function () {
  6474. var self = this;
  6475. var node, i = this.length;
  6476. while (i--) {
  6477. node = self[i];
  6478. Event$1.clean(node);
  6479. if (node.parentNode) {
  6480. node.parentNode.removeChild(node);
  6481. }
  6482. }
  6483. return this;
  6484. },
  6485. empty: function () {
  6486. var self = this;
  6487. var node, i = this.length;
  6488. while (i--) {
  6489. node = self[i];
  6490. while (node.firstChild) {
  6491. node.removeChild(node.firstChild);
  6492. }
  6493. }
  6494. return this;
  6495. },
  6496. html: function (value) {
  6497. var self = this;
  6498. var i;
  6499. if (isDefined(value)) {
  6500. i = self.length;
  6501. try {
  6502. while (i--) {
  6503. self[i].innerHTML = value;
  6504. }
  6505. } catch (ex) {
  6506. DomQuery(self[i]).empty().append(value);
  6507. }
  6508. return self;
  6509. }
  6510. return self[0] ? self[0].innerHTML : '';
  6511. },
  6512. text: function (value) {
  6513. var self = this;
  6514. var i;
  6515. if (isDefined(value)) {
  6516. i = self.length;
  6517. while (i--) {
  6518. if ('innerText' in self[i]) {
  6519. self[i].innerText = value;
  6520. } else {
  6521. self[0].textContent = value;
  6522. }
  6523. }
  6524. return self;
  6525. }
  6526. return self[0] ? self[0].innerText || self[0].textContent : '';
  6527. },
  6528. append: function () {
  6529. return domManipulate(this, arguments, function (node) {
  6530. if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6531. this.appendChild(node);
  6532. }
  6533. });
  6534. },
  6535. prepend: function () {
  6536. return domManipulate(this, arguments, function (node) {
  6537. if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6538. this.insertBefore(node, this.firstChild);
  6539. }
  6540. }, true);
  6541. },
  6542. before: function () {
  6543. var self = this;
  6544. if (self[0] && self[0].parentNode) {
  6545. return domManipulate(self, arguments, function (node) {
  6546. this.parentNode.insertBefore(node, this);
  6547. });
  6548. }
  6549. return self;
  6550. },
  6551. after: function () {
  6552. var self = this;
  6553. if (self[0] && self[0].parentNode) {
  6554. return domManipulate(self, arguments, function (node) {
  6555. this.parentNode.insertBefore(node, this.nextSibling);
  6556. }, true);
  6557. }
  6558. return self;
  6559. },
  6560. appendTo: function (val) {
  6561. DomQuery(val).append(this);
  6562. return this;
  6563. },
  6564. prependTo: function (val) {
  6565. DomQuery(val).prepend(this);
  6566. return this;
  6567. },
  6568. replaceWith: function (content) {
  6569. return this.before(content).remove();
  6570. },
  6571. wrap: function (content) {
  6572. return wrap$2(this, content);
  6573. },
  6574. wrapAll: function (content) {
  6575. return wrap$2(this, content, true);
  6576. },
  6577. wrapInner: function (content) {
  6578. this.each(function () {
  6579. DomQuery(this).contents().wrapAll(content);
  6580. });
  6581. return this;
  6582. },
  6583. unwrap: function () {
  6584. return this.parent().each(function () {
  6585. DomQuery(this).replaceWith(this.childNodes);
  6586. });
  6587. },
  6588. clone: function () {
  6589. var result = [];
  6590. this.each(function () {
  6591. result.push(this.cloneNode(true));
  6592. });
  6593. return DomQuery(result);
  6594. },
  6595. addClass: function (className) {
  6596. return this.toggleClass(className, true);
  6597. },
  6598. removeClass: function (className) {
  6599. return this.toggleClass(className, false);
  6600. },
  6601. toggleClass: function (className, state) {
  6602. var self = this;
  6603. if (typeof className !== 'string') {
  6604. return self;
  6605. }
  6606. if (className.indexOf(' ') !== -1) {
  6607. each$g(className.split(' '), function () {
  6608. self.toggleClass(this, state);
  6609. });
  6610. } else {
  6611. self.each(function (index, node) {
  6612. var classState = hasClass(node, className);
  6613. if (classState !== state) {
  6614. var existingClassName = node.className;
  6615. if (classState) {
  6616. node.className = trim$1((' ' + existingClassName + ' ').replace(' ' + className + ' ', ' '));
  6617. } else {
  6618. node.className += existingClassName ? ' ' + className : className;
  6619. }
  6620. }
  6621. });
  6622. }
  6623. return self;
  6624. },
  6625. hasClass: function (className) {
  6626. return hasClass(this[0], className);
  6627. },
  6628. each: function (callback) {
  6629. return each$g(this, callback);
  6630. },
  6631. on: function (name, callback) {
  6632. return this.each(function () {
  6633. Event$1.bind(this, name, callback);
  6634. });
  6635. },
  6636. off: function (name, callback) {
  6637. return this.each(function () {
  6638. Event$1.unbind(this, name, callback);
  6639. });
  6640. },
  6641. trigger: function (name) {
  6642. return this.each(function () {
  6643. if (typeof name === 'object') {
  6644. Event$1.fire(this, name.type, name);
  6645. } else {
  6646. Event$1.fire(this, name);
  6647. }
  6648. });
  6649. },
  6650. show: function () {
  6651. return this.css('display', '');
  6652. },
  6653. hide: function () {
  6654. return this.css('display', 'none');
  6655. },
  6656. slice: function () {
  6657. return DomQuery(slice.apply(this, arguments));
  6658. },
  6659. eq: function (index) {
  6660. return index === -1 ? this.slice(index) : this.slice(index, +index + 1);
  6661. },
  6662. first: function () {
  6663. return this.eq(0);
  6664. },
  6665. last: function () {
  6666. return this.eq(-1);
  6667. },
  6668. find: function (selector) {
  6669. var i, l;
  6670. var ret = [];
  6671. for (i = 0, l = this.length; i < l; i++) {
  6672. DomQuery.find(selector, this[i], ret);
  6673. }
  6674. return DomQuery(ret);
  6675. },
  6676. filter: function (selector) {
  6677. if (typeof selector === 'function') {
  6678. return DomQuery(grep$2(this.toArray(), function (item, i) {
  6679. return selector(i, item);
  6680. }));
  6681. }
  6682. return DomQuery(DomQuery.filter(selector, this.toArray()));
  6683. },
  6684. closest: function (selector) {
  6685. var result = [];
  6686. if (selector instanceof DomQuery) {
  6687. selector = selector[0];
  6688. }
  6689. this.each(function (i, node) {
  6690. while (node) {
  6691. if (typeof selector === 'string' && DomQuery(node).is(selector)) {
  6692. result.push(node);
  6693. break;
  6694. } else if (node === selector) {
  6695. result.push(node);
  6696. break;
  6697. }
  6698. node = node.parentNode;
  6699. }
  6700. });
  6701. return DomQuery(result);
  6702. },
  6703. offset: function (offset) {
  6704. var elm, doc, docElm;
  6705. var x = 0, y = 0, pos;
  6706. if (!offset) {
  6707. elm = this[0];
  6708. if (elm) {
  6709. doc = elm.ownerDocument;
  6710. docElm = doc.documentElement;
  6711. if (elm.getBoundingClientRect) {
  6712. pos = elm.getBoundingClientRect();
  6713. x = pos.left + (docElm.scrollLeft || doc.body.scrollLeft) - docElm.clientLeft;
  6714. y = pos.top + (docElm.scrollTop || doc.body.scrollTop) - docElm.clientTop;
  6715. }
  6716. }
  6717. return {
  6718. left: x,
  6719. top: y
  6720. };
  6721. }
  6722. return this.css(offset);
  6723. },
  6724. push: push,
  6725. sort: Array.prototype.sort,
  6726. splice: Array.prototype.splice
  6727. };
  6728. Tools.extend(DomQueryConstructor, {
  6729. extend: Tools.extend,
  6730. makeArray: function (object) {
  6731. if (isWindow(object) || object.nodeType) {
  6732. return [object];
  6733. }
  6734. return Tools.toArray(object);
  6735. },
  6736. inArray: inArray$1,
  6737. isArray: Tools.isArray,
  6738. each: each$g,
  6739. trim: trim$1,
  6740. grep: grep$2,
  6741. find: Sizzle,
  6742. expr: Sizzle.selectors,
  6743. unique: Sizzle.uniqueSort,
  6744. text: Sizzle.getText,
  6745. contains: Sizzle.contains,
  6746. filter: function (expr, elems, not) {
  6747. var i = elems.length;
  6748. if (not) {
  6749. expr = ':not(' + expr + ')';
  6750. }
  6751. while (i--) {
  6752. if (elems[i].nodeType !== 1) {
  6753. elems.splice(i, 1);
  6754. }
  6755. }
  6756. if (elems.length === 1) {
  6757. elems = DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [];
  6758. } else {
  6759. elems = DomQuery.find.matches(expr, elems);
  6760. }
  6761. return elems;
  6762. }
  6763. });
  6764. var dir = function (el, prop, until) {
  6765. var matched = [];
  6766. var cur = el[prop];
  6767. if (typeof until !== 'string' && until instanceof DomQuery) {
  6768. until = until[0];
  6769. }
  6770. while (cur && cur.nodeType !== 9) {
  6771. if (until !== undefined) {
  6772. if (cur === until) {
  6773. break;
  6774. }
  6775. if (typeof until === 'string' && DomQuery(cur).is(until)) {
  6776. break;
  6777. }
  6778. }
  6779. if (cur.nodeType === 1) {
  6780. matched.push(cur);
  6781. }
  6782. cur = cur[prop];
  6783. }
  6784. return matched;
  6785. };
  6786. var sibling$1 = function (node, siblingName, nodeType, until) {
  6787. var result = [];
  6788. if (until instanceof DomQuery) {
  6789. until = until[0];
  6790. }
  6791. for (; node; node = node[siblingName]) {
  6792. if (nodeType && node.nodeType !== nodeType) {
  6793. continue;
  6794. }
  6795. if (until !== undefined) {
  6796. if (node === until) {
  6797. break;
  6798. }
  6799. if (typeof until === 'string' && DomQuery(node).is(until)) {
  6800. break;
  6801. }
  6802. }
  6803. result.push(node);
  6804. }
  6805. return result;
  6806. };
  6807. var firstSibling = function (node, siblingName, nodeType) {
  6808. for (node = node[siblingName]; node; node = node[siblingName]) {
  6809. if (node.nodeType === nodeType) {
  6810. return node;
  6811. }
  6812. }
  6813. return null;
  6814. };
  6815. each$g({
  6816. parent: function (node) {
  6817. var parent = node.parentNode;
  6818. return parent && parent.nodeType !== 11 ? parent : null;
  6819. },
  6820. parents: function (node) {
  6821. return dir(node, 'parentNode');
  6822. },
  6823. next: function (node) {
  6824. return firstSibling(node, 'nextSibling', 1);
  6825. },
  6826. prev: function (node) {
  6827. return firstSibling(node, 'previousSibling', 1);
  6828. },
  6829. children: function (node) {
  6830. return sibling$1(node.firstChild, 'nextSibling', 1);
  6831. },
  6832. contents: function (node) {
  6833. return Tools.toArray((node.nodeName === 'iframe' ? node.contentDocument || node.contentWindow.document : node).childNodes);
  6834. }
  6835. }, function (name, fn) {
  6836. DomQueryConstructor.fn[name] = function (selector) {
  6837. var self = this;
  6838. var result = [];
  6839. self.each(function () {
  6840. var nodes = fn.call(result, this, selector, result);
  6841. if (nodes) {
  6842. if (DomQuery.isArray(nodes)) {
  6843. result.push.apply(result, nodes);
  6844. } else {
  6845. result.push(nodes);
  6846. }
  6847. }
  6848. });
  6849. if (this.length > 1) {
  6850. if (!skipUniques[name]) {
  6851. result = DomQuery.unique(result);
  6852. }
  6853. if (name.indexOf('parents') === 0) {
  6854. result = result.reverse();
  6855. }
  6856. }
  6857. var wrappedResult = DomQuery(result);
  6858. if (selector) {
  6859. return wrappedResult.filter(selector);
  6860. }
  6861. return wrappedResult;
  6862. };
  6863. });
  6864. each$g({
  6865. parentsUntil: function (node, until) {
  6866. return dir(node, 'parentNode', until);
  6867. },
  6868. nextUntil: function (node, until) {
  6869. return sibling$1(node, 'nextSibling', 1, until).slice(1);
  6870. },
  6871. prevUntil: function (node, until) {
  6872. return sibling$1(node, 'previousSibling', 1, until).slice(1);
  6873. }
  6874. }, function (name, fn) {
  6875. DomQueryConstructor.fn[name] = function (selector, filter) {
  6876. var self = this;
  6877. var result = [];
  6878. self.each(function () {
  6879. var nodes = fn.call(result, this, selector, result);
  6880. if (nodes) {
  6881. if (DomQuery.isArray(nodes)) {
  6882. result.push.apply(result, nodes);
  6883. } else {
  6884. result.push(nodes);
  6885. }
  6886. }
  6887. });
  6888. if (this.length > 1) {
  6889. result = DomQuery.unique(result);
  6890. if (name.indexOf('parents') === 0 || name === 'prevUntil') {
  6891. result = result.reverse();
  6892. }
  6893. }
  6894. var wrappedResult = DomQuery(result);
  6895. if (filter) {
  6896. return wrappedResult.filter(filter);
  6897. }
  6898. return wrappedResult;
  6899. };
  6900. });
  6901. DomQueryConstructor.fn.is = function (selector) {
  6902. return !!selector && this.filter(selector).length > 0;
  6903. };
  6904. DomQueryConstructor.fn.init.prototype = DomQueryConstructor.fn;
  6905. DomQueryConstructor.overrideDefaults = function (callback) {
  6906. var defaults;
  6907. var sub = function (selector, context) {
  6908. defaults = defaults || callback();
  6909. if (arguments.length === 0) {
  6910. selector = defaults.element;
  6911. }
  6912. if (!context) {
  6913. context = defaults.context;
  6914. }
  6915. return new sub.fn.init(selector, context);
  6916. };
  6917. DomQuery.extend(sub, this);
  6918. return sub;
  6919. };
  6920. DomQueryConstructor.attrHooks = attrHooks;
  6921. DomQueryConstructor.cssHooks = cssHooks;
  6922. var DomQuery = DomQueryConstructor;
  6923. var each$f = Tools.each;
  6924. var grep$1 = Tools.grep;
  6925. var isIE = Env.ie;
  6926. var simpleSelectorRe = /^([a-z0-9],?)+$/i;
  6927. var setupAttrHooks = function (styles, settings, getContext) {
  6928. var keepValues = settings.keep_values;
  6929. var keepUrlHook = {
  6930. set: function ($elm, value, name) {
  6931. if (settings.url_converter) {
  6932. value = settings.url_converter.call(settings.url_converter_scope || getContext(), value, name, $elm[0]);
  6933. }
  6934. $elm.attr('data-mce-' + name, value).attr(name, value);
  6935. },
  6936. get: function ($elm, name) {
  6937. return $elm.attr('data-mce-' + name) || $elm.attr(name);
  6938. }
  6939. };
  6940. var attrHooks = {
  6941. style: {
  6942. set: function ($elm, value) {
  6943. if (value !== null && typeof value === 'object') {
  6944. $elm.css(value);
  6945. return;
  6946. }
  6947. if (keepValues) {
  6948. $elm.attr('data-mce-style', value);
  6949. }
  6950. if (value !== null && typeof value === 'string') {
  6951. $elm.removeAttr('style');
  6952. $elm.css(styles.parse(value));
  6953. } else {
  6954. $elm.attr('style', value);
  6955. }
  6956. },
  6957. get: function ($elm) {
  6958. var value = $elm.attr('data-mce-style') || $elm.attr('style');
  6959. value = styles.serialize(styles.parse(value), $elm[0].nodeName);
  6960. return value;
  6961. }
  6962. }
  6963. };
  6964. if (keepValues) {
  6965. attrHooks.href = attrHooks.src = keepUrlHook;
  6966. }
  6967. return attrHooks;
  6968. };
  6969. var updateInternalStyleAttr = function (styles, $elm) {
  6970. var rawValue = $elm.attr('style');
  6971. var value = styles.serialize(styles.parse(rawValue), $elm[0].nodeName);
  6972. if (!value) {
  6973. value = null;
  6974. }
  6975. $elm.attr('data-mce-style', value);
  6976. };
  6977. var findNodeIndex = function (node, normalized) {
  6978. var idx = 0, lastNodeType, nodeType;
  6979. if (node) {
  6980. for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
  6981. nodeType = node.nodeType;
  6982. if (normalized && nodeType === 3) {
  6983. if (nodeType === lastNodeType || !node.nodeValue.length) {
  6984. continue;
  6985. }
  6986. }
  6987. idx++;
  6988. lastNodeType = nodeType;
  6989. }
  6990. }
  6991. return idx;
  6992. };
  6993. var DOMUtils = function (doc, settings) {
  6994. if (settings === void 0) {
  6995. settings = {};
  6996. }
  6997. var addedStyles = {};
  6998. var win = window;
  6999. var files = {};
  7000. var counter = 0;
  7001. var stdMode = true;
  7002. var boxModel = true;
  7003. var styleSheetLoader = instance.forElement(SugarElement.fromDom(doc), {
  7004. contentCssCors: settings.contentCssCors,
  7005. referrerPolicy: settings.referrerPolicy
  7006. });
  7007. var boundEvents = [];
  7008. var schema = settings.schema ? settings.schema : Schema({});
  7009. var styles = Styles({
  7010. url_converter: settings.url_converter,
  7011. url_converter_scope: settings.url_converter_scope
  7012. }, settings.schema);
  7013. var events = settings.ownEvents ? new EventUtils() : EventUtils.Event;
  7014. var blockElementsMap = schema.getBlockElements();
  7015. var $ = DomQuery.overrideDefaults(function () {
  7016. return {
  7017. context: doc,
  7018. element: self.getRoot()
  7019. };
  7020. });
  7021. var isBlock = function (node) {
  7022. if (typeof node === 'string') {
  7023. return !!blockElementsMap[node];
  7024. } else if (node) {
  7025. var type = node.nodeType;
  7026. if (type) {
  7027. return !!(type === 1 && blockElementsMap[node.nodeName]);
  7028. }
  7029. }
  7030. return false;
  7031. };
  7032. var get = function (elm) {
  7033. return elm && doc && isString$1(elm) ? doc.getElementById(elm) : elm;
  7034. };
  7035. var $$ = function (elm) {
  7036. return $(typeof elm === 'string' ? get(elm) : elm);
  7037. };
  7038. var getAttrib = function (elm, name, defaultVal) {
  7039. var hook, value;
  7040. var $elm = $$(elm);
  7041. if ($elm.length) {
  7042. hook = attrHooks[name];
  7043. if (hook && hook.get) {
  7044. value = hook.get($elm, name);
  7045. } else {
  7046. value = $elm.attr(name);
  7047. }
  7048. }
  7049. if (typeof value === 'undefined') {
  7050. value = defaultVal || '';
  7051. }
  7052. return value;
  7053. };
  7054. var getAttribs = function (elm) {
  7055. var node = get(elm);
  7056. if (!node) {
  7057. return [];
  7058. }
  7059. return node.attributes;
  7060. };
  7061. var setAttrib = function (elm, name, value) {
  7062. if (value === '') {
  7063. value = null;
  7064. }
  7065. var $elm = $$(elm);
  7066. var originalValue = $elm.attr(name);
  7067. if (!$elm.length) {
  7068. return;
  7069. }
  7070. var hook = attrHooks[name];
  7071. if (hook && hook.set) {
  7072. hook.set($elm, value, name);
  7073. } else {
  7074. $elm.attr(name, value);
  7075. }
  7076. if (originalValue !== value && settings.onSetAttrib) {
  7077. settings.onSetAttrib({
  7078. attrElm: $elm,
  7079. attrName: name,
  7080. attrValue: value
  7081. });
  7082. }
  7083. };
  7084. var clone = function (node, deep) {
  7085. if (!isIE || node.nodeType !== 1 || deep) {
  7086. return node.cloneNode(deep);
  7087. } else {
  7088. var clone_1 = doc.createElement(node.nodeName);
  7089. each$f(getAttribs(node), function (attr) {
  7090. setAttrib(clone_1, attr.nodeName, getAttrib(node, attr.nodeName));
  7091. });
  7092. return clone_1;
  7093. }
  7094. };
  7095. var getRoot = function () {
  7096. return settings.root_element || doc.body;
  7097. };
  7098. var getViewPort = function (argWin) {
  7099. var vp = getBounds(argWin);
  7100. return {
  7101. x: vp.x,
  7102. y: vp.y,
  7103. w: vp.width,
  7104. h: vp.height
  7105. };
  7106. };
  7107. var getPos$1 = function (elm, rootElm) {
  7108. return getPos(doc.body, get(elm), rootElm);
  7109. };
  7110. var setStyle = function (elm, name, value) {
  7111. var $elm = isString$1(name) ? $$(elm).css(name, value) : $$(elm).css(name);
  7112. if (settings.update_styles) {
  7113. updateInternalStyleAttr(styles, $elm);
  7114. }
  7115. };
  7116. var setStyles = function (elm, stylesArg) {
  7117. var $elm = $$(elm).css(stylesArg);
  7118. if (settings.update_styles) {
  7119. updateInternalStyleAttr(styles, $elm);
  7120. }
  7121. };
  7122. var getStyle = function (elm, name, computed) {
  7123. var $elm = $$(elm);
  7124. if (computed) {
  7125. return $elm.css(name);
  7126. }
  7127. name = name.replace(/-(\D)/g, function (a, b) {
  7128. return b.toUpperCase();
  7129. });
  7130. if (name === 'float') {
  7131. name = Env.browser.isIE() ? 'styleFloat' : 'cssFloat';
  7132. }
  7133. return $elm[0] && $elm[0].style ? $elm[0].style[name] : undefined;
  7134. };
  7135. var getSize = function (elm) {
  7136. var w, h;
  7137. elm = get(elm);
  7138. w = getStyle(elm, 'width');
  7139. h = getStyle(elm, 'height');
  7140. if (w.indexOf('px') === -1) {
  7141. w = 0;
  7142. }
  7143. if (h.indexOf('px') === -1) {
  7144. h = 0;
  7145. }
  7146. return {
  7147. w: parseInt(w, 10) || elm.offsetWidth || elm.clientWidth,
  7148. h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight
  7149. };
  7150. };
  7151. var getRect = function (elm) {
  7152. elm = get(elm);
  7153. var pos = getPos$1(elm);
  7154. var size = getSize(elm);
  7155. return {
  7156. x: pos.x,
  7157. y: pos.y,
  7158. w: size.w,
  7159. h: size.h
  7160. };
  7161. };
  7162. var is = function (elm, selector) {
  7163. var i;
  7164. if (!elm) {
  7165. return false;
  7166. }
  7167. if (!Array.isArray(elm)) {
  7168. if (selector === '*') {
  7169. return elm.nodeType === 1;
  7170. }
  7171. if (simpleSelectorRe.test(selector)) {
  7172. var selectors = selector.toLowerCase().split(/,/);
  7173. var elmName = elm.nodeName.toLowerCase();
  7174. for (i = selectors.length - 1; i >= 0; i--) {
  7175. if (selectors[i] === elmName) {
  7176. return true;
  7177. }
  7178. }
  7179. return false;
  7180. }
  7181. if (elm.nodeType && elm.nodeType !== 1) {
  7182. return false;
  7183. }
  7184. }
  7185. var elms = !Array.isArray(elm) ? [elm] : elm;
  7186. return Sizzle(selector, elms[0].ownerDocument || elms[0], null, elms).length > 0;
  7187. };
  7188. var getParents = function (elm, selector, root, collect) {
  7189. var result = [];
  7190. var selectorVal;
  7191. var node = get(elm);
  7192. collect = collect === undefined;
  7193. root = root || (getRoot().nodeName !== 'BODY' ? getRoot().parentNode : null);
  7194. if (Tools.is(selector, 'string')) {
  7195. selectorVal = selector;
  7196. if (selector === '*') {
  7197. selector = function (node) {
  7198. return node.nodeType === 1;
  7199. };
  7200. } else {
  7201. selector = function (node) {
  7202. return is(node, selectorVal);
  7203. };
  7204. }
  7205. }
  7206. while (node) {
  7207. if (node === root || isNullable(node.nodeType) || isDocument$1(node) || isDocumentFragment(node)) {
  7208. break;
  7209. }
  7210. if (!selector || typeof selector === 'function' && selector(node)) {
  7211. if (collect) {
  7212. result.push(node);
  7213. } else {
  7214. return [node];
  7215. }
  7216. }
  7217. node = node.parentNode;
  7218. }
  7219. return collect ? result : null;
  7220. };
  7221. var getParent = function (node, selector, root) {
  7222. var parents = getParents(node, selector, root, false);
  7223. return parents && parents.length > 0 ? parents[0] : null;
  7224. };
  7225. var _findSib = function (node, selector, name) {
  7226. var func = selector;
  7227. if (node) {
  7228. if (typeof selector === 'string') {
  7229. func = function (node) {
  7230. return is(node, selector);
  7231. };
  7232. }
  7233. for (node = node[name]; node; node = node[name]) {
  7234. if (typeof func === 'function' && func(node)) {
  7235. return node;
  7236. }
  7237. }
  7238. }
  7239. return null;
  7240. };
  7241. var getNext = function (node, selector) {
  7242. return _findSib(node, selector, 'nextSibling');
  7243. };
  7244. var getPrev = function (node, selector) {
  7245. return _findSib(node, selector, 'previousSibling');
  7246. };
  7247. var select = function (selector, scope) {
  7248. return Sizzle(selector, get(scope) || settings.root_element || doc, []);
  7249. };
  7250. var run = function (elm, func, scope) {
  7251. var result;
  7252. var node = typeof elm === 'string' ? get(elm) : elm;
  7253. if (!node) {
  7254. return false;
  7255. }
  7256. if (Tools.isArray(node) && (node.length || node.length === 0)) {
  7257. result = [];
  7258. each$f(node, function (elm, i) {
  7259. if (elm) {
  7260. result.push(func.call(scope, typeof elm === 'string' ? get(elm) : elm, i));
  7261. }
  7262. });
  7263. return result;
  7264. }
  7265. var context = scope ? scope : this;
  7266. return func.call(context, node);
  7267. };
  7268. var setAttribs = function (elm, attrs) {
  7269. $$(elm).each(function (i, node) {
  7270. each$f(attrs, function (value, name) {
  7271. setAttrib(node, name, value);
  7272. });
  7273. });
  7274. };
  7275. var setHTML = function (elm, html) {
  7276. var $elm = $$(elm);
  7277. if (isIE) {
  7278. $elm.each(function (i, target) {
  7279. if (target.canHaveHTML === false) {
  7280. return;
  7281. }
  7282. while (target.firstChild) {
  7283. target.removeChild(target.firstChild);
  7284. }
  7285. try {
  7286. target.innerHTML = '<br>' + html;
  7287. target.removeChild(target.firstChild);
  7288. } catch (ex) {
  7289. DomQuery('<div></div>').html('<br>' + html).contents().slice(1).appendTo(target);
  7290. }
  7291. return html;
  7292. });
  7293. } else {
  7294. $elm.html(html);
  7295. }
  7296. };
  7297. var add = function (parentElm, name, attrs, html, create) {
  7298. return run(parentElm, function (parentElm) {
  7299. var newElm = typeof name === 'string' ? doc.createElement(name) : name;
  7300. setAttribs(newElm, attrs);
  7301. if (html) {
  7302. if (typeof html !== 'string' && html.nodeType) {
  7303. newElm.appendChild(html);
  7304. } else if (typeof html === 'string') {
  7305. setHTML(newElm, html);
  7306. }
  7307. }
  7308. return !create ? parentElm.appendChild(newElm) : newElm;
  7309. });
  7310. };
  7311. var create = function (name, attrs, html) {
  7312. return add(doc.createElement(name), name, attrs, html, true);
  7313. };
  7314. var decode = Entities.decode;
  7315. var encode = Entities.encodeAllRaw;
  7316. var createHTML = function (name, attrs, html) {
  7317. var outHtml = '', key;
  7318. outHtml += '<' + name;
  7319. for (key in attrs) {
  7320. if (hasNonNullableKey(attrs, key)) {
  7321. outHtml += ' ' + key + '="' + encode(attrs[key]) + '"';
  7322. }
  7323. }
  7324. if (typeof html !== 'undefined') {
  7325. return outHtml + '>' + html + '</' + name + '>';
  7326. }
  7327. return outHtml + ' />';
  7328. };
  7329. var createFragment = function (html) {
  7330. var node;
  7331. var container = doc.createElement('div');
  7332. var frag = doc.createDocumentFragment();
  7333. frag.appendChild(container);
  7334. if (html) {
  7335. container.innerHTML = html;
  7336. }
  7337. while (node = container.firstChild) {
  7338. frag.appendChild(node);
  7339. }
  7340. frag.removeChild(container);
  7341. return frag;
  7342. };
  7343. var remove = function (node, keepChildren) {
  7344. var $node = $$(node);
  7345. if (keepChildren) {
  7346. $node.each(function () {
  7347. var child;
  7348. while (child = this.firstChild) {
  7349. if (child.nodeType === 3 && child.data.length === 0) {
  7350. this.removeChild(child);
  7351. } else {
  7352. this.parentNode.insertBefore(child, this);
  7353. }
  7354. }
  7355. }).remove();
  7356. } else {
  7357. $node.remove();
  7358. }
  7359. return $node.length > 1 ? $node.toArray() : $node[0];
  7360. };
  7361. var removeAllAttribs = function (e) {
  7362. return run(e, function (e) {
  7363. var i;
  7364. var attrs = e.attributes;
  7365. for (i = attrs.length - 1; i >= 0; i--) {
  7366. e.removeAttributeNode(attrs.item(i));
  7367. }
  7368. });
  7369. };
  7370. var parseStyle = function (cssText) {
  7371. return styles.parse(cssText);
  7372. };
  7373. var serializeStyle = function (stylesArg, name) {
  7374. return styles.serialize(stylesArg, name);
  7375. };
  7376. var addStyle = function (cssText) {
  7377. var head, styleElm;
  7378. if (self !== DOMUtils.DOM && doc === document) {
  7379. if (addedStyles[cssText]) {
  7380. return;
  7381. }
  7382. addedStyles[cssText] = true;
  7383. }
  7384. styleElm = doc.getElementById('mceDefaultStyles');
  7385. if (!styleElm) {
  7386. styleElm = doc.createElement('style');
  7387. styleElm.id = 'mceDefaultStyles';
  7388. styleElm.type = 'text/css';
  7389. head = doc.getElementsByTagName('head')[0];
  7390. if (head.firstChild) {
  7391. head.insertBefore(styleElm, head.firstChild);
  7392. } else {
  7393. head.appendChild(styleElm);
  7394. }
  7395. }
  7396. if (styleElm.styleSheet) {
  7397. styleElm.styleSheet.cssText += cssText;
  7398. } else {
  7399. styleElm.appendChild(doc.createTextNode(cssText));
  7400. }
  7401. };
  7402. var loadCSS = function (urls) {
  7403. if (!urls) {
  7404. urls = '';
  7405. }
  7406. each$k(urls.split(','), function (url) {
  7407. files[url] = true;
  7408. styleSheetLoader.load(url, noop);
  7409. });
  7410. };
  7411. var toggleClass = function (elm, cls, state) {
  7412. $$(elm).toggleClass(cls, state).each(function () {
  7413. if (this.className === '') {
  7414. DomQuery(this).attr('class', null);
  7415. }
  7416. });
  7417. };
  7418. var addClass = function (elm, cls) {
  7419. $$(elm).addClass(cls);
  7420. };
  7421. var removeClass = function (elm, cls) {
  7422. toggleClass(elm, cls, false);
  7423. };
  7424. var hasClass = function (elm, cls) {
  7425. return $$(elm).hasClass(cls);
  7426. };
  7427. var show = function (elm) {
  7428. $$(elm).show();
  7429. };
  7430. var hide = function (elm) {
  7431. $$(elm).hide();
  7432. };
  7433. var isHidden = function (elm) {
  7434. return $$(elm).css('display') === 'none';
  7435. };
  7436. var uniqueId = function (prefix) {
  7437. return (!prefix ? 'mce_' : prefix) + counter++;
  7438. };
  7439. var getOuterHTML = function (elm) {
  7440. var node = typeof elm === 'string' ? get(elm) : elm;
  7441. return isElement$5(node) ? node.outerHTML : DomQuery('<div></div>').append(DomQuery(node).clone()).html();
  7442. };
  7443. var setOuterHTML = function (elm, html) {
  7444. $$(elm).each(function () {
  7445. try {
  7446. if ('outerHTML' in this) {
  7447. this.outerHTML = html;
  7448. return;
  7449. }
  7450. } catch (ex) {
  7451. }
  7452. remove(DomQuery(this).html(html), true);
  7453. });
  7454. };
  7455. var insertAfter = function (node, reference) {
  7456. var referenceNode = get(reference);
  7457. return run(node, function (node) {
  7458. var parent = referenceNode.parentNode;
  7459. var nextSibling = referenceNode.nextSibling;
  7460. if (nextSibling) {
  7461. parent.insertBefore(node, nextSibling);
  7462. } else {
  7463. parent.appendChild(node);
  7464. }
  7465. return node;
  7466. });
  7467. };
  7468. var replace = function (newElm, oldElm, keepChildren) {
  7469. return run(oldElm, function (oldElm) {
  7470. if (Tools.is(oldElm, 'array')) {
  7471. newElm = newElm.cloneNode(true);
  7472. }
  7473. if (keepChildren) {
  7474. each$f(grep$1(oldElm.childNodes), function (node) {
  7475. newElm.appendChild(node);
  7476. });
  7477. }
  7478. return oldElm.parentNode.replaceChild(newElm, oldElm);
  7479. });
  7480. };
  7481. var rename = function (elm, name) {
  7482. var newElm;
  7483. if (elm.nodeName !== name.toUpperCase()) {
  7484. newElm = create(name);
  7485. each$f(getAttribs(elm), function (attrNode) {
  7486. setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
  7487. });
  7488. replace(newElm, elm, true);
  7489. }
  7490. return newElm || elm;
  7491. };
  7492. var findCommonAncestor = function (a, b) {
  7493. var ps = a, pe;
  7494. while (ps) {
  7495. pe = b;
  7496. while (pe && ps !== pe) {
  7497. pe = pe.parentNode;
  7498. }
  7499. if (ps === pe) {
  7500. break;
  7501. }
  7502. ps = ps.parentNode;
  7503. }
  7504. if (!ps && a.ownerDocument) {
  7505. return a.ownerDocument.documentElement;
  7506. }
  7507. return ps;
  7508. };
  7509. var toHex = function (rgbVal) {
  7510. return styles.toHex(Tools.trim(rgbVal));
  7511. };
  7512. var isNonEmptyElement = function (node) {
  7513. if (isElement$5(node)) {
  7514. var isNamedAnchor = node.nodeName.toLowerCase() === 'a' && !getAttrib(node, 'href') && getAttrib(node, 'id');
  7515. if (getAttrib(node, 'name') || getAttrib(node, 'data-mce-bookmark') || isNamedAnchor) {
  7516. return true;
  7517. }
  7518. }
  7519. return false;
  7520. };
  7521. var isEmpty = function (node, elements) {
  7522. var type, name, brCount = 0;
  7523. if (isNonEmptyElement(node)) {
  7524. return false;
  7525. }
  7526. node = node.firstChild;
  7527. if (node) {
  7528. var walker = new DomTreeWalker(node, node.parentNode);
  7529. var whitespace = schema ? schema.getWhiteSpaceElements() : {};
  7530. elements = elements || (schema ? schema.getNonEmptyElements() : null);
  7531. do {
  7532. type = node.nodeType;
  7533. if (isElement$5(node)) {
  7534. var bogusVal = node.getAttribute('data-mce-bogus');
  7535. if (bogusVal) {
  7536. node = walker.next(bogusVal === 'all');
  7537. continue;
  7538. }
  7539. name = node.nodeName.toLowerCase();
  7540. if (elements && elements[name]) {
  7541. if (name === 'br') {
  7542. brCount++;
  7543. node = walker.next();
  7544. continue;
  7545. }
  7546. return false;
  7547. }
  7548. if (isNonEmptyElement(node)) {
  7549. return false;
  7550. }
  7551. }
  7552. if (type === 8) {
  7553. return false;
  7554. }
  7555. if (type === 3 && !isWhitespaceText(node.nodeValue)) {
  7556. return false;
  7557. }
  7558. if (type === 3 && node.parentNode && whitespace[node.parentNode.nodeName] && isWhitespaceText(node.nodeValue)) {
  7559. return false;
  7560. }
  7561. node = walker.next();
  7562. } while (node);
  7563. }
  7564. return brCount <= 1;
  7565. };
  7566. var createRng = function () {
  7567. return doc.createRange();
  7568. };
  7569. var split = function (parentElm, splitElm, replacementElm) {
  7570. var range = createRng();
  7571. var beforeFragment;
  7572. var afterFragment;
  7573. var parentNode;
  7574. if (parentElm && splitElm) {
  7575. range.setStart(parentElm.parentNode, findNodeIndex(parentElm));
  7576. range.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
  7577. beforeFragment = range.extractContents();
  7578. range = createRng();
  7579. range.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
  7580. range.setEnd(parentElm.parentNode, findNodeIndex(parentElm) + 1);
  7581. afterFragment = range.extractContents();
  7582. parentNode = parentElm.parentNode;
  7583. parentNode.insertBefore(trimNode(self, beforeFragment), parentElm);
  7584. if (replacementElm) {
  7585. parentNode.insertBefore(replacementElm, parentElm);
  7586. } else {
  7587. parentNode.insertBefore(splitElm, parentElm);
  7588. }
  7589. parentNode.insertBefore(trimNode(self, afterFragment), parentElm);
  7590. remove(parentElm);
  7591. return replacementElm || splitElm;
  7592. }
  7593. };
  7594. var bind = function (target, name, func, scope) {
  7595. if (Tools.isArray(target)) {
  7596. var i = target.length;
  7597. var rv = [];
  7598. while (i--) {
  7599. rv[i] = bind(target[i], name, func, scope);
  7600. }
  7601. return rv;
  7602. }
  7603. if (settings.collect && (target === doc || target === win)) {
  7604. boundEvents.push([
  7605. target,
  7606. name,
  7607. func,
  7608. scope
  7609. ]);
  7610. }
  7611. var output = events.bind(target, name, func, scope || self);
  7612. return output;
  7613. };
  7614. var unbind = function (target, name, func) {
  7615. if (Tools.isArray(target)) {
  7616. var i = target.length;
  7617. var rv = [];
  7618. while (i--) {
  7619. rv[i] = unbind(target[i], name, func);
  7620. }
  7621. return rv;
  7622. } else {
  7623. if (boundEvents.length > 0 && (target === doc || target === win)) {
  7624. var i = boundEvents.length;
  7625. while (i--) {
  7626. var item = boundEvents[i];
  7627. if (target === item[0] && (!name || name === item[1]) && (!func || func === item[2])) {
  7628. events.unbind(item[0], item[1], item[2]);
  7629. }
  7630. }
  7631. }
  7632. return events.unbind(target, name, func);
  7633. }
  7634. };
  7635. var fire = function (target, name, evt) {
  7636. return events.fire(target, name, evt);
  7637. };
  7638. var getContentEditable = function (node) {
  7639. if (node && isElement$5(node)) {
  7640. var contentEditable = node.getAttribute('data-mce-contenteditable');
  7641. if (contentEditable && contentEditable !== 'inherit') {
  7642. return contentEditable;
  7643. }
  7644. return node.contentEditable !== 'inherit' ? node.contentEditable : null;
  7645. } else {
  7646. return null;
  7647. }
  7648. };
  7649. var getContentEditableParent = function (node) {
  7650. var root = getRoot();
  7651. var state = null;
  7652. for (; node && node !== root; node = node.parentNode) {
  7653. state = getContentEditable(node);
  7654. if (state !== null) {
  7655. break;
  7656. }
  7657. }
  7658. return state;
  7659. };
  7660. var destroy = function () {
  7661. if (boundEvents.length > 0) {
  7662. var i = boundEvents.length;
  7663. while (i--) {
  7664. var item = boundEvents[i];
  7665. events.unbind(item[0], item[1], item[2]);
  7666. }
  7667. }
  7668. each$j(files, function (_, url) {
  7669. styleSheetLoader.unload(url);
  7670. delete files[url];
  7671. });
  7672. if (Sizzle.setDocument) {
  7673. Sizzle.setDocument();
  7674. }
  7675. };
  7676. var isChildOf = function (node, parent) {
  7677. if (!isIE) {
  7678. return node === parent || parent.contains(node);
  7679. } else {
  7680. while (node) {
  7681. if (parent === node) {
  7682. return true;
  7683. }
  7684. node = node.parentNode;
  7685. }
  7686. return false;
  7687. }
  7688. };
  7689. var dumpRng = function (r) {
  7690. return 'startContainer: ' + r.startContainer.nodeName + ', startOffset: ' + r.startOffset + ', endContainer: ' + r.endContainer.nodeName + ', endOffset: ' + r.endOffset;
  7691. };
  7692. var self = {
  7693. doc: doc,
  7694. settings: settings,
  7695. win: win,
  7696. files: files,
  7697. stdMode: stdMode,
  7698. boxModel: boxModel,
  7699. styleSheetLoader: styleSheetLoader,
  7700. boundEvents: boundEvents,
  7701. styles: styles,
  7702. schema: schema,
  7703. events: events,
  7704. isBlock: isBlock,
  7705. $: $,
  7706. $$: $$,
  7707. root: null,
  7708. clone: clone,
  7709. getRoot: getRoot,
  7710. getViewPort: getViewPort,
  7711. getRect: getRect,
  7712. getSize: getSize,
  7713. getParent: getParent,
  7714. getParents: getParents,
  7715. get: get,
  7716. getNext: getNext,
  7717. getPrev: getPrev,
  7718. select: select,
  7719. is: is,
  7720. add: add,
  7721. create: create,
  7722. createHTML: createHTML,
  7723. createFragment: createFragment,
  7724. remove: remove,
  7725. setStyle: setStyle,
  7726. getStyle: getStyle,
  7727. setStyles: setStyles,
  7728. removeAllAttribs: removeAllAttribs,
  7729. setAttrib: setAttrib,
  7730. setAttribs: setAttribs,
  7731. getAttrib: getAttrib,
  7732. getPos: getPos$1,
  7733. parseStyle: parseStyle,
  7734. serializeStyle: serializeStyle,
  7735. addStyle: addStyle,
  7736. loadCSS: loadCSS,
  7737. addClass: addClass,
  7738. removeClass: removeClass,
  7739. hasClass: hasClass,
  7740. toggleClass: toggleClass,
  7741. show: show,
  7742. hide: hide,
  7743. isHidden: isHidden,
  7744. uniqueId: uniqueId,
  7745. setHTML: setHTML,
  7746. getOuterHTML: getOuterHTML,
  7747. setOuterHTML: setOuterHTML,
  7748. decode: decode,
  7749. encode: encode,
  7750. insertAfter: insertAfter,
  7751. replace: replace,
  7752. rename: rename,
  7753. findCommonAncestor: findCommonAncestor,
  7754. toHex: toHex,
  7755. run: run,
  7756. getAttribs: getAttribs,
  7757. isEmpty: isEmpty,
  7758. createRng: createRng,
  7759. nodeIndex: findNodeIndex,
  7760. split: split,
  7761. bind: bind,
  7762. unbind: unbind,
  7763. fire: fire,
  7764. getContentEditable: getContentEditable,
  7765. getContentEditableParent: getContentEditableParent,
  7766. destroy: destroy,
  7767. isChildOf: isChildOf,
  7768. dumpRng: dumpRng
  7769. };
  7770. var attrHooks = setupAttrHooks(styles, settings, constant(self));
  7771. return self;
  7772. };
  7773. DOMUtils.DOM = DOMUtils(document);
  7774. DOMUtils.nodeIndex = findNodeIndex;
  7775. var DOM$a = DOMUtils.DOM;
  7776. var each$e = Tools.each, grep = Tools.grep;
  7777. var QUEUED = 0;
  7778. var LOADING = 1;
  7779. var LOADED = 2;
  7780. var FAILED = 3;
  7781. var ScriptLoader = function () {
  7782. function ScriptLoader(settings) {
  7783. if (settings === void 0) {
  7784. settings = {};
  7785. }
  7786. this.states = {};
  7787. this.queue = [];
  7788. this.scriptLoadedCallbacks = {};
  7789. this.queueLoadedCallbacks = [];
  7790. this.loading = 0;
  7791. this.settings = settings;
  7792. }
  7793. ScriptLoader.prototype._setReferrerPolicy = function (referrerPolicy) {
  7794. this.settings.referrerPolicy = referrerPolicy;
  7795. };
  7796. ScriptLoader.prototype.loadScript = function (url, success, failure) {
  7797. var dom = DOM$a;
  7798. var elm;
  7799. var cleanup = function () {
  7800. dom.remove(id);
  7801. if (elm) {
  7802. elm.onerror = elm.onload = elm = null;
  7803. }
  7804. };
  7805. var done = function () {
  7806. cleanup();
  7807. success();
  7808. };
  7809. var error = function () {
  7810. cleanup();
  7811. if (isFunction(failure)) {
  7812. failure();
  7813. } else {
  7814. if (typeof console !== 'undefined' && console.log) {
  7815. console.log('Failed to load script: ' + url);
  7816. }
  7817. }
  7818. };
  7819. var id = dom.uniqueId();
  7820. elm = document.createElement('script');
  7821. elm.id = id;
  7822. elm.type = 'text/javascript';
  7823. elm.src = Tools._addCacheSuffix(url);
  7824. if (this.settings.referrerPolicy) {
  7825. dom.setAttrib(elm, 'referrerpolicy', this.settings.referrerPolicy);
  7826. }
  7827. elm.onload = done;
  7828. elm.onerror = error;
  7829. (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
  7830. };
  7831. ScriptLoader.prototype.isDone = function (url) {
  7832. return this.states[url] === LOADED;
  7833. };
  7834. ScriptLoader.prototype.markDone = function (url) {
  7835. this.states[url] = LOADED;
  7836. };
  7837. ScriptLoader.prototype.add = function (url, success, scope, failure) {
  7838. var state = this.states[url];
  7839. this.queue.push(url);
  7840. if (state === undefined) {
  7841. this.states[url] = QUEUED;
  7842. }
  7843. if (success) {
  7844. if (!this.scriptLoadedCallbacks[url]) {
  7845. this.scriptLoadedCallbacks[url] = [];
  7846. }
  7847. this.scriptLoadedCallbacks[url].push({
  7848. success: success,
  7849. failure: failure,
  7850. scope: scope || this
  7851. });
  7852. }
  7853. };
  7854. ScriptLoader.prototype.load = function (url, success, scope, failure) {
  7855. return this.add(url, success, scope, failure);
  7856. };
  7857. ScriptLoader.prototype.remove = function (url) {
  7858. delete this.states[url];
  7859. delete this.scriptLoadedCallbacks[url];
  7860. };
  7861. ScriptLoader.prototype.loadQueue = function (success, scope, failure) {
  7862. this.loadScripts(this.queue, success, scope, failure);
  7863. };
  7864. ScriptLoader.prototype.loadScripts = function (scripts, success, scope, failure) {
  7865. var self = this;
  7866. var failures = [];
  7867. var execCallbacks = function (name, url) {
  7868. each$e(self.scriptLoadedCallbacks[url], function (callback) {
  7869. if (isFunction(callback[name])) {
  7870. callback[name].call(callback.scope);
  7871. }
  7872. });
  7873. self.scriptLoadedCallbacks[url] = undefined;
  7874. };
  7875. self.queueLoadedCallbacks.push({
  7876. success: success,
  7877. failure: failure,
  7878. scope: scope || this
  7879. });
  7880. var loadScripts = function () {
  7881. var loadingScripts = grep(scripts);
  7882. scripts.length = 0;
  7883. each$e(loadingScripts, function (url) {
  7884. if (self.states[url] === LOADED) {
  7885. execCallbacks('success', url);
  7886. return;
  7887. }
  7888. if (self.states[url] === FAILED) {
  7889. execCallbacks('failure', url);
  7890. return;
  7891. }
  7892. if (self.states[url] !== LOADING) {
  7893. self.states[url] = LOADING;
  7894. self.loading++;
  7895. self.loadScript(url, function () {
  7896. self.states[url] = LOADED;
  7897. self.loading--;
  7898. execCallbacks('success', url);
  7899. loadScripts();
  7900. }, function () {
  7901. self.states[url] = FAILED;
  7902. self.loading--;
  7903. failures.push(url);
  7904. execCallbacks('failure', url);
  7905. loadScripts();
  7906. });
  7907. }
  7908. });
  7909. if (!self.loading) {
  7910. var notifyCallbacks = self.queueLoadedCallbacks.slice(0);
  7911. self.queueLoadedCallbacks.length = 0;
  7912. each$e(notifyCallbacks, function (callback) {
  7913. if (failures.length === 0) {
  7914. if (isFunction(callback.success)) {
  7915. callback.success.call(callback.scope);
  7916. }
  7917. } else {
  7918. if (isFunction(callback.failure)) {
  7919. callback.failure.call(callback.scope, failures);
  7920. }
  7921. }
  7922. });
  7923. }
  7924. };
  7925. loadScripts();
  7926. };
  7927. ScriptLoader.ScriptLoader = new ScriptLoader();
  7928. return ScriptLoader;
  7929. }();
  7930. var Cell = function (initial) {
  7931. var value = initial;
  7932. var get = function () {
  7933. return value;
  7934. };
  7935. var set = function (v) {
  7936. value = v;
  7937. };
  7938. return {
  7939. get: get,
  7940. set: set
  7941. };
  7942. };
  7943. var isRaw = function (str) {
  7944. return isObject(str) && has$2(str, 'raw');
  7945. };
  7946. var isTokenised = function (str) {
  7947. return isArray$1(str) && str.length > 1;
  7948. };
  7949. var data = {};
  7950. var currentCode = Cell('en');
  7951. var getLanguageData = function () {
  7952. return get$9(data, currentCode.get());
  7953. };
  7954. var getData = function () {
  7955. return map$2(data, function (value) {
  7956. return __assign({}, value);
  7957. });
  7958. };
  7959. var setCode = function (newCode) {
  7960. if (newCode) {
  7961. currentCode.set(newCode);
  7962. }
  7963. };
  7964. var getCode = function () {
  7965. return currentCode.get();
  7966. };
  7967. var add$4 = function (code, items) {
  7968. var langData = data[code];
  7969. if (!langData) {
  7970. data[code] = langData = {};
  7971. }
  7972. each$j(items, function (translation, name) {
  7973. langData[name.toLowerCase()] = translation;
  7974. });
  7975. };
  7976. var translate = function (text) {
  7977. var langData = getLanguageData().getOr({});
  7978. var toString = function (obj) {
  7979. if (isFunction(obj)) {
  7980. return Object.prototype.toString.call(obj);
  7981. }
  7982. return !isEmpty(obj) ? '' + obj : '';
  7983. };
  7984. var isEmpty = function (text) {
  7985. return text === '' || text === null || text === undefined;
  7986. };
  7987. var getLangData = function (text) {
  7988. var textstr = toString(text);
  7989. return get$9(langData, textstr.toLowerCase()).map(toString).getOr(textstr);
  7990. };
  7991. var removeContext = function (str) {
  7992. return str.replace(/{context:\w+}$/, '');
  7993. };
  7994. if (isEmpty(text)) {
  7995. return '';
  7996. }
  7997. if (isRaw(text)) {
  7998. return toString(text.raw);
  7999. }
  8000. if (isTokenised(text)) {
  8001. var values_1 = text.slice(1);
  8002. var substitued = getLangData(text[0]).replace(/\{([0-9]+)\}/g, function ($1, $2) {
  8003. return has$2(values_1, $2) ? toString(values_1[$2]) : $1;
  8004. });
  8005. return removeContext(substitued);
  8006. }
  8007. return removeContext(getLangData(text));
  8008. };
  8009. var isRtl$1 = function () {
  8010. return getLanguageData().bind(function (items) {
  8011. return get$9(items, '_dir');
  8012. }).exists(function (dir) {
  8013. return dir === 'rtl';
  8014. });
  8015. };
  8016. var hasCode = function (code) {
  8017. return has$2(data, code);
  8018. };
  8019. var I18n = {
  8020. getData: getData,
  8021. setCode: setCode,
  8022. getCode: getCode,
  8023. add: add$4,
  8024. translate: translate,
  8025. isRtl: isRtl$1,
  8026. hasCode: hasCode
  8027. };
  8028. var AddOnManager = function () {
  8029. var items = [];
  8030. var urls = {};
  8031. var lookup = {};
  8032. var _listeners = [];
  8033. var runListeners = function (name, state) {
  8034. var matchedListeners = filter$4(_listeners, function (listener) {
  8035. return listener.name === name && listener.state === state;
  8036. });
  8037. each$k(matchedListeners, function (listener) {
  8038. return listener.callback();
  8039. });
  8040. };
  8041. var get = function (name) {
  8042. if (lookup[name]) {
  8043. return lookup[name].instance;
  8044. }
  8045. return undefined;
  8046. };
  8047. var dependencies = function (name) {
  8048. var result;
  8049. if (lookup[name]) {
  8050. result = lookup[name].dependencies;
  8051. }
  8052. return result || [];
  8053. };
  8054. var requireLangPack = function (name, languages) {
  8055. if (AddOnManager.languageLoad !== false) {
  8056. waitFor(name, function () {
  8057. var language = I18n.getCode();
  8058. var wrappedLanguages = ',' + (languages || '') + ',';
  8059. if (!language || languages && wrappedLanguages.indexOf(',' + language + ',') === -1) {
  8060. return;
  8061. }
  8062. ScriptLoader.ScriptLoader.add(urls[name] + '/langs/' + language + '.js');
  8063. }, 'loaded');
  8064. }
  8065. };
  8066. var add = function (id, addOn, dependencies) {
  8067. var addOnConstructor = addOn;
  8068. items.push(addOnConstructor);
  8069. lookup[id] = {
  8070. instance: addOnConstructor,
  8071. dependencies: dependencies
  8072. };
  8073. runListeners(id, 'added');
  8074. return addOnConstructor;
  8075. };
  8076. var remove = function (name) {
  8077. delete urls[name];
  8078. delete lookup[name];
  8079. };
  8080. var createUrl = function (baseUrl, dep) {
  8081. if (typeof dep === 'object') {
  8082. return dep;
  8083. }
  8084. return typeof baseUrl === 'string' ? {
  8085. prefix: '',
  8086. resource: dep,
  8087. suffix: ''
  8088. } : {
  8089. prefix: baseUrl.prefix,
  8090. resource: dep,
  8091. suffix: baseUrl.suffix
  8092. };
  8093. };
  8094. var addComponents = function (pluginName, scripts) {
  8095. var pluginUrl = urls[pluginName];
  8096. each$k(scripts, function (script) {
  8097. ScriptLoader.ScriptLoader.add(pluginUrl + '/' + script);
  8098. });
  8099. };
  8100. var loadDependencies = function (name, addOnUrl, success, scope) {
  8101. var deps = dependencies(name);
  8102. each$k(deps, function (dep) {
  8103. var newUrl = createUrl(addOnUrl, dep);
  8104. load(newUrl.resource, newUrl, undefined, undefined);
  8105. });
  8106. if (success) {
  8107. if (scope) {
  8108. success.call(scope);
  8109. } else {
  8110. success.call(ScriptLoader);
  8111. }
  8112. }
  8113. };
  8114. var load = function (name, addOnUrl, success, scope, failure) {
  8115. if (urls[name]) {
  8116. return;
  8117. }
  8118. var urlString = typeof addOnUrl === 'string' ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
  8119. if (urlString.indexOf('/') !== 0 && urlString.indexOf('://') === -1) {
  8120. urlString = AddOnManager.baseURL + '/' + urlString;
  8121. }
  8122. urls[name] = urlString.substring(0, urlString.lastIndexOf('/'));
  8123. var done = function () {
  8124. runListeners(name, 'loaded');
  8125. loadDependencies(name, addOnUrl, success, scope);
  8126. };
  8127. if (lookup[name]) {
  8128. done();
  8129. } else {
  8130. ScriptLoader.ScriptLoader.add(urlString, done, scope, failure);
  8131. }
  8132. };
  8133. var waitFor = function (name, callback, state) {
  8134. if (state === void 0) {
  8135. state = 'added';
  8136. }
  8137. if (has$2(lookup, name) && state === 'added') {
  8138. callback();
  8139. } else if (has$2(urls, name) && state === 'loaded') {
  8140. callback();
  8141. } else {
  8142. _listeners.push({
  8143. name: name,
  8144. state: state,
  8145. callback: callback
  8146. });
  8147. }
  8148. };
  8149. return {
  8150. items: items,
  8151. urls: urls,
  8152. lookup: lookup,
  8153. _listeners: _listeners,
  8154. get: get,
  8155. dependencies: dependencies,
  8156. requireLangPack: requireLangPack,
  8157. add: add,
  8158. remove: remove,
  8159. createUrl: createUrl,
  8160. addComponents: addComponents,
  8161. load: load,
  8162. waitFor: waitFor
  8163. };
  8164. };
  8165. AddOnManager.languageLoad = true;
  8166. AddOnManager.baseURL = '';
  8167. AddOnManager.PluginManager = AddOnManager();
  8168. AddOnManager.ThemeManager = AddOnManager();
  8169. var singleton = function (doRevoke) {
  8170. var subject = Cell(Optional.none());
  8171. var revoke = function () {
  8172. return subject.get().each(doRevoke);
  8173. };
  8174. var clear = function () {
  8175. revoke();
  8176. subject.set(Optional.none());
  8177. };
  8178. var isSet = function () {
  8179. return subject.get().isSome();
  8180. };
  8181. var get = function () {
  8182. return subject.get();
  8183. };
  8184. var set = function (s) {
  8185. revoke();
  8186. subject.set(Optional.some(s));
  8187. };
  8188. return {
  8189. clear: clear,
  8190. isSet: isSet,
  8191. get: get,
  8192. set: set
  8193. };
  8194. };
  8195. var value = function () {
  8196. var subject = singleton(noop);
  8197. var on = function (f) {
  8198. return subject.get().each(f);
  8199. };
  8200. return __assign(__assign({}, subject), { on: on });
  8201. };
  8202. var first = function (fn, rate) {
  8203. var timer = null;
  8204. var cancel = function () {
  8205. if (!isNull(timer)) {
  8206. clearTimeout(timer);
  8207. timer = null;
  8208. }
  8209. };
  8210. var throttle = function () {
  8211. var args = [];
  8212. for (var _i = 0; _i < arguments.length; _i++) {
  8213. args[_i] = arguments[_i];
  8214. }
  8215. if (isNull(timer)) {
  8216. timer = setTimeout(function () {
  8217. timer = null;
  8218. fn.apply(null, args);
  8219. }, rate);
  8220. }
  8221. };
  8222. return {
  8223. cancel: cancel,
  8224. throttle: throttle
  8225. };
  8226. };
  8227. var last = function (fn, rate) {
  8228. var timer = null;
  8229. var cancel = function () {
  8230. if (!isNull(timer)) {
  8231. clearTimeout(timer);
  8232. timer = null;
  8233. }
  8234. };
  8235. var throttle = function () {
  8236. var args = [];
  8237. for (var _i = 0; _i < arguments.length; _i++) {
  8238. args[_i] = arguments[_i];
  8239. }
  8240. cancel();
  8241. timer = setTimeout(function () {
  8242. timer = null;
  8243. fn.apply(null, args);
  8244. }, rate);
  8245. };
  8246. return {
  8247. cancel: cancel,
  8248. throttle: throttle
  8249. };
  8250. };
  8251. var read$4 = function (element, attr) {
  8252. var value = get$6(element, attr);
  8253. return value === undefined || value === '' ? [] : value.split(' ');
  8254. };
  8255. var add$3 = function (element, attr, id) {
  8256. var old = read$4(element, attr);
  8257. var nu = old.concat([id]);
  8258. set$1(element, attr, nu.join(' '));
  8259. return true;
  8260. };
  8261. var remove$5 = function (element, attr, id) {
  8262. var nu = filter$4(read$4(element, attr), function (v) {
  8263. return v !== id;
  8264. });
  8265. if (nu.length > 0) {
  8266. set$1(element, attr, nu.join(' '));
  8267. } else {
  8268. remove$6(element, attr);
  8269. }
  8270. return false;
  8271. };
  8272. var supports = function (element) {
  8273. return element.dom.classList !== undefined;
  8274. };
  8275. var get$4 = function (element) {
  8276. return read$4(element, 'class');
  8277. };
  8278. var add$2 = function (element, clazz) {
  8279. return add$3(element, 'class', clazz);
  8280. };
  8281. var remove$4 = function (element, clazz) {
  8282. return remove$5(element, 'class', clazz);
  8283. };
  8284. var add$1 = function (element, clazz) {
  8285. if (supports(element)) {
  8286. element.dom.classList.add(clazz);
  8287. } else {
  8288. add$2(element, clazz);
  8289. }
  8290. };
  8291. var cleanClass = function (element) {
  8292. var classList = supports(element) ? element.dom.classList : get$4(element);
  8293. if (classList.length === 0) {
  8294. remove$6(element, 'class');
  8295. }
  8296. };
  8297. var remove$3 = function (element, clazz) {
  8298. if (supports(element)) {
  8299. var classList = element.dom.classList;
  8300. classList.remove(clazz);
  8301. } else {
  8302. remove$4(element, clazz);
  8303. }
  8304. cleanClass(element);
  8305. };
  8306. var has = function (element, clazz) {
  8307. return supports(element) && element.dom.classList.contains(clazz);
  8308. };
  8309. var descendants$1 = function (scope, predicate) {
  8310. var result = [];
  8311. each$k(children(scope), function (x) {
  8312. if (predicate(x)) {
  8313. result = result.concat([x]);
  8314. }
  8315. result = result.concat(descendants$1(x, predicate));
  8316. });
  8317. return result;
  8318. };
  8319. var descendants = function (scope, selector) {
  8320. return all(selector, scope);
  8321. };
  8322. var annotation = constant('mce-annotation');
  8323. var dataAnnotation = constant('data-mce-annotation');
  8324. var dataAnnotationId = constant('data-mce-annotation-uid');
  8325. var identify = function (editor, annotationName) {
  8326. var rng = editor.selection.getRng();
  8327. var start = SugarElement.fromDom(rng.startContainer);
  8328. var root = SugarElement.fromDom(editor.getBody());
  8329. var selector = annotationName.fold(function () {
  8330. return '.' + annotation();
  8331. }, function (an) {
  8332. return '[' + dataAnnotation() + '="' + an + '"]';
  8333. });
  8334. var newStart = child$1(start, rng.startOffset).getOr(start);
  8335. var closest = closest$2(newStart, selector, function (n) {
  8336. return eq(n, root);
  8337. });
  8338. var getAttr = function (c, property) {
  8339. if (has$1(c, property)) {
  8340. return Optional.some(get$6(c, property));
  8341. } else {
  8342. return Optional.none();
  8343. }
  8344. };
  8345. return closest.bind(function (c) {
  8346. return getAttr(c, '' + dataAnnotationId()).bind(function (uid) {
  8347. return getAttr(c, '' + dataAnnotation()).map(function (name) {
  8348. var elements = findMarkers(editor, uid);
  8349. return {
  8350. uid: uid,
  8351. name: name,
  8352. elements: elements
  8353. };
  8354. });
  8355. });
  8356. });
  8357. };
  8358. var isAnnotation = function (elem) {
  8359. return isElement$6(elem) && has(elem, annotation());
  8360. };
  8361. var findMarkers = function (editor, uid) {
  8362. var body = SugarElement.fromDom(editor.getBody());
  8363. return descendants(body, '[' + dataAnnotationId() + '="' + uid + '"]');
  8364. };
  8365. var findAll = function (editor, name) {
  8366. var body = SugarElement.fromDom(editor.getBody());
  8367. var markers = descendants(body, '[' + dataAnnotation() + '="' + name + '"]');
  8368. var directory = {};
  8369. each$k(markers, function (m) {
  8370. var uid = get$6(m, dataAnnotationId());
  8371. var nodesAlready = get$9(directory, uid).getOr([]);
  8372. directory[uid] = nodesAlready.concat([m]);
  8373. });
  8374. return directory;
  8375. };
  8376. var setup$n = function (editor, _registry) {
  8377. var changeCallbacks = Cell({});
  8378. var initData = function () {
  8379. return {
  8380. listeners: [],
  8381. previous: value()
  8382. };
  8383. };
  8384. var withCallbacks = function (name, f) {
  8385. updateCallbacks(name, function (data) {
  8386. f(data);
  8387. return data;
  8388. });
  8389. };
  8390. var updateCallbacks = function (name, f) {
  8391. var callbackMap = changeCallbacks.get();
  8392. var data = get$9(callbackMap, name).getOrThunk(initData);
  8393. var outputData = f(data);
  8394. callbackMap[name] = outputData;
  8395. changeCallbacks.set(callbackMap);
  8396. };
  8397. var fireCallbacks = function (name, uid, elements) {
  8398. withCallbacks(name, function (data) {
  8399. each$k(data.listeners, function (f) {
  8400. return f(true, name, {
  8401. uid: uid,
  8402. nodes: map$3(elements, function (elem) {
  8403. return elem.dom;
  8404. })
  8405. });
  8406. });
  8407. });
  8408. };
  8409. var fireNoAnnotation = function (name) {
  8410. withCallbacks(name, function (data) {
  8411. each$k(data.listeners, function (f) {
  8412. return f(false, name);
  8413. });
  8414. });
  8415. };
  8416. var onNodeChange = last(function () {
  8417. var callbackMap = changeCallbacks.get();
  8418. var annotations = sort(keys(callbackMap));
  8419. each$k(annotations, function (name) {
  8420. updateCallbacks(name, function (data) {
  8421. var prev = data.previous.get();
  8422. identify(editor, Optional.some(name)).fold(function () {
  8423. if (prev.isSome()) {
  8424. fireNoAnnotation(name);
  8425. data.previous.clear();
  8426. }
  8427. }, function (_a) {
  8428. var uid = _a.uid, name = _a.name, elements = _a.elements;
  8429. if (!is$1(prev, uid)) {
  8430. fireCallbacks(name, uid, elements);
  8431. data.previous.set(uid);
  8432. }
  8433. });
  8434. return {
  8435. previous: data.previous,
  8436. listeners: data.listeners
  8437. };
  8438. });
  8439. });
  8440. }, 30);
  8441. editor.on('remove', function () {
  8442. onNodeChange.cancel();
  8443. });
  8444. editor.on('NodeChange', function () {
  8445. onNodeChange.throttle();
  8446. });
  8447. var addListener = function (name, f) {
  8448. updateCallbacks(name, function (data) {
  8449. return {
  8450. previous: data.previous,
  8451. listeners: data.listeners.concat([f])
  8452. };
  8453. });
  8454. };
  8455. return { addListener: addListener };
  8456. };
  8457. var setup$m = function (editor, registry) {
  8458. var identifyParserNode = function (span) {
  8459. return Optional.from(span.attr(dataAnnotation())).bind(registry.lookup);
  8460. };
  8461. editor.on('init', function () {
  8462. editor.serializer.addNodeFilter('span', function (spans) {
  8463. each$k(spans, function (span) {
  8464. identifyParserNode(span).each(function (settings) {
  8465. if (settings.persistent === false) {
  8466. span.unwrap();
  8467. }
  8468. });
  8469. });
  8470. });
  8471. });
  8472. };
  8473. var create$7 = function () {
  8474. var annotations = {};
  8475. var register = function (name, settings) {
  8476. annotations[name] = {
  8477. name: name,
  8478. settings: settings
  8479. };
  8480. };
  8481. var lookup = function (name) {
  8482. return get$9(annotations, name).map(function (a) {
  8483. return a.settings;
  8484. });
  8485. };
  8486. return {
  8487. register: register,
  8488. lookup: lookup
  8489. };
  8490. };
  8491. var unique = 0;
  8492. var generate = function (prefix) {
  8493. var date = new Date();
  8494. var time = date.getTime();
  8495. var random = Math.floor(Math.random() * 1000000000);
  8496. unique++;
  8497. return prefix + '_' + random + unique + String(time);
  8498. };
  8499. var add = function (element, classes) {
  8500. each$k(classes, function (x) {
  8501. add$1(element, x);
  8502. });
  8503. };
  8504. var fromHtml = function (html, scope) {
  8505. var doc = scope || document;
  8506. var div = doc.createElement('div');
  8507. div.innerHTML = html;
  8508. return children(SugarElement.fromDom(div));
  8509. };
  8510. var fromDom$1 = function (nodes) {
  8511. return map$3(nodes, SugarElement.fromDom);
  8512. };
  8513. var get$3 = function (element) {
  8514. return element.dom.innerHTML;
  8515. };
  8516. var set = function (element, content) {
  8517. var owner = owner$1(element);
  8518. var docDom = owner.dom;
  8519. var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  8520. var contentElements = fromHtml(content, docDom);
  8521. append(fragment, contentElements);
  8522. empty(element);
  8523. append$1(element, fragment);
  8524. };
  8525. var clone$1 = function (original, isDeep) {
  8526. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  8527. };
  8528. var shallow = function (original) {
  8529. return clone$1(original, false);
  8530. };
  8531. var deep$1 = function (original) {
  8532. return clone$1(original, true);
  8533. };
  8534. var TextWalker = function (startNode, rootNode, isBoundary) {
  8535. if (isBoundary === void 0) {
  8536. isBoundary = never;
  8537. }
  8538. var walker = new DomTreeWalker(startNode, rootNode);
  8539. var walk = function (direction) {
  8540. var next;
  8541. do {
  8542. next = walker[direction]();
  8543. } while (next && !isText$7(next) && !isBoundary(next));
  8544. return Optional.from(next).filter(isText$7);
  8545. };
  8546. return {
  8547. current: function () {
  8548. return Optional.from(walker.current()).filter(isText$7);
  8549. },
  8550. next: function () {
  8551. return walk('next');
  8552. },
  8553. prev: function () {
  8554. return walk('prev');
  8555. },
  8556. prev2: function () {
  8557. return walk('prev2');
  8558. }
  8559. };
  8560. };
  8561. var TextSeeker = function (dom, isBoundary) {
  8562. var isBlockBoundary = isBoundary ? isBoundary : function (node) {
  8563. return dom.isBlock(node) || isBr$5(node) || isContentEditableFalse$b(node);
  8564. };
  8565. var walk = function (node, offset, walker, process) {
  8566. if (isText$7(node)) {
  8567. var newOffset = process(node, offset, node.data);
  8568. if (newOffset !== -1) {
  8569. return Optional.some({
  8570. container: node,
  8571. offset: newOffset
  8572. });
  8573. }
  8574. }
  8575. return walker().bind(function (next) {
  8576. return walk(next.container, next.offset, walker, process);
  8577. });
  8578. };
  8579. var backwards = function (node, offset, process, root) {
  8580. var walker = TextWalker(node, root, isBlockBoundary);
  8581. return walk(node, offset, function () {
  8582. return walker.prev().map(function (prev) {
  8583. return {
  8584. container: prev,
  8585. offset: prev.length
  8586. };
  8587. });
  8588. }, process).getOrNull();
  8589. };
  8590. var forwards = function (node, offset, process, root) {
  8591. var walker = TextWalker(node, root, isBlockBoundary);
  8592. return walk(node, offset, function () {
  8593. return walker.next().map(function (next) {
  8594. return {
  8595. container: next,
  8596. offset: 0
  8597. };
  8598. });
  8599. }, process).getOrNull();
  8600. };
  8601. return {
  8602. backwards: backwards,
  8603. forwards: forwards
  8604. };
  8605. };
  8606. var round$2 = Math.round;
  8607. var clone = function (rect) {
  8608. if (!rect) {
  8609. return {
  8610. left: 0,
  8611. top: 0,
  8612. bottom: 0,
  8613. right: 0,
  8614. width: 0,
  8615. height: 0
  8616. };
  8617. }
  8618. return {
  8619. left: round$2(rect.left),
  8620. top: round$2(rect.top),
  8621. bottom: round$2(rect.bottom),
  8622. right: round$2(rect.right),
  8623. width: round$2(rect.width),
  8624. height: round$2(rect.height)
  8625. };
  8626. };
  8627. var collapse = function (rect, toStart) {
  8628. rect = clone(rect);
  8629. if (toStart) {
  8630. rect.right = rect.left;
  8631. } else {
  8632. rect.left = rect.left + rect.width;
  8633. rect.right = rect.left;
  8634. }
  8635. rect.width = 0;
  8636. return rect;
  8637. };
  8638. var isEqual = function (rect1, rect2) {
  8639. return rect1.left === rect2.left && rect1.top === rect2.top && rect1.bottom === rect2.bottom && rect1.right === rect2.right;
  8640. };
  8641. var isValidOverflow = function (overflowY, rect1, rect2) {
  8642. return overflowY >= 0 && overflowY <= Math.min(rect1.height, rect2.height) / 2;
  8643. };
  8644. var isAbove$1 = function (rect1, rect2) {
  8645. var halfHeight = Math.min(rect2.height / 2, rect1.height / 2);
  8646. if (rect1.bottom - halfHeight < rect2.top) {
  8647. return true;
  8648. }
  8649. if (rect1.top > rect2.bottom) {
  8650. return false;
  8651. }
  8652. return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
  8653. };
  8654. var isBelow$1 = function (rect1, rect2) {
  8655. if (rect1.top > rect2.bottom) {
  8656. return true;
  8657. }
  8658. if (rect1.bottom < rect2.top) {
  8659. return false;
  8660. }
  8661. return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
  8662. };
  8663. var containsXY = function (rect, clientX, clientY) {
  8664. return clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
  8665. };
  8666. var clamp$2 = function (value, min, max) {
  8667. return Math.min(Math.max(value, min), max);
  8668. };
  8669. var getSelectedNode = function (range) {
  8670. var startContainer = range.startContainer, startOffset = range.startOffset;
  8671. if (startContainer.hasChildNodes() && range.endOffset === startOffset + 1) {
  8672. return startContainer.childNodes[startOffset];
  8673. }
  8674. return null;
  8675. };
  8676. var getNode$1 = function (container, offset) {
  8677. if (isElement$5(container) && container.hasChildNodes()) {
  8678. var childNodes = container.childNodes;
  8679. var safeOffset = clamp$2(offset, 0, childNodes.length - 1);
  8680. return childNodes[safeOffset];
  8681. } else {
  8682. return container;
  8683. }
  8684. };
  8685. var getNodeUnsafe = function (container, offset) {
  8686. if (offset < 0 && isElement$5(container) && container.hasChildNodes()) {
  8687. return undefined;
  8688. } else {
  8689. return getNode$1(container, offset);
  8690. }
  8691. };
  8692. 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]');
  8693. var isExtendingChar = function (ch) {
  8694. return typeof ch === 'string' && ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
  8695. };
  8696. var or = function () {
  8697. var args = [];
  8698. for (var _i = 0; _i < arguments.length; _i++) {
  8699. args[_i] = arguments[_i];
  8700. }
  8701. return function (x) {
  8702. for (var i = 0; i < args.length; i++) {
  8703. if (args[i](x)) {
  8704. return true;
  8705. }
  8706. }
  8707. return false;
  8708. };
  8709. };
  8710. var and = function () {
  8711. var args = [];
  8712. for (var _i = 0; _i < arguments.length; _i++) {
  8713. args[_i] = arguments[_i];
  8714. }
  8715. return function (x) {
  8716. for (var i = 0; i < args.length; i++) {
  8717. if (!args[i](x)) {
  8718. return false;
  8719. }
  8720. }
  8721. return true;
  8722. };
  8723. };
  8724. var isElement$3 = isElement$5;
  8725. var isCaretCandidate$2 = isCaretCandidate$3;
  8726. var isBlock$1 = matchStyleValues('display', 'block table');
  8727. var isFloated = matchStyleValues('float', 'left right');
  8728. var isValidElementCaretCandidate = and(isElement$3, isCaretCandidate$2, not(isFloated));
  8729. var isNotPre = not(matchStyleValues('white-space', 'pre pre-line pre-wrap'));
  8730. var isText$4 = isText$7;
  8731. var isBr$2 = isBr$5;
  8732. var nodeIndex$1 = DOMUtils.nodeIndex;
  8733. var resolveIndex$1 = getNodeUnsafe;
  8734. var createRange$1 = function (doc) {
  8735. return 'createRange' in doc ? doc.createRange() : DOMUtils.DOM.createRng();
  8736. };
  8737. var isWhiteSpace$1 = function (chr) {
  8738. return chr && /[\r\n\t ]/.test(chr);
  8739. };
  8740. var isRange = function (rng) {
  8741. return !!rng.setStart && !!rng.setEnd;
  8742. };
  8743. var isHiddenWhiteSpaceRange = function (range) {
  8744. var container = range.startContainer;
  8745. var offset = range.startOffset;
  8746. if (isWhiteSpace$1(range.toString()) && isNotPre(container.parentNode) && isText$7(container)) {
  8747. var text = container.data;
  8748. if (isWhiteSpace$1(text[offset - 1]) || isWhiteSpace$1(text[offset + 1])) {
  8749. return true;
  8750. }
  8751. }
  8752. return false;
  8753. };
  8754. var getBrClientRect = function (brNode) {
  8755. var doc = brNode.ownerDocument;
  8756. var rng = createRange$1(doc);
  8757. var nbsp$1 = doc.createTextNode(nbsp);
  8758. var parentNode = brNode.parentNode;
  8759. parentNode.insertBefore(nbsp$1, brNode);
  8760. rng.setStart(nbsp$1, 0);
  8761. rng.setEnd(nbsp$1, 1);
  8762. var clientRect = clone(rng.getBoundingClientRect());
  8763. parentNode.removeChild(nbsp$1);
  8764. return clientRect;
  8765. };
  8766. var getBoundingClientRectWebKitText = function (rng) {
  8767. var sc = rng.startContainer;
  8768. var ec = rng.endContainer;
  8769. var so = rng.startOffset;
  8770. var eo = rng.endOffset;
  8771. if (sc === ec && isText$7(ec) && so === 0 && eo === 1) {
  8772. var newRng = rng.cloneRange();
  8773. newRng.setEndAfter(ec);
  8774. return getBoundingClientRect$1(newRng);
  8775. } else {
  8776. return null;
  8777. }
  8778. };
  8779. var isZeroRect = function (r) {
  8780. return r.left === 0 && r.right === 0 && r.top === 0 && r.bottom === 0;
  8781. };
  8782. var getBoundingClientRect$1 = function (item) {
  8783. var clientRect;
  8784. var clientRects = item.getClientRects();
  8785. if (clientRects.length > 0) {
  8786. clientRect = clone(clientRects[0]);
  8787. } else {
  8788. clientRect = clone(item.getBoundingClientRect());
  8789. }
  8790. if (!isRange(item) && isBr$2(item) && isZeroRect(clientRect)) {
  8791. return getBrClientRect(item);
  8792. }
  8793. if (isZeroRect(clientRect) && isRange(item)) {
  8794. return getBoundingClientRectWebKitText(item);
  8795. }
  8796. return clientRect;
  8797. };
  8798. var collapseAndInflateWidth = function (clientRect, toStart) {
  8799. var newClientRect = collapse(clientRect, toStart);
  8800. newClientRect.width = 1;
  8801. newClientRect.right = newClientRect.left + 1;
  8802. return newClientRect;
  8803. };
  8804. var getCaretPositionClientRects = function (caretPosition) {
  8805. var clientRects = [];
  8806. var addUniqueAndValidRect = function (clientRect) {
  8807. if (clientRect.height === 0) {
  8808. return;
  8809. }
  8810. if (clientRects.length > 0) {
  8811. if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
  8812. return;
  8813. }
  8814. }
  8815. clientRects.push(clientRect);
  8816. };
  8817. var addCharacterOffset = function (container, offset) {
  8818. var range = createRange$1(container.ownerDocument);
  8819. if (offset < container.data.length) {
  8820. if (isExtendingChar(container.data[offset])) {
  8821. return clientRects;
  8822. }
  8823. if (isExtendingChar(container.data[offset - 1])) {
  8824. range.setStart(container, offset);
  8825. range.setEnd(container, offset + 1);
  8826. if (!isHiddenWhiteSpaceRange(range)) {
  8827. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  8828. return clientRects;
  8829. }
  8830. }
  8831. }
  8832. if (offset > 0) {
  8833. range.setStart(container, offset - 1);
  8834. range.setEnd(container, offset);
  8835. if (!isHiddenWhiteSpaceRange(range)) {
  8836. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  8837. }
  8838. }
  8839. if (offset < container.data.length) {
  8840. range.setStart(container, offset);
  8841. range.setEnd(container, offset + 1);
  8842. if (!isHiddenWhiteSpaceRange(range)) {
  8843. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), true));
  8844. }
  8845. }
  8846. };
  8847. var container = caretPosition.container();
  8848. var offset = caretPosition.offset();
  8849. if (isText$4(container)) {
  8850. addCharacterOffset(container, offset);
  8851. return clientRects;
  8852. }
  8853. if (isElement$3(container)) {
  8854. if (caretPosition.isAtEnd()) {
  8855. var node = resolveIndex$1(container, offset);
  8856. if (isText$4(node)) {
  8857. addCharacterOffset(node, node.data.length);
  8858. }
  8859. if (isValidElementCaretCandidate(node) && !isBr$2(node)) {
  8860. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  8861. }
  8862. } else {
  8863. var node = resolveIndex$1(container, offset);
  8864. if (isText$4(node)) {
  8865. addCharacterOffset(node, 0);
  8866. }
  8867. if (isValidElementCaretCandidate(node) && caretPosition.isAtEnd()) {
  8868. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  8869. return clientRects;
  8870. }
  8871. var beforeNode = resolveIndex$1(caretPosition.container(), caretPosition.offset() - 1);
  8872. if (isValidElementCaretCandidate(beforeNode) && !isBr$2(beforeNode)) {
  8873. if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
  8874. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(beforeNode), false));
  8875. }
  8876. }
  8877. if (isValidElementCaretCandidate(node)) {
  8878. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), true));
  8879. }
  8880. }
  8881. }
  8882. return clientRects;
  8883. };
  8884. var CaretPosition = function (container, offset, clientRects) {
  8885. var isAtStart = function () {
  8886. if (isText$4(container)) {
  8887. return offset === 0;
  8888. }
  8889. return offset === 0;
  8890. };
  8891. var isAtEnd = function () {
  8892. if (isText$4(container)) {
  8893. return offset >= container.data.length;
  8894. }
  8895. return offset >= container.childNodes.length;
  8896. };
  8897. var toRange = function () {
  8898. var range = createRange$1(container.ownerDocument);
  8899. range.setStart(container, offset);
  8900. range.setEnd(container, offset);
  8901. return range;
  8902. };
  8903. var getClientRects = function () {
  8904. if (!clientRects) {
  8905. clientRects = getCaretPositionClientRects(CaretPosition(container, offset));
  8906. }
  8907. return clientRects;
  8908. };
  8909. var isVisible = function () {
  8910. return getClientRects().length > 0;
  8911. };
  8912. var isEqual = function (caretPosition) {
  8913. return caretPosition && container === caretPosition.container() && offset === caretPosition.offset();
  8914. };
  8915. var getNode = function (before) {
  8916. return resolveIndex$1(container, before ? offset - 1 : offset);
  8917. };
  8918. return {
  8919. container: constant(container),
  8920. offset: constant(offset),
  8921. toRange: toRange,
  8922. getClientRects: getClientRects,
  8923. isVisible: isVisible,
  8924. isAtStart: isAtStart,
  8925. isAtEnd: isAtEnd,
  8926. isEqual: isEqual,
  8927. getNode: getNode
  8928. };
  8929. };
  8930. CaretPosition.fromRangeStart = function (range) {
  8931. return CaretPosition(range.startContainer, range.startOffset);
  8932. };
  8933. CaretPosition.fromRangeEnd = function (range) {
  8934. return CaretPosition(range.endContainer, range.endOffset);
  8935. };
  8936. CaretPosition.after = function (node) {
  8937. return CaretPosition(node.parentNode, nodeIndex$1(node) + 1);
  8938. };
  8939. CaretPosition.before = function (node) {
  8940. return CaretPosition(node.parentNode, nodeIndex$1(node));
  8941. };
  8942. CaretPosition.isAbove = function (pos1, pos2) {
  8943. return lift2(head(pos2.getClientRects()), last$2(pos1.getClientRects()), isAbove$1).getOr(false);
  8944. };
  8945. CaretPosition.isBelow = function (pos1, pos2) {
  8946. return lift2(last$2(pos2.getClientRects()), head(pos1.getClientRects()), isBelow$1).getOr(false);
  8947. };
  8948. CaretPosition.isAtStart = function (pos) {
  8949. return pos ? pos.isAtStart() : false;
  8950. };
  8951. CaretPosition.isAtEnd = function (pos) {
  8952. return pos ? pos.isAtEnd() : false;
  8953. };
  8954. CaretPosition.isTextPosition = function (pos) {
  8955. return pos ? isText$7(pos.container()) : false;
  8956. };
  8957. CaretPosition.isElementPosition = function (pos) {
  8958. return CaretPosition.isTextPosition(pos) === false;
  8959. };
  8960. var trimEmptyTextNode$1 = function (dom, node) {
  8961. if (isText$7(node) && node.data.length === 0) {
  8962. dom.remove(node);
  8963. }
  8964. };
  8965. var insertNode = function (dom, rng, node) {
  8966. rng.insertNode(node);
  8967. trimEmptyTextNode$1(dom, node.previousSibling);
  8968. trimEmptyTextNode$1(dom, node.nextSibling);
  8969. };
  8970. var insertFragment = function (dom, rng, frag) {
  8971. var firstChild = Optional.from(frag.firstChild);
  8972. var lastChild = Optional.from(frag.lastChild);
  8973. rng.insertNode(frag);
  8974. firstChild.each(function (child) {
  8975. return trimEmptyTextNode$1(dom, child.previousSibling);
  8976. });
  8977. lastChild.each(function (child) {
  8978. return trimEmptyTextNode$1(dom, child.nextSibling);
  8979. });
  8980. };
  8981. var rangeInsertNode = function (dom, rng, node) {
  8982. if (isDocumentFragment(node)) {
  8983. insertFragment(dom, rng, node);
  8984. } else {
  8985. insertNode(dom, rng, node);
  8986. }
  8987. };
  8988. var isText$3 = isText$7;
  8989. var isBogus = isBogus$2;
  8990. var nodeIndex = DOMUtils.nodeIndex;
  8991. var normalizedParent = function (node) {
  8992. var parentNode = node.parentNode;
  8993. if (isBogus(parentNode)) {
  8994. return normalizedParent(parentNode);
  8995. }
  8996. return parentNode;
  8997. };
  8998. var getChildNodes = function (node) {
  8999. if (!node) {
  9000. return [];
  9001. }
  9002. return reduce(node.childNodes, function (result, node) {
  9003. if (isBogus(node) && node.nodeName !== 'BR') {
  9004. result = result.concat(getChildNodes(node));
  9005. } else {
  9006. result.push(node);
  9007. }
  9008. return result;
  9009. }, []);
  9010. };
  9011. var normalizedTextOffset = function (node, offset) {
  9012. while (node = node.previousSibling) {
  9013. if (!isText$3(node)) {
  9014. break;
  9015. }
  9016. offset += node.data.length;
  9017. }
  9018. return offset;
  9019. };
  9020. var equal = function (a) {
  9021. return function (b) {
  9022. return a === b;
  9023. };
  9024. };
  9025. var normalizedNodeIndex = function (node) {
  9026. var nodes, index;
  9027. nodes = getChildNodes(normalizedParent(node));
  9028. index = findIndex$1(nodes, equal(node), node);
  9029. nodes = nodes.slice(0, index + 1);
  9030. var numTextFragments = reduce(nodes, function (result, node, i) {
  9031. if (isText$3(node) && isText$3(nodes[i - 1])) {
  9032. result++;
  9033. }
  9034. return result;
  9035. }, 0);
  9036. nodes = filter$2(nodes, matchNodeNames([node.nodeName]));
  9037. index = findIndex$1(nodes, equal(node), node);
  9038. return index - numTextFragments;
  9039. };
  9040. var createPathItem = function (node) {
  9041. var name;
  9042. if (isText$3(node)) {
  9043. name = 'text()';
  9044. } else {
  9045. name = node.nodeName.toLowerCase();
  9046. }
  9047. return name + '[' + normalizedNodeIndex(node) + ']';
  9048. };
  9049. var parentsUntil$1 = function (root, node, predicate) {
  9050. var parents = [];
  9051. for (node = node.parentNode; node !== root; node = node.parentNode) {
  9052. if (predicate && predicate(node)) {
  9053. break;
  9054. }
  9055. parents.push(node);
  9056. }
  9057. return parents;
  9058. };
  9059. var create$6 = function (root, caretPosition) {
  9060. var container, offset, path = [], outputOffset, childNodes, parents;
  9061. container = caretPosition.container();
  9062. offset = caretPosition.offset();
  9063. if (isText$3(container)) {
  9064. outputOffset = normalizedTextOffset(container, offset);
  9065. } else {
  9066. childNodes = container.childNodes;
  9067. if (offset >= childNodes.length) {
  9068. outputOffset = 'after';
  9069. offset = childNodes.length - 1;
  9070. } else {
  9071. outputOffset = 'before';
  9072. }
  9073. container = childNodes[offset];
  9074. }
  9075. path.push(createPathItem(container));
  9076. parents = parentsUntil$1(root, container);
  9077. parents = filter$2(parents, not(isBogus$2));
  9078. path = path.concat(map$1(parents, function (node) {
  9079. return createPathItem(node);
  9080. }));
  9081. return path.reverse().join('/') + ',' + outputOffset;
  9082. };
  9083. var resolvePathItem = function (node, name, index) {
  9084. var nodes = getChildNodes(node);
  9085. nodes = filter$2(nodes, function (node, index) {
  9086. return !isText$3(node) || !isText$3(nodes[index - 1]);
  9087. });
  9088. nodes = filter$2(nodes, matchNodeNames([name]));
  9089. return nodes[index];
  9090. };
  9091. var findTextPosition = function (container, offset) {
  9092. var node = container, targetOffset = 0, dataLen;
  9093. while (isText$3(node)) {
  9094. dataLen = node.data.length;
  9095. if (offset >= targetOffset && offset <= targetOffset + dataLen) {
  9096. container = node;
  9097. offset = offset - targetOffset;
  9098. break;
  9099. }
  9100. if (!isText$3(node.nextSibling)) {
  9101. container = node;
  9102. offset = dataLen;
  9103. break;
  9104. }
  9105. targetOffset += dataLen;
  9106. node = node.nextSibling;
  9107. }
  9108. if (isText$3(container) && offset > container.data.length) {
  9109. offset = container.data.length;
  9110. }
  9111. return CaretPosition(container, offset);
  9112. };
  9113. var resolve$2 = function (root, path) {
  9114. var offset;
  9115. if (!path) {
  9116. return null;
  9117. }
  9118. var parts = path.split(',');
  9119. var paths = parts[0].split('/');
  9120. offset = parts.length > 1 ? parts[1] : 'before';
  9121. var container = reduce(paths, function (result, value) {
  9122. var match = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value);
  9123. if (!match) {
  9124. return null;
  9125. }
  9126. if (match[1] === 'text()') {
  9127. match[1] = '#text';
  9128. }
  9129. return resolvePathItem(result, match[1], parseInt(match[2], 10));
  9130. }, root);
  9131. if (!container) {
  9132. return null;
  9133. }
  9134. if (!isText$3(container)) {
  9135. if (offset === 'after') {
  9136. offset = nodeIndex(container) + 1;
  9137. } else {
  9138. offset = nodeIndex(container);
  9139. }
  9140. return CaretPosition(container.parentNode, offset);
  9141. }
  9142. return findTextPosition(container, parseInt(offset, 10));
  9143. };
  9144. var isContentEditableFalse$9 = isContentEditableFalse$b;
  9145. var getNormalizedTextOffset = function (trim, container, offset) {
  9146. var node, trimmedOffset;
  9147. trimmedOffset = trim(container.data.slice(0, offset)).length;
  9148. for (node = container.previousSibling; node && isText$7(node); node = node.previousSibling) {
  9149. trimmedOffset += trim(node.data).length;
  9150. }
  9151. return trimmedOffset;
  9152. };
  9153. var getPoint = function (dom, trim, normalized, rng, start) {
  9154. var container = rng[start ? 'startContainer' : 'endContainer'];
  9155. var offset = rng[start ? 'startOffset' : 'endOffset'];
  9156. var point = [];
  9157. var childNodes, after = 0;
  9158. var root = dom.getRoot();
  9159. if (isText$7(container)) {
  9160. point.push(normalized ? getNormalizedTextOffset(trim, container, offset) : offset);
  9161. } else {
  9162. childNodes = container.childNodes;
  9163. if (offset >= childNodes.length && childNodes.length) {
  9164. after = 1;
  9165. offset = Math.max(0, childNodes.length - 1);
  9166. }
  9167. point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
  9168. }
  9169. for (; container && container !== root; container = container.parentNode) {
  9170. point.push(dom.nodeIndex(container, normalized));
  9171. }
  9172. return point;
  9173. };
  9174. var getLocation = function (trim, selection, normalized, rng) {
  9175. var dom = selection.dom, bookmark = {};
  9176. bookmark.start = getPoint(dom, trim, normalized, rng, true);
  9177. if (!selection.isCollapsed()) {
  9178. bookmark.end = getPoint(dom, trim, normalized, rng, false);
  9179. }
  9180. if (isRangeInCaretContainerBlock(rng)) {
  9181. bookmark.isFakeCaret = true;
  9182. }
  9183. return bookmark;
  9184. };
  9185. var findIndex = function (dom, name, element) {
  9186. var count = 0;
  9187. Tools.each(dom.select(name), function (node) {
  9188. if (node.getAttribute('data-mce-bogus') === 'all') {
  9189. return;
  9190. }
  9191. if (node === element) {
  9192. return false;
  9193. }
  9194. count++;
  9195. });
  9196. return count;
  9197. };
  9198. var moveEndPoint$1 = function (rng, start) {
  9199. var container, offset, childNodes;
  9200. var prefix = start ? 'start' : 'end';
  9201. container = rng[prefix + 'Container'];
  9202. offset = rng[prefix + 'Offset'];
  9203. if (isElement$5(container) && container.nodeName === 'TR') {
  9204. childNodes = container.childNodes;
  9205. container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
  9206. if (container) {
  9207. offset = start ? 0 : container.childNodes.length;
  9208. rng['set' + (start ? 'Start' : 'End')](container, offset);
  9209. }
  9210. }
  9211. };
  9212. var normalizeTableCellSelection = function (rng) {
  9213. moveEndPoint$1(rng, true);
  9214. moveEndPoint$1(rng, false);
  9215. return rng;
  9216. };
  9217. var findSibling = function (node, offset) {
  9218. var sibling;
  9219. if (isElement$5(node)) {
  9220. node = getNode$1(node, offset);
  9221. if (isContentEditableFalse$9(node)) {
  9222. return node;
  9223. }
  9224. }
  9225. if (isCaretContainer$2(node)) {
  9226. if (isText$7(node) && isCaretContainerBlock$1(node)) {
  9227. node = node.parentNode;
  9228. }
  9229. sibling = node.previousSibling;
  9230. if (isContentEditableFalse$9(sibling)) {
  9231. return sibling;
  9232. }
  9233. sibling = node.nextSibling;
  9234. if (isContentEditableFalse$9(sibling)) {
  9235. return sibling;
  9236. }
  9237. }
  9238. };
  9239. var findAdjacentContentEditableFalseElm = function (rng) {
  9240. return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
  9241. };
  9242. var getOffsetBookmark = function (trim, normalized, selection) {
  9243. var element = selection.getNode();
  9244. var name = element ? element.nodeName : null;
  9245. var rng = selection.getRng();
  9246. if (isContentEditableFalse$9(element) || name === 'IMG') {
  9247. return {
  9248. name: name,
  9249. index: findIndex(selection.dom, name, element)
  9250. };
  9251. }
  9252. var sibling = findAdjacentContentEditableFalseElm(rng);
  9253. if (sibling) {
  9254. name = sibling.tagName;
  9255. return {
  9256. name: name,
  9257. index: findIndex(selection.dom, name, sibling)
  9258. };
  9259. }
  9260. return getLocation(trim, selection, normalized, rng);
  9261. };
  9262. var getCaretBookmark = function (selection) {
  9263. var rng = selection.getRng();
  9264. return {
  9265. start: create$6(selection.dom.getRoot(), CaretPosition.fromRangeStart(rng)),
  9266. end: create$6(selection.dom.getRoot(), CaretPosition.fromRangeEnd(rng))
  9267. };
  9268. };
  9269. var getRangeBookmark = function (selection) {
  9270. return { rng: selection.getRng() };
  9271. };
  9272. var createBookmarkSpan = function (dom, id, filled) {
  9273. var args = {
  9274. 'data-mce-type': 'bookmark',
  9275. id: id,
  9276. 'style': 'overflow:hidden;line-height:0px'
  9277. };
  9278. return filled ? dom.create('span', args, '&#xFEFF;') : dom.create('span', args);
  9279. };
  9280. var getPersistentBookmark = function (selection, filled) {
  9281. var dom = selection.dom;
  9282. var rng = selection.getRng();
  9283. var id = dom.uniqueId();
  9284. var collapsed = selection.isCollapsed();
  9285. var element = selection.getNode();
  9286. var name = element.nodeName;
  9287. if (name === 'IMG') {
  9288. return {
  9289. name: name,
  9290. index: findIndex(dom, name, element)
  9291. };
  9292. }
  9293. var rng2 = normalizeTableCellSelection(rng.cloneRange());
  9294. if (!collapsed) {
  9295. rng2.collapse(false);
  9296. var endBookmarkNode = createBookmarkSpan(dom, id + '_end', filled);
  9297. rangeInsertNode(dom, rng2, endBookmarkNode);
  9298. }
  9299. rng = normalizeTableCellSelection(rng);
  9300. rng.collapse(true);
  9301. var startBookmarkNode = createBookmarkSpan(dom, id + '_start', filled);
  9302. rangeInsertNode(dom, rng, startBookmarkNode);
  9303. selection.moveToBookmark({
  9304. id: id,
  9305. keep: true
  9306. });
  9307. return { id: id };
  9308. };
  9309. var getBookmark$2 = function (selection, type, normalized) {
  9310. if (type === 2) {
  9311. return getOffsetBookmark(trim$2, normalized, selection);
  9312. } else if (type === 3) {
  9313. return getCaretBookmark(selection);
  9314. } else if (type) {
  9315. return getRangeBookmark(selection);
  9316. } else {
  9317. return getPersistentBookmark(selection, false);
  9318. }
  9319. };
  9320. var getUndoBookmark = curry(getOffsetBookmark, identity, true);
  9321. var DOM$9 = DOMUtils.DOM;
  9322. var defaultPreviewStyles = 'font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow';
  9323. var getBodySetting = function (editor, name, defaultValue) {
  9324. var value = editor.getParam(name, defaultValue);
  9325. if (value.indexOf('=') !== -1) {
  9326. var bodyObj = editor.getParam(name, '', 'hash');
  9327. return get$9(bodyObj, editor.id).getOr(defaultValue);
  9328. } else {
  9329. return value;
  9330. }
  9331. };
  9332. var getIframeAttrs = function (editor) {
  9333. return editor.getParam('iframe_attrs', {});
  9334. };
  9335. var getDocType = function (editor) {
  9336. return editor.getParam('doctype', '<!DOCTYPE html>');
  9337. };
  9338. var getDocumentBaseUrl = function (editor) {
  9339. return editor.getParam('document_base_url', '');
  9340. };
  9341. var getBodyId = function (editor) {
  9342. return getBodySetting(editor, 'body_id', 'tinymce');
  9343. };
  9344. var getBodyClass = function (editor) {
  9345. return getBodySetting(editor, 'body_class', '');
  9346. };
  9347. var getContentSecurityPolicy = function (editor) {
  9348. return editor.getParam('content_security_policy', '');
  9349. };
  9350. var shouldPutBrInPre$1 = function (editor) {
  9351. return editor.getParam('br_in_pre', true);
  9352. };
  9353. var getForcedRootBlock = function (editor) {
  9354. if (editor.getParam('force_p_newlines', false)) {
  9355. return 'p';
  9356. }
  9357. var block = editor.getParam('forced_root_block', 'p');
  9358. if (block === false) {
  9359. return '';
  9360. } else if (block === true) {
  9361. return 'p';
  9362. } else {
  9363. return block;
  9364. }
  9365. };
  9366. var getForcedRootBlockAttrs = function (editor) {
  9367. return editor.getParam('forced_root_block_attrs', {});
  9368. };
  9369. var getBrNewLineSelector = function (editor) {
  9370. return editor.getParam('br_newline_selector', '.mce-toc h2,figcaption,caption');
  9371. };
  9372. var getNoNewLineSelector = function (editor) {
  9373. return editor.getParam('no_newline_selector', '');
  9374. };
  9375. var shouldKeepStyles = function (editor) {
  9376. return editor.getParam('keep_styles', true);
  9377. };
  9378. var shouldEndContainerOnEmptyBlock = function (editor) {
  9379. return editor.getParam('end_container_on_empty_block', false);
  9380. };
  9381. var getFontStyleValues = function (editor) {
  9382. return Tools.explode(editor.getParam('font_size_style_values', 'xx-small,x-small,small,medium,large,x-large,xx-large'));
  9383. };
  9384. var getFontSizeClasses = function (editor) {
  9385. return Tools.explode(editor.getParam('font_size_classes', ''));
  9386. };
  9387. var getImagesDataImgFilter = function (editor) {
  9388. return editor.getParam('images_dataimg_filter', always, 'function');
  9389. };
  9390. var isAutomaticUploadsEnabled = function (editor) {
  9391. return editor.getParam('automatic_uploads', true, 'boolean');
  9392. };
  9393. var shouldReuseFileName = function (editor) {
  9394. return editor.getParam('images_reuse_filename', false, 'boolean');
  9395. };
  9396. var shouldReplaceBlobUris = function (editor) {
  9397. return editor.getParam('images_replace_blob_uris', true, 'boolean');
  9398. };
  9399. var getIconPackName = function (editor) {
  9400. return editor.getParam('icons', '', 'string');
  9401. };
  9402. var getIconsUrl = function (editor) {
  9403. return editor.getParam('icons_url', '', 'string');
  9404. };
  9405. var getImageUploadUrl = function (editor) {
  9406. return editor.getParam('images_upload_url', '', 'string');
  9407. };
  9408. var getImageUploadBasePath = function (editor) {
  9409. return editor.getParam('images_upload_base_path', '', 'string');
  9410. };
  9411. var getImagesUploadCredentials = function (editor) {
  9412. return editor.getParam('images_upload_credentials', false, 'boolean');
  9413. };
  9414. var getImagesUploadHandler = function (editor) {
  9415. return editor.getParam('images_upload_handler', null, 'function');
  9416. };
  9417. var shouldUseContentCssCors = function (editor) {
  9418. return editor.getParam('content_css_cors', false, 'boolean');
  9419. };
  9420. var getReferrerPolicy = function (editor) {
  9421. return editor.getParam('referrer_policy', '', 'string');
  9422. };
  9423. var getLanguageCode = function (editor) {
  9424. return editor.getParam('language', 'en', 'string');
  9425. };
  9426. var getLanguageUrl = function (editor) {
  9427. return editor.getParam('language_url', '', 'string');
  9428. };
  9429. var shouldIndentUseMargin = function (editor) {
  9430. return editor.getParam('indent_use_margin', false);
  9431. };
  9432. var getIndentation = function (editor) {
  9433. return editor.getParam('indentation', '40px', 'string');
  9434. };
  9435. var getContentCss = function (editor) {
  9436. var contentCss = editor.getParam('content_css');
  9437. if (isString$1(contentCss)) {
  9438. return map$3(contentCss.split(','), trim$4);
  9439. } else if (isArray$1(contentCss)) {
  9440. return contentCss;
  9441. } else if (contentCss === false || editor.inline) {
  9442. return [];
  9443. } else {
  9444. return ['default'];
  9445. }
  9446. };
  9447. var getFontCss = function (editor) {
  9448. var fontCss = editor.getParam('font_css', []);
  9449. return isArray$1(fontCss) ? fontCss : map$3(fontCss.split(','), trim$4);
  9450. };
  9451. var getDirectionality = function (editor) {
  9452. return editor.getParam('directionality', I18n.isRtl() ? 'rtl' : undefined);
  9453. };
  9454. var getInlineBoundarySelector = function (editor) {
  9455. return editor.getParam('inline_boundaries_selector', 'a[href],code,.mce-annotation', 'string');
  9456. };
  9457. var getObjectResizing = function (editor) {
  9458. var selector = editor.getParam('object_resizing');
  9459. if (selector === false || Env.iOS) {
  9460. return false;
  9461. } else {
  9462. return isString$1(selector) ? selector : 'table,img,figure.image,div,video,iframe';
  9463. }
  9464. };
  9465. var getResizeImgProportional = function (editor) {
  9466. return editor.getParam('resize_img_proportional', true, 'boolean');
  9467. };
  9468. var getPlaceholder = function (editor) {
  9469. return editor.getParam('placeholder', DOM$9.getAttrib(editor.getElement(), 'placeholder'), 'string');
  9470. };
  9471. var getEventRoot = function (editor) {
  9472. return editor.getParam('event_root');
  9473. };
  9474. var getServiceMessage = function (editor) {
  9475. return editor.getParam('service_message');
  9476. };
  9477. var getTheme = function (editor) {
  9478. return editor.getParam('theme');
  9479. };
  9480. var shouldValidate = function (editor) {
  9481. return editor.getParam('validate');
  9482. };
  9483. var isInlineBoundariesEnabled = function (editor) {
  9484. return editor.getParam('inline_boundaries') !== false;
  9485. };
  9486. var getFormats = function (editor) {
  9487. return editor.getParam('formats');
  9488. };
  9489. var getPreviewStyles = function (editor) {
  9490. var style = editor.getParam('preview_styles', defaultPreviewStyles);
  9491. if (isString$1(style)) {
  9492. return style;
  9493. } else {
  9494. return '';
  9495. }
  9496. };
  9497. var canFormatEmptyLines = function (editor) {
  9498. return editor.getParam('format_empty_lines', false, 'boolean');
  9499. };
  9500. var getCustomUiSelector = function (editor) {
  9501. return editor.getParam('custom_ui_selector', '', 'string');
  9502. };
  9503. var getThemeUrl = function (editor) {
  9504. return editor.getParam('theme_url');
  9505. };
  9506. var isInline = function (editor) {
  9507. return editor.getParam('inline');
  9508. };
  9509. var hasHiddenInput = function (editor) {
  9510. return editor.getParam('hidden_input');
  9511. };
  9512. var shouldPatchSubmit = function (editor) {
  9513. return editor.getParam('submit_patch');
  9514. };
  9515. var isEncodingXml = function (editor) {
  9516. return editor.getParam('encoding') === 'xml';
  9517. };
  9518. var shouldAddFormSubmitTrigger = function (editor) {
  9519. return editor.getParam('add_form_submit_trigger');
  9520. };
  9521. var shouldAddUnloadTrigger = function (editor) {
  9522. return editor.getParam('add_unload_trigger');
  9523. };
  9524. var hasForcedRootBlock = function (editor) {
  9525. return getForcedRootBlock(editor) !== '';
  9526. };
  9527. var getCustomUndoRedoLevels = function (editor) {
  9528. return editor.getParam('custom_undo_redo_levels', 0, 'number');
  9529. };
  9530. var shouldDisableNodeChange = function (editor) {
  9531. return editor.getParam('disable_nodechange');
  9532. };
  9533. var isReadOnly$1 = function (editor) {
  9534. return editor.getParam('readonly');
  9535. };
  9536. var hasContentCssCors = function (editor) {
  9537. return editor.getParam('content_css_cors');
  9538. };
  9539. var getPlugins = function (editor) {
  9540. return editor.getParam('plugins', '', 'string');
  9541. };
  9542. var getExternalPlugins$1 = function (editor) {
  9543. return editor.getParam('external_plugins');
  9544. };
  9545. var shouldBlockUnsupportedDrop = function (editor) {
  9546. return editor.getParam('block_unsupported_drop', true, 'boolean');
  9547. };
  9548. var isVisualAidsEnabled = function (editor) {
  9549. return editor.getParam('visual', true, 'boolean');
  9550. };
  9551. var getVisualAidsTableClass = function (editor) {
  9552. return editor.getParam('visual_table_class', 'mce-item-table', 'string');
  9553. };
  9554. var getVisualAidsAnchorClass = function (editor) {
  9555. return editor.getParam('visual_anchor_class', 'mce-item-anchor', 'string');
  9556. };
  9557. var getIframeTitle = function (editor) {
  9558. return editor.getParam('iframe_aria_text', 'Rich Text Area. Press ALT-0 for help.', 'string');
  9559. };
  9560. var isElement$2 = isElement$5;
  9561. var isText$2 = isText$7;
  9562. var removeNode$1 = function (node) {
  9563. var parentNode = node.parentNode;
  9564. if (parentNode) {
  9565. parentNode.removeChild(node);
  9566. }
  9567. };
  9568. var trimCount = function (text) {
  9569. var trimmedText = trim$2(text);
  9570. return {
  9571. count: text.length - trimmedText.length,
  9572. text: trimmedText
  9573. };
  9574. };
  9575. var deleteZwspChars = function (caretContainer) {
  9576. var idx;
  9577. while ((idx = caretContainer.data.lastIndexOf(ZWSP$1)) !== -1) {
  9578. caretContainer.deleteData(idx, 1);
  9579. }
  9580. };
  9581. var removeUnchanged = function (caretContainer, pos) {
  9582. remove$2(caretContainer);
  9583. return pos;
  9584. };
  9585. var removeTextAndReposition = function (caretContainer, pos) {
  9586. var before = trimCount(caretContainer.data.substr(0, pos.offset()));
  9587. var after = trimCount(caretContainer.data.substr(pos.offset()));
  9588. var text = before.text + after.text;
  9589. if (text.length > 0) {
  9590. deleteZwspChars(caretContainer);
  9591. return CaretPosition(caretContainer, pos.offset() - before.count);
  9592. } else {
  9593. return pos;
  9594. }
  9595. };
  9596. var removeElementAndReposition = function (caretContainer, pos) {
  9597. var parentNode = pos.container();
  9598. var newPosition = indexOf$2(from(parentNode.childNodes), caretContainer).map(function (index) {
  9599. return index < pos.offset() ? CaretPosition(parentNode, pos.offset() - 1) : pos;
  9600. }).getOr(pos);
  9601. remove$2(caretContainer);
  9602. return newPosition;
  9603. };
  9604. var removeTextCaretContainer = function (caretContainer, pos) {
  9605. return isText$2(caretContainer) && pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9606. };
  9607. var removeElementCaretContainer = function (caretContainer, pos) {
  9608. return pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9609. };
  9610. var removeAndReposition = function (container, pos) {
  9611. return CaretPosition.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
  9612. };
  9613. var remove$2 = function (caretContainerNode) {
  9614. if (isElement$2(caretContainerNode) && isCaretContainer$2(caretContainerNode)) {
  9615. if (hasContent(caretContainerNode)) {
  9616. caretContainerNode.removeAttribute('data-mce-caret');
  9617. } else {
  9618. removeNode$1(caretContainerNode);
  9619. }
  9620. }
  9621. if (isText$2(caretContainerNode)) {
  9622. deleteZwspChars(caretContainerNode);
  9623. if (caretContainerNode.data.length === 0) {
  9624. removeNode$1(caretContainerNode);
  9625. }
  9626. }
  9627. };
  9628. var browser$2 = detect().browser;
  9629. var isContentEditableFalse$8 = isContentEditableFalse$b;
  9630. var isMedia$1 = isMedia$2;
  9631. var isTableCell$3 = isTableCell$5;
  9632. var inlineFakeCaretSelector = '*[contentEditable=false],video,audio,embed,object';
  9633. var getAbsoluteClientRect = function (root, element, before) {
  9634. var clientRect = collapse(element.getBoundingClientRect(), before);
  9635. var scrollX;
  9636. var scrollY;
  9637. if (root.tagName === 'BODY') {
  9638. var docElm = root.ownerDocument.documentElement;
  9639. scrollX = root.scrollLeft || docElm.scrollLeft;
  9640. scrollY = root.scrollTop || docElm.scrollTop;
  9641. } else {
  9642. var rootRect = root.getBoundingClientRect();
  9643. scrollX = root.scrollLeft - rootRect.left;
  9644. scrollY = root.scrollTop - rootRect.top;
  9645. }
  9646. clientRect.left += scrollX;
  9647. clientRect.right += scrollX;
  9648. clientRect.top += scrollY;
  9649. clientRect.bottom += scrollY;
  9650. clientRect.width = 1;
  9651. var margin = element.offsetWidth - element.clientWidth;
  9652. if (margin > 0) {
  9653. if (before) {
  9654. margin *= -1;
  9655. }
  9656. clientRect.left += margin;
  9657. clientRect.right += margin;
  9658. }
  9659. return clientRect;
  9660. };
  9661. var trimInlineCaretContainers = function (root) {
  9662. var fakeCaretTargetNodes = descendants(SugarElement.fromDom(root), inlineFakeCaretSelector);
  9663. for (var i = 0; i < fakeCaretTargetNodes.length; i++) {
  9664. var node = fakeCaretTargetNodes[i].dom;
  9665. var sibling = node.previousSibling;
  9666. if (endsWithCaretContainer$1(sibling)) {
  9667. var data = sibling.data;
  9668. if (data.length === 1) {
  9669. sibling.parentNode.removeChild(sibling);
  9670. } else {
  9671. sibling.deleteData(data.length - 1, 1);
  9672. }
  9673. }
  9674. sibling = node.nextSibling;
  9675. if (startsWithCaretContainer$1(sibling)) {
  9676. var data = sibling.data;
  9677. if (data.length === 1) {
  9678. sibling.parentNode.removeChild(sibling);
  9679. } else {
  9680. sibling.deleteData(0, 1);
  9681. }
  9682. }
  9683. }
  9684. };
  9685. var FakeCaret = function (editor, root, isBlock, hasFocus) {
  9686. var lastVisualCaret = value();
  9687. var cursorInterval;
  9688. var caretContainerNode;
  9689. var rootBlock = getForcedRootBlock(editor);
  9690. var caretBlock = rootBlock.length > 0 ? rootBlock : 'p';
  9691. var show = function (before, element) {
  9692. var rng;
  9693. hide();
  9694. if (isTableCell$3(element)) {
  9695. return null;
  9696. }
  9697. if (isBlock(element)) {
  9698. caretContainerNode = insertBlock$1(caretBlock, element, before);
  9699. var clientRect = getAbsoluteClientRect(root, element, before);
  9700. DomQuery(caretContainerNode).css('top', clientRect.top);
  9701. var caret = DomQuery('<div class="mce-visual-caret" data-mce-bogus="all"></div>').css(__assign({}, clientRect)).appendTo(root)[0];
  9702. lastVisualCaret.set({
  9703. caret: caret,
  9704. element: element,
  9705. before: before
  9706. });
  9707. if (before) {
  9708. DomQuery(caret).addClass('mce-visual-caret-before');
  9709. }
  9710. startBlink();
  9711. rng = element.ownerDocument.createRange();
  9712. rng.setStart(caretContainerNode, 0);
  9713. rng.setEnd(caretContainerNode, 0);
  9714. } else {
  9715. caretContainerNode = insertInline$1(element, before);
  9716. rng = element.ownerDocument.createRange();
  9717. if (isInlineFakeCaretTarget(caretContainerNode.nextSibling)) {
  9718. rng.setStart(caretContainerNode, 0);
  9719. rng.setEnd(caretContainerNode, 0);
  9720. } else {
  9721. rng.setStart(caretContainerNode, 1);
  9722. rng.setEnd(caretContainerNode, 1);
  9723. }
  9724. return rng;
  9725. }
  9726. return rng;
  9727. };
  9728. var hide = function () {
  9729. trimInlineCaretContainers(root);
  9730. if (caretContainerNode) {
  9731. remove$2(caretContainerNode);
  9732. caretContainerNode = null;
  9733. }
  9734. lastVisualCaret.on(function (caretState) {
  9735. DomQuery(caretState.caret).remove();
  9736. lastVisualCaret.clear();
  9737. });
  9738. if (cursorInterval) {
  9739. Delay.clearInterval(cursorInterval);
  9740. cursorInterval = undefined;
  9741. }
  9742. };
  9743. var startBlink = function () {
  9744. cursorInterval = Delay.setInterval(function () {
  9745. if (hasFocus()) {
  9746. DomQuery('div.mce-visual-caret', root).toggleClass('mce-visual-caret-hidden');
  9747. } else {
  9748. DomQuery('div.mce-visual-caret', root).addClass('mce-visual-caret-hidden');
  9749. }
  9750. }, 500);
  9751. };
  9752. var reposition = function () {
  9753. lastVisualCaret.on(function (caretState) {
  9754. var clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
  9755. DomQuery(caretState.caret).css(__assign({}, clientRect));
  9756. });
  9757. };
  9758. var destroy = function () {
  9759. return Delay.clearInterval(cursorInterval);
  9760. };
  9761. var getCss = function () {
  9762. 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;' + '}';
  9763. };
  9764. return {
  9765. show: show,
  9766. hide: hide,
  9767. getCss: getCss,
  9768. reposition: reposition,
  9769. destroy: destroy
  9770. };
  9771. };
  9772. var isFakeCaretTableBrowser = function () {
  9773. return browser$2.isIE() || browser$2.isEdge() || browser$2.isFirefox();
  9774. };
  9775. var isInlineFakeCaretTarget = function (node) {
  9776. return isContentEditableFalse$8(node) || isMedia$1(node);
  9777. };
  9778. var isFakeCaretTarget = function (node) {
  9779. return isInlineFakeCaretTarget(node) || isTable$3(node) && isFakeCaretTableBrowser();
  9780. };
  9781. var isContentEditableFalse$7 = isContentEditableFalse$b;
  9782. var isMedia = isMedia$2;
  9783. var isBlockLike = matchStyleValues('display', 'block table table-cell table-caption list-item');
  9784. var isCaretContainer = isCaretContainer$2;
  9785. var isCaretContainerBlock = isCaretContainerBlock$1;
  9786. var isElement$1 = isElement$5;
  9787. var isCaretCandidate$1 = isCaretCandidate$3;
  9788. var isForwards = function (direction) {
  9789. return direction > 0;
  9790. };
  9791. var isBackwards = function (direction) {
  9792. return direction < 0;
  9793. };
  9794. var skipCaretContainers = function (walk, shallow) {
  9795. var node;
  9796. while (node = walk(shallow)) {
  9797. if (!isCaretContainerBlock(node)) {
  9798. return node;
  9799. }
  9800. }
  9801. return null;
  9802. };
  9803. var findNode$1 = function (node, direction, predicateFn, rootNode, shallow) {
  9804. var walker = new DomTreeWalker(node, rootNode);
  9805. var isCefOrCaretContainer = isContentEditableFalse$7(node) || isCaretContainerBlock(node);
  9806. if (isBackwards(direction)) {
  9807. if (isCefOrCaretContainer) {
  9808. node = skipCaretContainers(walker.prev.bind(walker), true);
  9809. if (predicateFn(node)) {
  9810. return node;
  9811. }
  9812. }
  9813. while (node = skipCaretContainers(walker.prev.bind(walker), shallow)) {
  9814. if (predicateFn(node)) {
  9815. return node;
  9816. }
  9817. }
  9818. }
  9819. if (isForwards(direction)) {
  9820. if (isCefOrCaretContainer) {
  9821. node = skipCaretContainers(walker.next.bind(walker), true);
  9822. if (predicateFn(node)) {
  9823. return node;
  9824. }
  9825. }
  9826. while (node = skipCaretContainers(walker.next.bind(walker), shallow)) {
  9827. if (predicateFn(node)) {
  9828. return node;
  9829. }
  9830. }
  9831. }
  9832. return null;
  9833. };
  9834. var getParentBlock$2 = function (node, rootNode) {
  9835. while (node && node !== rootNode) {
  9836. if (isBlockLike(node)) {
  9837. return node;
  9838. }
  9839. node = node.parentNode;
  9840. }
  9841. return null;
  9842. };
  9843. var isInSameBlock = function (caretPosition1, caretPosition2, rootNode) {
  9844. return getParentBlock$2(caretPosition1.container(), rootNode) === getParentBlock$2(caretPosition2.container(), rootNode);
  9845. };
  9846. var getChildNodeAtRelativeOffset = function (relativeOffset, caretPosition) {
  9847. if (!caretPosition) {
  9848. return null;
  9849. }
  9850. var container = caretPosition.container();
  9851. var offset = caretPosition.offset();
  9852. if (!isElement$1(container)) {
  9853. return null;
  9854. }
  9855. return container.childNodes[offset + relativeOffset];
  9856. };
  9857. var beforeAfter = function (before, node) {
  9858. var range = node.ownerDocument.createRange();
  9859. if (before) {
  9860. range.setStartBefore(node);
  9861. range.setEndBefore(node);
  9862. } else {
  9863. range.setStartAfter(node);
  9864. range.setEndAfter(node);
  9865. }
  9866. return range;
  9867. };
  9868. var isNodesInSameBlock = function (root, node1, node2) {
  9869. return getParentBlock$2(node1, root) === getParentBlock$2(node2, root);
  9870. };
  9871. var lean = function (left, root, node) {
  9872. var siblingName = left ? 'previousSibling' : 'nextSibling';
  9873. while (node && node !== root) {
  9874. var sibling = node[siblingName];
  9875. if (isCaretContainer(sibling)) {
  9876. sibling = sibling[siblingName];
  9877. }
  9878. if (isContentEditableFalse$7(sibling) || isMedia(sibling)) {
  9879. if (isNodesInSameBlock(root, sibling, node)) {
  9880. return sibling;
  9881. }
  9882. break;
  9883. }
  9884. if (isCaretCandidate$1(sibling)) {
  9885. break;
  9886. }
  9887. node = node.parentNode;
  9888. }
  9889. return null;
  9890. };
  9891. var before$2 = curry(beforeAfter, true);
  9892. var after$2 = curry(beforeAfter, false);
  9893. var normalizeRange = function (direction, root, range) {
  9894. var node;
  9895. var leanLeft = curry(lean, true, root);
  9896. var leanRight = curry(lean, false, root);
  9897. var container = range.startContainer;
  9898. var offset = range.startOffset;
  9899. if (isCaretContainerBlock$1(container)) {
  9900. if (!isElement$1(container)) {
  9901. container = container.parentNode;
  9902. }
  9903. var location_1 = container.getAttribute('data-mce-caret');
  9904. if (location_1 === 'before') {
  9905. node = container.nextSibling;
  9906. if (isFakeCaretTarget(node)) {
  9907. return before$2(node);
  9908. }
  9909. }
  9910. if (location_1 === 'after') {
  9911. node = container.previousSibling;
  9912. if (isFakeCaretTarget(node)) {
  9913. return after$2(node);
  9914. }
  9915. }
  9916. }
  9917. if (!range.collapsed) {
  9918. return range;
  9919. }
  9920. if (isText$7(container)) {
  9921. if (isCaretContainer(container)) {
  9922. if (direction === 1) {
  9923. node = leanRight(container);
  9924. if (node) {
  9925. return before$2(node);
  9926. }
  9927. node = leanLeft(container);
  9928. if (node) {
  9929. return after$2(node);
  9930. }
  9931. }
  9932. if (direction === -1) {
  9933. node = leanLeft(container);
  9934. if (node) {
  9935. return after$2(node);
  9936. }
  9937. node = leanRight(container);
  9938. if (node) {
  9939. return before$2(node);
  9940. }
  9941. }
  9942. return range;
  9943. }
  9944. if (endsWithCaretContainer$1(container) && offset >= container.data.length - 1) {
  9945. if (direction === 1) {
  9946. node = leanRight(container);
  9947. if (node) {
  9948. return before$2(node);
  9949. }
  9950. }
  9951. return range;
  9952. }
  9953. if (startsWithCaretContainer$1(container) && offset <= 1) {
  9954. if (direction === -1) {
  9955. node = leanLeft(container);
  9956. if (node) {
  9957. return after$2(node);
  9958. }
  9959. }
  9960. return range;
  9961. }
  9962. if (offset === container.data.length) {
  9963. node = leanRight(container);
  9964. if (node) {
  9965. return before$2(node);
  9966. }
  9967. return range;
  9968. }
  9969. if (offset === 0) {
  9970. node = leanLeft(container);
  9971. if (node) {
  9972. return after$2(node);
  9973. }
  9974. return range;
  9975. }
  9976. }
  9977. return range;
  9978. };
  9979. var getRelativeCefElm = function (forward, caretPosition) {
  9980. return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition)).filter(isContentEditableFalse$7);
  9981. };
  9982. var getNormalizedRangeEndPoint = function (direction, root, range) {
  9983. var normalizedRange = normalizeRange(direction, root, range);
  9984. if (direction === -1) {
  9985. return CaretPosition.fromRangeStart(normalizedRange);
  9986. }
  9987. return CaretPosition.fromRangeEnd(normalizedRange);
  9988. };
  9989. var getElementFromPosition = function (pos) {
  9990. return Optional.from(pos.getNode()).map(SugarElement.fromDom);
  9991. };
  9992. var getElementFromPrevPosition = function (pos) {
  9993. return Optional.from(pos.getNode(true)).map(SugarElement.fromDom);
  9994. };
  9995. var getVisualCaretPosition = function (walkFn, caretPosition) {
  9996. while (caretPosition = walkFn(caretPosition)) {
  9997. if (caretPosition.isVisible()) {
  9998. return caretPosition;
  9999. }
  10000. }
  10001. return caretPosition;
  10002. };
  10003. var isMoveInsideSameBlock = function (from, to) {
  10004. var inSameBlock = isInSameBlock(from, to);
  10005. if (!inSameBlock && isBr$5(from.getNode())) {
  10006. return true;
  10007. }
  10008. return inSameBlock;
  10009. };
  10010. var HDirection;
  10011. (function (HDirection) {
  10012. HDirection[HDirection['Backwards'] = -1] = 'Backwards';
  10013. HDirection[HDirection['Forwards'] = 1] = 'Forwards';
  10014. }(HDirection || (HDirection = {})));
  10015. var isContentEditableFalse$6 = isContentEditableFalse$b;
  10016. var isText$1 = isText$7;
  10017. var isElement = isElement$5;
  10018. var isBr$1 = isBr$5;
  10019. var isCaretCandidate = isCaretCandidate$3;
  10020. var isAtomic = isAtomic$1;
  10021. var isEditableCaretCandidate = isEditableCaretCandidate$1;
  10022. var getParents$3 = function (node, root) {
  10023. var parents = [];
  10024. while (node && node !== root) {
  10025. parents.push(node);
  10026. node = node.parentNode;
  10027. }
  10028. return parents;
  10029. };
  10030. var nodeAtIndex = function (container, offset) {
  10031. if (container.hasChildNodes() && offset < container.childNodes.length) {
  10032. return container.childNodes[offset];
  10033. }
  10034. return null;
  10035. };
  10036. var getCaretCandidatePosition = function (direction, node) {
  10037. if (isForwards(direction)) {
  10038. if (isCaretCandidate(node.previousSibling) && !isText$1(node.previousSibling)) {
  10039. return CaretPosition.before(node);
  10040. }
  10041. if (isText$1(node)) {
  10042. return CaretPosition(node, 0);
  10043. }
  10044. }
  10045. if (isBackwards(direction)) {
  10046. if (isCaretCandidate(node.nextSibling) && !isText$1(node.nextSibling)) {
  10047. return CaretPosition.after(node);
  10048. }
  10049. if (isText$1(node)) {
  10050. return CaretPosition(node, node.data.length);
  10051. }
  10052. }
  10053. if (isBackwards(direction)) {
  10054. if (isBr$1(node)) {
  10055. return CaretPosition.before(node);
  10056. }
  10057. return CaretPosition.after(node);
  10058. }
  10059. return CaretPosition.before(node);
  10060. };
  10061. var moveForwardFromBr = function (root, nextNode) {
  10062. var nextSibling = nextNode.nextSibling;
  10063. if (nextSibling && isCaretCandidate(nextSibling)) {
  10064. if (isText$1(nextSibling)) {
  10065. return CaretPosition(nextSibling, 0);
  10066. } else {
  10067. return CaretPosition.before(nextSibling);
  10068. }
  10069. } else {
  10070. return findCaretPosition$1(HDirection.Forwards, CaretPosition.after(nextNode), root);
  10071. }
  10072. };
  10073. var findCaretPosition$1 = function (direction, startPos, root) {
  10074. var node;
  10075. var nextNode;
  10076. var innerNode;
  10077. var caretPosition;
  10078. if (!isElement(root) || !startPos) {
  10079. return null;
  10080. }
  10081. if (startPos.isEqual(CaretPosition.after(root)) && root.lastChild) {
  10082. caretPosition = CaretPosition.after(root.lastChild);
  10083. if (isBackwards(direction) && isCaretCandidate(root.lastChild) && isElement(root.lastChild)) {
  10084. return isBr$1(root.lastChild) ? CaretPosition.before(root.lastChild) : caretPosition;
  10085. }
  10086. } else {
  10087. caretPosition = startPos;
  10088. }
  10089. var container = caretPosition.container();
  10090. var offset = caretPosition.offset();
  10091. if (isText$1(container)) {
  10092. if (isBackwards(direction) && offset > 0) {
  10093. return CaretPosition(container, --offset);
  10094. }
  10095. if (isForwards(direction) && offset < container.length) {
  10096. return CaretPosition(container, ++offset);
  10097. }
  10098. node = container;
  10099. } else {
  10100. if (isBackwards(direction) && offset > 0) {
  10101. nextNode = nodeAtIndex(container, offset - 1);
  10102. if (isCaretCandidate(nextNode)) {
  10103. if (!isAtomic(nextNode)) {
  10104. innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
  10105. if (innerNode) {
  10106. if (isText$1(innerNode)) {
  10107. return CaretPosition(innerNode, innerNode.data.length);
  10108. }
  10109. return CaretPosition.after(innerNode);
  10110. }
  10111. }
  10112. if (isText$1(nextNode)) {
  10113. return CaretPosition(nextNode, nextNode.data.length);
  10114. }
  10115. return CaretPosition.before(nextNode);
  10116. }
  10117. }
  10118. if (isForwards(direction) && offset < container.childNodes.length) {
  10119. nextNode = nodeAtIndex(container, offset);
  10120. if (isCaretCandidate(nextNode)) {
  10121. if (isBr$1(nextNode)) {
  10122. return moveForwardFromBr(root, nextNode);
  10123. }
  10124. if (!isAtomic(nextNode)) {
  10125. innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
  10126. if (innerNode) {
  10127. if (isText$1(innerNode)) {
  10128. return CaretPosition(innerNode, 0);
  10129. }
  10130. return CaretPosition.before(innerNode);
  10131. }
  10132. }
  10133. if (isText$1(nextNode)) {
  10134. return CaretPosition(nextNode, 0);
  10135. }
  10136. return CaretPosition.after(nextNode);
  10137. }
  10138. }
  10139. node = nextNode ? nextNode : caretPosition.getNode();
  10140. }
  10141. if (isForwards(direction) && caretPosition.isAtEnd() || isBackwards(direction) && caretPosition.isAtStart()) {
  10142. node = findNode$1(node, direction, always, root, true);
  10143. if (isEditableCaretCandidate(node, root)) {
  10144. return getCaretCandidatePosition(direction, node);
  10145. }
  10146. }
  10147. nextNode = findNode$1(node, direction, isEditableCaretCandidate, root);
  10148. var rootContentEditableFalseElm = last$1(filter$4(getParents$3(container, root), isContentEditableFalse$6));
  10149. if (rootContentEditableFalseElm && (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
  10150. if (isForwards(direction)) {
  10151. caretPosition = CaretPosition.after(rootContentEditableFalseElm);
  10152. } else {
  10153. caretPosition = CaretPosition.before(rootContentEditableFalseElm);
  10154. }
  10155. return caretPosition;
  10156. }
  10157. if (nextNode) {
  10158. return getCaretCandidatePosition(direction, nextNode);
  10159. }
  10160. return null;
  10161. };
  10162. var CaretWalker = function (root) {
  10163. return {
  10164. next: function (caretPosition) {
  10165. return findCaretPosition$1(HDirection.Forwards, caretPosition, root);
  10166. },
  10167. prev: function (caretPosition) {
  10168. return findCaretPosition$1(HDirection.Backwards, caretPosition, root);
  10169. }
  10170. };
  10171. };
  10172. var walkToPositionIn = function (forward, root, start) {
  10173. var position = forward ? CaretPosition.before(start) : CaretPosition.after(start);
  10174. return fromPosition(forward, root, position);
  10175. };
  10176. var afterElement = function (node) {
  10177. return isBr$5(node) ? CaretPosition.before(node) : CaretPosition.after(node);
  10178. };
  10179. var isBeforeOrStart = function (position) {
  10180. if (CaretPosition.isTextPosition(position)) {
  10181. return position.offset() === 0;
  10182. } else {
  10183. return isCaretCandidate$3(position.getNode());
  10184. }
  10185. };
  10186. var isAfterOrEnd = function (position) {
  10187. if (CaretPosition.isTextPosition(position)) {
  10188. var container = position.container();
  10189. return position.offset() === container.data.length;
  10190. } else {
  10191. return isCaretCandidate$3(position.getNode(true));
  10192. }
  10193. };
  10194. var isBeforeAfterSameElement = function (from, to) {
  10195. return !CaretPosition.isTextPosition(from) && !CaretPosition.isTextPosition(to) && from.getNode() === to.getNode(true);
  10196. };
  10197. var isAtBr = function (position) {
  10198. return !CaretPosition.isTextPosition(position) && isBr$5(position.getNode());
  10199. };
  10200. var shouldSkipPosition = function (forward, from, to) {
  10201. if (forward) {
  10202. return !isBeforeAfterSameElement(from, to) && !isAtBr(from) && isAfterOrEnd(from) && isBeforeOrStart(to);
  10203. } else {
  10204. return !isBeforeAfterSameElement(to, from) && isBeforeOrStart(from) && isAfterOrEnd(to);
  10205. }
  10206. };
  10207. var fromPosition = function (forward, root, pos) {
  10208. var walker = CaretWalker(root);
  10209. return Optional.from(forward ? walker.next(pos) : walker.prev(pos));
  10210. };
  10211. var navigate = function (forward, root, from) {
  10212. return fromPosition(forward, root, from).bind(function (to) {
  10213. if (isInSameBlock(from, to, root) && shouldSkipPosition(forward, from, to)) {
  10214. return fromPosition(forward, root, to);
  10215. } else {
  10216. return Optional.some(to);
  10217. }
  10218. });
  10219. };
  10220. var navigateIgnore = function (forward, root, from, ignoreFilter) {
  10221. return navigate(forward, root, from).bind(function (pos) {
  10222. return ignoreFilter(pos) ? navigateIgnore(forward, root, pos, ignoreFilter) : Optional.some(pos);
  10223. });
  10224. };
  10225. var positionIn = function (forward, element) {
  10226. var startNode = forward ? element.firstChild : element.lastChild;
  10227. if (isText$7(startNode)) {
  10228. return Optional.some(CaretPosition(startNode, forward ? 0 : startNode.data.length));
  10229. } else if (startNode) {
  10230. if (isCaretCandidate$3(startNode)) {
  10231. return Optional.some(forward ? CaretPosition.before(startNode) : afterElement(startNode));
  10232. } else {
  10233. return walkToPositionIn(forward, element, startNode);
  10234. }
  10235. } else {
  10236. return Optional.none();
  10237. }
  10238. };
  10239. var nextPosition = curry(fromPosition, true);
  10240. var prevPosition = curry(fromPosition, false);
  10241. var firstPositionIn = curry(positionIn, true);
  10242. var lastPositionIn = curry(positionIn, false);
  10243. var CARET_ID$1 = '_mce_caret';
  10244. var isCaretNode = function (node) {
  10245. return isElement$5(node) && node.id === CARET_ID$1;
  10246. };
  10247. var getParentCaretContainer = function (body, node) {
  10248. while (node && node !== body) {
  10249. if (node.id === CARET_ID$1) {
  10250. return node;
  10251. }
  10252. node = node.parentNode;
  10253. }
  10254. return null;
  10255. };
  10256. var isStringPathBookmark = function (bookmark) {
  10257. return isString$1(bookmark.start);
  10258. };
  10259. var isRangeBookmark = function (bookmark) {
  10260. return has$2(bookmark, 'rng');
  10261. };
  10262. var isIdBookmark = function (bookmark) {
  10263. return has$2(bookmark, 'id');
  10264. };
  10265. var isIndexBookmark = function (bookmark) {
  10266. return has$2(bookmark, 'name');
  10267. };
  10268. var isPathBookmark = function (bookmark) {
  10269. return Tools.isArray(bookmark.start);
  10270. };
  10271. var addBogus = function (dom, node) {
  10272. if (isElement$5(node) && dom.isBlock(node) && !node.innerHTML && !Env.ie) {
  10273. node.innerHTML = '<br data-mce-bogus="1" />';
  10274. }
  10275. return node;
  10276. };
  10277. var resolveCaretPositionBookmark = function (dom, bookmark) {
  10278. var pos;
  10279. var rng = dom.createRng();
  10280. pos = resolve$2(dom.getRoot(), bookmark.start);
  10281. rng.setStart(pos.container(), pos.offset());
  10282. pos = resolve$2(dom.getRoot(), bookmark.end);
  10283. rng.setEnd(pos.container(), pos.offset());
  10284. return rng;
  10285. };
  10286. var insertZwsp = function (node, rng) {
  10287. var textNode = node.ownerDocument.createTextNode(ZWSP$1);
  10288. node.appendChild(textNode);
  10289. rng.setStart(textNode, 0);
  10290. rng.setEnd(textNode, 0);
  10291. };
  10292. var isEmpty$1 = function (node) {
  10293. return node.hasChildNodes() === false;
  10294. };
  10295. var tryFindRangePosition = function (node, rng) {
  10296. return lastPositionIn(node).fold(never, function (pos) {
  10297. rng.setStart(pos.container(), pos.offset());
  10298. rng.setEnd(pos.container(), pos.offset());
  10299. return true;
  10300. });
  10301. };
  10302. var padEmptyCaretContainer = function (root, node, rng) {
  10303. if (isEmpty$1(node) && getParentCaretContainer(root, node)) {
  10304. insertZwsp(node, rng);
  10305. return true;
  10306. } else {
  10307. return false;
  10308. }
  10309. };
  10310. var setEndPoint = function (dom, start, bookmark, rng) {
  10311. var point = bookmark[start ? 'start' : 'end'];
  10312. var i, node, offset, children;
  10313. var root = dom.getRoot();
  10314. if (point) {
  10315. offset = point[0];
  10316. for (node = root, i = point.length - 1; i >= 1; i--) {
  10317. children = node.childNodes;
  10318. if (padEmptyCaretContainer(root, node, rng)) {
  10319. return true;
  10320. }
  10321. if (point[i] > children.length - 1) {
  10322. if (padEmptyCaretContainer(root, node, rng)) {
  10323. return true;
  10324. }
  10325. return tryFindRangePosition(node, rng);
  10326. }
  10327. node = children[point[i]];
  10328. }
  10329. if (node.nodeType === 3) {
  10330. offset = Math.min(point[0], node.nodeValue.length);
  10331. }
  10332. if (node.nodeType === 1) {
  10333. offset = Math.min(point[0], node.childNodes.length);
  10334. }
  10335. if (start) {
  10336. rng.setStart(node, offset);
  10337. } else {
  10338. rng.setEnd(node, offset);
  10339. }
  10340. }
  10341. return true;
  10342. };
  10343. var isValidTextNode = function (node) {
  10344. return isText$7(node) && node.data.length > 0;
  10345. };
  10346. var restoreEndPoint = function (dom, suffix, bookmark) {
  10347. var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev;
  10348. var keep = bookmark.keep;
  10349. var container, offset;
  10350. if (marker) {
  10351. node = marker.parentNode;
  10352. if (suffix === 'start') {
  10353. if (!keep) {
  10354. idx = dom.nodeIndex(marker);
  10355. } else {
  10356. if (marker.hasChildNodes()) {
  10357. node = marker.firstChild;
  10358. idx = 1;
  10359. } else if (isValidTextNode(marker.nextSibling)) {
  10360. node = marker.nextSibling;
  10361. idx = 0;
  10362. } else if (isValidTextNode(marker.previousSibling)) {
  10363. node = marker.previousSibling;
  10364. idx = marker.previousSibling.data.length;
  10365. } else {
  10366. node = marker.parentNode;
  10367. idx = dom.nodeIndex(marker) + 1;
  10368. }
  10369. }
  10370. container = node;
  10371. offset = idx;
  10372. } else {
  10373. if (!keep) {
  10374. idx = dom.nodeIndex(marker);
  10375. } else {
  10376. if (marker.hasChildNodes()) {
  10377. node = marker.firstChild;
  10378. idx = 1;
  10379. } else if (isValidTextNode(marker.previousSibling)) {
  10380. node = marker.previousSibling;
  10381. idx = marker.previousSibling.data.length;
  10382. } else {
  10383. node = marker.parentNode;
  10384. idx = dom.nodeIndex(marker);
  10385. }
  10386. }
  10387. container = node;
  10388. offset = idx;
  10389. }
  10390. if (!keep) {
  10391. prev = marker.previousSibling;
  10392. next = marker.nextSibling;
  10393. Tools.each(Tools.grep(marker.childNodes), function (node) {
  10394. if (isText$7(node)) {
  10395. node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
  10396. }
  10397. });
  10398. while (marker = dom.get(bookmark.id + '_' + suffix)) {
  10399. dom.remove(marker, true);
  10400. }
  10401. if (prev && next && prev.nodeType === next.nodeType && isText$7(prev) && !Env.opera) {
  10402. idx = prev.nodeValue.length;
  10403. prev.appendData(next.nodeValue);
  10404. dom.remove(next);
  10405. container = prev;
  10406. offset = idx;
  10407. }
  10408. }
  10409. return Optional.some(CaretPosition(container, offset));
  10410. } else {
  10411. return Optional.none();
  10412. }
  10413. };
  10414. var resolvePaths = function (dom, bookmark) {
  10415. var rng = dom.createRng();
  10416. if (setEndPoint(dom, true, bookmark, rng) && setEndPoint(dom, false, bookmark, rng)) {
  10417. return Optional.some(rng);
  10418. } else {
  10419. return Optional.none();
  10420. }
  10421. };
  10422. var resolveId = function (dom, bookmark) {
  10423. var startPos = restoreEndPoint(dom, 'start', bookmark);
  10424. var endPos = restoreEndPoint(dom, 'end', bookmark);
  10425. return lift2(startPos, endPos.or(startPos), function (spos, epos) {
  10426. var rng = dom.createRng();
  10427. rng.setStart(addBogus(dom, spos.container()), spos.offset());
  10428. rng.setEnd(addBogus(dom, epos.container()), epos.offset());
  10429. return rng;
  10430. });
  10431. };
  10432. var resolveIndex = function (dom, bookmark) {
  10433. return Optional.from(dom.select(bookmark.name)[bookmark.index]).map(function (elm) {
  10434. var rng = dom.createRng();
  10435. rng.selectNode(elm);
  10436. return rng;
  10437. });
  10438. };
  10439. var resolve$1 = function (selection, bookmark) {
  10440. var dom = selection.dom;
  10441. if (bookmark) {
  10442. if (isPathBookmark(bookmark)) {
  10443. return resolvePaths(dom, bookmark);
  10444. } else if (isStringPathBookmark(bookmark)) {
  10445. return Optional.some(resolveCaretPositionBookmark(dom, bookmark));
  10446. } else if (isIdBookmark(bookmark)) {
  10447. return resolveId(dom, bookmark);
  10448. } else if (isIndexBookmark(bookmark)) {
  10449. return resolveIndex(dom, bookmark);
  10450. } else if (isRangeBookmark(bookmark)) {
  10451. return Optional.some(bookmark.rng);
  10452. }
  10453. }
  10454. return Optional.none();
  10455. };
  10456. var getBookmark$1 = function (selection, type, normalized) {
  10457. return getBookmark$2(selection, type, normalized);
  10458. };
  10459. var moveToBookmark = function (selection, bookmark) {
  10460. resolve$1(selection, bookmark).each(function (rng) {
  10461. selection.setRng(rng);
  10462. });
  10463. };
  10464. var isBookmarkNode$1 = function (node) {
  10465. return isElement$5(node) && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
  10466. };
  10467. var is = function (expected) {
  10468. return function (actual) {
  10469. return expected === actual;
  10470. };
  10471. };
  10472. var isNbsp = is(nbsp);
  10473. var isWhiteSpace = function (chr) {
  10474. return chr !== '' && ' \f\n\r\t\x0B'.indexOf(chr) !== -1;
  10475. };
  10476. var isContent = function (chr) {
  10477. return !isWhiteSpace(chr) && !isNbsp(chr);
  10478. };
  10479. var isNode = function (node) {
  10480. return !!node.nodeType;
  10481. };
  10482. var isInlineBlock = function (node) {
  10483. return node && /^(IMG)$/.test(node.nodeName);
  10484. };
  10485. var moveStart = function (dom, selection, rng) {
  10486. var offset = rng.startOffset;
  10487. var container = rng.startContainer;
  10488. if (container === rng.endContainer) {
  10489. if (isInlineBlock(container.childNodes[offset])) {
  10490. return;
  10491. }
  10492. }
  10493. if (isElement$5(container)) {
  10494. var nodes = container.childNodes;
  10495. var walker = void 0;
  10496. if (offset < nodes.length) {
  10497. container = nodes[offset];
  10498. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10499. } else {
  10500. container = nodes[nodes.length - 1];
  10501. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10502. walker.next(true);
  10503. }
  10504. for (var node = walker.current(); node; node = walker.next()) {
  10505. if (isText$7(node) && !isWhiteSpaceNode$1(node)) {
  10506. rng.setStart(node, 0);
  10507. selection.setRng(rng);
  10508. return;
  10509. }
  10510. }
  10511. }
  10512. };
  10513. var getNonWhiteSpaceSibling = function (node, next, inc) {
  10514. if (node) {
  10515. var nextName = next ? 'nextSibling' : 'previousSibling';
  10516. for (node = inc ? node : node[nextName]; node; node = node[nextName]) {
  10517. if (isElement$5(node) || !isWhiteSpaceNode$1(node)) {
  10518. return node;
  10519. }
  10520. }
  10521. }
  10522. };
  10523. var isTextBlock$1 = function (editor, name) {
  10524. if (isNode(name)) {
  10525. name = name.nodeName;
  10526. }
  10527. return !!editor.schema.getTextBlockElements()[name.toLowerCase()];
  10528. };
  10529. var isValid = function (ed, parent, child) {
  10530. return ed.schema.isValidChild(parent, child);
  10531. };
  10532. var isWhiteSpaceNode$1 = function (node, allowSpaces) {
  10533. if (allowSpaces === void 0) {
  10534. allowSpaces = false;
  10535. }
  10536. if (isNonNullable(node) && isText$7(node)) {
  10537. var data = allowSpaces ? node.data.replace(/ /g, '\xA0') : node.data;
  10538. return isWhitespaceText(data);
  10539. } else {
  10540. return false;
  10541. }
  10542. };
  10543. var isEmptyTextNode$1 = function (node) {
  10544. return isNonNullable(node) && isText$7(node) && node.length === 0;
  10545. };
  10546. var replaceVars = function (value, vars) {
  10547. if (isFunction(value)) {
  10548. value = value(vars);
  10549. } else if (isNonNullable(vars)) {
  10550. value = value.replace(/%(\w+)/g, function (str, name) {
  10551. return vars[name] || str;
  10552. });
  10553. }
  10554. return value;
  10555. };
  10556. var isEq$5 = function (str1, str2) {
  10557. str1 = str1 || '';
  10558. str2 = str2 || '';
  10559. str1 = '' + (str1.nodeName || str1);
  10560. str2 = '' + (str2.nodeName || str2);
  10561. return str1.toLowerCase() === str2.toLowerCase();
  10562. };
  10563. var normalizeStyleValue = function (dom, value, name) {
  10564. if (name === 'color' || name === 'backgroundColor') {
  10565. value = dom.toHex(value);
  10566. }
  10567. if (name === 'fontWeight' && value === 700) {
  10568. value = 'bold';
  10569. }
  10570. if (name === 'fontFamily') {
  10571. value = value.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
  10572. }
  10573. return '' + value;
  10574. };
  10575. var getStyle = function (dom, node, name) {
  10576. return normalizeStyleValue(dom, dom.getStyle(node, name), name);
  10577. };
  10578. var getTextDecoration = function (dom, node) {
  10579. var decoration;
  10580. dom.getParent(node, function (n) {
  10581. decoration = dom.getStyle(n, 'text-decoration');
  10582. return decoration && decoration !== 'none';
  10583. });
  10584. return decoration;
  10585. };
  10586. var getParents$2 = function (dom, node, selector) {
  10587. return dom.getParents(node, selector, dom.getRoot());
  10588. };
  10589. var isVariableFormatName = function (editor, formatName) {
  10590. var hasVariableValues = function (format) {
  10591. var isVariableValue = function (val) {
  10592. return val.length > 1 && val.charAt(0) === '%';
  10593. };
  10594. return exists([
  10595. 'styles',
  10596. 'attributes'
  10597. ], function (key) {
  10598. return get$9(format, key).exists(function (field) {
  10599. var fieldValues = isArray$1(field) ? field : values(field);
  10600. return exists(fieldValues, isVariableValue);
  10601. });
  10602. });
  10603. };
  10604. return exists(editor.formatter.get(formatName), hasVariableValues);
  10605. };
  10606. var areSimilarFormats = function (editor, formatName, otherFormatName) {
  10607. var validKeys = [
  10608. 'inline',
  10609. 'block',
  10610. 'selector',
  10611. 'attributes',
  10612. 'styles',
  10613. 'classes'
  10614. ];
  10615. var filterObj = function (format) {
  10616. return filter$3(format, function (_, key) {
  10617. return exists(validKeys, function (validKey) {
  10618. return validKey === key;
  10619. });
  10620. });
  10621. };
  10622. return exists(editor.formatter.get(formatName), function (fmt1) {
  10623. var filteredFmt1 = filterObj(fmt1);
  10624. return exists(editor.formatter.get(otherFormatName), function (fmt2) {
  10625. var filteredFmt2 = filterObj(fmt2);
  10626. return equal$1(filteredFmt1, filteredFmt2);
  10627. });
  10628. });
  10629. };
  10630. var isBlockFormat = function (format) {
  10631. return hasNonNullableKey(format, 'block');
  10632. };
  10633. var isSelectorFormat = function (format) {
  10634. return hasNonNullableKey(format, 'selector');
  10635. };
  10636. var isInlineFormat = function (format) {
  10637. return hasNonNullableKey(format, 'inline');
  10638. };
  10639. var isMixedFormat = function (format) {
  10640. return isSelectorFormat(format) && isInlineFormat(format) && is$1(get$9(format, 'mixed'), true);
  10641. };
  10642. var shouldExpandToSelector = function (format) {
  10643. return isSelectorFormat(format) && format.expand !== false && !isInlineFormat(format);
  10644. };
  10645. var isBookmarkNode = isBookmarkNode$1;
  10646. var getParents$1 = getParents$2;
  10647. var isWhiteSpaceNode = isWhiteSpaceNode$1;
  10648. var isTextBlock = isTextBlock$1;
  10649. var isBogusBr = function (node) {
  10650. return isBr$5(node) && node.getAttribute('data-mce-bogus') && !node.nextSibling;
  10651. };
  10652. var findParentContentEditable = function (dom, node) {
  10653. var parent = node;
  10654. while (parent) {
  10655. if (isElement$5(parent) && dom.getContentEditable(parent)) {
  10656. return dom.getContentEditable(parent) === 'false' ? parent : node;
  10657. }
  10658. parent = parent.parentNode;
  10659. }
  10660. return node;
  10661. };
  10662. var walkText = function (start, node, offset, predicate) {
  10663. var str = node.data;
  10664. for (var i = offset; start ? i >= 0 : i < str.length; start ? i-- : i++) {
  10665. if (predicate(str.charAt(i))) {
  10666. return start ? i + 1 : i;
  10667. }
  10668. }
  10669. return -1;
  10670. };
  10671. var findSpace = function (start, node, offset) {
  10672. return walkText(start, node, offset, function (c) {
  10673. return isNbsp(c) || isWhiteSpace(c);
  10674. });
  10675. };
  10676. var findContent = function (start, node, offset) {
  10677. return walkText(start, node, offset, isContent);
  10678. };
  10679. var findWordEndPoint = function (dom, body, container, offset, start, includeTrailingSpaces) {
  10680. var lastTextNode;
  10681. var rootNode = dom.getParent(container, dom.isBlock) || body;
  10682. var walk = function (container, offset, pred) {
  10683. var textSeeker = TextSeeker(dom);
  10684. var walker = start ? textSeeker.backwards : textSeeker.forwards;
  10685. return Optional.from(walker(container, offset, function (text, textOffset) {
  10686. if (isBookmarkNode(text.parentNode)) {
  10687. return -1;
  10688. } else {
  10689. lastTextNode = text;
  10690. return pred(start, text, textOffset);
  10691. }
  10692. }, rootNode));
  10693. };
  10694. var spaceResult = walk(container, offset, findSpace);
  10695. return spaceResult.bind(function (result) {
  10696. return includeTrailingSpaces ? walk(result.container, result.offset + (start ? -1 : 0), findContent) : Optional.some(result);
  10697. }).orThunk(function () {
  10698. return lastTextNode ? Optional.some({
  10699. container: lastTextNode,
  10700. offset: start ? 0 : lastTextNode.length
  10701. }) : Optional.none();
  10702. });
  10703. };
  10704. var findSelectorEndPoint = function (dom, formatList, rng, container, siblingName) {
  10705. if (isText$7(container) && isEmpty$3(container.data) && container[siblingName]) {
  10706. container = container[siblingName];
  10707. }
  10708. var parents = getParents$1(dom, container);
  10709. for (var i = 0; i < parents.length; i++) {
  10710. for (var y = 0; y < formatList.length; y++) {
  10711. var curFormat = formatList[y];
  10712. if (isNonNullable(curFormat.collapsed) && curFormat.collapsed !== rng.collapsed) {
  10713. continue;
  10714. }
  10715. if (isSelectorFormat(curFormat) && dom.is(parents[i], curFormat.selector)) {
  10716. return parents[i];
  10717. }
  10718. }
  10719. }
  10720. return container;
  10721. };
  10722. var findBlockEndPoint = function (editor, formatList, container, siblingName) {
  10723. var node = container;
  10724. var dom = editor.dom;
  10725. var root = dom.getRoot();
  10726. var format = formatList[0];
  10727. if (isBlockFormat(format) && !format.wrapper) {
  10728. node = dom.getParent(container, format.block, root);
  10729. }
  10730. if (!node) {
  10731. var scopeRoot = dom.getParent(container, 'LI,TD,TH');
  10732. node = dom.getParent(isText$7(container) ? container.parentNode : container, function (node) {
  10733. return node !== root && isTextBlock(editor, node);
  10734. }, scopeRoot);
  10735. }
  10736. if (node && isBlockFormat(format) && format.wrapper) {
  10737. node = getParents$1(dom, node, 'ul,ol').reverse()[0] || node;
  10738. }
  10739. if (!node) {
  10740. node = container;
  10741. while (node[siblingName] && !dom.isBlock(node[siblingName])) {
  10742. node = node[siblingName];
  10743. if (isEq$5(node, 'br')) {
  10744. break;
  10745. }
  10746. }
  10747. }
  10748. return node || container;
  10749. };
  10750. var isAtBlockBoundary$1 = function (dom, root, container, siblingName) {
  10751. var parent = container.parentNode;
  10752. if (isNonNullable(container[siblingName])) {
  10753. return false;
  10754. } else if (parent === root || isNullable(parent) || dom.isBlock(parent)) {
  10755. return true;
  10756. } else {
  10757. return isAtBlockBoundary$1(dom, root, parent, siblingName);
  10758. }
  10759. };
  10760. var findParentContainer = function (dom, formatList, container, offset, start) {
  10761. var parent = container;
  10762. var siblingName = start ? 'previousSibling' : 'nextSibling';
  10763. var root = dom.getRoot();
  10764. if (isText$7(container) && !isWhiteSpaceNode(container)) {
  10765. if (start ? offset > 0 : offset < container.data.length) {
  10766. return container;
  10767. }
  10768. }
  10769. while (true) {
  10770. if (!formatList[0].block_expand && dom.isBlock(parent)) {
  10771. return parent;
  10772. }
  10773. for (var sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
  10774. var allowSpaces = isText$7(sibling) && !isAtBlockBoundary$1(dom, root, sibling, siblingName);
  10775. if (!isBookmarkNode(sibling) && !isBogusBr(sibling) && !isWhiteSpaceNode(sibling, allowSpaces)) {
  10776. return parent;
  10777. }
  10778. }
  10779. if (parent === root || parent.parentNode === root) {
  10780. container = parent;
  10781. break;
  10782. }
  10783. parent = parent.parentNode;
  10784. }
  10785. return container;
  10786. };
  10787. var isSelfOrParentBookmark = function (container) {
  10788. return isBookmarkNode(container.parentNode) || isBookmarkNode(container);
  10789. };
  10790. var expandRng = function (editor, rng, formatList, includeTrailingSpace) {
  10791. if (includeTrailingSpace === void 0) {
  10792. includeTrailingSpace = false;
  10793. }
  10794. var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  10795. var dom = editor.dom;
  10796. var format = formatList[0];
  10797. if (isElement$5(startContainer) && startContainer.hasChildNodes()) {
  10798. startContainer = getNode$1(startContainer, startOffset);
  10799. if (isText$7(startContainer)) {
  10800. startOffset = 0;
  10801. }
  10802. }
  10803. if (isElement$5(endContainer) && endContainer.hasChildNodes()) {
  10804. endContainer = getNode$1(endContainer, rng.collapsed ? endOffset : endOffset - 1);
  10805. if (isText$7(endContainer)) {
  10806. endOffset = endContainer.nodeValue.length;
  10807. }
  10808. }
  10809. startContainer = findParentContentEditable(dom, startContainer);
  10810. endContainer = findParentContentEditable(dom, endContainer);
  10811. if (isSelfOrParentBookmark(startContainer)) {
  10812. startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
  10813. if (rng.collapsed) {
  10814. startContainer = startContainer.previousSibling || startContainer;
  10815. } else {
  10816. startContainer = startContainer.nextSibling || startContainer;
  10817. }
  10818. if (isText$7(startContainer)) {
  10819. startOffset = rng.collapsed ? startContainer.length : 0;
  10820. }
  10821. }
  10822. if (isSelfOrParentBookmark(endContainer)) {
  10823. endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
  10824. if (rng.collapsed) {
  10825. endContainer = endContainer.nextSibling || endContainer;
  10826. } else {
  10827. endContainer = endContainer.previousSibling || endContainer;
  10828. }
  10829. if (isText$7(endContainer)) {
  10830. endOffset = rng.collapsed ? 0 : endContainer.length;
  10831. }
  10832. }
  10833. if (rng.collapsed) {
  10834. var startPoint = findWordEndPoint(dom, editor.getBody(), startContainer, startOffset, true, includeTrailingSpace);
  10835. startPoint.each(function (_a) {
  10836. var container = _a.container, offset = _a.offset;
  10837. startContainer = container;
  10838. startOffset = offset;
  10839. });
  10840. var endPoint = findWordEndPoint(dom, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
  10841. endPoint.each(function (_a) {
  10842. var container = _a.container, offset = _a.offset;
  10843. endContainer = container;
  10844. endOffset = offset;
  10845. });
  10846. }
  10847. if (isInlineFormat(format) || format.block_expand) {
  10848. if (!isInlineFormat(format) || (!isText$7(startContainer) || startOffset === 0)) {
  10849. startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  10850. }
  10851. if (!isInlineFormat(format) || (!isText$7(endContainer) || endOffset === endContainer.nodeValue.length)) {
  10852. endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  10853. }
  10854. }
  10855. if (shouldExpandToSelector(format)) {
  10856. startContainer = findSelectorEndPoint(dom, formatList, rng, startContainer, 'previousSibling');
  10857. endContainer = findSelectorEndPoint(dom, formatList, rng, endContainer, 'nextSibling');
  10858. }
  10859. if (isBlockFormat(format) || isSelectorFormat(format)) {
  10860. startContainer = findBlockEndPoint(editor, formatList, startContainer, 'previousSibling');
  10861. endContainer = findBlockEndPoint(editor, formatList, endContainer, 'nextSibling');
  10862. if (isBlockFormat(format)) {
  10863. if (!dom.isBlock(startContainer)) {
  10864. startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  10865. }
  10866. if (!dom.isBlock(endContainer)) {
  10867. endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  10868. }
  10869. }
  10870. }
  10871. if (isElement$5(startContainer)) {
  10872. startOffset = dom.nodeIndex(startContainer);
  10873. startContainer = startContainer.parentNode;
  10874. }
  10875. if (isElement$5(endContainer)) {
  10876. endOffset = dom.nodeIndex(endContainer) + 1;
  10877. endContainer = endContainer.parentNode;
  10878. }
  10879. return {
  10880. startContainer: startContainer,
  10881. startOffset: startOffset,
  10882. endContainer: endContainer,
  10883. endOffset: endOffset
  10884. };
  10885. };
  10886. var walk$2 = function (dom, rng, callback) {
  10887. var startOffset = rng.startOffset;
  10888. var startContainer = getNode$1(rng.startContainer, startOffset);
  10889. var endOffset = rng.endOffset;
  10890. var endContainer = getNode$1(rng.endContainer, endOffset - 1);
  10891. var exclude = function (nodes) {
  10892. var firstNode = nodes[0];
  10893. if (isText$7(firstNode) && firstNode === startContainer && startOffset >= firstNode.data.length) {
  10894. nodes.splice(0, 1);
  10895. }
  10896. var lastNode = nodes[nodes.length - 1];
  10897. if (endOffset === 0 && nodes.length > 0 && lastNode === endContainer && isText$7(lastNode)) {
  10898. nodes.splice(nodes.length - 1, 1);
  10899. }
  10900. return nodes;
  10901. };
  10902. var collectSiblings = function (node, name, endNode) {
  10903. var siblings = [];
  10904. for (; node && node !== endNode; node = node[name]) {
  10905. siblings.push(node);
  10906. }
  10907. return siblings;
  10908. };
  10909. var findEndPoint = function (node, root) {
  10910. return dom.getParent(node, function (node) {
  10911. return node.parentNode === root;
  10912. }, root);
  10913. };
  10914. var walkBoundary = function (startNode, endNode, next) {
  10915. var siblingName = next ? 'nextSibling' : 'previousSibling';
  10916. for (var node = startNode, parent_1 = node.parentNode; node && node !== endNode; node = parent_1) {
  10917. parent_1 = node.parentNode;
  10918. var siblings_1 = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
  10919. if (siblings_1.length) {
  10920. if (!next) {
  10921. siblings_1.reverse();
  10922. }
  10923. callback(exclude(siblings_1));
  10924. }
  10925. }
  10926. };
  10927. if (startContainer === endContainer) {
  10928. return callback(exclude([startContainer]));
  10929. }
  10930. var ancestor = dom.findCommonAncestor(startContainer, endContainer);
  10931. if (dom.isChildOf(startContainer, endContainer)) {
  10932. return walkBoundary(startContainer, ancestor, true);
  10933. }
  10934. if (dom.isChildOf(endContainer, startContainer)) {
  10935. return walkBoundary(endContainer, ancestor);
  10936. }
  10937. var startPoint = findEndPoint(startContainer, ancestor) || startContainer;
  10938. var endPoint = findEndPoint(endContainer, ancestor) || endContainer;
  10939. walkBoundary(startContainer, startPoint, true);
  10940. var siblings = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint === endContainer ? endPoint.nextSibling : endPoint);
  10941. if (siblings.length) {
  10942. callback(exclude(siblings));
  10943. }
  10944. walkBoundary(endContainer, endPoint);
  10945. };
  10946. var getRanges = function (selection) {
  10947. var ranges = [];
  10948. if (selection) {
  10949. for (var i = 0; i < selection.rangeCount; i++) {
  10950. ranges.push(selection.getRangeAt(i));
  10951. }
  10952. }
  10953. return ranges;
  10954. };
  10955. var getSelectedNodes = function (ranges) {
  10956. return bind(ranges, function (range) {
  10957. var node = getSelectedNode(range);
  10958. return node ? [SugarElement.fromDom(node)] : [];
  10959. });
  10960. };
  10961. var hasMultipleRanges = function (selection) {
  10962. return getRanges(selection).length > 1;
  10963. };
  10964. var getCellsFromRanges = function (ranges) {
  10965. return filter$4(getSelectedNodes(ranges), isTableCell$4);
  10966. };
  10967. var getCellsFromElement = function (elm) {
  10968. return descendants(elm, 'td[data-mce-selected],th[data-mce-selected]');
  10969. };
  10970. var getCellsFromElementOrRanges = function (ranges, element) {
  10971. var selectedCells = getCellsFromElement(element);
  10972. return selectedCells.length > 0 ? selectedCells : getCellsFromRanges(ranges);
  10973. };
  10974. var getCellsFromEditor = function (editor) {
  10975. return getCellsFromElementOrRanges(getRanges(editor.selection.getSel()), SugarElement.fromDom(editor.getBody()));
  10976. };
  10977. var getClosestTable = function (cell, isRoot) {
  10978. return ancestor$2(cell, 'table', isRoot);
  10979. };
  10980. var getStartNode = function (rng) {
  10981. var sc = rng.startContainer, so = rng.startOffset;
  10982. if (isText$7(sc)) {
  10983. return so === 0 ? Optional.some(SugarElement.fromDom(sc)) : Optional.none();
  10984. } else {
  10985. return Optional.from(sc.childNodes[so]).map(SugarElement.fromDom);
  10986. }
  10987. };
  10988. var getEndNode = function (rng) {
  10989. var ec = rng.endContainer, eo = rng.endOffset;
  10990. if (isText$7(ec)) {
  10991. return eo === ec.data.length ? Optional.some(SugarElement.fromDom(ec)) : Optional.none();
  10992. } else {
  10993. return Optional.from(ec.childNodes[eo - 1]).map(SugarElement.fromDom);
  10994. }
  10995. };
  10996. var getFirstChildren = function (node) {
  10997. return firstChild(node).fold(constant([node]), function (child) {
  10998. return [node].concat(getFirstChildren(child));
  10999. });
  11000. };
  11001. var getLastChildren$1 = function (node) {
  11002. return lastChild(node).fold(constant([node]), function (child) {
  11003. if (name(child) === 'br') {
  11004. return prevSibling(child).map(function (sibling) {
  11005. return [node].concat(getLastChildren$1(sibling));
  11006. }).getOr([]);
  11007. } else {
  11008. return [node].concat(getLastChildren$1(child));
  11009. }
  11010. });
  11011. };
  11012. var hasAllContentsSelected = function (elm, rng) {
  11013. return lift2(getStartNode(rng), getEndNode(rng), function (startNode, endNode) {
  11014. var start = find$3(getFirstChildren(elm), curry(eq, startNode));
  11015. var end = find$3(getLastChildren$1(elm), curry(eq, endNode));
  11016. return start.isSome() && end.isSome();
  11017. }).getOr(false);
  11018. };
  11019. var moveEndPoint = function (dom, rng, node, start) {
  11020. var root = node, walker = new DomTreeWalker(node, root);
  11021. var moveCaretBeforeOnEnterElementsMap = filter$3(dom.schema.getMoveCaretBeforeOnEnterElements(), function (_, name) {
  11022. return !contains$3([
  11023. 'td',
  11024. 'th',
  11025. 'table'
  11026. ], name.toLowerCase());
  11027. });
  11028. do {
  11029. if (isText$7(node) && Tools.trim(node.nodeValue).length !== 0) {
  11030. if (start) {
  11031. rng.setStart(node, 0);
  11032. } else {
  11033. rng.setEnd(node, node.nodeValue.length);
  11034. }
  11035. return;
  11036. }
  11037. if (moveCaretBeforeOnEnterElementsMap[node.nodeName]) {
  11038. if (start) {
  11039. rng.setStartBefore(node);
  11040. } else {
  11041. if (node.nodeName === 'BR') {
  11042. rng.setEndBefore(node);
  11043. } else {
  11044. rng.setEndAfter(node);
  11045. }
  11046. }
  11047. return;
  11048. }
  11049. } while (node = start ? walker.next() : walker.prev());
  11050. if (root.nodeName === 'BODY') {
  11051. if (start) {
  11052. rng.setStart(root, 0);
  11053. } else {
  11054. rng.setEnd(root, root.childNodes.length);
  11055. }
  11056. }
  11057. };
  11058. var hasAnyRanges = function (editor) {
  11059. var sel = editor.selection.getSel();
  11060. return sel && sel.rangeCount > 0;
  11061. };
  11062. var runOnRanges = function (editor, executor) {
  11063. var fakeSelectionNodes = getCellsFromEditor(editor);
  11064. if (fakeSelectionNodes.length > 0) {
  11065. each$k(fakeSelectionNodes, function (elem) {
  11066. var node = elem.dom;
  11067. var fakeNodeRng = editor.dom.createRng();
  11068. fakeNodeRng.setStartBefore(node);
  11069. fakeNodeRng.setEndAfter(node);
  11070. executor(fakeNodeRng, true);
  11071. });
  11072. } else {
  11073. executor(editor.selection.getRng(), false);
  11074. }
  11075. };
  11076. var preserve = function (selection, fillBookmark, executor) {
  11077. var bookmark = getPersistentBookmark(selection, fillBookmark);
  11078. executor(bookmark);
  11079. selection.moveToBookmark(bookmark);
  11080. };
  11081. var NodeValue = function (is, name) {
  11082. var get = function (element) {
  11083. if (!is(element)) {
  11084. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  11085. }
  11086. return getOption(element).getOr('');
  11087. };
  11088. var getOption = function (element) {
  11089. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  11090. };
  11091. var set = function (element, value) {
  11092. if (!is(element)) {
  11093. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  11094. }
  11095. element.dom.nodeValue = value;
  11096. };
  11097. return {
  11098. get: get,
  11099. getOption: getOption,
  11100. set: set
  11101. };
  11102. };
  11103. var api$1 = NodeValue(isText$8, 'text');
  11104. var get$2 = function (element) {
  11105. return api$1.get(element);
  11106. };
  11107. var isZeroWidth = function (elem) {
  11108. return isText$8(elem) && get$2(elem) === ZWSP$1;
  11109. };
  11110. var context = function (editor, elem, wrapName, nodeName) {
  11111. return parent(elem).fold(function () {
  11112. return 'skipping';
  11113. }, function (parent) {
  11114. if (nodeName === 'br' || isZeroWidth(elem)) {
  11115. return 'valid';
  11116. } else if (isAnnotation(elem)) {
  11117. return 'existing';
  11118. } else if (isCaretNode(elem.dom)) {
  11119. return 'caret';
  11120. } else if (!isValid(editor, wrapName, nodeName) || !isValid(editor, name(parent), wrapName)) {
  11121. return 'invalid-child';
  11122. } else {
  11123. return 'valid';
  11124. }
  11125. });
  11126. };
  11127. var applyWordGrab = function (editor, rng) {
  11128. var r = expandRng(editor, rng, [{ inline: 'span' }]);
  11129. rng.setStart(r.startContainer, r.startOffset);
  11130. rng.setEnd(r.endContainer, r.endOffset);
  11131. editor.selection.setRng(rng);
  11132. };
  11133. var makeAnnotation = function (eDoc, _a, annotationName, decorate) {
  11134. var _b = _a.uid, uid = _b === void 0 ? generate('mce-annotation') : _b, data = __rest(_a, ['uid']);
  11135. var master = SugarElement.fromTag('span', eDoc);
  11136. add$1(master, annotation());
  11137. set$1(master, '' + dataAnnotationId(), uid);
  11138. set$1(master, '' + dataAnnotation(), annotationName);
  11139. var _c = decorate(uid, data), _d = _c.attributes, attributes = _d === void 0 ? {} : _d, _e = _c.classes, classes = _e === void 0 ? [] : _e;
  11140. setAll$1(master, attributes);
  11141. add(master, classes);
  11142. return master;
  11143. };
  11144. var annotate = function (editor, rng, annotationName, decorate, data) {
  11145. var newWrappers = [];
  11146. var master = makeAnnotation(editor.getDoc(), data, annotationName, decorate);
  11147. var wrapper = value();
  11148. var finishWrapper = function () {
  11149. wrapper.clear();
  11150. };
  11151. var getOrOpenWrapper = function () {
  11152. return wrapper.get().getOrThunk(function () {
  11153. var nu = shallow(master);
  11154. newWrappers.push(nu);
  11155. wrapper.set(nu);
  11156. return nu;
  11157. });
  11158. };
  11159. var processElements = function (elems) {
  11160. each$k(elems, processElement);
  11161. };
  11162. var processElement = function (elem) {
  11163. var ctx = context(editor, elem, 'span', name(elem));
  11164. switch (ctx) {
  11165. case 'invalid-child': {
  11166. finishWrapper();
  11167. var children$1 = children(elem);
  11168. processElements(children$1);
  11169. finishWrapper();
  11170. break;
  11171. }
  11172. case 'valid': {
  11173. var w = getOrOpenWrapper();
  11174. wrap$3(elem, w);
  11175. break;
  11176. }
  11177. }
  11178. };
  11179. var processNodes = function (nodes) {
  11180. var elems = map$3(nodes, SugarElement.fromDom);
  11181. processElements(elems);
  11182. };
  11183. walk$2(editor.dom, rng, function (nodes) {
  11184. finishWrapper();
  11185. processNodes(nodes);
  11186. });
  11187. return newWrappers;
  11188. };
  11189. var annotateWithBookmark = function (editor, name, settings, data) {
  11190. editor.undoManager.transact(function () {
  11191. var selection = editor.selection;
  11192. var initialRng = selection.getRng();
  11193. var hasFakeSelection = getCellsFromEditor(editor).length > 0;
  11194. if (initialRng.collapsed && !hasFakeSelection) {
  11195. applyWordGrab(editor, initialRng);
  11196. }
  11197. if (selection.getRng().collapsed && !hasFakeSelection) {
  11198. var wrapper = makeAnnotation(editor.getDoc(), data, name, settings.decorate);
  11199. set(wrapper, nbsp);
  11200. selection.getRng().insertNode(wrapper.dom);
  11201. selection.select(wrapper.dom);
  11202. } else {
  11203. preserve(selection, false, function () {
  11204. runOnRanges(editor, function (selectionRng) {
  11205. annotate(editor, selectionRng, name, settings.decorate, data);
  11206. });
  11207. });
  11208. }
  11209. });
  11210. };
  11211. var Annotator = function (editor) {
  11212. var registry = create$7();
  11213. setup$m(editor, registry);
  11214. var changes = setup$n(editor);
  11215. return {
  11216. register: function (name, settings) {
  11217. registry.register(name, settings);
  11218. },
  11219. annotate: function (name, data) {
  11220. registry.lookup(name).each(function (settings) {
  11221. annotateWithBookmark(editor, name, settings, data);
  11222. });
  11223. },
  11224. annotationChanged: function (name, callback) {
  11225. changes.addListener(name, callback);
  11226. },
  11227. remove: function (name) {
  11228. identify(editor, Optional.some(name)).each(function (_a) {
  11229. var elements = _a.elements;
  11230. each$k(elements, unwrap);
  11231. });
  11232. },
  11233. getAll: function (name) {
  11234. var directory = findAll(editor, name);
  11235. return map$2(directory, function (elems) {
  11236. return map$3(elems, function (elem) {
  11237. return elem.dom;
  11238. });
  11239. });
  11240. }
  11241. };
  11242. };
  11243. var BookmarkManager = function (selection) {
  11244. return {
  11245. getBookmark: curry(getBookmark$1, selection),
  11246. moveToBookmark: curry(moveToBookmark, selection)
  11247. };
  11248. };
  11249. BookmarkManager.isBookmarkNode = isBookmarkNode$1;
  11250. var getContentEditableRoot$1 = function (root, node) {
  11251. while (node && node !== root) {
  11252. if (isContentEditableTrue$4(node) || isContentEditableFalse$b(node)) {
  11253. return node;
  11254. }
  11255. node = node.parentNode;
  11256. }
  11257. return null;
  11258. };
  11259. var isXYWithinRange = function (clientX, clientY, range) {
  11260. if (range.collapsed) {
  11261. return false;
  11262. }
  11263. if (Env.browser.isIE() && range.startOffset === range.endOffset - 1 && range.startContainer === range.endContainer) {
  11264. var elm = range.startContainer.childNodes[range.startOffset];
  11265. if (isElement$5(elm)) {
  11266. return exists(elm.getClientRects(), function (rect) {
  11267. return containsXY(rect, clientX, clientY);
  11268. });
  11269. }
  11270. }
  11271. return exists(range.getClientRects(), function (rect) {
  11272. return containsXY(rect, clientX, clientY);
  11273. });
  11274. };
  11275. var firePreProcess = function (editor, args) {
  11276. return editor.fire('PreProcess', args);
  11277. };
  11278. var firePostProcess = function (editor, args) {
  11279. return editor.fire('PostProcess', args);
  11280. };
  11281. var fireRemove = function (editor) {
  11282. return editor.fire('remove');
  11283. };
  11284. var fireDetach = function (editor) {
  11285. return editor.fire('detach');
  11286. };
  11287. var fireSwitchMode = function (editor, mode) {
  11288. return editor.fire('SwitchMode', { mode: mode });
  11289. };
  11290. var fireObjectResizeStart = function (editor, target, width, height, origin) {
  11291. editor.fire('ObjectResizeStart', {
  11292. target: target,
  11293. width: width,
  11294. height: height,
  11295. origin: origin
  11296. });
  11297. };
  11298. var fireObjectResized = function (editor, target, width, height, origin) {
  11299. editor.fire('ObjectResized', {
  11300. target: target,
  11301. width: width,
  11302. height: height,
  11303. origin: origin
  11304. });
  11305. };
  11306. var firePreInit = function (editor) {
  11307. return editor.fire('PreInit');
  11308. };
  11309. var firePostRender = function (editor) {
  11310. return editor.fire('PostRender');
  11311. };
  11312. var fireInit = function (editor) {
  11313. return editor.fire('Init');
  11314. };
  11315. var firePlaceholderToggle = function (editor, state) {
  11316. return editor.fire('PlaceholderToggle', { state: state });
  11317. };
  11318. var fireError = function (editor, errorType, error) {
  11319. return editor.fire(errorType, error);
  11320. };
  11321. var fireFormatApply = function (editor, format, node, vars) {
  11322. return editor.fire('FormatApply', {
  11323. format: format,
  11324. node: node,
  11325. vars: vars
  11326. });
  11327. };
  11328. var fireFormatRemove = function (editor, format, node, vars) {
  11329. return editor.fire('FormatRemove', {
  11330. format: format,
  11331. node: node,
  11332. vars: vars
  11333. });
  11334. };
  11335. var VK = {
  11336. BACKSPACE: 8,
  11337. DELETE: 46,
  11338. DOWN: 40,
  11339. ENTER: 13,
  11340. LEFT: 37,
  11341. RIGHT: 39,
  11342. SPACEBAR: 32,
  11343. TAB: 9,
  11344. UP: 38,
  11345. PAGE_UP: 33,
  11346. PAGE_DOWN: 34,
  11347. END: 35,
  11348. HOME: 36,
  11349. modifierPressed: function (e) {
  11350. return e.shiftKey || e.ctrlKey || e.altKey || VK.metaKeyPressed(e);
  11351. },
  11352. metaKeyPressed: function (e) {
  11353. return Env.mac ? e.metaKey : e.ctrlKey && !e.altKey;
  11354. }
  11355. };
  11356. var isContentEditableFalse$5 = isContentEditableFalse$b;
  11357. var ControlSelection = function (selection, editor) {
  11358. var elementSelectionAttr = 'data-mce-selected';
  11359. var dom = editor.dom, each = Tools.each;
  11360. var selectedElm, selectedElmGhost, resizeHelper, selectedHandle, resizeBackdrop;
  11361. var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
  11362. var width, height;
  11363. var editableDoc = editor.getDoc(), rootDocument = document;
  11364. var abs = Math.abs, round = Math.round, rootElement = editor.getBody();
  11365. var startScrollWidth, startScrollHeight;
  11366. var resizeHandles = {
  11367. nw: [
  11368. 0,
  11369. 0,
  11370. -1,
  11371. -1
  11372. ],
  11373. ne: [
  11374. 1,
  11375. 0,
  11376. 1,
  11377. -1
  11378. ],
  11379. se: [
  11380. 1,
  11381. 1,
  11382. 1,
  11383. 1
  11384. ],
  11385. sw: [
  11386. 0,
  11387. 1,
  11388. -1,
  11389. 1
  11390. ]
  11391. };
  11392. var isImage = function (elm) {
  11393. return elm && (elm.nodeName === 'IMG' || editor.dom.is(elm, 'figure.image'));
  11394. };
  11395. var isMedia = function (elm) {
  11396. return isMedia$2(elm) || dom.hasClass(elm, 'mce-preview-object');
  11397. };
  11398. var isEventOnImageOutsideRange = function (evt, range) {
  11399. if (evt.type === 'longpress' || evt.type.indexOf('touch') === 0) {
  11400. var touch = evt.touches[0];
  11401. return isImage(evt.target) && !isXYWithinRange(touch.clientX, touch.clientY, range);
  11402. } else {
  11403. return isImage(evt.target) && !isXYWithinRange(evt.clientX, evt.clientY, range);
  11404. }
  11405. };
  11406. var contextMenuSelectImage = function (evt) {
  11407. var target = evt.target;
  11408. if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) && !evt.isDefaultPrevented()) {
  11409. editor.selection.select(target);
  11410. }
  11411. };
  11412. var getResizeTargets = function (elm) {
  11413. if (dom.is(elm, 'figure.image')) {
  11414. return [elm.querySelector('img')];
  11415. } else if (dom.hasClass(elm, 'mce-preview-object') && isNonNullable(elm.firstElementChild)) {
  11416. return [
  11417. elm,
  11418. elm.firstElementChild
  11419. ];
  11420. } else {
  11421. return [elm];
  11422. }
  11423. };
  11424. var isResizable = function (elm) {
  11425. var selector = getObjectResizing(editor);
  11426. if (!selector) {
  11427. return false;
  11428. }
  11429. if (elm.getAttribute('data-mce-resize') === 'false') {
  11430. return false;
  11431. }
  11432. if (elm === editor.getBody()) {
  11433. return false;
  11434. }
  11435. if (dom.hasClass(elm, 'mce-preview-object')) {
  11436. return is$2(SugarElement.fromDom(elm.firstElementChild), selector);
  11437. } else {
  11438. return is$2(SugarElement.fromDom(elm), selector);
  11439. }
  11440. };
  11441. var createGhostElement = function (elm) {
  11442. if (isMedia(elm)) {
  11443. return dom.create('img', { src: Env.transparentSrc });
  11444. } else {
  11445. return elm.cloneNode(true);
  11446. }
  11447. };
  11448. var setSizeProp = function (element, name, value) {
  11449. if (isNonNullable(value)) {
  11450. var targets = getResizeTargets(element);
  11451. each$k(targets, function (target) {
  11452. if (target.style[name] || !editor.schema.isValid(target.nodeName.toLowerCase(), name)) {
  11453. dom.setStyle(target, name, value);
  11454. } else {
  11455. dom.setAttrib(target, name, '' + value);
  11456. }
  11457. });
  11458. }
  11459. };
  11460. var setGhostElmSize = function (ghostElm, width, height) {
  11461. setSizeProp(ghostElm, 'width', width);
  11462. setSizeProp(ghostElm, 'height', height);
  11463. };
  11464. var resizeGhostElement = function (e) {
  11465. var deltaX, deltaY, proportional;
  11466. var resizeHelperX, resizeHelperY;
  11467. deltaX = e.screenX - startX;
  11468. deltaY = e.screenY - startY;
  11469. width = deltaX * selectedHandle[2] + startW;
  11470. height = deltaY * selectedHandle[3] + startH;
  11471. width = width < 5 ? 5 : width;
  11472. height = height < 5 ? 5 : height;
  11473. if ((isImage(selectedElm) || isMedia(selectedElm)) && getResizeImgProportional(editor) !== false) {
  11474. proportional = !VK.modifierPressed(e);
  11475. } else {
  11476. proportional = VK.modifierPressed(e);
  11477. }
  11478. if (proportional) {
  11479. if (abs(deltaX) > abs(deltaY)) {
  11480. height = round(width * ratio);
  11481. width = round(height / ratio);
  11482. } else {
  11483. width = round(height / ratio);
  11484. height = round(width * ratio);
  11485. }
  11486. }
  11487. setGhostElmSize(selectedElmGhost, width, height);
  11488. resizeHelperX = selectedHandle.startPos.x + deltaX;
  11489. resizeHelperY = selectedHandle.startPos.y + deltaY;
  11490. resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
  11491. resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
  11492. dom.setStyles(resizeHelper, {
  11493. left: resizeHelperX,
  11494. top: resizeHelperY,
  11495. display: 'block'
  11496. });
  11497. resizeHelper.innerHTML = width + ' &times; ' + height;
  11498. if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
  11499. dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
  11500. }
  11501. if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
  11502. dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
  11503. }
  11504. deltaX = rootElement.scrollWidth - startScrollWidth;
  11505. deltaY = rootElement.scrollHeight - startScrollHeight;
  11506. if (deltaX + deltaY !== 0) {
  11507. dom.setStyles(resizeHelper, {
  11508. left: resizeHelperX - deltaX,
  11509. top: resizeHelperY - deltaY
  11510. });
  11511. }
  11512. if (!resizeStarted) {
  11513. fireObjectResizeStart(editor, selectedElm, startW, startH, 'corner-' + selectedHandle.name);
  11514. resizeStarted = true;
  11515. }
  11516. };
  11517. var endGhostResize = function () {
  11518. var wasResizeStarted = resizeStarted;
  11519. resizeStarted = false;
  11520. if (wasResizeStarted) {
  11521. setSizeProp(selectedElm, 'width', width);
  11522. setSizeProp(selectedElm, 'height', height);
  11523. }
  11524. dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
  11525. dom.unbind(editableDoc, 'mouseup', endGhostResize);
  11526. if (rootDocument !== editableDoc) {
  11527. dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
  11528. dom.unbind(rootDocument, 'mouseup', endGhostResize);
  11529. }
  11530. dom.remove(selectedElmGhost);
  11531. dom.remove(resizeHelper);
  11532. dom.remove(resizeBackdrop);
  11533. showResizeRect(selectedElm);
  11534. if (wasResizeStarted) {
  11535. fireObjectResized(editor, selectedElm, width, height, 'corner-' + selectedHandle.name);
  11536. dom.setAttrib(selectedElm, 'style', dom.getAttrib(selectedElm, 'style'));
  11537. }
  11538. editor.nodeChanged();
  11539. };
  11540. var showResizeRect = function (targetElm) {
  11541. unbindResizeHandleEvents();
  11542. var position = dom.getPos(targetElm, rootElement);
  11543. var selectedElmX = position.x;
  11544. var selectedElmY = position.y;
  11545. var rect = targetElm.getBoundingClientRect();
  11546. var targetWidth = rect.width || rect.right - rect.left;
  11547. var targetHeight = rect.height || rect.bottom - rect.top;
  11548. if (selectedElm !== targetElm) {
  11549. hideResizeRect();
  11550. selectedElm = targetElm;
  11551. width = height = 0;
  11552. }
  11553. var e = editor.fire('ObjectSelected', { target: targetElm });
  11554. var selectedValue = dom.getAttrib(selectedElm, elementSelectionAttr, '1');
  11555. if (isResizable(targetElm) && !e.isDefaultPrevented()) {
  11556. each(resizeHandles, function (handle, name) {
  11557. var handleElm;
  11558. var startDrag = function (e) {
  11559. var target = getResizeTargets(selectedElm)[0];
  11560. startX = e.screenX;
  11561. startY = e.screenY;
  11562. startW = target.clientWidth;
  11563. startH = target.clientHeight;
  11564. ratio = startH / startW;
  11565. selectedHandle = handle;
  11566. selectedHandle.name = name;
  11567. selectedHandle.startPos = {
  11568. x: targetWidth * handle[0] + selectedElmX,
  11569. y: targetHeight * handle[1] + selectedElmY
  11570. };
  11571. startScrollWidth = rootElement.scrollWidth;
  11572. startScrollHeight = rootElement.scrollHeight;
  11573. resizeBackdrop = dom.add(rootElement, 'div', { class: 'mce-resize-backdrop' });
  11574. dom.setStyles(resizeBackdrop, {
  11575. position: 'fixed',
  11576. left: '0',
  11577. top: '0',
  11578. width: '100%',
  11579. height: '100%'
  11580. });
  11581. selectedElmGhost = createGhostElement(selectedElm);
  11582. dom.addClass(selectedElmGhost, 'mce-clonedresizable');
  11583. dom.setAttrib(selectedElmGhost, 'data-mce-bogus', 'all');
  11584. selectedElmGhost.contentEditable = 'false';
  11585. dom.setStyles(selectedElmGhost, {
  11586. left: selectedElmX,
  11587. top: selectedElmY,
  11588. margin: 0
  11589. });
  11590. setGhostElmSize(selectedElmGhost, targetWidth, targetHeight);
  11591. selectedElmGhost.removeAttribute(elementSelectionAttr);
  11592. rootElement.appendChild(selectedElmGhost);
  11593. dom.bind(editableDoc, 'mousemove', resizeGhostElement);
  11594. dom.bind(editableDoc, 'mouseup', endGhostResize);
  11595. if (rootDocument !== editableDoc) {
  11596. dom.bind(rootDocument, 'mousemove', resizeGhostElement);
  11597. dom.bind(rootDocument, 'mouseup', endGhostResize);
  11598. }
  11599. resizeHelper = dom.add(rootElement, 'div', {
  11600. 'class': 'mce-resize-helper',
  11601. 'data-mce-bogus': 'all'
  11602. }, startW + ' &times; ' + startH);
  11603. };
  11604. handleElm = dom.get('mceResizeHandle' + name);
  11605. if (handleElm) {
  11606. dom.remove(handleElm);
  11607. }
  11608. handleElm = dom.add(rootElement, 'div', {
  11609. 'id': 'mceResizeHandle' + name,
  11610. 'data-mce-bogus': 'all',
  11611. 'class': 'mce-resizehandle',
  11612. 'unselectable': true,
  11613. 'style': 'cursor:' + name + '-resize; margin:0; padding:0'
  11614. });
  11615. if (Env.ie === 11) {
  11616. handleElm.contentEditable = false;
  11617. }
  11618. dom.bind(handleElm, 'mousedown', function (e) {
  11619. e.stopImmediatePropagation();
  11620. e.preventDefault();
  11621. startDrag(e);
  11622. });
  11623. handle.elm = handleElm;
  11624. dom.setStyles(handleElm, {
  11625. left: targetWidth * handle[0] + selectedElmX - handleElm.offsetWidth / 2,
  11626. top: targetHeight * handle[1] + selectedElmY - handleElm.offsetHeight / 2
  11627. });
  11628. });
  11629. } else {
  11630. hideResizeRect();
  11631. }
  11632. if (!dom.getAttrib(selectedElm, elementSelectionAttr)) {
  11633. selectedElm.setAttribute(elementSelectionAttr, selectedValue);
  11634. }
  11635. };
  11636. var hideResizeRect = function () {
  11637. unbindResizeHandleEvents();
  11638. if (selectedElm) {
  11639. selectedElm.removeAttribute(elementSelectionAttr);
  11640. }
  11641. each$j(resizeHandles, function (value, name) {
  11642. var handleElm = dom.get('mceResizeHandle' + name);
  11643. if (handleElm) {
  11644. dom.unbind(handleElm);
  11645. dom.remove(handleElm);
  11646. }
  11647. });
  11648. };
  11649. var updateResizeRect = function (e) {
  11650. var startElm, controlElm;
  11651. var isChildOrEqual = function (node, parent) {
  11652. if (node) {
  11653. do {
  11654. if (node === parent) {
  11655. return true;
  11656. }
  11657. } while (node = node.parentNode);
  11658. }
  11659. };
  11660. if (resizeStarted || editor.removed) {
  11661. return;
  11662. }
  11663. each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function (img) {
  11664. img.removeAttribute(elementSelectionAttr);
  11665. });
  11666. controlElm = e.type === 'mousedown' ? e.target : selection.getNode();
  11667. controlElm = dom.$(controlElm).closest('table,img,figure.image,hr,video,span.mce-preview-object')[0];
  11668. if (isChildOrEqual(controlElm, rootElement)) {
  11669. disableGeckoResize();
  11670. startElm = selection.getStart(true);
  11671. if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
  11672. showResizeRect(controlElm);
  11673. return;
  11674. }
  11675. }
  11676. hideResizeRect();
  11677. };
  11678. var isWithinContentEditableFalse = function (elm) {
  11679. return isContentEditableFalse$5(getContentEditableRoot$1(editor.getBody(), elm));
  11680. };
  11681. var unbindResizeHandleEvents = function () {
  11682. each$j(resizeHandles, function (handle) {
  11683. if (handle.elm) {
  11684. dom.unbind(handle.elm);
  11685. delete handle.elm;
  11686. }
  11687. });
  11688. };
  11689. var disableGeckoResize = function () {
  11690. try {
  11691. editor.getDoc().execCommand('enableObjectResizing', false, 'false');
  11692. } catch (ex) {
  11693. }
  11694. };
  11695. editor.on('init', function () {
  11696. disableGeckoResize();
  11697. if (Env.browser.isIE() || Env.browser.isEdge()) {
  11698. editor.on('mousedown click', function (e) {
  11699. var target = e.target, nodeName = target.nodeName;
  11700. if (!resizeStarted && /^(TABLE|IMG|HR)$/.test(nodeName) && !isWithinContentEditableFalse(target)) {
  11701. if (e.button !== 2) {
  11702. editor.selection.select(target, nodeName === 'TABLE');
  11703. }
  11704. if (e.type === 'mousedown') {
  11705. editor.nodeChanged();
  11706. }
  11707. }
  11708. });
  11709. var handleMSControlSelect_1 = function (e) {
  11710. var delayedSelect = function (node) {
  11711. Delay.setEditorTimeout(editor, function () {
  11712. return editor.selection.select(node);
  11713. });
  11714. };
  11715. if (isWithinContentEditableFalse(e.target) || isMedia$2(e.target)) {
  11716. e.preventDefault();
  11717. delayedSelect(e.target);
  11718. return;
  11719. }
  11720. if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) {
  11721. e.preventDefault();
  11722. if (e.target.tagName === 'IMG') {
  11723. delayedSelect(e.target);
  11724. }
  11725. }
  11726. };
  11727. dom.bind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11728. editor.on('remove', function () {
  11729. return dom.unbind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11730. });
  11731. }
  11732. var throttledUpdateResizeRect = Delay.throttle(function (e) {
  11733. if (!editor.composing) {
  11734. updateResizeRect(e);
  11735. }
  11736. });
  11737. editor.on('nodechange ResizeEditor ResizeWindow ResizeContent drop FullscreenStateChanged', throttledUpdateResizeRect);
  11738. editor.on('keyup compositionend', function (e) {
  11739. if (selectedElm && selectedElm.nodeName === 'TABLE') {
  11740. throttledUpdateResizeRect(e);
  11741. }
  11742. });
  11743. editor.on('hide blur', hideResizeRect);
  11744. editor.on('contextmenu longpress', contextMenuSelectImage, true);
  11745. });
  11746. editor.on('remove', unbindResizeHandleEvents);
  11747. var destroy = function () {
  11748. selectedElm = selectedElmGhost = resizeBackdrop = null;
  11749. };
  11750. return {
  11751. isResizable: isResizable,
  11752. showResizeRect: showResizeRect,
  11753. hideResizeRect: hideResizeRect,
  11754. updateResizeRect: updateResizeRect,
  11755. destroy: destroy
  11756. };
  11757. };
  11758. var hasCeProperty = function (node) {
  11759. return isContentEditableTrue$4(node) || isContentEditableFalse$b(node);
  11760. };
  11761. var findParent$1 = function (node, rootNode, predicate) {
  11762. while (node && node !== rootNode) {
  11763. if (predicate(node)) {
  11764. return node;
  11765. }
  11766. node = node.parentNode;
  11767. }
  11768. return null;
  11769. };
  11770. var findClosestIeRange = function (clientX, clientY, doc) {
  11771. var rects;
  11772. var element = doc.elementFromPoint(clientX, clientY);
  11773. var rng = doc.body.createTextRange();
  11774. if (!element || element.tagName === 'HTML') {
  11775. element = doc.body;
  11776. }
  11777. rng.moveToElementText(element);
  11778. rects = Tools.toArray(rng.getClientRects());
  11779. rects = rects.sort(function (a, b) {
  11780. a = Math.abs(Math.max(a.top - clientY, a.bottom - clientY));
  11781. b = Math.abs(Math.max(b.top - clientY, b.bottom - clientY));
  11782. return a - b;
  11783. });
  11784. if (rects.length > 0) {
  11785. clientY = (rects[0].bottom + rects[0].top) / 2;
  11786. try {
  11787. rng.moveToPoint(clientX, clientY);
  11788. rng.collapse(true);
  11789. return rng;
  11790. } catch (ex) {
  11791. }
  11792. }
  11793. return null;
  11794. };
  11795. var moveOutOfContentEditableFalse = function (rng, rootNode) {
  11796. var parentElement = rng && rng.parentElement ? rng.parentElement() : null;
  11797. return isContentEditableFalse$b(findParent$1(parentElement, rootNode, hasCeProperty)) ? null : rng;
  11798. };
  11799. var fromPoint = function (clientX, clientY, doc) {
  11800. var rng, point;
  11801. var pointDoc = doc;
  11802. if (pointDoc.caretPositionFromPoint) {
  11803. point = pointDoc.caretPositionFromPoint(clientX, clientY);
  11804. if (point) {
  11805. rng = doc.createRange();
  11806. rng.setStart(point.offsetNode, point.offset);
  11807. rng.collapse(true);
  11808. }
  11809. } else if (pointDoc.caretRangeFromPoint) {
  11810. rng = pointDoc.caretRangeFromPoint(clientX, clientY);
  11811. } else if (pointDoc.body.createTextRange) {
  11812. rng = pointDoc.body.createTextRange();
  11813. try {
  11814. rng.moveToPoint(clientX, clientY);
  11815. rng.collapse(true);
  11816. } catch (ex) {
  11817. rng = findClosestIeRange(clientX, clientY, doc);
  11818. }
  11819. return moveOutOfContentEditableFalse(rng, doc.body);
  11820. }
  11821. return rng;
  11822. };
  11823. var isEq$4 = function (rng1, rng2) {
  11824. return rng1 && rng2 && (rng1.startContainer === rng2.startContainer && rng1.startOffset === rng2.startOffset) && (rng1.endContainer === rng2.endContainer && rng1.endOffset === rng2.endOffset);
  11825. };
  11826. var findParent = function (node, rootNode, predicate) {
  11827. while (node && node !== rootNode) {
  11828. if (predicate(node)) {
  11829. return node;
  11830. }
  11831. node = node.parentNode;
  11832. }
  11833. return null;
  11834. };
  11835. var hasParent$1 = function (node, rootNode, predicate) {
  11836. return findParent(node, rootNode, predicate) !== null;
  11837. };
  11838. var hasParentWithName = function (node, rootNode, name) {
  11839. return hasParent$1(node, rootNode, function (node) {
  11840. return node.nodeName === name;
  11841. });
  11842. };
  11843. var isTable = function (node) {
  11844. return node && node.nodeName === 'TABLE';
  11845. };
  11846. var isTableCell$2 = function (node) {
  11847. return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  11848. };
  11849. var isCeFalseCaretContainer = function (node, rootNode) {
  11850. return isCaretContainer$2(node) && hasParent$1(node, rootNode, isCaretNode) === false;
  11851. };
  11852. var hasBrBeforeAfter = function (dom, node, left) {
  11853. var walker = new DomTreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || dom.getRoot());
  11854. while (node = walker[left ? 'prev' : 'next']()) {
  11855. if (isBr$5(node)) {
  11856. return true;
  11857. }
  11858. }
  11859. };
  11860. var isPrevNode = function (node, name) {
  11861. return node.previousSibling && node.previousSibling.nodeName === name;
  11862. };
  11863. var hasContentEditableFalseParent = function (body, node) {
  11864. while (node && node !== body) {
  11865. if (isContentEditableFalse$b(node)) {
  11866. return true;
  11867. }
  11868. node = node.parentNode;
  11869. }
  11870. return false;
  11871. };
  11872. var findTextNodeRelative = function (dom, isAfterNode, collapsed, left, startNode) {
  11873. var lastInlineElement;
  11874. var body = dom.getRoot();
  11875. var node;
  11876. var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11877. var parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body;
  11878. if (left && isBr$5(startNode) && isAfterNode && dom.isEmpty(parentBlockContainer)) {
  11879. return Optional.some(CaretPosition(startNode.parentNode, dom.nodeIndex(startNode)));
  11880. }
  11881. var walker = new DomTreeWalker(startNode, parentBlockContainer);
  11882. while (node = walker[left ? 'prev' : 'next']()) {
  11883. if (dom.getContentEditableParent(node) === 'false' || isCeFalseCaretContainer(node, body)) {
  11884. return Optional.none();
  11885. }
  11886. if (isText$7(node) && node.nodeValue.length > 0) {
  11887. if (hasParentWithName(node, body, 'A') === false) {
  11888. return Optional.some(CaretPosition(node, left ? node.nodeValue.length : 0));
  11889. }
  11890. return Optional.none();
  11891. }
  11892. if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  11893. return Optional.none();
  11894. }
  11895. lastInlineElement = node;
  11896. }
  11897. if (collapsed && lastInlineElement) {
  11898. return Optional.some(CaretPosition(lastInlineElement, 0));
  11899. }
  11900. return Optional.none();
  11901. };
  11902. var normalizeEndPoint = function (dom, collapsed, start, rng) {
  11903. var container, offset;
  11904. var body = dom.getRoot();
  11905. var node;
  11906. var directionLeft, normalized = false;
  11907. container = rng[(start ? 'start' : 'end') + 'Container'];
  11908. offset = rng[(start ? 'start' : 'end') + 'Offset'];
  11909. var isAfterNode = isElement$5(container) && offset === container.childNodes.length;
  11910. var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11911. directionLeft = start;
  11912. if (isCaretContainer$2(container)) {
  11913. return Optional.none();
  11914. }
  11915. if (isElement$5(container) && offset > container.childNodes.length - 1) {
  11916. directionLeft = false;
  11917. }
  11918. if (isDocument$1(container)) {
  11919. container = body;
  11920. offset = 0;
  11921. }
  11922. if (container === body) {
  11923. if (directionLeft) {
  11924. node = container.childNodes[offset > 0 ? offset - 1 : 0];
  11925. if (node) {
  11926. if (isCaretContainer$2(node)) {
  11927. return Optional.none();
  11928. }
  11929. if (nonEmptyElementsMap[node.nodeName] || isTable(node)) {
  11930. return Optional.none();
  11931. }
  11932. }
  11933. }
  11934. if (container.hasChildNodes()) {
  11935. offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
  11936. container = container.childNodes[offset];
  11937. offset = isText$7(container) && isAfterNode ? container.data.length : 0;
  11938. if (!collapsed && container === body.lastChild && isTable(container)) {
  11939. return Optional.none();
  11940. }
  11941. if (hasContentEditableFalseParent(body, container) || isCaretContainer$2(container)) {
  11942. return Optional.none();
  11943. }
  11944. if (container.hasChildNodes() && isTable(container) === false) {
  11945. node = container;
  11946. var walker = new DomTreeWalker(container, body);
  11947. do {
  11948. if (isContentEditableFalse$b(node) || isCaretContainer$2(node)) {
  11949. normalized = false;
  11950. break;
  11951. }
  11952. if (isText$7(node) && node.nodeValue.length > 0) {
  11953. offset = directionLeft ? 0 : node.nodeValue.length;
  11954. container = node;
  11955. normalized = true;
  11956. break;
  11957. }
  11958. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCell$2(node)) {
  11959. offset = dom.nodeIndex(node);
  11960. container = node.parentNode;
  11961. if (!directionLeft) {
  11962. offset++;
  11963. }
  11964. normalized = true;
  11965. break;
  11966. }
  11967. } while (node = directionLeft ? walker.next() : walker.prev());
  11968. }
  11969. }
  11970. }
  11971. if (collapsed) {
  11972. if (isText$7(container) && offset === 0) {
  11973. findTextNodeRelative(dom, isAfterNode, collapsed, true, container).each(function (pos) {
  11974. container = pos.container();
  11975. offset = pos.offset();
  11976. normalized = true;
  11977. });
  11978. }
  11979. if (isElement$5(container)) {
  11980. node = container.childNodes[offset];
  11981. if (!node) {
  11982. node = container.childNodes[offset - 1];
  11983. }
  11984. if (node && isBr$5(node) && !isPrevNode(node, 'A') && !hasBrBeforeAfter(dom, node, false) && !hasBrBeforeAfter(dom, node, true)) {
  11985. findTextNodeRelative(dom, isAfterNode, collapsed, true, node).each(function (pos) {
  11986. container = pos.container();
  11987. offset = pos.offset();
  11988. normalized = true;
  11989. });
  11990. }
  11991. }
  11992. }
  11993. if (directionLeft && !collapsed && isText$7(container) && offset === container.nodeValue.length) {
  11994. findTextNodeRelative(dom, isAfterNode, collapsed, false, container).each(function (pos) {
  11995. container = pos.container();
  11996. offset = pos.offset();
  11997. normalized = true;
  11998. });
  11999. }
  12000. return normalized ? Optional.some(CaretPosition(container, offset)) : Optional.none();
  12001. };
  12002. var normalize$2 = function (dom, rng) {
  12003. var collapsed = rng.collapsed, normRng = rng.cloneRange();
  12004. var startPos = CaretPosition.fromRangeStart(rng);
  12005. normalizeEndPoint(dom, collapsed, true, normRng).each(function (pos) {
  12006. if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
  12007. normRng.setStart(pos.container(), pos.offset());
  12008. }
  12009. });
  12010. if (!collapsed) {
  12011. normalizeEndPoint(dom, collapsed, false, normRng).each(function (pos) {
  12012. normRng.setEnd(pos.container(), pos.offset());
  12013. });
  12014. }
  12015. if (collapsed) {
  12016. normRng.collapse(true);
  12017. }
  12018. return isEq$4(rng, normRng) ? Optional.none() : Optional.some(normRng);
  12019. };
  12020. var splitText = function (node, offset) {
  12021. return node.splitText(offset);
  12022. };
  12023. var split = function (rng) {
  12024. var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  12025. if (startContainer === endContainer && isText$7(startContainer)) {
  12026. if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  12027. endContainer = splitText(startContainer, startOffset);
  12028. startContainer = endContainer.previousSibling;
  12029. if (endOffset > startOffset) {
  12030. endOffset = endOffset - startOffset;
  12031. startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
  12032. endOffset = endContainer.nodeValue.length;
  12033. startOffset = 0;
  12034. } else {
  12035. endOffset = 0;
  12036. }
  12037. }
  12038. } else {
  12039. if (isText$7(startContainer) && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  12040. startContainer = splitText(startContainer, startOffset);
  12041. startOffset = 0;
  12042. }
  12043. if (isText$7(endContainer) && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
  12044. endContainer = splitText(endContainer, endOffset).previousSibling;
  12045. endOffset = endContainer.nodeValue.length;
  12046. }
  12047. }
  12048. return {
  12049. startContainer: startContainer,
  12050. startOffset: startOffset,
  12051. endContainer: endContainer,
  12052. endOffset: endOffset
  12053. };
  12054. };
  12055. var RangeUtils = function (dom) {
  12056. var walk = function (rng, callback) {
  12057. return walk$2(dom, rng, callback);
  12058. };
  12059. var split$1 = split;
  12060. var normalize = function (rng) {
  12061. return normalize$2(dom, rng).fold(never, function (normalizedRng) {
  12062. rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
  12063. rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
  12064. return true;
  12065. });
  12066. };
  12067. return {
  12068. walk: walk,
  12069. split: split$1,
  12070. normalize: normalize
  12071. };
  12072. };
  12073. RangeUtils.compareRanges = isEq$4;
  12074. RangeUtils.getCaretRangeFromPoint = fromPoint;
  12075. RangeUtils.getSelectedNode = getSelectedNode;
  12076. RangeUtils.getNode = getNode$1;
  12077. var Dimension = function (name, getOffset) {
  12078. var set = function (element, h) {
  12079. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  12080. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  12081. }
  12082. var dom = element.dom;
  12083. if (isSupported(dom)) {
  12084. dom.style[name] = h + 'px';
  12085. }
  12086. };
  12087. var get = function (element) {
  12088. var r = getOffset(element);
  12089. if (r <= 0 || r === null) {
  12090. var css = get$5(element, name);
  12091. return parseFloat(css) || 0;
  12092. }
  12093. return r;
  12094. };
  12095. var getOuter = get;
  12096. var aggregate = function (element, properties) {
  12097. return foldl(properties, function (acc, property) {
  12098. var val = get$5(element, property);
  12099. var value = val === undefined ? 0 : parseInt(val, 10);
  12100. return isNaN(value) ? acc : acc + value;
  12101. }, 0);
  12102. };
  12103. var max = function (element, value, properties) {
  12104. var cumulativeInclusions = aggregate(element, properties);
  12105. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  12106. return absoluteMax;
  12107. };
  12108. return {
  12109. set: set,
  12110. get: get,
  12111. getOuter: getOuter,
  12112. aggregate: aggregate,
  12113. max: max
  12114. };
  12115. };
  12116. var api = Dimension('height', function (element) {
  12117. var dom = element.dom;
  12118. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  12119. });
  12120. var get$1 = function (element) {
  12121. return api.get(element);
  12122. };
  12123. var walkUp = function (navigation, doc) {
  12124. var frame = navigation.view(doc);
  12125. return frame.fold(constant([]), function (f) {
  12126. var parent = navigation.owner(f);
  12127. var rest = walkUp(navigation, parent);
  12128. return [f].concat(rest);
  12129. });
  12130. };
  12131. var pathTo = function (element, navigation) {
  12132. var d = navigation.owner(element);
  12133. return walkUp(navigation, d);
  12134. };
  12135. var view = function (doc) {
  12136. var _a;
  12137. var element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  12138. return element.map(SugarElement.fromDom);
  12139. };
  12140. var owner = function (element) {
  12141. return documentOrOwner(element);
  12142. };
  12143. var Navigation = /*#__PURE__*/Object.freeze({
  12144. __proto__: null,
  12145. view: view,
  12146. owner: owner
  12147. });
  12148. var find$1 = function (element) {
  12149. var doc = SugarElement.fromDom(document);
  12150. var scroll = get$8(doc);
  12151. var frames = pathTo(element, Navigation);
  12152. var offset = viewport(element);
  12153. var r = foldr(frames, function (b, a) {
  12154. var loc = viewport(a);
  12155. return {
  12156. left: b.left + loc.left,
  12157. top: b.top + loc.top
  12158. };
  12159. }, {
  12160. left: 0,
  12161. top: 0
  12162. });
  12163. return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  12164. };
  12165. var excludeFromDescend = function (element) {
  12166. return name(element) === 'textarea';
  12167. };
  12168. var fireScrollIntoViewEvent = function (editor, data) {
  12169. var scrollEvent = editor.fire('ScrollIntoView', data);
  12170. return scrollEvent.isDefaultPrevented();
  12171. };
  12172. var fireAfterScrollIntoViewEvent = function (editor, data) {
  12173. editor.fire('AfterScrollIntoView', data);
  12174. };
  12175. var descend = function (element, offset) {
  12176. var children$1 = children(element);
  12177. if (children$1.length === 0 || excludeFromDescend(element)) {
  12178. return {
  12179. element: element,
  12180. offset: offset
  12181. };
  12182. } else if (offset < children$1.length && !excludeFromDescend(children$1[offset])) {
  12183. return {
  12184. element: children$1[offset],
  12185. offset: 0
  12186. };
  12187. } else {
  12188. var last = children$1[children$1.length - 1];
  12189. if (excludeFromDescend(last)) {
  12190. return {
  12191. element: element,
  12192. offset: offset
  12193. };
  12194. } else {
  12195. if (name(last) === 'img') {
  12196. return {
  12197. element: last,
  12198. offset: 1
  12199. };
  12200. } else if (isText$8(last)) {
  12201. return {
  12202. element: last,
  12203. offset: get$2(last).length
  12204. };
  12205. } else {
  12206. return {
  12207. element: last,
  12208. offset: children(last).length
  12209. };
  12210. }
  12211. }
  12212. }
  12213. };
  12214. var markerInfo = function (element, cleanupFun) {
  12215. var pos = absolute(element);
  12216. var height = get$1(element);
  12217. return {
  12218. element: element,
  12219. bottom: pos.top + height,
  12220. height: height,
  12221. pos: pos,
  12222. cleanup: cleanupFun
  12223. };
  12224. };
  12225. var createMarker = function (element, offset) {
  12226. var startPoint = descend(element, offset);
  12227. var span = SugarElement.fromHtml('<span data-mce-bogus="all">' + ZWSP$1 + '</span>');
  12228. before$4(startPoint.element, span);
  12229. return markerInfo(span, function () {
  12230. return remove$7(span);
  12231. });
  12232. };
  12233. var elementMarker = function (element) {
  12234. return markerInfo(SugarElement.fromDom(element), noop);
  12235. };
  12236. var withMarker = function (editor, f, rng, alignToTop) {
  12237. preserveWith(editor, function (_s, _e) {
  12238. return applyWithMarker(editor, f, rng, alignToTop);
  12239. }, rng);
  12240. };
  12241. var withScrollEvents = function (editor, doc, f, marker, alignToTop) {
  12242. var data = {
  12243. elm: marker.element.dom,
  12244. alignToTop: alignToTop
  12245. };
  12246. if (fireScrollIntoViewEvent(editor, data)) {
  12247. return;
  12248. }
  12249. var scrollTop = get$8(doc).top;
  12250. f(doc, scrollTop, marker, alignToTop);
  12251. fireAfterScrollIntoViewEvent(editor, data);
  12252. };
  12253. var applyWithMarker = function (editor, f, rng, alignToTop) {
  12254. var body = SugarElement.fromDom(editor.getBody());
  12255. var doc = SugarElement.fromDom(editor.getDoc());
  12256. reflow(body);
  12257. var marker = createMarker(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  12258. withScrollEvents(editor, doc, f, marker, alignToTop);
  12259. marker.cleanup();
  12260. };
  12261. var withElement = function (editor, element, f, alignToTop) {
  12262. var doc = SugarElement.fromDom(editor.getDoc());
  12263. withScrollEvents(editor, doc, f, elementMarker(element), alignToTop);
  12264. };
  12265. var preserveWith = function (editor, f, rng) {
  12266. var startElement = rng.startContainer;
  12267. var startOffset = rng.startOffset;
  12268. var endElement = rng.endContainer;
  12269. var endOffset = rng.endOffset;
  12270. f(SugarElement.fromDom(startElement), SugarElement.fromDom(endElement));
  12271. var newRng = editor.dom.createRng();
  12272. newRng.setStart(startElement, startOffset);
  12273. newRng.setEnd(endElement, endOffset);
  12274. editor.selection.setRng(rng);
  12275. };
  12276. var scrollToMarker = function (marker, viewHeight, alignToTop, doc) {
  12277. var pos = marker.pos;
  12278. if (alignToTop) {
  12279. to(pos.left, pos.top, doc);
  12280. } else {
  12281. var y = pos.top - viewHeight + marker.height;
  12282. to(pos.left, y, doc);
  12283. }
  12284. };
  12285. var intoWindowIfNeeded = function (doc, scrollTop, viewHeight, marker, alignToTop) {
  12286. var viewportBottom = viewHeight + scrollTop;
  12287. var markerTop = marker.pos.top;
  12288. var markerBottom = marker.bottom;
  12289. var largerThanViewport = markerBottom - markerTop >= viewHeight;
  12290. if (markerTop < scrollTop) {
  12291. scrollToMarker(marker, viewHeight, alignToTop !== false, doc);
  12292. } else if (markerTop > viewportBottom) {
  12293. var align = largerThanViewport ? alignToTop !== false : alignToTop === true;
  12294. scrollToMarker(marker, viewHeight, align, doc);
  12295. } else if (markerBottom > viewportBottom && !largerThanViewport) {
  12296. scrollToMarker(marker, viewHeight, alignToTop === true, doc);
  12297. }
  12298. };
  12299. var intoWindow = function (doc, scrollTop, marker, alignToTop) {
  12300. var viewHeight = doc.dom.defaultView.innerHeight;
  12301. intoWindowIfNeeded(doc, scrollTop, viewHeight, marker, alignToTop);
  12302. };
  12303. var intoFrame = function (doc, scrollTop, marker, alignToTop) {
  12304. var frameViewHeight = doc.dom.defaultView.innerHeight;
  12305. intoWindowIfNeeded(doc, scrollTop, frameViewHeight, marker, alignToTop);
  12306. var op = find$1(marker.element);
  12307. var viewportBounds = getBounds(window);
  12308. if (op.top < viewportBounds.y) {
  12309. intoView(marker.element, alignToTop !== false);
  12310. } else if (op.top > viewportBounds.bottom) {
  12311. intoView(marker.element, alignToTop === true);
  12312. }
  12313. };
  12314. var rangeIntoWindow = function (editor, rng, alignToTop) {
  12315. return withMarker(editor, intoWindow, rng, alignToTop);
  12316. };
  12317. var elementIntoWindow = function (editor, element, alignToTop) {
  12318. return withElement(editor, element, intoWindow, alignToTop);
  12319. };
  12320. var rangeIntoFrame = function (editor, rng, alignToTop) {
  12321. return withMarker(editor, intoFrame, rng, alignToTop);
  12322. };
  12323. var elementIntoFrame = function (editor, element, alignToTop) {
  12324. return withElement(editor, element, intoFrame, alignToTop);
  12325. };
  12326. var scrollElementIntoView = function (editor, element, alignToTop) {
  12327. var scroller = editor.inline ? elementIntoWindow : elementIntoFrame;
  12328. scroller(editor, element, alignToTop);
  12329. };
  12330. var scrollRangeIntoView = function (editor, rng, alignToTop) {
  12331. var scroller = editor.inline ? rangeIntoWindow : rangeIntoFrame;
  12332. scroller(editor, rng, alignToTop);
  12333. };
  12334. var getDocument = function () {
  12335. return SugarElement.fromDom(document);
  12336. };
  12337. var focus$1 = function (element) {
  12338. return element.dom.focus();
  12339. };
  12340. var hasFocus$1 = function (element) {
  12341. var root = getRootNode(element).dom;
  12342. return element.dom === root.activeElement;
  12343. };
  12344. var active = function (root) {
  12345. if (root === void 0) {
  12346. root = getDocument();
  12347. }
  12348. return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  12349. };
  12350. var search = function (element) {
  12351. return active(getRootNode(element)).filter(function (e) {
  12352. return element.dom.contains(e.dom);
  12353. });
  12354. };
  12355. var create$5 = function (start, soffset, finish, foffset) {
  12356. return {
  12357. start: start,
  12358. soffset: soffset,
  12359. finish: finish,
  12360. foffset: foffset
  12361. };
  12362. };
  12363. var SimRange = { create: create$5 };
  12364. var adt$1 = Adt.generate([
  12365. { before: ['element'] },
  12366. {
  12367. on: [
  12368. 'element',
  12369. 'offset'
  12370. ]
  12371. },
  12372. { after: ['element'] }
  12373. ]);
  12374. var cata = function (subject, onBefore, onOn, onAfter) {
  12375. return subject.fold(onBefore, onOn, onAfter);
  12376. };
  12377. var getStart$2 = function (situ) {
  12378. return situ.fold(identity, identity, identity);
  12379. };
  12380. var before$1 = adt$1.before;
  12381. var on = adt$1.on;
  12382. var after$1 = adt$1.after;
  12383. var Situ = {
  12384. before: before$1,
  12385. on: on,
  12386. after: after$1,
  12387. cata: cata,
  12388. getStart: getStart$2
  12389. };
  12390. var adt = Adt.generate([
  12391. { domRange: ['rng'] },
  12392. {
  12393. relative: [
  12394. 'startSitu',
  12395. 'finishSitu'
  12396. ]
  12397. },
  12398. {
  12399. exact: [
  12400. 'start',
  12401. 'soffset',
  12402. 'finish',
  12403. 'foffset'
  12404. ]
  12405. }
  12406. ]);
  12407. var exactFromRange = function (simRange) {
  12408. return adt.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  12409. };
  12410. var getStart$1 = function (selection) {
  12411. return selection.match({
  12412. domRange: function (rng) {
  12413. return SugarElement.fromDom(rng.startContainer);
  12414. },
  12415. relative: function (startSitu, _finishSitu) {
  12416. return Situ.getStart(startSitu);
  12417. },
  12418. exact: function (start, _soffset, _finish, _foffset) {
  12419. return start;
  12420. }
  12421. });
  12422. };
  12423. var domRange = adt.domRange;
  12424. var relative = adt.relative;
  12425. var exact = adt.exact;
  12426. var getWin = function (selection) {
  12427. var start = getStart$1(selection);
  12428. return defaultView(start);
  12429. };
  12430. var range = SimRange.create;
  12431. var SimSelection = {
  12432. domRange: domRange,
  12433. relative: relative,
  12434. exact: exact,
  12435. exactFromRange: exactFromRange,
  12436. getWin: getWin,
  12437. range: range
  12438. };
  12439. var browser$1 = detect().browser;
  12440. var clamp$1 = function (offset, element) {
  12441. var max = isText$8(element) ? get$2(element).length : children(element).length + 1;
  12442. if (offset > max) {
  12443. return max;
  12444. } else if (offset < 0) {
  12445. return 0;
  12446. }
  12447. return offset;
  12448. };
  12449. var normalizeRng = function (rng) {
  12450. return SimSelection.range(rng.start, clamp$1(rng.soffset, rng.start), rng.finish, clamp$1(rng.foffset, rng.finish));
  12451. };
  12452. var isOrContains = function (root, elm) {
  12453. return !isRestrictedNode(elm.dom) && (contains$1(root, elm) || eq(root, elm));
  12454. };
  12455. var isRngInRoot = function (root) {
  12456. return function (rng) {
  12457. return isOrContains(root, rng.start) && isOrContains(root, rng.finish);
  12458. };
  12459. };
  12460. var shouldStore = function (editor) {
  12461. return editor.inline === true || browser$1.isIE();
  12462. };
  12463. var nativeRangeToSelectionRange = function (r) {
  12464. return SimSelection.range(SugarElement.fromDom(r.startContainer), r.startOffset, SugarElement.fromDom(r.endContainer), r.endOffset);
  12465. };
  12466. var readRange = function (win) {
  12467. var selection = win.getSelection();
  12468. var rng = !selection || selection.rangeCount === 0 ? Optional.none() : Optional.from(selection.getRangeAt(0));
  12469. return rng.map(nativeRangeToSelectionRange);
  12470. };
  12471. var getBookmark = function (root) {
  12472. var win = defaultView(root);
  12473. return readRange(win.dom).filter(isRngInRoot(root));
  12474. };
  12475. var validate = function (root, bookmark) {
  12476. return Optional.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
  12477. };
  12478. var bookmarkToNativeRng = function (bookmark) {
  12479. var rng = document.createRange();
  12480. try {
  12481. rng.setStart(bookmark.start.dom, bookmark.soffset);
  12482. rng.setEnd(bookmark.finish.dom, bookmark.foffset);
  12483. return Optional.some(rng);
  12484. } catch (_) {
  12485. return Optional.none();
  12486. }
  12487. };
  12488. var store = function (editor) {
  12489. var newBookmark = shouldStore(editor) ? getBookmark(SugarElement.fromDom(editor.getBody())) : Optional.none();
  12490. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12491. };
  12492. var storeNative = function (editor, rng) {
  12493. var root = SugarElement.fromDom(editor.getBody());
  12494. var range = shouldStore(editor) ? Optional.from(rng) : Optional.none();
  12495. var newBookmark = range.map(nativeRangeToSelectionRange).filter(isRngInRoot(root));
  12496. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12497. };
  12498. var getRng = function (editor) {
  12499. var bookmark = editor.bookmark ? editor.bookmark : Optional.none();
  12500. return bookmark.bind(function (x) {
  12501. return validate(SugarElement.fromDom(editor.getBody()), x);
  12502. }).bind(bookmarkToNativeRng);
  12503. };
  12504. var restore = function (editor) {
  12505. getRng(editor).each(function (rng) {
  12506. return editor.selection.setRng(rng);
  12507. });
  12508. };
  12509. var isEditorUIElement$1 = function (elm) {
  12510. var className = elm.className.toString();
  12511. return className.indexOf('tox-') !== -1 || className.indexOf('mce-') !== -1;
  12512. };
  12513. var FocusManager = { isEditorUIElement: isEditorUIElement$1 };
  12514. var isManualNodeChange = function (e) {
  12515. return e.type === 'nodechange' && e.selectionChange;
  12516. };
  12517. var registerPageMouseUp = function (editor, throttledStore) {
  12518. var mouseUpPage = function () {
  12519. throttledStore.throttle();
  12520. };
  12521. DOMUtils.DOM.bind(document, 'mouseup', mouseUpPage);
  12522. editor.on('remove', function () {
  12523. DOMUtils.DOM.unbind(document, 'mouseup', mouseUpPage);
  12524. });
  12525. };
  12526. var registerFocusOut = function (editor) {
  12527. editor.on('focusout', function () {
  12528. store(editor);
  12529. });
  12530. };
  12531. var registerMouseUp = function (editor, throttledStore) {
  12532. editor.on('mouseup touchend', function (_e) {
  12533. throttledStore.throttle();
  12534. });
  12535. };
  12536. var registerEditorEvents = function (editor, throttledStore) {
  12537. var browser = detect().browser;
  12538. if (browser.isIE()) {
  12539. registerFocusOut(editor);
  12540. } else {
  12541. registerMouseUp(editor, throttledStore);
  12542. }
  12543. editor.on('keyup NodeChange', function (e) {
  12544. if (!isManualNodeChange(e)) {
  12545. store(editor);
  12546. }
  12547. });
  12548. };
  12549. var register$3 = function (editor) {
  12550. var throttledStore = first(function () {
  12551. store(editor);
  12552. }, 0);
  12553. editor.on('init', function () {
  12554. if (editor.inline) {
  12555. registerPageMouseUp(editor, throttledStore);
  12556. }
  12557. registerEditorEvents(editor, throttledStore);
  12558. });
  12559. editor.on('remove', function () {
  12560. throttledStore.cancel();
  12561. });
  12562. };
  12563. var documentFocusInHandler;
  12564. var DOM$8 = DOMUtils.DOM;
  12565. var isEditorUIElement = function (elm) {
  12566. return FocusManager.isEditorUIElement(elm);
  12567. };
  12568. var isEditorContentAreaElement = function (elm) {
  12569. var classList = elm.classList;
  12570. if (classList !== undefined) {
  12571. return classList.contains('tox-edit-area') || classList.contains('tox-edit-area__iframe') || classList.contains('mce-content-body');
  12572. } else {
  12573. return false;
  12574. }
  12575. };
  12576. var isUIElement = function (editor, elm) {
  12577. var customSelector = getCustomUiSelector(editor);
  12578. var parent = DOM$8.getParent(elm, function (elm) {
  12579. return isEditorUIElement(elm) || (customSelector ? editor.dom.is(elm, customSelector) : false);
  12580. });
  12581. return parent !== null;
  12582. };
  12583. var getActiveElement = function (editor) {
  12584. try {
  12585. var root = getRootNode(SugarElement.fromDom(editor.getElement()));
  12586. return active(root).fold(function () {
  12587. return document.body;
  12588. }, function (x) {
  12589. return x.dom;
  12590. });
  12591. } catch (ex) {
  12592. return document.body;
  12593. }
  12594. };
  12595. var registerEvents$1 = function (editorManager, e) {
  12596. var editor = e.editor;
  12597. register$3(editor);
  12598. editor.on('focusin', function () {
  12599. var focusedEditor = editorManager.focusedEditor;
  12600. if (focusedEditor !== editor) {
  12601. if (focusedEditor) {
  12602. focusedEditor.fire('blur', { focusedEditor: editor });
  12603. }
  12604. editorManager.setActive(editor);
  12605. editorManager.focusedEditor = editor;
  12606. editor.fire('focus', { blurredEditor: focusedEditor });
  12607. editor.focus(true);
  12608. }
  12609. });
  12610. editor.on('focusout', function () {
  12611. Delay.setEditorTimeout(editor, function () {
  12612. var focusedEditor = editorManager.focusedEditor;
  12613. if (!isUIElement(editor, getActiveElement(editor)) && focusedEditor === editor) {
  12614. editor.fire('blur', { focusedEditor: null });
  12615. editorManager.focusedEditor = null;
  12616. }
  12617. });
  12618. });
  12619. if (!documentFocusInHandler) {
  12620. documentFocusInHandler = function (e) {
  12621. var activeEditor = editorManager.activeEditor;
  12622. if (activeEditor) {
  12623. getOriginalEventTarget(e).each(function (target) {
  12624. if (target.ownerDocument === document) {
  12625. if (target !== document.body && !isUIElement(activeEditor, target) && editorManager.focusedEditor === activeEditor) {
  12626. activeEditor.fire('blur', { focusedEditor: null });
  12627. editorManager.focusedEditor = null;
  12628. }
  12629. }
  12630. });
  12631. }
  12632. };
  12633. DOM$8.bind(document, 'focusin', documentFocusInHandler);
  12634. }
  12635. };
  12636. var unregisterDocumentEvents = function (editorManager, e) {
  12637. if (editorManager.focusedEditor === e.editor) {
  12638. editorManager.focusedEditor = null;
  12639. }
  12640. if (!editorManager.activeEditor) {
  12641. DOM$8.unbind(document, 'focusin', documentFocusInHandler);
  12642. documentFocusInHandler = null;
  12643. }
  12644. };
  12645. var setup$l = function (editorManager) {
  12646. editorManager.on('AddEditor', curry(registerEvents$1, editorManager));
  12647. editorManager.on('RemoveEditor', curry(unregisterDocumentEvents, editorManager));
  12648. };
  12649. var getContentEditableHost = function (editor, node) {
  12650. return editor.dom.getParent(node, function (node) {
  12651. return editor.dom.getContentEditable(node) === 'true';
  12652. });
  12653. };
  12654. var getCollapsedNode = function (rng) {
  12655. return rng.collapsed ? Optional.from(getNode$1(rng.startContainer, rng.startOffset)).map(SugarElement.fromDom) : Optional.none();
  12656. };
  12657. var getFocusInElement = function (root, rng) {
  12658. return getCollapsedNode(rng).bind(function (node) {
  12659. if (isTableSection(node)) {
  12660. return Optional.some(node);
  12661. } else if (contains$1(root, node) === false) {
  12662. return Optional.some(root);
  12663. } else {
  12664. return Optional.none();
  12665. }
  12666. });
  12667. };
  12668. var normalizeSelection$1 = function (editor, rng) {
  12669. getFocusInElement(SugarElement.fromDom(editor.getBody()), rng).bind(function (elm) {
  12670. return firstPositionIn(elm.dom);
  12671. }).fold(function () {
  12672. editor.selection.normalize();
  12673. return;
  12674. }, function (caretPos) {
  12675. return editor.selection.setRng(caretPos.toRange());
  12676. });
  12677. };
  12678. var focusBody = function (body) {
  12679. if (body.setActive) {
  12680. try {
  12681. body.setActive();
  12682. } catch (ex) {
  12683. body.focus();
  12684. }
  12685. } else {
  12686. body.focus();
  12687. }
  12688. };
  12689. var hasElementFocus = function (elm) {
  12690. return hasFocus$1(elm) || search(elm).isSome();
  12691. };
  12692. var hasIframeFocus = function (editor) {
  12693. return editor.iframeElement && hasFocus$1(SugarElement.fromDom(editor.iframeElement));
  12694. };
  12695. var hasInlineFocus = function (editor) {
  12696. var rawBody = editor.getBody();
  12697. return rawBody && hasElementFocus(SugarElement.fromDom(rawBody));
  12698. };
  12699. var hasUiFocus = function (editor) {
  12700. var dos = getRootNode(SugarElement.fromDom(editor.getElement()));
  12701. return active(dos).filter(function (elem) {
  12702. return !isEditorContentAreaElement(elem.dom) && isUIElement(editor, elem.dom);
  12703. }).isSome();
  12704. };
  12705. var hasFocus = function (editor) {
  12706. return editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
  12707. };
  12708. var hasEditorOrUiFocus = function (editor) {
  12709. return hasFocus(editor) || hasUiFocus(editor);
  12710. };
  12711. var focusEditor = function (editor) {
  12712. var selection = editor.selection;
  12713. var body = editor.getBody();
  12714. var rng = selection.getRng();
  12715. editor.quirks.refreshContentEditable();
  12716. if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  12717. getRng(editor).each(function (bookmarkRng) {
  12718. editor.selection.setRng(bookmarkRng);
  12719. rng = bookmarkRng;
  12720. });
  12721. }
  12722. var contentEditableHost = getContentEditableHost(editor, selection.getNode());
  12723. if (editor.$.contains(body, contentEditableHost)) {
  12724. focusBody(contentEditableHost);
  12725. normalizeSelection$1(editor, rng);
  12726. activateEditor(editor);
  12727. return;
  12728. }
  12729. if (!editor.inline) {
  12730. if (!Env.opera) {
  12731. focusBody(body);
  12732. }
  12733. editor.getWin().focus();
  12734. }
  12735. if (Env.gecko || editor.inline) {
  12736. focusBody(body);
  12737. normalizeSelection$1(editor, rng);
  12738. }
  12739. activateEditor(editor);
  12740. };
  12741. var activateEditor = function (editor) {
  12742. return editor.editorManager.setActive(editor);
  12743. };
  12744. var focus = function (editor, skipFocus) {
  12745. if (editor.removed) {
  12746. return;
  12747. }
  12748. if (skipFocus) {
  12749. activateEditor(editor);
  12750. } else {
  12751. focusEditor(editor);
  12752. }
  12753. };
  12754. var getEndpointElement = function (root, rng, start, real, resolve) {
  12755. var container = start ? rng.startContainer : rng.endContainer;
  12756. var offset = start ? rng.startOffset : rng.endOffset;
  12757. return Optional.from(container).map(SugarElement.fromDom).map(function (elm) {
  12758. return !real || !rng.collapsed ? child$1(elm, resolve(elm, offset)).getOr(elm) : elm;
  12759. }).bind(function (elm) {
  12760. return isElement$6(elm) ? Optional.some(elm) : parent(elm).filter(isElement$6);
  12761. }).map(function (elm) {
  12762. return elm.dom;
  12763. }).getOr(root);
  12764. };
  12765. var getStart = function (root, rng, real) {
  12766. return getEndpointElement(root, rng, true, real, function (elm, offset) {
  12767. return Math.min(childNodesCount(elm), offset);
  12768. });
  12769. };
  12770. var getEnd = function (root, rng, real) {
  12771. return getEndpointElement(root, rng, false, real, function (elm, offset) {
  12772. return offset > 0 ? offset - 1 : offset;
  12773. });
  12774. };
  12775. var skipEmptyTextNodes = function (node, forwards) {
  12776. var orig = node;
  12777. while (node && isText$7(node) && node.length === 0) {
  12778. node = forwards ? node.nextSibling : node.previousSibling;
  12779. }
  12780. return node || orig;
  12781. };
  12782. var getNode = function (root, rng) {
  12783. var elm, startContainer, endContainer;
  12784. if (!rng) {
  12785. return root;
  12786. }
  12787. startContainer = rng.startContainer;
  12788. endContainer = rng.endContainer;
  12789. var startOffset = rng.startOffset;
  12790. var endOffset = rng.endOffset;
  12791. elm = rng.commonAncestorContainer;
  12792. if (!rng.collapsed) {
  12793. if (startContainer === endContainer) {
  12794. if (endOffset - startOffset < 2) {
  12795. if (startContainer.hasChildNodes()) {
  12796. elm = startContainer.childNodes[startOffset];
  12797. }
  12798. }
  12799. }
  12800. if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
  12801. if (startContainer.length === startOffset) {
  12802. startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
  12803. } else {
  12804. startContainer = startContainer.parentNode;
  12805. }
  12806. if (endOffset === 0) {
  12807. endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
  12808. } else {
  12809. endContainer = endContainer.parentNode;
  12810. }
  12811. if (startContainer && startContainer === endContainer) {
  12812. return startContainer;
  12813. }
  12814. }
  12815. }
  12816. if (elm && elm.nodeType === 3) {
  12817. return elm.parentNode;
  12818. }
  12819. return elm;
  12820. };
  12821. var getSelectedBlocks = function (dom, rng, startElm, endElm) {
  12822. var node;
  12823. var selectedBlocks = [];
  12824. var root = dom.getRoot();
  12825. startElm = dom.getParent(startElm || getStart(root, rng, rng.collapsed), dom.isBlock);
  12826. endElm = dom.getParent(endElm || getEnd(root, rng, rng.collapsed), dom.isBlock);
  12827. if (startElm && startElm !== root) {
  12828. selectedBlocks.push(startElm);
  12829. }
  12830. if (startElm && endElm && startElm !== endElm) {
  12831. node = startElm;
  12832. var walker = new DomTreeWalker(startElm, root);
  12833. while ((node = walker.next()) && node !== endElm) {
  12834. if (dom.isBlock(node)) {
  12835. selectedBlocks.push(node);
  12836. }
  12837. }
  12838. }
  12839. if (endElm && startElm !== endElm && endElm !== root) {
  12840. selectedBlocks.push(endElm);
  12841. }
  12842. return selectedBlocks;
  12843. };
  12844. var select = function (dom, node, content) {
  12845. return Optional.from(node).map(function (node) {
  12846. var idx = dom.nodeIndex(node);
  12847. var rng = dom.createRng();
  12848. rng.setStart(node.parentNode, idx);
  12849. rng.setEnd(node.parentNode, idx + 1);
  12850. if (content) {
  12851. moveEndPoint(dom, rng, node, true);
  12852. moveEndPoint(dom, rng, node, false);
  12853. }
  12854. return rng;
  12855. });
  12856. };
  12857. var processRanges = function (editor, ranges) {
  12858. return map$3(ranges, function (range) {
  12859. var evt = editor.fire('GetSelectionRange', { range: range });
  12860. return evt.range !== range ? evt.range : range;
  12861. });
  12862. };
  12863. var typeLookup = {
  12864. '#text': 3,
  12865. '#comment': 8,
  12866. '#cdata': 4,
  12867. '#pi': 7,
  12868. '#doctype': 10,
  12869. '#document-fragment': 11
  12870. };
  12871. var walk$1 = function (node, root, prev) {
  12872. var startName = prev ? 'lastChild' : 'firstChild';
  12873. var siblingName = prev ? 'prev' : 'next';
  12874. if (node[startName]) {
  12875. return node[startName];
  12876. }
  12877. if (node !== root) {
  12878. var sibling = node[siblingName];
  12879. if (sibling) {
  12880. return sibling;
  12881. }
  12882. for (var parent_1 = node.parent; parent_1 && parent_1 !== root; parent_1 = parent_1.parent) {
  12883. sibling = parent_1[siblingName];
  12884. if (sibling) {
  12885. return sibling;
  12886. }
  12887. }
  12888. }
  12889. };
  12890. var isEmptyTextNode = function (node) {
  12891. if (!isWhitespaceText(node.value)) {
  12892. return false;
  12893. }
  12894. var parentNode = node.parent;
  12895. if (parentNode && (parentNode.name !== 'span' || parentNode.attr('style')) && /^[ ]+$/.test(node.value)) {
  12896. return false;
  12897. }
  12898. return true;
  12899. };
  12900. var isNonEmptyElement = function (node) {
  12901. var isNamedAnchor = node.name === 'a' && !node.attr('href') && node.attr('id');
  12902. return node.attr('name') || node.attr('id') && !node.firstChild || node.attr('data-mce-bookmark') || isNamedAnchor;
  12903. };
  12904. var AstNode = function () {
  12905. function AstNode(name, type) {
  12906. this.name = name;
  12907. this.type = type;
  12908. if (type === 1) {
  12909. this.attributes = [];
  12910. this.attributes.map = {};
  12911. }
  12912. }
  12913. AstNode.create = function (name, attrs) {
  12914. var node = new AstNode(name, typeLookup[name] || 1);
  12915. if (attrs) {
  12916. each$j(attrs, function (value, attrName) {
  12917. node.attr(attrName, value);
  12918. });
  12919. }
  12920. return node;
  12921. };
  12922. AstNode.prototype.replace = function (node) {
  12923. var self = this;
  12924. if (node.parent) {
  12925. node.remove();
  12926. }
  12927. self.insert(node, self);
  12928. self.remove();
  12929. return self;
  12930. };
  12931. AstNode.prototype.attr = function (name, value) {
  12932. var self = this;
  12933. var attrs;
  12934. if (typeof name !== 'string') {
  12935. if (name !== undefined && name !== null) {
  12936. each$j(name, function (value, key) {
  12937. self.attr(key, value);
  12938. });
  12939. }
  12940. return self;
  12941. }
  12942. if (attrs = self.attributes) {
  12943. if (value !== undefined) {
  12944. if (value === null) {
  12945. if (name in attrs.map) {
  12946. delete attrs.map[name];
  12947. var i = attrs.length;
  12948. while (i--) {
  12949. if (attrs[i].name === name) {
  12950. attrs.splice(i, 1);
  12951. return self;
  12952. }
  12953. }
  12954. }
  12955. return self;
  12956. }
  12957. if (name in attrs.map) {
  12958. var i = attrs.length;
  12959. while (i--) {
  12960. if (attrs[i].name === name) {
  12961. attrs[i].value = value;
  12962. break;
  12963. }
  12964. }
  12965. } else {
  12966. attrs.push({
  12967. name: name,
  12968. value: value
  12969. });
  12970. }
  12971. attrs.map[name] = value;
  12972. return self;
  12973. }
  12974. return attrs.map[name];
  12975. }
  12976. };
  12977. AstNode.prototype.clone = function () {
  12978. var self = this;
  12979. var clone = new AstNode(self.name, self.type);
  12980. var selfAttrs;
  12981. if (selfAttrs = self.attributes) {
  12982. var cloneAttrs = [];
  12983. cloneAttrs.map = {};
  12984. for (var i = 0, l = selfAttrs.length; i < l; i++) {
  12985. var selfAttr = selfAttrs[i];
  12986. if (selfAttr.name !== 'id') {
  12987. cloneAttrs[cloneAttrs.length] = {
  12988. name: selfAttr.name,
  12989. value: selfAttr.value
  12990. };
  12991. cloneAttrs.map[selfAttr.name] = selfAttr.value;
  12992. }
  12993. }
  12994. clone.attributes = cloneAttrs;
  12995. }
  12996. clone.value = self.value;
  12997. clone.shortEnded = self.shortEnded;
  12998. return clone;
  12999. };
  13000. AstNode.prototype.wrap = function (wrapper) {
  13001. var self = this;
  13002. self.parent.insert(wrapper, self);
  13003. wrapper.append(self);
  13004. return self;
  13005. };
  13006. AstNode.prototype.unwrap = function () {
  13007. var self = this;
  13008. for (var node = self.firstChild; node;) {
  13009. var next = node.next;
  13010. self.insert(node, self, true);
  13011. node = next;
  13012. }
  13013. self.remove();
  13014. };
  13015. AstNode.prototype.remove = function () {
  13016. var self = this, parent = self.parent, next = self.next, prev = self.prev;
  13017. if (parent) {
  13018. if (parent.firstChild === self) {
  13019. parent.firstChild = next;
  13020. if (next) {
  13021. next.prev = null;
  13022. }
  13023. } else {
  13024. prev.next = next;
  13025. }
  13026. if (parent.lastChild === self) {
  13027. parent.lastChild = prev;
  13028. if (prev) {
  13029. prev.next = null;
  13030. }
  13031. } else {
  13032. next.prev = prev;
  13033. }
  13034. self.parent = self.next = self.prev = null;
  13035. }
  13036. return self;
  13037. };
  13038. AstNode.prototype.append = function (node) {
  13039. var self = this;
  13040. if (node.parent) {
  13041. node.remove();
  13042. }
  13043. var last = self.lastChild;
  13044. if (last) {
  13045. last.next = node;
  13046. node.prev = last;
  13047. self.lastChild = node;
  13048. } else {
  13049. self.lastChild = self.firstChild = node;
  13050. }
  13051. node.parent = self;
  13052. return node;
  13053. };
  13054. AstNode.prototype.insert = function (node, refNode, before) {
  13055. if (node.parent) {
  13056. node.remove();
  13057. }
  13058. var parent = refNode.parent || this;
  13059. if (before) {
  13060. if (refNode === parent.firstChild) {
  13061. parent.firstChild = node;
  13062. } else {
  13063. refNode.prev.next = node;
  13064. }
  13065. node.prev = refNode.prev;
  13066. node.next = refNode;
  13067. refNode.prev = node;
  13068. } else {
  13069. if (refNode === parent.lastChild) {
  13070. parent.lastChild = node;
  13071. } else {
  13072. refNode.next.prev = node;
  13073. }
  13074. node.next = refNode.next;
  13075. node.prev = refNode;
  13076. refNode.next = node;
  13077. }
  13078. node.parent = parent;
  13079. return node;
  13080. };
  13081. AstNode.prototype.getAll = function (name) {
  13082. var self = this;
  13083. var collection = [];
  13084. for (var node = self.firstChild; node; node = walk$1(node, self)) {
  13085. if (node.name === name) {
  13086. collection.push(node);
  13087. }
  13088. }
  13089. return collection;
  13090. };
  13091. AstNode.prototype.children = function () {
  13092. var self = this;
  13093. var collection = [];
  13094. for (var node = self.firstChild; node; node = node.next) {
  13095. collection.push(node);
  13096. }
  13097. return collection;
  13098. };
  13099. AstNode.prototype.empty = function () {
  13100. var self = this;
  13101. if (self.firstChild) {
  13102. var nodes = [];
  13103. for (var node = self.firstChild; node; node = walk$1(node, self)) {
  13104. nodes.push(node);
  13105. }
  13106. var i = nodes.length;
  13107. while (i--) {
  13108. var node = nodes[i];
  13109. node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
  13110. }
  13111. }
  13112. self.firstChild = self.lastChild = null;
  13113. return self;
  13114. };
  13115. AstNode.prototype.isEmpty = function (elements, whitespace, predicate) {
  13116. if (whitespace === void 0) {
  13117. whitespace = {};
  13118. }
  13119. var self = this;
  13120. var node = self.firstChild;
  13121. if (isNonEmptyElement(self)) {
  13122. return false;
  13123. }
  13124. if (node) {
  13125. do {
  13126. if (node.type === 1) {
  13127. if (node.attr('data-mce-bogus')) {
  13128. continue;
  13129. }
  13130. if (elements[node.name]) {
  13131. return false;
  13132. }
  13133. if (isNonEmptyElement(node)) {
  13134. return false;
  13135. }
  13136. }
  13137. if (node.type === 8) {
  13138. return false;
  13139. }
  13140. if (node.type === 3 && !isEmptyTextNode(node)) {
  13141. return false;
  13142. }
  13143. if (node.type === 3 && node.parent && whitespace[node.parent.name] && isWhitespaceText(node.value)) {
  13144. return false;
  13145. }
  13146. if (predicate && predicate(node)) {
  13147. return false;
  13148. }
  13149. } while (node = walk$1(node, self));
  13150. }
  13151. return true;
  13152. };
  13153. AstNode.prototype.walk = function (prev) {
  13154. return walk$1(this, null, prev);
  13155. };
  13156. return AstNode;
  13157. }();
  13158. var extractBase64DataUris = function (html) {
  13159. var dataImageUri = /data:[^;]+;base64,([a-z0-9\+\/=\s]+)/gi;
  13160. var chunks = [];
  13161. var uris = {};
  13162. var prefix = generate('img');
  13163. var matches;
  13164. var index = 0;
  13165. var count = 0;
  13166. while (matches = dataImageUri.exec(html)) {
  13167. var uri = matches[0];
  13168. var imageId = prefix + '_' + count++;
  13169. uris[imageId] = uri;
  13170. if (index < matches.index) {
  13171. chunks.push(html.substr(index, matches.index - index));
  13172. }
  13173. chunks.push(imageId);
  13174. index = matches.index + uri.length;
  13175. }
  13176. var re = new RegExp(prefix + '_[0-9]+', 'g');
  13177. if (index === 0) {
  13178. return {
  13179. prefix: prefix,
  13180. uris: uris,
  13181. html: html,
  13182. re: re
  13183. };
  13184. } else {
  13185. if (index < html.length) {
  13186. chunks.push(html.substr(index));
  13187. }
  13188. return {
  13189. prefix: prefix,
  13190. uris: uris,
  13191. html: chunks.join(''),
  13192. re: re
  13193. };
  13194. }
  13195. };
  13196. var restoreDataUris = function (html, result) {
  13197. return html.replace(result.re, function (imageId) {
  13198. return get$9(result.uris, imageId).getOr(imageId);
  13199. });
  13200. };
  13201. var parseDataUri$1 = function (uri) {
  13202. var matches = /data:([^;]+);base64,([a-z0-9\+\/=\s]+)/i.exec(uri);
  13203. if (matches) {
  13204. return Optional.some({
  13205. type: matches[1],
  13206. data: decodeURIComponent(matches[2])
  13207. });
  13208. } else {
  13209. return Optional.none();
  13210. }
  13211. };
  13212. var safeSvgDataUrlElements = [
  13213. 'img',
  13214. 'video'
  13215. ];
  13216. var filteredClobberElements = Tools.makeMap('button,fieldset,form,iframe,img,image,input,object,output,select,textarea');
  13217. var isValidPrefixAttrName = function (name) {
  13218. return name.indexOf('data-') === 0 || name.indexOf('aria-') === 0;
  13219. };
  13220. var blockSvgDataUris = function (allowSvgDataUrls, tagName) {
  13221. var allowed = isNullable(allowSvgDataUrls) ? contains$3(safeSvgDataUrlElements, tagName) : allowSvgDataUrls;
  13222. return !allowed;
  13223. };
  13224. var isInvalidUri = function (settings, uri, tagName) {
  13225. if (settings.allow_html_data_urls) {
  13226. return false;
  13227. } else if (/^data:image\//i.test(uri)) {
  13228. return blockSvgDataUris(settings.allow_svg_data_urls, tagName) && /^data:image\/svg\+xml/i.test(uri);
  13229. } else {
  13230. return /^data:/i.test(uri);
  13231. }
  13232. };
  13233. var findMatchingEndTagIndex = function (schema, html, startIndex) {
  13234. var startTagRegExp = /<([!?\/])?([A-Za-z0-9\-_:.]+)/g;
  13235. var endTagRegExp = /(?:\s(?:[^'">]+(?:"[^"]*"|'[^']*'))*[^"'>]*(?:"[^">]*|'[^'>]*)?|\s*|\/)>/g;
  13236. var shortEndedElements = schema.getShortEndedElements();
  13237. var count = 1, index = startIndex;
  13238. while (count !== 0) {
  13239. startTagRegExp.lastIndex = index;
  13240. while (true) {
  13241. var startMatch = startTagRegExp.exec(html);
  13242. if (startMatch === null) {
  13243. return index;
  13244. } else if (startMatch[1] === '!') {
  13245. if (startsWith(startMatch[2], '--')) {
  13246. index = findCommentEndIndex(html, false, startMatch.index + '!--'.length);
  13247. } else {
  13248. index = findCommentEndIndex(html, true, startMatch.index + 1);
  13249. }
  13250. break;
  13251. } else {
  13252. endTagRegExp.lastIndex = startTagRegExp.lastIndex;
  13253. var endMatch = endTagRegExp.exec(html);
  13254. if (isNull(endMatch) || endMatch.index !== startTagRegExp.lastIndex) {
  13255. continue;
  13256. }
  13257. if (startMatch[1] === '/') {
  13258. count -= 1;
  13259. } else if (!has$2(shortEndedElements, startMatch[2])) {
  13260. count += 1;
  13261. }
  13262. index = startTagRegExp.lastIndex + endMatch[0].length;
  13263. break;
  13264. }
  13265. }
  13266. }
  13267. return index;
  13268. };
  13269. var isConditionalComment = function (html, startIndex) {
  13270. return /^\s*\[if [\w\W]+\]>.*<!\[endif\](--!?)?>/.test(html.substr(startIndex));
  13271. };
  13272. var findCommentEndIndex = function (html, isBogus, startIndex) {
  13273. if (startIndex === void 0) {
  13274. startIndex = 0;
  13275. }
  13276. var lcHtml = html.toLowerCase();
  13277. if (lcHtml.indexOf('[if ', startIndex) !== -1 && isConditionalComment(lcHtml, startIndex)) {
  13278. var endIfIndex = lcHtml.indexOf('[endif]', startIndex);
  13279. return lcHtml.indexOf('>', endIfIndex);
  13280. } else {
  13281. if (isBogus) {
  13282. var endIndex = lcHtml.indexOf('>', startIndex);
  13283. return endIndex !== -1 ? endIndex : lcHtml.length;
  13284. } else {
  13285. var endCommentRegexp = /--!?>/g;
  13286. endCommentRegexp.lastIndex = startIndex;
  13287. var match = endCommentRegexp.exec(html);
  13288. return match ? match.index + match[0].length : lcHtml.length;
  13289. }
  13290. }
  13291. };
  13292. var checkBogusAttribute = function (regExp, attrString) {
  13293. var matches = regExp.exec(attrString);
  13294. if (matches) {
  13295. var name_1 = matches[1];
  13296. var value = matches[2];
  13297. return typeof name_1 === 'string' && name_1.toLowerCase() === 'data-mce-bogus' ? value : null;
  13298. } else {
  13299. return null;
  13300. }
  13301. };
  13302. var SaxParser = function (settings, schema) {
  13303. var _a;
  13304. if (schema === void 0) {
  13305. schema = Schema();
  13306. }
  13307. settings = settings || {};
  13308. var doc = (_a = settings.document) !== null && _a !== void 0 ? _a : document;
  13309. var form = doc.createElement('form');
  13310. if (settings.fix_self_closing !== false) {
  13311. settings.fix_self_closing = true;
  13312. }
  13313. var comment = settings.comment ? settings.comment : noop;
  13314. var cdata = settings.cdata ? settings.cdata : noop;
  13315. var text = settings.text ? settings.text : noop;
  13316. var start = settings.start ? settings.start : noop;
  13317. var end = settings.end ? settings.end : noop;
  13318. var pi = settings.pi ? settings.pi : noop;
  13319. var doctype = settings.doctype ? settings.doctype : noop;
  13320. var parseInternal = function (base64Extract, format) {
  13321. if (format === void 0) {
  13322. format = 'html';
  13323. }
  13324. var html = base64Extract.html;
  13325. var matches, index = 0, value, endRegExp;
  13326. var stack = [];
  13327. var attrList, i, textData, name;
  13328. var isInternalElement, isShortEnded;
  13329. var elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns;
  13330. var attributesRequired, attributesDefault, attributesForced;
  13331. var anyAttributesRequired, attrValue, idCount = 0;
  13332. var decode = Entities.decode;
  13333. var filteredUrlAttrs = Tools.makeMap('src,href,data,background,action,formaction,poster,xlink:href');
  13334. var scriptUriRegExp = /((java|vb)script|mhtml):/i;
  13335. var parsingMode = format === 'html' ? 0 : 1;
  13336. var processEndTag = function (name) {
  13337. var pos, i;
  13338. pos = stack.length;
  13339. while (pos--) {
  13340. if (stack[pos].name === name) {
  13341. break;
  13342. }
  13343. }
  13344. if (pos >= 0) {
  13345. for (i = stack.length - 1; i >= pos; i--) {
  13346. name = stack[i];
  13347. if (name.valid) {
  13348. end(name.name);
  13349. }
  13350. }
  13351. stack.length = pos;
  13352. }
  13353. };
  13354. var processText = function (value, raw) {
  13355. return text(restoreDataUris(value, base64Extract), raw);
  13356. };
  13357. var processComment = function (value) {
  13358. if (value === '') {
  13359. return;
  13360. }
  13361. if (value.charAt(0) === '>') {
  13362. value = ' ' + value;
  13363. }
  13364. if (!settings.allow_conditional_comments && value.substr(0, 3).toLowerCase() === '[if') {
  13365. value = ' ' + value;
  13366. }
  13367. comment(restoreDataUris(value, base64Extract));
  13368. };
  13369. var processAttr = function (value) {
  13370. return restoreDataUris(value, base64Extract);
  13371. };
  13372. var processMalformedComment = function (value, startIndex) {
  13373. var startTag = value || '';
  13374. var isBogus = !startsWith(startTag, '--');
  13375. var endIndex = findCommentEndIndex(html, isBogus, startIndex);
  13376. value = html.substr(startIndex, endIndex - startIndex);
  13377. processComment(isBogus ? startTag + value : value);
  13378. return endIndex + 1;
  13379. };
  13380. var parseAttribute = function (tagName, name, value, val2, val3) {
  13381. var attrRule, i;
  13382. var trimRegExp = /[\s\u0000-\u001F]+/g;
  13383. name = name.toLowerCase();
  13384. value = processAttr(name in fillAttrsMap ? name : decode(value || val2 || val3 || ''));
  13385. if (validate && !isInternalElement && isValidPrefixAttrName(name) === false) {
  13386. attrRule = validAttributesMap[name];
  13387. if (!attrRule && validAttributePatterns) {
  13388. i = validAttributePatterns.length;
  13389. while (i--) {
  13390. attrRule = validAttributePatterns[i];
  13391. if (attrRule.pattern.test(name)) {
  13392. break;
  13393. }
  13394. }
  13395. if (i === -1) {
  13396. attrRule = null;
  13397. }
  13398. }
  13399. if (!attrRule) {
  13400. return;
  13401. }
  13402. if (attrRule.validValues && !(value in attrRule.validValues)) {
  13403. return;
  13404. }
  13405. }
  13406. var isNameOrId = name === 'name' || name === 'id';
  13407. if (isNameOrId && tagName in filteredClobberElements && (value in doc || value in form)) {
  13408. return;
  13409. }
  13410. if (filteredUrlAttrs[name] && !settings.allow_script_urls) {
  13411. var uri = value.replace(trimRegExp, '');
  13412. try {
  13413. uri = decodeURIComponent(uri);
  13414. } catch (ex) {
  13415. uri = unescape(uri);
  13416. }
  13417. if (scriptUriRegExp.test(uri)) {
  13418. return;
  13419. }
  13420. if (isInvalidUri(settings, uri, tagName)) {
  13421. return;
  13422. }
  13423. }
  13424. if (isInternalElement && (name in filteredUrlAttrs || name.indexOf('on') === 0)) {
  13425. return;
  13426. }
  13427. attrList.map[name] = value;
  13428. attrList.push({
  13429. name: name,
  13430. value: value
  13431. });
  13432. };
  13433. 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');
  13434. var attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g;
  13435. var shortEndedElements = schema.getShortEndedElements();
  13436. var selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
  13437. var fillAttrsMap = schema.getBoolAttrs();
  13438. var validate = settings.validate;
  13439. var removeInternalElements = settings.remove_internals;
  13440. var fixSelfClosing = settings.fix_self_closing;
  13441. var specialElements = schema.getSpecialElements();
  13442. var processHtml = html + '>';
  13443. while (matches = tokenRegExp.exec(processHtml)) {
  13444. var matchText = matches[0];
  13445. if (index < matches.index) {
  13446. processText(decode(html.substr(index, matches.index - index)));
  13447. }
  13448. if (value = matches[7]) {
  13449. value = value.toLowerCase();
  13450. if (value.charAt(0) === ':') {
  13451. value = value.substr(1);
  13452. }
  13453. processEndTag(value);
  13454. } else if (value = matches[8]) {
  13455. if (matches.index + matchText.length > html.length) {
  13456. processText(decode(html.substr(matches.index)));
  13457. index = matches.index + matchText.length;
  13458. continue;
  13459. }
  13460. value = value.toLowerCase();
  13461. if (value.charAt(0) === ':') {
  13462. value = value.substr(1);
  13463. }
  13464. isShortEnded = value in shortEndedElements;
  13465. if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value) {
  13466. processEndTag(value);
  13467. }
  13468. var bogusValue = checkBogusAttribute(attrRegExp, matches[9]);
  13469. if (bogusValue !== null) {
  13470. if (bogusValue === 'all') {
  13471. index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
  13472. tokenRegExp.lastIndex = index;
  13473. continue;
  13474. }
  13475. isValidElement = false;
  13476. }
  13477. if (!validate || (elementRule = schema.getElementRule(value))) {
  13478. isValidElement = true;
  13479. if (validate) {
  13480. validAttributesMap = elementRule.attributes;
  13481. validAttributePatterns = elementRule.attributePatterns;
  13482. }
  13483. if (attribsValue = matches[9]) {
  13484. isInternalElement = attribsValue.indexOf('data-mce-type') !== -1;
  13485. if (isInternalElement && removeInternalElements) {
  13486. isValidElement = false;
  13487. }
  13488. attrList = [];
  13489. attrList.map = {};
  13490. attribsValue.replace(attrRegExp, function (match, name, val, val2, val3) {
  13491. parseAttribute(value, name, val, val2, val3);
  13492. return '';
  13493. });
  13494. } else {
  13495. attrList = [];
  13496. attrList.map = {};
  13497. }
  13498. if (validate && !isInternalElement) {
  13499. attributesRequired = elementRule.attributesRequired;
  13500. attributesDefault = elementRule.attributesDefault;
  13501. attributesForced = elementRule.attributesForced;
  13502. anyAttributesRequired = elementRule.removeEmptyAttrs;
  13503. if (anyAttributesRequired && !attrList.length) {
  13504. isValidElement = false;
  13505. }
  13506. if (attributesForced) {
  13507. i = attributesForced.length;
  13508. while (i--) {
  13509. attr = attributesForced[i];
  13510. name = attr.name;
  13511. attrValue = attr.value;
  13512. if (attrValue === '{$uid}') {
  13513. attrValue = 'mce_' + idCount++;
  13514. }
  13515. attrList.map[name] = attrValue;
  13516. attrList.push({
  13517. name: name,
  13518. value: attrValue
  13519. });
  13520. }
  13521. }
  13522. if (attributesDefault) {
  13523. i = attributesDefault.length;
  13524. while (i--) {
  13525. attr = attributesDefault[i];
  13526. name = attr.name;
  13527. if (!(name in attrList.map)) {
  13528. attrValue = attr.value;
  13529. if (attrValue === '{$uid}') {
  13530. attrValue = 'mce_' + idCount++;
  13531. }
  13532. attrList.map[name] = attrValue;
  13533. attrList.push({
  13534. name: name,
  13535. value: attrValue
  13536. });
  13537. }
  13538. }
  13539. }
  13540. if (attributesRequired) {
  13541. i = attributesRequired.length;
  13542. while (i--) {
  13543. if (attributesRequired[i] in attrList.map) {
  13544. break;
  13545. }
  13546. }
  13547. if (i === -1) {
  13548. isValidElement = false;
  13549. }
  13550. }
  13551. if (attr = attrList.map['data-mce-bogus']) {
  13552. if (attr === 'all') {
  13553. index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
  13554. tokenRegExp.lastIndex = index;
  13555. continue;
  13556. }
  13557. isValidElement = false;
  13558. }
  13559. }
  13560. if (isValidElement) {
  13561. start(value, attrList, isShortEnded);
  13562. }
  13563. } else {
  13564. isValidElement = false;
  13565. }
  13566. if (endRegExp = specialElements[value]) {
  13567. endRegExp.lastIndex = index = matches.index + matchText.length;
  13568. if (matches = endRegExp.exec(html)) {
  13569. if (isValidElement) {
  13570. textData = html.substr(index, matches.index - index);
  13571. }
  13572. index = matches.index + matches[0].length;
  13573. } else {
  13574. textData = html.substr(index);
  13575. index = html.length;
  13576. }
  13577. if (isValidElement) {
  13578. if (textData.length > 0) {
  13579. processText(textData, true);
  13580. }
  13581. end(value);
  13582. }
  13583. tokenRegExp.lastIndex = index;
  13584. continue;
  13585. }
  13586. if (!isShortEnded) {
  13587. if (!attribsValue || attribsValue.indexOf('/') !== attribsValue.length - 1) {
  13588. stack.push({
  13589. name: value,
  13590. valid: isValidElement
  13591. });
  13592. } else if (isValidElement) {
  13593. end(value);
  13594. }
  13595. }
  13596. } else if (value = matches[1]) {
  13597. processComment(value);
  13598. } else if (value = matches[2]) {
  13599. var isValidCdataSection = parsingMode === 1 || settings.preserve_cdata || stack.length > 0 && schema.isValidChild(stack[stack.length - 1].name, '#cdata');
  13600. if (isValidCdataSection) {
  13601. cdata(value);
  13602. } else {
  13603. index = processMalformedComment('', matches.index + 2);
  13604. tokenRegExp.lastIndex = index;
  13605. continue;
  13606. }
  13607. } else if (value = matches[3]) {
  13608. doctype(value);
  13609. } else if ((value = matches[4]) || matchText === '<!') {
  13610. index = processMalformedComment(value, matches.index + matchText.length);
  13611. tokenRegExp.lastIndex = index;
  13612. continue;
  13613. } else if (value = matches[5]) {
  13614. if (parsingMode === 1) {
  13615. pi(value, matches[6]);
  13616. } else {
  13617. index = processMalformedComment('?', matches.index + 2);
  13618. tokenRegExp.lastIndex = index;
  13619. continue;
  13620. }
  13621. }
  13622. index = matches.index + matchText.length;
  13623. }
  13624. if (index < html.length) {
  13625. processText(decode(html.substr(index)));
  13626. }
  13627. for (i = stack.length - 1; i >= 0; i--) {
  13628. value = stack[i];
  13629. if (value.valid) {
  13630. end(value.name);
  13631. }
  13632. }
  13633. };
  13634. var parse = function (html, format) {
  13635. if (format === void 0) {
  13636. format = 'html';
  13637. }
  13638. parseInternal(extractBase64DataUris(html), format);
  13639. };
  13640. return { parse: parse };
  13641. };
  13642. SaxParser.findEndTag = findMatchingEndTagIndex;
  13643. var trimHtml = function (tempAttrs, html) {
  13644. var trimContentRegExp = new RegExp(['\\s?(' + tempAttrs.join('|') + ')="[^"]+"'].join('|'), 'gi');
  13645. return html.replace(trimContentRegExp, '');
  13646. };
  13647. var trimInternal = function (serializer, html) {
  13648. var bogusAllRegExp = /<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g;
  13649. var schema = serializer.schema;
  13650. var content = trimHtml(serializer.getTempAttrs(), html);
  13651. var shortEndedElements = schema.getShortEndedElements();
  13652. var matches;
  13653. while (matches = bogusAllRegExp.exec(content)) {
  13654. var index = bogusAllRegExp.lastIndex;
  13655. var matchLength = matches[0].length;
  13656. var endTagIndex = void 0;
  13657. if (shortEndedElements[matches[1]]) {
  13658. endTagIndex = index;
  13659. } else {
  13660. endTagIndex = SaxParser.findEndTag(schema, content, index);
  13661. }
  13662. content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
  13663. bogusAllRegExp.lastIndex = index - matchLength;
  13664. }
  13665. return trim$2(content);
  13666. };
  13667. var trimExternal = trimInternal;
  13668. var trimEmptyContents = function (editor, html) {
  13669. var blockName = getForcedRootBlock(editor);
  13670. var emptyRegExp = new RegExp('^(<' + blockName + '[^>]*>(&nbsp;|&#160;|\\s|\xA0|<br \\/>|)<\\/' + blockName + '>[\r\n]*|<br \\/>[\r\n]*)$');
  13671. return html.replace(emptyRegExp, '');
  13672. };
  13673. var getContentFromBody = function (editor, args, format, body) {
  13674. var updatedArgs = args.no_events ? args : editor.fire('BeforeGetContent', __assign(__assign({}, args), {
  13675. format: format,
  13676. get: true,
  13677. getInner: true
  13678. }));
  13679. var content;
  13680. if (updatedArgs.format === 'raw') {
  13681. content = Tools.trim(trimExternal(editor.serializer, body.innerHTML));
  13682. } else if (updatedArgs.format === 'text') {
  13683. content = editor.dom.isEmpty(body) ? '' : trim$2(body.innerText || body.textContent);
  13684. } else if (updatedArgs.format === 'tree') {
  13685. content = editor.serializer.serialize(body, updatedArgs);
  13686. } else {
  13687. content = trimEmptyContents(editor, editor.serializer.serialize(body, updatedArgs));
  13688. }
  13689. if (!contains$3([
  13690. 'text',
  13691. 'tree'
  13692. ], updatedArgs.format) && !isWsPreserveElement(SugarElement.fromDom(body))) {
  13693. updatedArgs.content = Tools.trim(content);
  13694. } else {
  13695. updatedArgs.content = content;
  13696. }
  13697. if (updatedArgs.no_events) {
  13698. return updatedArgs.content;
  13699. } else {
  13700. return editor.fire('GetContent', updatedArgs).content;
  13701. }
  13702. };
  13703. var getContentInternal = function (editor, args, format) {
  13704. return Optional.from(editor.getBody()).fold(constant(args.format === 'tree' ? new AstNode('body', 11) : ''), function (body) {
  13705. return getContentFromBody(editor, args, format, body);
  13706. });
  13707. };
  13708. var each$d = Tools.each;
  13709. var ElementUtils = function (dom) {
  13710. var compare = function (node1, node2) {
  13711. if (node1.nodeName !== node2.nodeName) {
  13712. return false;
  13713. }
  13714. var getAttribs = function (node) {
  13715. var attribs = {};
  13716. each$d(dom.getAttribs(node), function (attr) {
  13717. var name = attr.nodeName.toLowerCase();
  13718. if (name.indexOf('_') !== 0 && name !== 'style' && name.indexOf('data-') !== 0) {
  13719. attribs[name] = dom.getAttrib(node, name);
  13720. }
  13721. });
  13722. return attribs;
  13723. };
  13724. var compareObjects = function (obj1, obj2) {
  13725. var value, name;
  13726. for (name in obj1) {
  13727. if (has$2(obj1, name)) {
  13728. value = obj2[name];
  13729. if (typeof value === 'undefined') {
  13730. return false;
  13731. }
  13732. if (obj1[name] !== value) {
  13733. return false;
  13734. }
  13735. delete obj2[name];
  13736. }
  13737. }
  13738. for (name in obj2) {
  13739. if (has$2(obj2, name)) {
  13740. return false;
  13741. }
  13742. }
  13743. return true;
  13744. };
  13745. if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
  13746. return false;
  13747. }
  13748. if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
  13749. return false;
  13750. }
  13751. return !isBookmarkNode$1(node1) && !isBookmarkNode$1(node2);
  13752. };
  13753. return { compare: compare };
  13754. };
  13755. var makeMap$1 = Tools.makeMap;
  13756. var Writer = function (settings) {
  13757. var html = [];
  13758. settings = settings || {};
  13759. var indent = settings.indent;
  13760. var indentBefore = makeMap$1(settings.indent_before || '');
  13761. var indentAfter = makeMap$1(settings.indent_after || '');
  13762. var encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
  13763. var htmlOutput = settings.element_format === 'html';
  13764. return {
  13765. start: function (name, attrs, empty) {
  13766. var i, l, attr, value;
  13767. if (indent && indentBefore[name] && html.length > 0) {
  13768. value = html[html.length - 1];
  13769. if (value.length > 0 && value !== '\n') {
  13770. html.push('\n');
  13771. }
  13772. }
  13773. html.push('<', name);
  13774. if (attrs) {
  13775. for (i = 0, l = attrs.length; i < l; i++) {
  13776. attr = attrs[i];
  13777. html.push(' ', attr.name, '="', encode(attr.value, true), '"');
  13778. }
  13779. }
  13780. if (!empty || htmlOutput) {
  13781. html[html.length] = '>';
  13782. } else {
  13783. html[html.length] = ' />';
  13784. }
  13785. if (empty && indent && indentAfter[name] && html.length > 0) {
  13786. value = html[html.length - 1];
  13787. if (value.length > 0 && value !== '\n') {
  13788. html.push('\n');
  13789. }
  13790. }
  13791. },
  13792. end: function (name) {
  13793. var value;
  13794. html.push('</', name, '>');
  13795. if (indent && indentAfter[name] && html.length > 0) {
  13796. value = html[html.length - 1];
  13797. if (value.length > 0 && value !== '\n') {
  13798. html.push('\n');
  13799. }
  13800. }
  13801. },
  13802. text: function (text, raw) {
  13803. if (text.length > 0) {
  13804. html[html.length] = raw ? text : encode(text);
  13805. }
  13806. },
  13807. cdata: function (text) {
  13808. html.push('<![CDATA[', text, ']]>');
  13809. },
  13810. comment: function (text) {
  13811. html.push('<!--', text, '-->');
  13812. },
  13813. pi: function (name, text) {
  13814. if (text) {
  13815. html.push('<?', name, ' ', encode(text), '?>');
  13816. } else {
  13817. html.push('<?', name, '?>');
  13818. }
  13819. if (indent) {
  13820. html.push('\n');
  13821. }
  13822. },
  13823. doctype: function (text) {
  13824. html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
  13825. },
  13826. reset: function () {
  13827. html.length = 0;
  13828. },
  13829. getContent: function () {
  13830. return html.join('').replace(/\n$/, '');
  13831. }
  13832. };
  13833. };
  13834. var HtmlSerializer = function (settings, schema) {
  13835. if (schema === void 0) {
  13836. schema = Schema();
  13837. }
  13838. var writer = Writer(settings);
  13839. settings = settings || {};
  13840. settings.validate = 'validate' in settings ? settings.validate : true;
  13841. var serialize = function (node) {
  13842. var validate = settings.validate;
  13843. var handlers = {
  13844. 3: function (node) {
  13845. writer.text(node.value, node.raw);
  13846. },
  13847. 8: function (node) {
  13848. writer.comment(node.value);
  13849. },
  13850. 7: function (node) {
  13851. writer.pi(node.name, node.value);
  13852. },
  13853. 10: function (node) {
  13854. writer.doctype(node.value);
  13855. },
  13856. 4: function (node) {
  13857. writer.cdata(node.value);
  13858. },
  13859. 11: function (node) {
  13860. if (node = node.firstChild) {
  13861. do {
  13862. walk(node);
  13863. } while (node = node.next);
  13864. }
  13865. }
  13866. };
  13867. writer.reset();
  13868. var walk = function (node) {
  13869. var handler = handlers[node.type];
  13870. if (!handler) {
  13871. var name_1 = node.name;
  13872. var isEmpty = node.shortEnded;
  13873. var attrs = node.attributes;
  13874. if (validate && attrs && attrs.length > 1) {
  13875. var sortedAttrs = [];
  13876. sortedAttrs.map = {};
  13877. var elementRule = schema.getElementRule(node.name);
  13878. if (elementRule) {
  13879. for (var i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
  13880. var attrName = elementRule.attributesOrder[i];
  13881. if (attrName in attrs.map) {
  13882. var attrValue = attrs.map[attrName];
  13883. sortedAttrs.map[attrName] = attrValue;
  13884. sortedAttrs.push({
  13885. name: attrName,
  13886. value: attrValue
  13887. });
  13888. }
  13889. }
  13890. for (var i = 0, l = attrs.length; i < l; i++) {
  13891. var attrName = attrs[i].name;
  13892. if (!(attrName in sortedAttrs.map)) {
  13893. var attrValue = attrs.map[attrName];
  13894. sortedAttrs.map[attrName] = attrValue;
  13895. sortedAttrs.push({
  13896. name: attrName,
  13897. value: attrValue
  13898. });
  13899. }
  13900. }
  13901. attrs = sortedAttrs;
  13902. }
  13903. }
  13904. writer.start(node.name, attrs, isEmpty);
  13905. if (!isEmpty) {
  13906. if (node = node.firstChild) {
  13907. do {
  13908. walk(node);
  13909. } while (node = node.next);
  13910. }
  13911. writer.end(name_1);
  13912. }
  13913. } else {
  13914. handler(node);
  13915. }
  13916. };
  13917. if (node.type === 1 && !settings.inner) {
  13918. walk(node);
  13919. } else {
  13920. handlers[11](node);
  13921. }
  13922. return writer.getContent();
  13923. };
  13924. return { serialize: serialize };
  13925. };
  13926. var nonInheritableStyles = new Set();
  13927. (function () {
  13928. var nonInheritableStylesArr = [
  13929. 'margin',
  13930. 'margin-left',
  13931. 'margin-right',
  13932. 'margin-top',
  13933. 'margin-bottom',
  13934. 'padding',
  13935. 'padding-left',
  13936. 'padding-right',
  13937. 'padding-top',
  13938. 'padding-bottom',
  13939. 'border',
  13940. 'border-width',
  13941. 'border-style',
  13942. 'border-color',
  13943. 'background',
  13944. 'background-attachment',
  13945. 'background-clip',
  13946. 'background-color',
  13947. 'background-image',
  13948. 'background-origin',
  13949. 'background-position',
  13950. 'background-repeat',
  13951. 'background-size',
  13952. 'float',
  13953. 'position',
  13954. 'left',
  13955. 'right',
  13956. 'top',
  13957. 'bottom',
  13958. 'z-index',
  13959. 'display',
  13960. 'transform',
  13961. 'width',
  13962. 'max-width',
  13963. 'min-width',
  13964. 'height',
  13965. 'max-height',
  13966. 'min-height',
  13967. 'overflow',
  13968. 'overflow-x',
  13969. 'overflow-y',
  13970. 'text-overflow',
  13971. 'vertical-align',
  13972. 'transition',
  13973. 'transition-delay',
  13974. 'transition-duration',
  13975. 'transition-property',
  13976. 'transition-timing-function'
  13977. ];
  13978. each$k(nonInheritableStylesArr, function (style) {
  13979. nonInheritableStyles.add(style);
  13980. });
  13981. }());
  13982. var shorthandStyleProps = [
  13983. 'font',
  13984. 'text-decoration',
  13985. 'text-emphasis'
  13986. ];
  13987. var getStyleProps = function (dom, node) {
  13988. return keys(dom.parseStyle(dom.getAttrib(node, 'style')));
  13989. };
  13990. var isNonInheritableStyle = function (style) {
  13991. return nonInheritableStyles.has(style);
  13992. };
  13993. var hasInheritableStyles = function (dom, node) {
  13994. return forall(getStyleProps(dom, node), function (style) {
  13995. return !isNonInheritableStyle(style);
  13996. });
  13997. };
  13998. var getLonghandStyleProps = function (styles) {
  13999. return filter$4(styles, function (style) {
  14000. return exists(shorthandStyleProps, function (prop) {
  14001. return startsWith(style, prop);
  14002. });
  14003. });
  14004. };
  14005. var hasStyleConflict = function (dom, node, parentNode) {
  14006. var nodeStyleProps = getStyleProps(dom, node);
  14007. var parentNodeStyleProps = getStyleProps(dom, parentNode);
  14008. var valueMismatch = function (prop) {
  14009. var nodeValue = dom.getStyle(node, prop);
  14010. var parentValue = dom.getStyle(parentNode, prop);
  14011. return isNotEmpty(nodeValue) && isNotEmpty(parentValue) && nodeValue !== parentValue;
  14012. };
  14013. return exists(nodeStyleProps, function (nodeStyleProp) {
  14014. var propExists = function (props) {
  14015. return exists(props, function (prop) {
  14016. return prop === nodeStyleProp;
  14017. });
  14018. };
  14019. if (!propExists(parentNodeStyleProps) && propExists(shorthandStyleProps)) {
  14020. var longhandProps = getLonghandStyleProps(parentNodeStyleProps);
  14021. return exists(longhandProps, valueMismatch);
  14022. } else {
  14023. return valueMismatch(nodeStyleProp);
  14024. }
  14025. });
  14026. };
  14027. var isChar = function (forward, predicate, pos) {
  14028. return Optional.from(pos.container()).filter(isText$7).exists(function (text) {
  14029. var delta = forward ? 0 : -1;
  14030. return predicate(text.data.charAt(pos.offset() + delta));
  14031. });
  14032. };
  14033. var isBeforeSpace = curry(isChar, true, isWhiteSpace);
  14034. var isAfterSpace = curry(isChar, false, isWhiteSpace);
  14035. var isEmptyText = function (pos) {
  14036. var container = pos.container();
  14037. return isText$7(container) && (container.data.length === 0 || isZwsp(container.data) && BookmarkManager.isBookmarkNode(container.parentNode));
  14038. };
  14039. var matchesElementPosition = function (before, predicate) {
  14040. return function (pos) {
  14041. return Optional.from(getChildNodeAtRelativeOffset(before ? 0 : -1, pos)).filter(predicate).isSome();
  14042. };
  14043. };
  14044. var isImageBlock = function (node) {
  14045. return isImg(node) && get$5(SugarElement.fromDom(node), 'display') === 'block';
  14046. };
  14047. var isCefNode = function (node) {
  14048. return isContentEditableFalse$b(node) && !isBogusAll$1(node);
  14049. };
  14050. var isBeforeImageBlock = matchesElementPosition(true, isImageBlock);
  14051. var isAfterImageBlock = matchesElementPosition(false, isImageBlock);
  14052. var isBeforeMedia = matchesElementPosition(true, isMedia$2);
  14053. var isAfterMedia = matchesElementPosition(false, isMedia$2);
  14054. var isBeforeTable = matchesElementPosition(true, isTable$3);
  14055. var isAfterTable = matchesElementPosition(false, isTable$3);
  14056. var isBeforeContentEditableFalse = matchesElementPosition(true, isCefNode);
  14057. var isAfterContentEditableFalse = matchesElementPosition(false, isCefNode);
  14058. var getLastChildren = function (elm) {
  14059. var children = [];
  14060. var rawNode = elm.dom;
  14061. while (rawNode) {
  14062. children.push(SugarElement.fromDom(rawNode));
  14063. rawNode = rawNode.lastChild;
  14064. }
  14065. return children;
  14066. };
  14067. var removeTrailingBr = function (elm) {
  14068. var allBrs = descendants(elm, 'br');
  14069. var brs = filter$4(getLastChildren(elm).slice(-1), isBr$4);
  14070. if (allBrs.length === brs.length) {
  14071. each$k(brs, remove$7);
  14072. }
  14073. };
  14074. var fillWithPaddingBr = function (elm) {
  14075. empty(elm);
  14076. append$1(elm, SugarElement.fromHtml('<br data-mce-bogus="1">'));
  14077. };
  14078. var trimBlockTrailingBr = function (elm) {
  14079. lastChild(elm).each(function (lastChild) {
  14080. prevSibling(lastChild).each(function (lastChildPrevSibling) {
  14081. if (isBlock$2(elm) && isBr$4(lastChild) && isBlock$2(lastChildPrevSibling)) {
  14082. remove$7(lastChild);
  14083. }
  14084. });
  14085. });
  14086. };
  14087. var dropLast = function (xs) {
  14088. return xs.slice(0, -1);
  14089. };
  14090. var parentsUntil = function (start, root, predicate) {
  14091. if (contains$1(root, start)) {
  14092. return dropLast(parents$1(start, function (elm) {
  14093. return predicate(elm) || eq(elm, root);
  14094. }));
  14095. } else {
  14096. return [];
  14097. }
  14098. };
  14099. var parents = function (start, root) {
  14100. return parentsUntil(start, root, never);
  14101. };
  14102. var parentsAndSelf = function (start, root) {
  14103. return [start].concat(parents(start, root));
  14104. };
  14105. var navigateIgnoreEmptyTextNodes = function (forward, root, from) {
  14106. return navigateIgnore(forward, root, from, isEmptyText);
  14107. };
  14108. var getClosestBlock$1 = function (root, pos) {
  14109. return find$3(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  14110. };
  14111. var isAtBeforeAfterBlockBoundary = function (forward, root, pos) {
  14112. return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  14113. return getClosestBlock$1(root, pos).fold(function () {
  14114. return isInSameBlock(newPos, pos, root.dom) === false;
  14115. }, function (fromBlock) {
  14116. return isInSameBlock(newPos, pos, root.dom) === false && contains$1(fromBlock, SugarElement.fromDom(newPos.container()));
  14117. });
  14118. });
  14119. };
  14120. var isAtBlockBoundary = function (forward, root, pos) {
  14121. return getClosestBlock$1(root, pos).fold(function () {
  14122. return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  14123. return isInSameBlock(newPos, pos, root.dom) === false;
  14124. });
  14125. }, function (parent) {
  14126. return navigateIgnoreEmptyTextNodes(forward, parent.dom, pos).isNone();
  14127. });
  14128. };
  14129. var isAtStartOfBlock = curry(isAtBlockBoundary, false);
  14130. var isAtEndOfBlock = curry(isAtBlockBoundary, true);
  14131. var isBeforeBlock = curry(isAtBeforeAfterBlockBoundary, false);
  14132. var isAfterBlock = curry(isAtBeforeAfterBlockBoundary, true);
  14133. var isBr = function (pos) {
  14134. return getElementFromPosition(pos).exists(isBr$4);
  14135. };
  14136. var findBr = function (forward, root, pos) {
  14137. var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  14138. var scope = head(parentBlocks).getOr(root);
  14139. return fromPosition(forward, scope.dom, pos).filter(isBr);
  14140. };
  14141. var isBeforeBr$1 = function (root, pos) {
  14142. return getElementFromPosition(pos).exists(isBr$4) || findBr(true, root, pos).isSome();
  14143. };
  14144. var isAfterBr = function (root, pos) {
  14145. return getElementFromPrevPosition(pos).exists(isBr$4) || findBr(false, root, pos).isSome();
  14146. };
  14147. var findPreviousBr = curry(findBr, false);
  14148. var findNextBr = curry(findBr, true);
  14149. var isInMiddleOfText = function (pos) {
  14150. return CaretPosition.isTextPosition(pos) && !pos.isAtStart() && !pos.isAtEnd();
  14151. };
  14152. var getClosestBlock = function (root, pos) {
  14153. var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  14154. return head(parentBlocks).getOr(root);
  14155. };
  14156. var hasSpaceBefore = function (root, pos) {
  14157. if (isInMiddleOfText(pos)) {
  14158. return isAfterSpace(pos);
  14159. } else {
  14160. return isAfterSpace(pos) || prevPosition(getClosestBlock(root, pos).dom, pos).exists(isAfterSpace);
  14161. }
  14162. };
  14163. var hasSpaceAfter = function (root, pos) {
  14164. if (isInMiddleOfText(pos)) {
  14165. return isBeforeSpace(pos);
  14166. } else {
  14167. return isBeforeSpace(pos) || nextPosition(getClosestBlock(root, pos).dom, pos).exists(isBeforeSpace);
  14168. }
  14169. };
  14170. var isPreValue = function (value) {
  14171. return contains$3([
  14172. 'pre',
  14173. 'pre-wrap'
  14174. ], value);
  14175. };
  14176. var isInPre = function (pos) {
  14177. return getElementFromPosition(pos).bind(function (elm) {
  14178. return closest$3(elm, isElement$6);
  14179. }).exists(function (elm) {
  14180. return isPreValue(get$5(elm, 'white-space'));
  14181. });
  14182. };
  14183. var isAtBeginningOfBody = function (root, pos) {
  14184. return prevPosition(root.dom, pos).isNone();
  14185. };
  14186. var isAtEndOfBody = function (root, pos) {
  14187. return nextPosition(root.dom, pos).isNone();
  14188. };
  14189. var isAtLineBoundary = function (root, pos) {
  14190. return isAtBeginningOfBody(root, pos) || isAtEndOfBody(root, pos) || isAtStartOfBlock(root, pos) || isAtEndOfBlock(root, pos) || isAfterBr(root, pos) || isBeforeBr$1(root, pos);
  14191. };
  14192. var needsToHaveNbsp = function (root, pos) {
  14193. if (isInPre(pos)) {
  14194. return false;
  14195. } else {
  14196. return isAtLineBoundary(root, pos) || hasSpaceBefore(root, pos) || hasSpaceAfter(root, pos);
  14197. }
  14198. };
  14199. var needsToBeNbspLeft = function (root, pos) {
  14200. if (isInPre(pos)) {
  14201. return false;
  14202. } else {
  14203. return isAtStartOfBlock(root, pos) || isBeforeBlock(root, pos) || isAfterBr(root, pos) || hasSpaceBefore(root, pos);
  14204. }
  14205. };
  14206. var leanRight = function (pos) {
  14207. var container = pos.container();
  14208. var offset = pos.offset();
  14209. if (isText$7(container) && offset < container.data.length) {
  14210. return CaretPosition(container, offset + 1);
  14211. } else {
  14212. return pos;
  14213. }
  14214. };
  14215. var needsToBeNbspRight = function (root, pos) {
  14216. if (isInPre(pos)) {
  14217. return false;
  14218. } else {
  14219. return isAtEndOfBlock(root, pos) || isAfterBlock(root, pos) || isBeforeBr$1(root, pos) || hasSpaceAfter(root, pos);
  14220. }
  14221. };
  14222. var needsToBeNbsp = function (root, pos) {
  14223. return needsToBeNbspLeft(root, pos) || needsToBeNbspRight(root, leanRight(pos));
  14224. };
  14225. var isNbspAt = function (text, offset) {
  14226. return isNbsp(text.charAt(offset));
  14227. };
  14228. var hasNbsp = function (pos) {
  14229. var container = pos.container();
  14230. return isText$7(container) && contains$2(container.data, nbsp);
  14231. };
  14232. var normalizeNbspMiddle = function (text) {
  14233. var chars = text.split('');
  14234. return map$3(chars, function (chr, i) {
  14235. if (isNbsp(chr) && i > 0 && i < chars.length - 1 && isContent(chars[i - 1]) && isContent(chars[i + 1])) {
  14236. return ' ';
  14237. } else {
  14238. return chr;
  14239. }
  14240. }).join('');
  14241. };
  14242. var normalizeNbspAtStart = function (root, node) {
  14243. var text = node.data;
  14244. var firstPos = CaretPosition(node, 0);
  14245. if (isNbspAt(text, 0) && !needsToBeNbsp(root, firstPos)) {
  14246. node.data = ' ' + text.slice(1);
  14247. return true;
  14248. } else {
  14249. return false;
  14250. }
  14251. };
  14252. var normalizeNbspInMiddleOfTextNode = function (node) {
  14253. var text = node.data;
  14254. var newText = normalizeNbspMiddle(text);
  14255. if (newText !== text) {
  14256. node.data = newText;
  14257. return true;
  14258. } else {
  14259. return false;
  14260. }
  14261. };
  14262. var normalizeNbspAtEnd = function (root, node) {
  14263. var text = node.data;
  14264. var lastPos = CaretPosition(node, text.length - 1);
  14265. if (isNbspAt(text, text.length - 1) && !needsToBeNbsp(root, lastPos)) {
  14266. node.data = text.slice(0, -1) + ' ';
  14267. return true;
  14268. } else {
  14269. return false;
  14270. }
  14271. };
  14272. var normalizeNbsps = function (root, pos) {
  14273. return Optional.some(pos).filter(hasNbsp).bind(function (pos) {
  14274. var container = pos.container();
  14275. var normalized = normalizeNbspAtStart(root, container) || normalizeNbspInMiddleOfTextNode(container) || normalizeNbspAtEnd(root, container);
  14276. return normalized ? Optional.some(pos) : Optional.none();
  14277. });
  14278. };
  14279. var normalizeNbspsInEditor = function (editor) {
  14280. var root = SugarElement.fromDom(editor.getBody());
  14281. if (editor.selection.isCollapsed()) {
  14282. normalizeNbsps(root, CaretPosition.fromRangeStart(editor.selection.getRng())).each(function (pos) {
  14283. editor.selection.setRng(pos.toRange());
  14284. });
  14285. }
  14286. };
  14287. var normalizeContent = function (content, isStartOfContent, isEndOfContent) {
  14288. var result = foldl(content, function (acc, c) {
  14289. if (isWhiteSpace(c) || isNbsp(c)) {
  14290. if (acc.previousCharIsSpace || acc.str === '' && isStartOfContent || acc.str.length === content.length - 1 && isEndOfContent) {
  14291. return {
  14292. previousCharIsSpace: false,
  14293. str: acc.str + nbsp
  14294. };
  14295. } else {
  14296. return {
  14297. previousCharIsSpace: true,
  14298. str: acc.str + ' '
  14299. };
  14300. }
  14301. } else {
  14302. return {
  14303. previousCharIsSpace: false,
  14304. str: acc.str + c
  14305. };
  14306. }
  14307. }, {
  14308. previousCharIsSpace: false,
  14309. str: ''
  14310. });
  14311. return result.str;
  14312. };
  14313. var normalize$1 = function (node, offset, count) {
  14314. if (count === 0) {
  14315. return;
  14316. }
  14317. var elm = SugarElement.fromDom(node);
  14318. var root = ancestor$3(elm, isBlock$2).getOr(elm);
  14319. var whitespace = node.data.slice(offset, offset + count);
  14320. var isEndOfContent = offset + count >= node.data.length && needsToBeNbspRight(root, CaretPosition(node, node.data.length));
  14321. var isStartOfContent = offset === 0 && needsToBeNbspLeft(root, CaretPosition(node, 0));
  14322. node.replaceData(offset, count, normalizeContent(whitespace, isStartOfContent, isEndOfContent));
  14323. };
  14324. var normalizeWhitespaceAfter = function (node, offset) {
  14325. var content = node.data.slice(offset);
  14326. var whitespaceCount = content.length - lTrim(content).length;
  14327. normalize$1(node, offset, whitespaceCount);
  14328. };
  14329. var normalizeWhitespaceBefore = function (node, offset) {
  14330. var content = node.data.slice(0, offset);
  14331. var whitespaceCount = content.length - rTrim(content).length;
  14332. normalize$1(node, offset - whitespaceCount, whitespaceCount);
  14333. };
  14334. var mergeTextNodes = function (prevNode, nextNode, normalizeWhitespace, mergeToPrev) {
  14335. if (mergeToPrev === void 0) {
  14336. mergeToPrev = true;
  14337. }
  14338. var whitespaceOffset = rTrim(prevNode.data).length;
  14339. var newNode = mergeToPrev ? prevNode : nextNode;
  14340. var removeNode = mergeToPrev ? nextNode : prevNode;
  14341. if (mergeToPrev) {
  14342. newNode.appendData(removeNode.data);
  14343. } else {
  14344. newNode.insertData(0, removeNode.data);
  14345. }
  14346. remove$7(SugarElement.fromDom(removeNode));
  14347. if (normalizeWhitespace) {
  14348. normalizeWhitespaceAfter(newNode, whitespaceOffset);
  14349. }
  14350. return newNode;
  14351. };
  14352. var needsReposition = function (pos, elm) {
  14353. var container = pos.container();
  14354. var offset = pos.offset();
  14355. return CaretPosition.isTextPosition(pos) === false && container === elm.parentNode && offset > CaretPosition.before(elm).offset();
  14356. };
  14357. var reposition = function (elm, pos) {
  14358. return needsReposition(pos, elm) ? CaretPosition(pos.container(), pos.offset() - 1) : pos;
  14359. };
  14360. var beforeOrStartOf = function (node) {
  14361. return isText$7(node) ? CaretPosition(node, 0) : CaretPosition.before(node);
  14362. };
  14363. var afterOrEndOf = function (node) {
  14364. return isText$7(node) ? CaretPosition(node, node.data.length) : CaretPosition.after(node);
  14365. };
  14366. var getPreviousSiblingCaretPosition = function (elm) {
  14367. if (isCaretCandidate$3(elm.previousSibling)) {
  14368. return Optional.some(afterOrEndOf(elm.previousSibling));
  14369. } else {
  14370. return elm.previousSibling ? lastPositionIn(elm.previousSibling) : Optional.none();
  14371. }
  14372. };
  14373. var getNextSiblingCaretPosition = function (elm) {
  14374. if (isCaretCandidate$3(elm.nextSibling)) {
  14375. return Optional.some(beforeOrStartOf(elm.nextSibling));
  14376. } else {
  14377. return elm.nextSibling ? firstPositionIn(elm.nextSibling) : Optional.none();
  14378. }
  14379. };
  14380. var findCaretPositionBackwardsFromElm = function (rootElement, elm) {
  14381. var startPosition = CaretPosition.before(elm.previousSibling ? elm.previousSibling : elm.parentNode);
  14382. return prevPosition(rootElement, startPosition).fold(function () {
  14383. return nextPosition(rootElement, CaretPosition.after(elm));
  14384. }, Optional.some);
  14385. };
  14386. var findCaretPositionForwardsFromElm = function (rootElement, elm) {
  14387. return nextPosition(rootElement, CaretPosition.after(elm)).fold(function () {
  14388. return prevPosition(rootElement, CaretPosition.before(elm));
  14389. }, Optional.some);
  14390. };
  14391. var findCaretPositionBackwards = function (rootElement, elm) {
  14392. return getPreviousSiblingCaretPosition(elm).orThunk(function () {
  14393. return getNextSiblingCaretPosition(elm);
  14394. }).orThunk(function () {
  14395. return findCaretPositionBackwardsFromElm(rootElement, elm);
  14396. });
  14397. };
  14398. var findCaretPositionForward = function (rootElement, elm) {
  14399. return getNextSiblingCaretPosition(elm).orThunk(function () {
  14400. return getPreviousSiblingCaretPosition(elm);
  14401. }).orThunk(function () {
  14402. return findCaretPositionForwardsFromElm(rootElement, elm);
  14403. });
  14404. };
  14405. var findCaretPosition = function (forward, rootElement, elm) {
  14406. return forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
  14407. };
  14408. var findCaretPosOutsideElmAfterDelete = function (forward, rootElement, elm) {
  14409. return findCaretPosition(forward, rootElement, elm).map(curry(reposition, elm));
  14410. };
  14411. var setSelection$1 = function (editor, forward, pos) {
  14412. pos.fold(function () {
  14413. editor.focus();
  14414. }, function (pos) {
  14415. editor.selection.setRng(pos.toRange(), forward);
  14416. });
  14417. };
  14418. var eqRawNode = function (rawNode) {
  14419. return function (elm) {
  14420. return elm.dom === rawNode;
  14421. };
  14422. };
  14423. var isBlock = function (editor, elm) {
  14424. return elm && has$2(editor.schema.getBlockElements(), name(elm));
  14425. };
  14426. var paddEmptyBlock = function (elm) {
  14427. if (isEmpty$2(elm)) {
  14428. var br = SugarElement.fromHtml('<br data-mce-bogus="1">');
  14429. empty(elm);
  14430. append$1(elm, br);
  14431. return Optional.some(CaretPosition.before(br.dom));
  14432. } else {
  14433. return Optional.none();
  14434. }
  14435. };
  14436. var deleteNormalized = function (elm, afterDeletePosOpt, normalizeWhitespace) {
  14437. var prevTextOpt = prevSibling(elm).filter(isText$8);
  14438. var nextTextOpt = nextSibling(elm).filter(isText$8);
  14439. remove$7(elm);
  14440. return lift3(prevTextOpt, nextTextOpt, afterDeletePosOpt, function (prev, next, pos) {
  14441. var prevNode = prev.dom, nextNode = next.dom;
  14442. var offset = prevNode.data.length;
  14443. mergeTextNodes(prevNode, nextNode, normalizeWhitespace);
  14444. return pos.container() === nextNode ? CaretPosition(prevNode, offset) : pos;
  14445. }).orThunk(function () {
  14446. if (normalizeWhitespace) {
  14447. prevTextOpt.each(function (elm) {
  14448. return normalizeWhitespaceBefore(elm.dom, elm.dom.length);
  14449. });
  14450. nextTextOpt.each(function (elm) {
  14451. return normalizeWhitespaceAfter(elm.dom, 0);
  14452. });
  14453. }
  14454. return afterDeletePosOpt;
  14455. });
  14456. };
  14457. var isInlineElement = function (editor, element) {
  14458. return has$2(editor.schema.getTextInlineElements(), name(element));
  14459. };
  14460. var deleteElement$2 = function (editor, forward, elm, moveCaret) {
  14461. if (moveCaret === void 0) {
  14462. moveCaret = true;
  14463. }
  14464. var afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom);
  14465. var parentBlock = ancestor$3(elm, curry(isBlock, editor), eqRawNode(editor.getBody()));
  14466. var normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos, isInlineElement(editor, elm));
  14467. if (editor.dom.isEmpty(editor.getBody())) {
  14468. editor.setContent('');
  14469. editor.selection.setCursorLocation();
  14470. } else {
  14471. parentBlock.bind(paddEmptyBlock).fold(function () {
  14472. if (moveCaret) {
  14473. setSelection$1(editor, forward, normalizedAfterDeletePos);
  14474. }
  14475. }, function (paddPos) {
  14476. if (moveCaret) {
  14477. setSelection$1(editor, forward, Optional.some(paddPos));
  14478. }
  14479. });
  14480. }
  14481. };
  14482. var isRootFromElement = function (root) {
  14483. return function (cur) {
  14484. return eq(root, cur);
  14485. };
  14486. };
  14487. var getTableCells = function (table) {
  14488. return descendants(table, 'td,th');
  14489. };
  14490. var getTableDetailsFromRange = function (rng, isRoot) {
  14491. var getTable = function (node) {
  14492. return getClosestTable(SugarElement.fromDom(node), isRoot);
  14493. };
  14494. var startTable = getTable(rng.startContainer);
  14495. var endTable = getTable(rng.endContainer);
  14496. var isStartInTable = startTable.isSome();
  14497. var isEndInTable = endTable.isSome();
  14498. var isSameTable = lift2(startTable, endTable, eq).getOr(false);
  14499. var isMultiTable = !isSameTable && isStartInTable && isEndInTable;
  14500. return {
  14501. startTable: startTable,
  14502. endTable: endTable,
  14503. isStartInTable: isStartInTable,
  14504. isEndInTable: isEndInTable,
  14505. isSameTable: isSameTable,
  14506. isMultiTable: isMultiTable
  14507. };
  14508. };
  14509. var tableCellRng = function (start, end) {
  14510. return {
  14511. start: start,
  14512. end: end
  14513. };
  14514. };
  14515. var tableSelection = function (rng, table, cells) {
  14516. return {
  14517. rng: rng,
  14518. table: table,
  14519. cells: cells
  14520. };
  14521. };
  14522. var deleteAction = Adt.generate([
  14523. {
  14524. singleCellTable: [
  14525. 'rng',
  14526. 'cell'
  14527. ]
  14528. },
  14529. { fullTable: ['table'] },
  14530. {
  14531. partialTable: [
  14532. 'cells',
  14533. 'outsideDetails'
  14534. ]
  14535. },
  14536. {
  14537. multiTable: [
  14538. 'startTableCells',
  14539. 'endTableCells',
  14540. 'betweenRng'
  14541. ]
  14542. }
  14543. ]);
  14544. var getClosestCell$1 = function (container, isRoot) {
  14545. return closest$2(SugarElement.fromDom(container), 'td,th', isRoot);
  14546. };
  14547. var isExpandedCellRng = function (cellRng) {
  14548. return !eq(cellRng.start, cellRng.end);
  14549. };
  14550. var getTableFromCellRng = function (cellRng, isRoot) {
  14551. return getClosestTable(cellRng.start, isRoot).bind(function (startParentTable) {
  14552. return getClosestTable(cellRng.end, isRoot).bind(function (endParentTable) {
  14553. return someIf(eq(startParentTable, endParentTable), startParentTable);
  14554. });
  14555. });
  14556. };
  14557. var isSingleCellTable = function (cellRng, isRoot) {
  14558. return !isExpandedCellRng(cellRng) && getTableFromCellRng(cellRng, isRoot).exists(function (table) {
  14559. var rows = table.dom.rows;
  14560. return rows.length === 1 && rows[0].cells.length === 1;
  14561. });
  14562. };
  14563. var getCellRng = function (rng, isRoot) {
  14564. var startCell = getClosestCell$1(rng.startContainer, isRoot);
  14565. var endCell = getClosestCell$1(rng.endContainer, isRoot);
  14566. return lift2(startCell, endCell, tableCellRng);
  14567. };
  14568. var getCellRangeFromStartTable = function (isRoot) {
  14569. return function (startCell) {
  14570. return getClosestTable(startCell, isRoot).bind(function (table) {
  14571. return last$2(getTableCells(table)).map(function (endCell) {
  14572. return tableCellRng(startCell, endCell);
  14573. });
  14574. });
  14575. };
  14576. };
  14577. var getCellRangeFromEndTable = function (isRoot) {
  14578. return function (endCell) {
  14579. return getClosestTable(endCell, isRoot).bind(function (table) {
  14580. return head(getTableCells(table)).map(function (startCell) {
  14581. return tableCellRng(startCell, endCell);
  14582. });
  14583. });
  14584. };
  14585. };
  14586. var getTableSelectionFromCellRng = function (isRoot) {
  14587. return function (cellRng) {
  14588. return getTableFromCellRng(cellRng, isRoot).map(function (table) {
  14589. return tableSelection(cellRng, table, getTableCells(table));
  14590. });
  14591. };
  14592. };
  14593. var getTableSelections = function (cellRng, selectionDetails, rng, isRoot) {
  14594. if (rng.collapsed || !cellRng.forall(isExpandedCellRng)) {
  14595. return Optional.none();
  14596. } else if (selectionDetails.isSameTable) {
  14597. var sameTableSelection = cellRng.bind(getTableSelectionFromCellRng(isRoot));
  14598. return Optional.some({
  14599. start: sameTableSelection,
  14600. end: sameTableSelection
  14601. });
  14602. } else {
  14603. var startCell = getClosestCell$1(rng.startContainer, isRoot);
  14604. var endCell = getClosestCell$1(rng.endContainer, isRoot);
  14605. var startTableSelection = startCell.bind(getCellRangeFromStartTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  14606. var endTableSelection = endCell.bind(getCellRangeFromEndTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  14607. return Optional.some({
  14608. start: startTableSelection,
  14609. end: endTableSelection
  14610. });
  14611. }
  14612. };
  14613. var getCellIndex = function (cells, cell) {
  14614. return findIndex$2(cells, function (x) {
  14615. return eq(x, cell);
  14616. });
  14617. };
  14618. var getSelectedCells = function (tableSelection) {
  14619. return lift2(getCellIndex(tableSelection.cells, tableSelection.rng.start), getCellIndex(tableSelection.cells, tableSelection.rng.end), function (startIndex, endIndex) {
  14620. return tableSelection.cells.slice(startIndex, endIndex + 1);
  14621. });
  14622. };
  14623. var isSingleCellTableContentSelected = function (optCellRng, rng, isRoot) {
  14624. return optCellRng.exists(function (cellRng) {
  14625. return isSingleCellTable(cellRng, isRoot) && hasAllContentsSelected(cellRng.start, rng);
  14626. });
  14627. };
  14628. var unselectCells = function (rng, selectionDetails) {
  14629. var startTable = selectionDetails.startTable, endTable = selectionDetails.endTable;
  14630. var otherContentRng = rng.cloneRange();
  14631. startTable.each(function (table) {
  14632. return otherContentRng.setStartAfter(table.dom);
  14633. });
  14634. endTable.each(function (table) {
  14635. return otherContentRng.setEndBefore(table.dom);
  14636. });
  14637. return otherContentRng;
  14638. };
  14639. var handleSingleTable = function (cellRng, selectionDetails, rng, isRoot) {
  14640. return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function (_a) {
  14641. var start = _a.start, end = _a.end;
  14642. return start.or(end);
  14643. }).bind(function (tableSelection) {
  14644. var isSameTable = selectionDetails.isSameTable;
  14645. var selectedCells = getSelectedCells(tableSelection).getOr([]);
  14646. if (isSameTable && tableSelection.cells.length === selectedCells.length) {
  14647. return Optional.some(deleteAction.fullTable(tableSelection.table));
  14648. } else if (selectedCells.length > 0) {
  14649. if (isSameTable) {
  14650. return Optional.some(deleteAction.partialTable(selectedCells, Optional.none()));
  14651. } else {
  14652. var otherContentRng = unselectCells(rng, selectionDetails);
  14653. return Optional.some(deleteAction.partialTable(selectedCells, Optional.some(__assign(__assign({}, selectionDetails), { rng: otherContentRng }))));
  14654. }
  14655. } else {
  14656. return Optional.none();
  14657. }
  14658. });
  14659. };
  14660. var handleMultiTable = function (cellRng, selectionDetails, rng, isRoot) {
  14661. return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function (_a) {
  14662. var start = _a.start, end = _a.end;
  14663. var startTableSelectedCells = start.bind(getSelectedCells).getOr([]);
  14664. var endTableSelectedCells = end.bind(getSelectedCells).getOr([]);
  14665. if (startTableSelectedCells.length > 0 && endTableSelectedCells.length > 0) {
  14666. var otherContentRng = unselectCells(rng, selectionDetails);
  14667. return Optional.some(deleteAction.multiTable(startTableSelectedCells, endTableSelectedCells, otherContentRng));
  14668. } else {
  14669. return Optional.none();
  14670. }
  14671. });
  14672. };
  14673. var getActionFromRange = function (root, rng) {
  14674. var isRoot = isRootFromElement(root);
  14675. var optCellRng = getCellRng(rng, isRoot);
  14676. var selectionDetails = getTableDetailsFromRange(rng, isRoot);
  14677. if (isSingleCellTableContentSelected(optCellRng, rng, isRoot)) {
  14678. return optCellRng.map(function (cellRng) {
  14679. return deleteAction.singleCellTable(rng, cellRng.start);
  14680. });
  14681. } else if (selectionDetails.isMultiTable) {
  14682. return handleMultiTable(optCellRng, selectionDetails, rng, isRoot);
  14683. } else {
  14684. return handleSingleTable(optCellRng, selectionDetails, rng, isRoot);
  14685. }
  14686. };
  14687. var freefallRtl = function (root) {
  14688. var child = isComment$1(root) ? prevSibling(root) : lastChild(root);
  14689. return child.bind(freefallRtl).orThunk(function () {
  14690. return Optional.some(root);
  14691. });
  14692. };
  14693. var cleanCells = function (cells) {
  14694. return each$k(cells, function (cell) {
  14695. remove$6(cell, 'contenteditable');
  14696. fillWithPaddingBr(cell);
  14697. });
  14698. };
  14699. var getOutsideBlock = function (editor, container) {
  14700. return Optional.from(editor.dom.getParent(container, editor.dom.isBlock)).map(SugarElement.fromDom);
  14701. };
  14702. var handleEmptyBlock = function (editor, startInTable, emptyBlock) {
  14703. emptyBlock.each(function (block) {
  14704. if (startInTable) {
  14705. remove$7(block);
  14706. } else {
  14707. fillWithPaddingBr(block);
  14708. editor.selection.setCursorLocation(block.dom, 0);
  14709. }
  14710. });
  14711. };
  14712. var setCursorInCell = function (editor, cell) {
  14713. var selectedCells = getCellsFromEditor(editor);
  14714. editor.selection.setCursorLocation(cell.dom, 0);
  14715. if (selectedCells.length > 1) {
  14716. set$1(cell, 'data-mce-selected', '1');
  14717. }
  14718. };
  14719. var emptySingleTableCells = function (editor, cells, outsideDetails) {
  14720. cleanCells(cells);
  14721. outsideDetails.map(function (_a) {
  14722. var rng = _a.rng, isStartInTable = _a.isStartInTable;
  14723. var outsideBlock = getOutsideBlock(editor, isStartInTable ? rng.endContainer : rng.startContainer);
  14724. rng.deleteContents();
  14725. handleEmptyBlock(editor, isStartInTable, outsideBlock.filter(isEmpty$2));
  14726. });
  14727. if (outsideDetails.forall(function (details) {
  14728. return details.isStartInTable;
  14729. })) {
  14730. setCursorInCell(editor, cells[0]);
  14731. } else {
  14732. editor.selection.collapse(true);
  14733. }
  14734. return true;
  14735. };
  14736. var emptyMultiTableCells = function (editor, startTableCells, endTableCells, betweenRng) {
  14737. cleanCells(startTableCells.concat(endTableCells));
  14738. betweenRng.deleteContents();
  14739. setCursorInCell(editor, startTableCells[0]);
  14740. return true;
  14741. };
  14742. var deleteCellContents = function (editor, rng, cell) {
  14743. rng.deleteContents();
  14744. var lastNode = freefallRtl(cell).getOr(cell);
  14745. var lastBlock = SugarElement.fromDom(editor.dom.getParent(lastNode.dom, editor.dom.isBlock));
  14746. if (isEmpty$2(lastBlock)) {
  14747. fillWithPaddingBr(lastBlock);
  14748. editor.selection.setCursorLocation(lastBlock.dom, 0);
  14749. }
  14750. if (!eq(cell, lastBlock)) {
  14751. var additionalCleanupNodes = is$1(parent(lastBlock), cell) ? [] : siblings(lastBlock);
  14752. each$k(additionalCleanupNodes.concat(children(cell)), function (node) {
  14753. if (!eq(node, lastBlock) && !contains$1(node, lastBlock)) {
  14754. remove$7(node);
  14755. }
  14756. });
  14757. }
  14758. return true;
  14759. };
  14760. var deleteTableElement = function (editor, table) {
  14761. deleteElement$2(editor, false, table);
  14762. return true;
  14763. };
  14764. var deleteCellRange = function (editor, rootElm, rng) {
  14765. return getActionFromRange(rootElm, rng).map(function (action) {
  14766. return action.fold(curry(deleteCellContents, editor), curry(deleteTableElement, editor), curry(emptySingleTableCells, editor), curry(emptyMultiTableCells, editor));
  14767. });
  14768. };
  14769. var deleteCaptionRange = function (editor, caption) {
  14770. return emptyElement(editor, caption);
  14771. };
  14772. var deleteTableRange = function (editor, rootElm, rng, startElm) {
  14773. return getParentCaption(rootElm, startElm).fold(function () {
  14774. return deleteCellRange(editor, rootElm, rng);
  14775. }, function (caption) {
  14776. return deleteCaptionRange(editor, caption);
  14777. }).getOr(false);
  14778. };
  14779. var deleteRange$2 = function (editor, startElm, selectedCells) {
  14780. var rootNode = SugarElement.fromDom(editor.getBody());
  14781. var rng = editor.selection.getRng();
  14782. return selectedCells.length !== 0 ? emptySingleTableCells(editor, selectedCells, Optional.none()) : deleteTableRange(editor, rootNode, rng, startElm);
  14783. };
  14784. var getParentCell = function (rootElm, elm) {
  14785. return find$3(parentsAndSelf(elm, rootElm), isTableCell$4);
  14786. };
  14787. var getParentCaption = function (rootElm, elm) {
  14788. return find$3(parentsAndSelf(elm, rootElm), isTag('caption'));
  14789. };
  14790. var deleteBetweenCells = function (editor, rootElm, forward, fromCell, from) {
  14791. return navigate(forward, editor.getBody(), from).bind(function (to) {
  14792. return getParentCell(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCell) {
  14793. return eq(toCell, fromCell) === false;
  14794. });
  14795. });
  14796. };
  14797. var emptyElement = function (editor, elm) {
  14798. fillWithPaddingBr(elm);
  14799. editor.selection.setCursorLocation(elm.dom, 0);
  14800. return Optional.some(true);
  14801. };
  14802. var isDeleteOfLastCharPos = function (fromCaption, forward, from, to) {
  14803. return firstPositionIn(fromCaption.dom).bind(function (first) {
  14804. return lastPositionIn(fromCaption.dom).map(function (last) {
  14805. return forward ? from.isEqual(first) && to.isEqual(last) : from.isEqual(last) && to.isEqual(first);
  14806. });
  14807. }).getOr(true);
  14808. };
  14809. var emptyCaretCaption = function (editor, elm) {
  14810. return emptyElement(editor, elm);
  14811. };
  14812. var validateCaretCaption = function (rootElm, fromCaption, to) {
  14813. return getParentCaption(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCaption) {
  14814. return eq(toCaption, fromCaption) === false;
  14815. });
  14816. };
  14817. var deleteCaretInsideCaption = function (editor, rootElm, forward, fromCaption, from) {
  14818. return navigate(forward, editor.getBody(), from).bind(function (to) {
  14819. return isDeleteOfLastCharPos(fromCaption, forward, from, to) ? emptyCaretCaption(editor, fromCaption) : validateCaretCaption(rootElm, fromCaption, to);
  14820. }).or(Optional.some(true));
  14821. };
  14822. var deleteCaretCells = function (editor, forward, rootElm, startElm) {
  14823. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  14824. return getParentCell(rootElm, startElm).bind(function (fromCell) {
  14825. return isEmpty$2(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from);
  14826. }).getOr(false);
  14827. };
  14828. var deleteCaretCaption = function (editor, forward, rootElm, fromCaption) {
  14829. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  14830. return isEmpty$2(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from);
  14831. };
  14832. var isNearTable = function (forward, pos) {
  14833. return forward ? isBeforeTable(pos) : isAfterTable(pos);
  14834. };
  14835. var isBeforeOrAfterTable = function (editor, forward) {
  14836. var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  14837. return isNearTable(forward, fromPos) || fromPosition(forward, editor.getBody(), fromPos).exists(function (pos) {
  14838. return isNearTable(forward, pos);
  14839. });
  14840. };
  14841. var deleteCaret$3 = function (editor, forward, startElm) {
  14842. var rootElm = SugarElement.fromDom(editor.getBody());
  14843. return getParentCaption(rootElm, startElm).fold(function () {
  14844. return deleteCaretCells(editor, forward, rootElm, startElm) || isBeforeOrAfterTable(editor, forward);
  14845. }, function (fromCaption) {
  14846. return deleteCaretCaption(editor, forward, rootElm, fromCaption).getOr(false);
  14847. });
  14848. };
  14849. var backspaceDelete$9 = function (editor, forward) {
  14850. var startElm = SugarElement.fromDom(editor.selection.getStart(true));
  14851. var cells = getCellsFromEditor(editor);
  14852. return editor.selection.isCollapsed() && cells.length === 0 ? deleteCaret$3(editor, forward, startElm) : deleteRange$2(editor, startElm, cells);
  14853. };
  14854. var createRange = function (sc, so, ec, eo) {
  14855. var rng = document.createRange();
  14856. rng.setStart(sc, so);
  14857. rng.setEnd(ec, eo);
  14858. return rng;
  14859. };
  14860. var normalizeBlockSelectionRange = function (rng) {
  14861. var startPos = CaretPosition.fromRangeStart(rng);
  14862. var endPos = CaretPosition.fromRangeEnd(rng);
  14863. var rootNode = rng.commonAncestorContainer;
  14864. return fromPosition(false, rootNode, endPos).map(function (newEndPos) {
  14865. if (!isInSameBlock(startPos, endPos, rootNode) && isInSameBlock(startPos, newEndPos, rootNode)) {
  14866. return createRange(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
  14867. } else {
  14868. return rng;
  14869. }
  14870. }).getOr(rng);
  14871. };
  14872. var normalize = function (rng) {
  14873. return rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
  14874. };
  14875. var hasOnlyOneChild$1 = function (node) {
  14876. return node.firstChild && node.firstChild === node.lastChild;
  14877. };
  14878. var isPaddingNode = function (node) {
  14879. return node.name === 'br' || node.value === nbsp;
  14880. };
  14881. var isPaddedEmptyBlock = function (schema, node) {
  14882. var blockElements = schema.getBlockElements();
  14883. return blockElements[node.name] && hasOnlyOneChild$1(node) && isPaddingNode(node.firstChild);
  14884. };
  14885. var isEmptyFragmentElement = function (schema, node) {
  14886. var nonEmptyElements = schema.getNonEmptyElements();
  14887. return node && (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
  14888. };
  14889. var isListFragment = function (schema, fragment) {
  14890. var firstChild = fragment.firstChild;
  14891. var lastChild = fragment.lastChild;
  14892. if (firstChild && firstChild.name === 'meta') {
  14893. firstChild = firstChild.next;
  14894. }
  14895. if (lastChild && lastChild.attr('id') === 'mce_marker') {
  14896. lastChild = lastChild.prev;
  14897. }
  14898. if (isEmptyFragmentElement(schema, lastChild)) {
  14899. lastChild = lastChild.prev;
  14900. }
  14901. if (!firstChild || firstChild !== lastChild) {
  14902. return false;
  14903. }
  14904. return firstChild.name === 'ul' || firstChild.name === 'ol';
  14905. };
  14906. var cleanupDomFragment = function (domFragment) {
  14907. var firstChild = domFragment.firstChild;
  14908. var lastChild = domFragment.lastChild;
  14909. if (firstChild && firstChild.nodeName === 'META') {
  14910. firstChild.parentNode.removeChild(firstChild);
  14911. }
  14912. if (lastChild && lastChild.id === 'mce_marker') {
  14913. lastChild.parentNode.removeChild(lastChild);
  14914. }
  14915. return domFragment;
  14916. };
  14917. var toDomFragment = function (dom, serializer, fragment) {
  14918. var html = serializer.serialize(fragment);
  14919. var domFragment = dom.createFragment(html);
  14920. return cleanupDomFragment(domFragment);
  14921. };
  14922. var listItems = function (elm) {
  14923. return filter$4(elm.childNodes, function (child) {
  14924. return child.nodeName === 'LI';
  14925. });
  14926. };
  14927. var isPadding = function (node) {
  14928. return node.data === nbsp || isBr$5(node);
  14929. };
  14930. var isListItemPadded = function (node) {
  14931. return node && node.firstChild && node.firstChild === node.lastChild && isPadding(node.firstChild);
  14932. };
  14933. var isEmptyOrPadded = function (elm) {
  14934. return !elm.firstChild || isListItemPadded(elm);
  14935. };
  14936. var trimListItems = function (elms) {
  14937. return elms.length > 0 && isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
  14938. };
  14939. var getParentLi = function (dom, node) {
  14940. var parentBlock = dom.getParent(node, dom.isBlock);
  14941. return parentBlock && parentBlock.nodeName === 'LI' ? parentBlock : null;
  14942. };
  14943. var isParentBlockLi = function (dom, node) {
  14944. return !!getParentLi(dom, node);
  14945. };
  14946. var getSplit = function (parentNode, rng) {
  14947. var beforeRng = rng.cloneRange();
  14948. var afterRng = rng.cloneRange();
  14949. beforeRng.setStartBefore(parentNode);
  14950. afterRng.setEndAfter(parentNode);
  14951. return [
  14952. beforeRng.cloneContents(),
  14953. afterRng.cloneContents()
  14954. ];
  14955. };
  14956. var findFirstIn = function (node, rootNode) {
  14957. var caretPos = CaretPosition.before(node);
  14958. var caretWalker = CaretWalker(rootNode);
  14959. var newCaretPos = caretWalker.next(caretPos);
  14960. return newCaretPos ? newCaretPos.toRange() : null;
  14961. };
  14962. var findLastOf = function (node, rootNode) {
  14963. var caretPos = CaretPosition.after(node);
  14964. var caretWalker = CaretWalker(rootNode);
  14965. var newCaretPos = caretWalker.prev(caretPos);
  14966. return newCaretPos ? newCaretPos.toRange() : null;
  14967. };
  14968. var insertMiddle = function (target, elms, rootNode, rng) {
  14969. var parts = getSplit(target, rng);
  14970. var parentElm = target.parentNode;
  14971. parentElm.insertBefore(parts[0], target);
  14972. Tools.each(elms, function (li) {
  14973. parentElm.insertBefore(li, target);
  14974. });
  14975. parentElm.insertBefore(parts[1], target);
  14976. parentElm.removeChild(target);
  14977. return findLastOf(elms[elms.length - 1], rootNode);
  14978. };
  14979. var insertBefore$1 = function (target, elms, rootNode) {
  14980. var parentElm = target.parentNode;
  14981. Tools.each(elms, function (elm) {
  14982. parentElm.insertBefore(elm, target);
  14983. });
  14984. return findFirstIn(target, rootNode);
  14985. };
  14986. var insertAfter$1 = function (target, elms, rootNode, dom) {
  14987. dom.insertAfter(elms.reverse(), target);
  14988. return findLastOf(elms[0], rootNode);
  14989. };
  14990. var insertAtCaret$1 = function (serializer, dom, rng, fragment) {
  14991. var domFragment = toDomFragment(dom, serializer, fragment);
  14992. var liTarget = getParentLi(dom, rng.startContainer);
  14993. var liElms = trimListItems(listItems(domFragment.firstChild));
  14994. var BEGINNING = 1, END = 2;
  14995. var rootNode = dom.getRoot();
  14996. var isAt = function (location) {
  14997. var caretPos = CaretPosition.fromRangeStart(rng);
  14998. var caretWalker = CaretWalker(dom.getRoot());
  14999. var newPos = location === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
  15000. return newPos ? getParentLi(dom, newPos.getNode()) !== liTarget : true;
  15001. };
  15002. if (isAt(BEGINNING)) {
  15003. return insertBefore$1(liTarget, liElms, rootNode);
  15004. } else if (isAt(END)) {
  15005. return insertAfter$1(liTarget, liElms, rootNode, dom);
  15006. }
  15007. return insertMiddle(liTarget, liElms, rootNode, rng);
  15008. };
  15009. var trimOrPadLeftRight = function (dom, rng, html) {
  15010. var root = SugarElement.fromDom(dom.getRoot());
  15011. if (needsToBeNbspLeft(root, CaretPosition.fromRangeStart(rng))) {
  15012. html = html.replace(/^ /, '&nbsp;');
  15013. } else {
  15014. html = html.replace(/^&nbsp;/, ' ');
  15015. }
  15016. if (needsToBeNbspRight(root, CaretPosition.fromRangeEnd(rng))) {
  15017. html = html.replace(/(&nbsp;| )(<br( \/)>)?$/, '&nbsp;');
  15018. } else {
  15019. html = html.replace(/&nbsp;(<br( \/)?>)?$/, ' ');
  15020. }
  15021. return html;
  15022. };
  15023. var isTableCell$1 = isTableCell$5;
  15024. var isTableCellContentSelected = function (dom, rng, cell) {
  15025. if (cell !== null) {
  15026. var endCell = dom.getParent(rng.endContainer, isTableCell$1);
  15027. return cell === endCell && hasAllContentsSelected(SugarElement.fromDom(cell), rng);
  15028. } else {
  15029. return false;
  15030. }
  15031. };
  15032. var validInsertion = function (editor, value, parentNode) {
  15033. if (parentNode.getAttribute('data-mce-bogus') === 'all') {
  15034. parentNode.parentNode.insertBefore(editor.dom.createFragment(value), parentNode);
  15035. } else {
  15036. var node = parentNode.firstChild;
  15037. var node2 = parentNode.lastChild;
  15038. if (!node || node === node2 && node.nodeName === 'BR') {
  15039. editor.dom.setHTML(parentNode, value);
  15040. } else {
  15041. editor.selection.setContent(value);
  15042. }
  15043. }
  15044. };
  15045. var trimBrsFromTableCell = function (dom, elm) {
  15046. Optional.from(dom.getParent(elm, 'td,th')).map(SugarElement.fromDom).each(trimBlockTrailingBr);
  15047. };
  15048. var reduceInlineTextElements = function (editor, merge) {
  15049. var textInlineElements = editor.schema.getTextInlineElements();
  15050. var dom = editor.dom;
  15051. if (merge) {
  15052. var root_1 = editor.getBody();
  15053. var elementUtils_1 = ElementUtils(dom);
  15054. Tools.each(dom.select('*[data-mce-fragment]'), function (node) {
  15055. var isInline = isNonNullable(textInlineElements[node.nodeName.toLowerCase()]);
  15056. if (isInline && hasInheritableStyles(dom, node)) {
  15057. for (var parentNode = node.parentNode; isNonNullable(parentNode) && parentNode !== root_1; parentNode = parentNode.parentNode) {
  15058. var styleConflict = hasStyleConflict(dom, node, parentNode);
  15059. if (styleConflict) {
  15060. break;
  15061. }
  15062. if (elementUtils_1.compare(parentNode, node)) {
  15063. dom.remove(node, true);
  15064. break;
  15065. }
  15066. }
  15067. }
  15068. });
  15069. }
  15070. };
  15071. var markFragmentElements = function (fragment) {
  15072. var node = fragment;
  15073. while (node = node.walk()) {
  15074. if (node.type === 1) {
  15075. node.attr('data-mce-fragment', '1');
  15076. }
  15077. }
  15078. };
  15079. var unmarkFragmentElements = function (elm) {
  15080. Tools.each(elm.getElementsByTagName('*'), function (elm) {
  15081. elm.removeAttribute('data-mce-fragment');
  15082. });
  15083. };
  15084. var isPartOfFragment = function (node) {
  15085. return !!node.getAttribute('data-mce-fragment');
  15086. };
  15087. var canHaveChildren = function (editor, node) {
  15088. return node && !editor.schema.getShortEndedElements()[node.nodeName];
  15089. };
  15090. var moveSelectionToMarker = function (editor, marker) {
  15091. var nextRng;
  15092. var dom = editor.dom;
  15093. var selection = editor.selection;
  15094. var getContentEditableFalseParent = function (node) {
  15095. var root = editor.getBody();
  15096. for (; node && node !== root; node = node.parentNode) {
  15097. if (dom.getContentEditable(node) === 'false') {
  15098. return node;
  15099. }
  15100. }
  15101. return null;
  15102. };
  15103. if (!marker) {
  15104. return;
  15105. }
  15106. selection.scrollIntoView(marker);
  15107. var parentEditableFalseElm = getContentEditableFalseParent(marker);
  15108. if (parentEditableFalseElm) {
  15109. dom.remove(marker);
  15110. selection.select(parentEditableFalseElm);
  15111. return;
  15112. }
  15113. var rng = dom.createRng();
  15114. var node = marker.previousSibling;
  15115. if (isText$7(node)) {
  15116. rng.setStart(node, node.nodeValue.length);
  15117. if (!Env.ie) {
  15118. var node2 = marker.nextSibling;
  15119. if (isText$7(node2)) {
  15120. node.appendData(node2.data);
  15121. node2.parentNode.removeChild(node2);
  15122. }
  15123. }
  15124. } else {
  15125. rng.setStartBefore(marker);
  15126. rng.setEndBefore(marker);
  15127. }
  15128. var findNextCaretRng = function (rng) {
  15129. var caretPos = CaretPosition.fromRangeStart(rng);
  15130. var caretWalker = CaretWalker(editor.getBody());
  15131. caretPos = caretWalker.next(caretPos);
  15132. if (caretPos) {
  15133. return caretPos.toRange();
  15134. }
  15135. };
  15136. var parentBlock = dom.getParent(marker, dom.isBlock);
  15137. dom.remove(marker);
  15138. if (parentBlock && dom.isEmpty(parentBlock)) {
  15139. editor.$(parentBlock).empty();
  15140. rng.setStart(parentBlock, 0);
  15141. rng.setEnd(parentBlock, 0);
  15142. if (!isTableCell$1(parentBlock) && !isPartOfFragment(parentBlock) && (nextRng = findNextCaretRng(rng))) {
  15143. rng = nextRng;
  15144. dom.remove(parentBlock);
  15145. } else {
  15146. dom.add(parentBlock, dom.create('br', { 'data-mce-bogus': '1' }));
  15147. }
  15148. }
  15149. selection.setRng(rng);
  15150. };
  15151. var deleteSelectedContent = function (editor) {
  15152. var dom = editor.dom;
  15153. var rng = normalize(editor.selection.getRng());
  15154. editor.selection.setRng(rng);
  15155. var startCell = dom.getParent(rng.startContainer, isTableCell$1);
  15156. if (isTableCellContentSelected(dom, rng, startCell)) {
  15157. deleteCellContents(editor, rng, SugarElement.fromDom(startCell));
  15158. } else {
  15159. editor.getDoc().execCommand('Delete', false, null);
  15160. }
  15161. };
  15162. var insertHtmlAtCaret = function (editor, value, details) {
  15163. var parentNode;
  15164. var rng, node;
  15165. var selection = editor.selection;
  15166. var dom = editor.dom;
  15167. if (/^ | $/.test(value)) {
  15168. value = trimOrPadLeftRight(dom, selection.getRng(), value);
  15169. }
  15170. var parser = editor.parser;
  15171. var merge = details.merge;
  15172. var serializer = HtmlSerializer({ validate: shouldValidate(editor) }, editor.schema);
  15173. var bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>';
  15174. var args = editor.fire('BeforeSetContent', {
  15175. content: value,
  15176. format: 'html',
  15177. selection: true,
  15178. paste: details.paste
  15179. });
  15180. if (args.isDefaultPrevented()) {
  15181. editor.fire('SetContent', {
  15182. content: args.content,
  15183. format: 'html',
  15184. selection: true,
  15185. paste: details.paste
  15186. });
  15187. return;
  15188. }
  15189. value = args.content;
  15190. if (value.indexOf('{$caret}') === -1) {
  15191. value += '{$caret}';
  15192. }
  15193. value = value.replace(/\{\$caret\}/, bookmarkHtml);
  15194. rng = selection.getRng();
  15195. var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
  15196. var body = editor.getBody();
  15197. if (caretElement === body && selection.isCollapsed()) {
  15198. if (dom.isBlock(body.firstChild) && canHaveChildren(editor, body.firstChild) && dom.isEmpty(body.firstChild)) {
  15199. rng = dom.createRng();
  15200. rng.setStart(body.firstChild, 0);
  15201. rng.setEnd(body.firstChild, 0);
  15202. selection.setRng(rng);
  15203. }
  15204. }
  15205. if (!selection.isCollapsed()) {
  15206. deleteSelectedContent(editor);
  15207. }
  15208. parentNode = selection.getNode();
  15209. var parserArgs = {
  15210. context: parentNode.nodeName.toLowerCase(),
  15211. data: details.data,
  15212. insert: true
  15213. };
  15214. var fragment = parser.parse(value, parserArgs);
  15215. if (details.paste === true && isListFragment(editor.schema, fragment) && isParentBlockLi(dom, parentNode)) {
  15216. rng = insertAtCaret$1(serializer, dom, selection.getRng(), fragment);
  15217. selection.setRng(rng);
  15218. editor.fire('SetContent', args);
  15219. return;
  15220. }
  15221. markFragmentElements(fragment);
  15222. node = fragment.lastChild;
  15223. if (node.attr('id') === 'mce_marker') {
  15224. var marker = node;
  15225. for (node = node.prev; node; node = node.walk(true)) {
  15226. if (node.type === 3 || !dom.isBlock(node.name)) {
  15227. if (editor.schema.isValidChild(node.parent.name, 'span')) {
  15228. node.parent.insert(marker, node, node.name === 'br');
  15229. }
  15230. break;
  15231. }
  15232. }
  15233. }
  15234. editor._selectionOverrides.showBlockCaretContainer(parentNode);
  15235. if (!parserArgs.invalid) {
  15236. value = serializer.serialize(fragment);
  15237. validInsertion(editor, value, parentNode);
  15238. } else {
  15239. editor.selection.setContent(bookmarkHtml);
  15240. parentNode = selection.getNode();
  15241. var rootNode = editor.getBody();
  15242. if (parentNode.nodeType === 9) {
  15243. parentNode = node = rootNode;
  15244. } else {
  15245. node = parentNode;
  15246. }
  15247. while (node !== rootNode) {
  15248. parentNode = node;
  15249. node = node.parentNode;
  15250. }
  15251. value = parentNode === rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
  15252. value = serializer.serialize(parser.parse(value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function () {
  15253. return serializer.serialize(fragment);
  15254. })));
  15255. if (parentNode === rootNode) {
  15256. dom.setHTML(rootNode, value);
  15257. } else {
  15258. dom.setOuterHTML(parentNode, value);
  15259. }
  15260. }
  15261. reduceInlineTextElements(editor, merge);
  15262. moveSelectionToMarker(editor, dom.get('mce_marker'));
  15263. unmarkFragmentElements(editor.getBody());
  15264. trimBrsFromTableCell(dom, selection.getStart());
  15265. editor.fire('SetContent', args);
  15266. editor.addVisual();
  15267. };
  15268. var traverse = function (node, fn) {
  15269. fn(node);
  15270. if (node.firstChild) {
  15271. traverse(node.firstChild, fn);
  15272. }
  15273. if (node.next) {
  15274. traverse(node.next, fn);
  15275. }
  15276. };
  15277. var findMatchingNodes = function (nodeFilters, attributeFilters, node) {
  15278. var nodeMatches = {};
  15279. var attrMatches = {};
  15280. var matches = [];
  15281. if (node.firstChild) {
  15282. traverse(node.firstChild, function (node) {
  15283. each$k(nodeFilters, function (filter) {
  15284. if (filter.name === node.name) {
  15285. if (nodeMatches[filter.name]) {
  15286. nodeMatches[filter.name].nodes.push(node);
  15287. } else {
  15288. nodeMatches[filter.name] = {
  15289. filter: filter,
  15290. nodes: [node]
  15291. };
  15292. }
  15293. }
  15294. });
  15295. each$k(attributeFilters, function (filter) {
  15296. if (typeof node.attr(filter.name) === 'string') {
  15297. if (attrMatches[filter.name]) {
  15298. attrMatches[filter.name].nodes.push(node);
  15299. } else {
  15300. attrMatches[filter.name] = {
  15301. filter: filter,
  15302. nodes: [node]
  15303. };
  15304. }
  15305. }
  15306. });
  15307. });
  15308. }
  15309. for (var name_1 in nodeMatches) {
  15310. if (has$2(nodeMatches, name_1)) {
  15311. matches.push(nodeMatches[name_1]);
  15312. }
  15313. }
  15314. for (var name_2 in attrMatches) {
  15315. if (has$2(attrMatches, name_2)) {
  15316. matches.push(attrMatches[name_2]);
  15317. }
  15318. }
  15319. return matches;
  15320. };
  15321. var filter$1 = function (nodeFilters, attributeFilters, node) {
  15322. var matches = findMatchingNodes(nodeFilters, attributeFilters, node);
  15323. each$k(matches, function (match) {
  15324. each$k(match.filter.callbacks, function (callback) {
  15325. callback(match.nodes, match.filter.name, {});
  15326. });
  15327. });
  15328. };
  15329. var defaultFormat$1 = 'html';
  15330. var isTreeNode = function (content) {
  15331. return content instanceof AstNode;
  15332. };
  15333. var moveSelection = function (editor) {
  15334. if (hasFocus(editor)) {
  15335. firstPositionIn(editor.getBody()).each(function (pos) {
  15336. var node = pos.getNode();
  15337. var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  15338. editor.selection.setRng(caretPos.toRange());
  15339. });
  15340. }
  15341. };
  15342. var setEditorHtml = function (editor, html, noSelection) {
  15343. editor.dom.setHTML(editor.getBody(), html);
  15344. if (noSelection !== true) {
  15345. moveSelection(editor);
  15346. }
  15347. };
  15348. var setContentString = function (editor, body, content, args) {
  15349. if (content.length === 0 || /^\s+$/.test(content)) {
  15350. var padd = '<br data-mce-bogus="1">';
  15351. if (body.nodeName === 'TABLE') {
  15352. content = '<tr><td>' + padd + '</td></tr>';
  15353. } else if (/^(UL|OL)$/.test(body.nodeName)) {
  15354. content = '<li>' + padd + '</li>';
  15355. }
  15356. var forcedRootBlockName = getForcedRootBlock(editor);
  15357. if (forcedRootBlockName && editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
  15358. content = padd;
  15359. content = editor.dom.createHTML(forcedRootBlockName, getForcedRootBlockAttrs(editor), content);
  15360. } else if (!content) {
  15361. content = '<br data-mce-bogus="1">';
  15362. }
  15363. setEditorHtml(editor, content, args.no_selection);
  15364. editor.fire('SetContent', args);
  15365. } else {
  15366. if (args.format !== 'raw') {
  15367. content = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(editor.parser.parse(content, {
  15368. isRootContent: true,
  15369. insert: true
  15370. }));
  15371. }
  15372. args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? content : Tools.trim(content);
  15373. setEditorHtml(editor, args.content, args.no_selection);
  15374. if (!args.no_events) {
  15375. editor.fire('SetContent', args);
  15376. }
  15377. }
  15378. return args.content;
  15379. };
  15380. var setContentTree = function (editor, body, content, args) {
  15381. filter$1(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
  15382. var html = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(content);
  15383. args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? html : Tools.trim(html);
  15384. setEditorHtml(editor, args.content, args.no_selection);
  15385. if (!args.no_events) {
  15386. editor.fire('SetContent', args);
  15387. }
  15388. return content;
  15389. };
  15390. var setContentInternal = function (editor, content, args) {
  15391. var updatedArgs = args.no_events ? args : editor.fire('BeforeSetContent', __assign(__assign({ format: defaultFormat$1 }, args), {
  15392. set: true,
  15393. content: isTreeNode(content) ? '' : content
  15394. }));
  15395. if (!isTreeNode(content)) {
  15396. content = updatedArgs.content;
  15397. }
  15398. return Optional.from(editor.getBody()).fold(constant(content), function (body) {
  15399. return isTreeNode(content) ? setContentTree(editor, body, content, updatedArgs) : setContentString(editor, body, content, updatedArgs);
  15400. });
  15401. };
  15402. var sibling = function (scope, predicate) {
  15403. return sibling$2(scope, predicate).isSome();
  15404. };
  15405. var ensureIsRoot = function (isRoot) {
  15406. return isFunction(isRoot) ? isRoot : never;
  15407. };
  15408. var ancestor = function (scope, transform, isRoot) {
  15409. var element = scope.dom;
  15410. var stop = ensureIsRoot(isRoot);
  15411. while (element.parentNode) {
  15412. element = element.parentNode;
  15413. var el = SugarElement.fromDom(element);
  15414. var transformed = transform(el);
  15415. if (transformed.isSome()) {
  15416. return transformed;
  15417. } else if (stop(el)) {
  15418. break;
  15419. }
  15420. }
  15421. return Optional.none();
  15422. };
  15423. var closest$1 = function (scope, transform, isRoot) {
  15424. var current = transform(scope);
  15425. var stop = ensureIsRoot(isRoot);
  15426. return current.orThunk(function () {
  15427. return stop(scope) ? Optional.none() : ancestor(scope, transform, stop);
  15428. });
  15429. };
  15430. var isEq$3 = isEq$5;
  15431. var matchesUnInheritedFormatSelector = function (ed, node, name) {
  15432. var formatList = ed.formatter.get(name);
  15433. if (formatList) {
  15434. for (var i = 0; i < formatList.length; i++) {
  15435. var format = formatList[i];
  15436. if (isSelectorFormat(format) && format.inherit === false && ed.dom.is(node, format.selector)) {
  15437. return true;
  15438. }
  15439. }
  15440. }
  15441. return false;
  15442. };
  15443. var matchParents = function (editor, node, name, vars, similar) {
  15444. var root = editor.dom.getRoot();
  15445. if (node === root) {
  15446. return false;
  15447. }
  15448. node = editor.dom.getParent(node, function (node) {
  15449. if (matchesUnInheritedFormatSelector(editor, node, name)) {
  15450. return true;
  15451. }
  15452. return node.parentNode === root || !!matchNode(editor, node, name, vars, true);
  15453. });
  15454. return !!matchNode(editor, node, name, vars, similar);
  15455. };
  15456. var matchName$1 = function (dom, node, format) {
  15457. if (isEq$3(node, format.inline)) {
  15458. return true;
  15459. }
  15460. if (isEq$3(node, format.block)) {
  15461. return true;
  15462. }
  15463. if (format.selector) {
  15464. return node.nodeType === 1 && dom.is(node, format.selector);
  15465. }
  15466. };
  15467. var matchItems = function (dom, node, format, itemName, similar, vars) {
  15468. var items = format[itemName];
  15469. if (isFunction(format.onmatch)) {
  15470. return format.onmatch(node, format, itemName);
  15471. }
  15472. if (items) {
  15473. if (isUndefined(items.length)) {
  15474. for (var key in items) {
  15475. if (has$2(items, key)) {
  15476. var value = itemName === 'attributes' ? dom.getAttrib(node, key) : getStyle(dom, node, key);
  15477. var expectedValue = replaceVars(items[key], vars);
  15478. var isEmptyValue = isNullable(value) || isEmpty$3(value);
  15479. if (isEmptyValue && isNullable(expectedValue)) {
  15480. continue;
  15481. }
  15482. if (similar && isEmptyValue && !format.exact) {
  15483. return false;
  15484. }
  15485. if ((!similar || format.exact) && !isEq$3(value, normalizeStyleValue(dom, expectedValue, key))) {
  15486. return false;
  15487. }
  15488. }
  15489. }
  15490. } else {
  15491. for (var i = 0; i < items.length; i++) {
  15492. if (itemName === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(dom, node, items[i])) {
  15493. return true;
  15494. }
  15495. }
  15496. }
  15497. }
  15498. return true;
  15499. };
  15500. var matchNode = function (ed, node, name, vars, similar) {
  15501. var formatList = ed.formatter.get(name);
  15502. var dom = ed.dom;
  15503. if (formatList && node) {
  15504. for (var i = 0; i < formatList.length; i++) {
  15505. var format = formatList[i];
  15506. if (matchName$1(ed.dom, node, format) && matchItems(dom, node, format, 'attributes', similar, vars) && matchItems(dom, node, format, 'styles', similar, vars)) {
  15507. var classes = format.classes;
  15508. if (classes) {
  15509. for (var x = 0; x < classes.length; x++) {
  15510. if (!ed.dom.hasClass(node, replaceVars(classes[x], vars))) {
  15511. return;
  15512. }
  15513. }
  15514. }
  15515. return format;
  15516. }
  15517. }
  15518. }
  15519. };
  15520. var match$2 = function (editor, name, vars, node, similar) {
  15521. if (node) {
  15522. return matchParents(editor, node, name, vars, similar);
  15523. }
  15524. node = editor.selection.getNode();
  15525. if (matchParents(editor, node, name, vars, similar)) {
  15526. return true;
  15527. }
  15528. var startNode = editor.selection.getStart();
  15529. if (startNode !== node) {
  15530. if (matchParents(editor, startNode, name, vars, similar)) {
  15531. return true;
  15532. }
  15533. }
  15534. return false;
  15535. };
  15536. var matchAll = function (editor, names, vars) {
  15537. var matchedFormatNames = [];
  15538. var checkedMap = {};
  15539. var startElement = editor.selection.getStart();
  15540. editor.dom.getParent(startElement, function (node) {
  15541. for (var i = 0; i < names.length; i++) {
  15542. var name_1 = names[i];
  15543. if (!checkedMap[name_1] && matchNode(editor, node, name_1, vars)) {
  15544. checkedMap[name_1] = true;
  15545. matchedFormatNames.push(name_1);
  15546. }
  15547. }
  15548. }, editor.dom.getRoot());
  15549. return matchedFormatNames;
  15550. };
  15551. var closest = function (editor, names) {
  15552. var isRoot = function (elm) {
  15553. return eq(elm, SugarElement.fromDom(editor.getBody()));
  15554. };
  15555. var match = function (elm, name) {
  15556. return matchNode(editor, elm.dom, name) ? Optional.some(name) : Optional.none();
  15557. };
  15558. return Optional.from(editor.selection.getStart(true)).bind(function (rawElm) {
  15559. return closest$1(SugarElement.fromDom(rawElm), function (elm) {
  15560. return findMap(names, function (name) {
  15561. return match(elm, name);
  15562. });
  15563. }, isRoot);
  15564. }).getOrNull();
  15565. };
  15566. var canApply = function (editor, name) {
  15567. var formatList = editor.formatter.get(name);
  15568. var dom = editor.dom;
  15569. if (formatList) {
  15570. var startNode = editor.selection.getStart();
  15571. var parents = getParents$2(dom, startNode);
  15572. for (var x = formatList.length - 1; x >= 0; x--) {
  15573. var format = formatList[x];
  15574. if (!isSelectorFormat(format) || isNonNullable(format.defaultBlock)) {
  15575. return true;
  15576. }
  15577. for (var i = parents.length - 1; i >= 0; i--) {
  15578. if (dom.is(parents[i], format.selector)) {
  15579. return true;
  15580. }
  15581. }
  15582. }
  15583. }
  15584. return false;
  15585. };
  15586. var matchAllOnNode = function (editor, node, formatNames) {
  15587. return foldl(formatNames, function (acc, name) {
  15588. var matchSimilar = isVariableFormatName(editor, name);
  15589. if (editor.formatter.matchNode(node, name, {}, matchSimilar)) {
  15590. return acc.concat([name]);
  15591. } else {
  15592. return acc;
  15593. }
  15594. }, []);
  15595. };
  15596. var ZWSP = ZWSP$1, CARET_ID = '_mce_caret';
  15597. var importNode = function (ownerDocument, node) {
  15598. return ownerDocument.importNode(node, true);
  15599. };
  15600. var getEmptyCaretContainers = function (node) {
  15601. var nodes = [];
  15602. while (node) {
  15603. if (node.nodeType === 3 && node.nodeValue !== ZWSP || node.childNodes.length > 1) {
  15604. return [];
  15605. }
  15606. if (node.nodeType === 1) {
  15607. nodes.push(node);
  15608. }
  15609. node = node.firstChild;
  15610. }
  15611. return nodes;
  15612. };
  15613. var isCaretContainerEmpty = function (node) {
  15614. return getEmptyCaretContainers(node).length > 0;
  15615. };
  15616. var findFirstTextNode = function (node) {
  15617. if (node) {
  15618. var walker = new DomTreeWalker(node, node);
  15619. for (node = walker.current(); node; node = walker.next()) {
  15620. if (isText$7(node)) {
  15621. return node;
  15622. }
  15623. }
  15624. }
  15625. return null;
  15626. };
  15627. var createCaretContainer = function (fill) {
  15628. var caretContainer = SugarElement.fromTag('span');
  15629. setAll$1(caretContainer, {
  15630. 'id': CARET_ID,
  15631. 'data-mce-bogus': '1',
  15632. 'data-mce-type': 'format-caret'
  15633. });
  15634. if (fill) {
  15635. append$1(caretContainer, SugarElement.fromText(ZWSP));
  15636. }
  15637. return caretContainer;
  15638. };
  15639. var trimZwspFromCaretContainer = function (caretContainerNode) {
  15640. var textNode = findFirstTextNode(caretContainerNode);
  15641. if (textNode && textNode.nodeValue.charAt(0) === ZWSP) {
  15642. textNode.deleteData(0, 1);
  15643. }
  15644. return textNode;
  15645. };
  15646. var removeCaretContainerNode = function (editor, node, moveCaret) {
  15647. if (moveCaret === void 0) {
  15648. moveCaret = true;
  15649. }
  15650. var dom = editor.dom, selection = editor.selection;
  15651. if (isCaretContainerEmpty(node)) {
  15652. deleteElement$2(editor, false, SugarElement.fromDom(node), moveCaret);
  15653. } else {
  15654. var rng = selection.getRng();
  15655. var block = dom.getParent(node, dom.isBlock);
  15656. var startContainer = rng.startContainer;
  15657. var startOffset = rng.startOffset;
  15658. var endContainer = rng.endContainer;
  15659. var endOffset = rng.endOffset;
  15660. var textNode = trimZwspFromCaretContainer(node);
  15661. dom.remove(node, true);
  15662. if (startContainer === textNode && startOffset > 0) {
  15663. rng.setStart(textNode, startOffset - 1);
  15664. }
  15665. if (endContainer === textNode && endOffset > 0) {
  15666. rng.setEnd(textNode, endOffset - 1);
  15667. }
  15668. if (block && dom.isEmpty(block)) {
  15669. fillWithPaddingBr(SugarElement.fromDom(block));
  15670. }
  15671. selection.setRng(rng);
  15672. }
  15673. };
  15674. var removeCaretContainer = function (editor, node, moveCaret) {
  15675. if (moveCaret === void 0) {
  15676. moveCaret = true;
  15677. }
  15678. var dom = editor.dom, selection = editor.selection;
  15679. if (!node) {
  15680. node = getParentCaretContainer(editor.getBody(), selection.getStart());
  15681. if (!node) {
  15682. while (node = dom.get(CARET_ID)) {
  15683. removeCaretContainerNode(editor, node, false);
  15684. }
  15685. }
  15686. } else {
  15687. removeCaretContainerNode(editor, node, moveCaret);
  15688. }
  15689. };
  15690. var insertCaretContainerNode = function (editor, caretContainer, formatNode) {
  15691. var dom = editor.dom, block = dom.getParent(formatNode, curry(isTextBlock$1, editor));
  15692. if (block && dom.isEmpty(block)) {
  15693. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15694. } else {
  15695. removeTrailingBr(SugarElement.fromDom(formatNode));
  15696. if (dom.isEmpty(formatNode)) {
  15697. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15698. } else {
  15699. dom.insertAfter(caretContainer, formatNode);
  15700. }
  15701. }
  15702. };
  15703. var appendNode = function (parentNode, node) {
  15704. parentNode.appendChild(node);
  15705. return node;
  15706. };
  15707. var insertFormatNodesIntoCaretContainer = function (formatNodes, caretContainer) {
  15708. var innerMostFormatNode = foldr(formatNodes, function (parentNode, formatNode) {
  15709. return appendNode(parentNode, formatNode.cloneNode(false));
  15710. }, caretContainer);
  15711. return appendNode(innerMostFormatNode, innerMostFormatNode.ownerDocument.createTextNode(ZWSP));
  15712. };
  15713. var cleanFormatNode = function (editor, caretContainer, formatNode, name, vars, similar) {
  15714. var formatter = editor.formatter;
  15715. var dom = editor.dom;
  15716. var validFormats = filter$4(keys(formatter.get()), function (formatName) {
  15717. return formatName !== name && !contains$2(formatName, 'removeformat');
  15718. });
  15719. var matchedFormats = matchAllOnNode(editor, formatNode, validFormats);
  15720. var uniqueFormats = filter$4(matchedFormats, function (fmtName) {
  15721. return !areSimilarFormats(editor, fmtName, name);
  15722. });
  15723. if (uniqueFormats.length > 0) {
  15724. var clonedFormatNode = formatNode.cloneNode(false);
  15725. dom.add(caretContainer, clonedFormatNode);
  15726. formatter.remove(name, vars, clonedFormatNode, similar);
  15727. dom.remove(clonedFormatNode);
  15728. return Optional.some(clonedFormatNode);
  15729. } else {
  15730. return Optional.none();
  15731. }
  15732. };
  15733. var applyCaretFormat = function (editor, name, vars) {
  15734. var caretContainer, textNode;
  15735. var selection = editor.selection;
  15736. var selectionRng = selection.getRng();
  15737. var offset = selectionRng.startOffset;
  15738. var container = selectionRng.startContainer;
  15739. var text = container.nodeValue;
  15740. caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
  15741. if (caretContainer) {
  15742. textNode = findFirstTextNode(caretContainer);
  15743. }
  15744. var wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
  15745. if (text && offset > 0 && offset < text.length && wordcharRegex.test(text.charAt(offset)) && wordcharRegex.test(text.charAt(offset - 1))) {
  15746. var bookmark = selection.getBookmark();
  15747. selectionRng.collapse(true);
  15748. var rng = expandRng(editor, selectionRng, editor.formatter.get(name));
  15749. rng = split(rng);
  15750. editor.formatter.apply(name, vars, rng);
  15751. selection.moveToBookmark(bookmark);
  15752. } else {
  15753. if (!caretContainer || textNode.nodeValue !== ZWSP) {
  15754. caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom);
  15755. textNode = caretContainer.firstChild;
  15756. selectionRng.insertNode(caretContainer);
  15757. offset = 1;
  15758. editor.formatter.apply(name, vars, caretContainer);
  15759. } else {
  15760. editor.formatter.apply(name, vars, caretContainer);
  15761. }
  15762. selection.setCursorLocation(textNode, offset);
  15763. }
  15764. };
  15765. var removeCaretFormat = function (editor, name, vars, similar) {
  15766. var dom = editor.dom;
  15767. var selection = editor.selection;
  15768. var hasContentAfter, node, formatNode;
  15769. var parents = [];
  15770. var rng = selection.getRng();
  15771. var container = rng.startContainer;
  15772. var offset = rng.startOffset;
  15773. node = container;
  15774. if (container.nodeType === 3) {
  15775. if (offset !== container.nodeValue.length) {
  15776. hasContentAfter = true;
  15777. }
  15778. node = node.parentNode;
  15779. }
  15780. while (node) {
  15781. if (matchNode(editor, node, name, vars, similar)) {
  15782. formatNode = node;
  15783. break;
  15784. }
  15785. if (node.nextSibling) {
  15786. hasContentAfter = true;
  15787. }
  15788. parents.push(node);
  15789. node = node.parentNode;
  15790. }
  15791. if (!formatNode) {
  15792. return;
  15793. }
  15794. if (hasContentAfter) {
  15795. var bookmark = selection.getBookmark();
  15796. rng.collapse(true);
  15797. var expandedRng = expandRng(editor, rng, editor.formatter.get(name), true);
  15798. expandedRng = split(expandedRng);
  15799. editor.formatter.remove(name, vars, expandedRng, similar);
  15800. selection.moveToBookmark(bookmark);
  15801. } else {
  15802. var caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
  15803. var newCaretContainer = createCaretContainer(false).dom;
  15804. insertCaretContainerNode(editor, newCaretContainer, caretContainer !== null ? caretContainer : formatNode);
  15805. var cleanedFormatNode = cleanFormatNode(editor, newCaretContainer, formatNode, name, vars, similar);
  15806. var caretTextNode = insertFormatNodesIntoCaretContainer(parents.concat(cleanedFormatNode.toArray()), newCaretContainer);
  15807. removeCaretContainerNode(editor, caretContainer, false);
  15808. selection.setCursorLocation(caretTextNode, 1);
  15809. if (dom.isEmpty(formatNode)) {
  15810. dom.remove(formatNode);
  15811. }
  15812. }
  15813. };
  15814. var disableCaretContainer = function (editor, keyCode) {
  15815. var selection = editor.selection, body = editor.getBody();
  15816. removeCaretContainer(editor, null, false);
  15817. if ((keyCode === 8 || keyCode === 46) && selection.isCollapsed() && selection.getStart().innerHTML === ZWSP) {
  15818. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15819. }
  15820. if (keyCode === 37 || keyCode === 39) {
  15821. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15822. }
  15823. };
  15824. var setup$k = function (editor) {
  15825. editor.on('mouseup keydown', function (e) {
  15826. disableCaretContainer(editor, e.keyCode);
  15827. });
  15828. };
  15829. var replaceWithCaretFormat = function (targetNode, formatNodes) {
  15830. var caretContainer = createCaretContainer(false);
  15831. var innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom);
  15832. before$4(SugarElement.fromDom(targetNode), caretContainer);
  15833. remove$7(SugarElement.fromDom(targetNode));
  15834. return CaretPosition(innerMost, 0);
  15835. };
  15836. var isFormatElement = function (editor, element) {
  15837. var inlineElements = editor.schema.getTextInlineElements();
  15838. return has$2(inlineElements, name(element)) && !isCaretNode(element.dom) && !isBogus$2(element.dom);
  15839. };
  15840. var isEmptyCaretFormatElement = function (element) {
  15841. return isCaretNode(element.dom) && isCaretContainerEmpty(element.dom);
  15842. };
  15843. var postProcessHooks = {};
  15844. var filter = filter$2;
  15845. var each$c = each$i;
  15846. var addPostProcessHook = function (name, hook) {
  15847. var hooks = postProcessHooks[name];
  15848. if (!hooks) {
  15849. postProcessHooks[name] = [];
  15850. }
  15851. postProcessHooks[name].push(hook);
  15852. };
  15853. var postProcess$1 = function (name, editor) {
  15854. each$c(postProcessHooks[name], function (hook) {
  15855. hook(editor);
  15856. });
  15857. };
  15858. addPostProcessHook('pre', function (editor) {
  15859. var rng = editor.selection.getRng();
  15860. var blocks;
  15861. var hasPreSibling = function (pre) {
  15862. return isPre(pre.previousSibling) && indexOf$1(blocks, pre.previousSibling) !== -1;
  15863. };
  15864. var joinPre = function (pre1, pre2) {
  15865. DomQuery(pre2).remove();
  15866. DomQuery(pre1).append('<br><br>').append(pre2.childNodes);
  15867. };
  15868. var isPre = matchNodeNames(['pre']);
  15869. if (!rng.collapsed) {
  15870. blocks = editor.selection.getSelectedBlocks();
  15871. each$c(filter(filter(blocks, isPre), hasPreSibling), function (pre) {
  15872. joinPre(pre.previousSibling, pre);
  15873. });
  15874. }
  15875. });
  15876. var each$b = Tools.each;
  15877. var isElementNode$1 = function (node) {
  15878. return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  15879. };
  15880. var findElementSibling = function (node, siblingName) {
  15881. for (var sibling = node; sibling; sibling = sibling[siblingName]) {
  15882. if (isText$7(sibling) && isNotEmpty(sibling.data)) {
  15883. return node;
  15884. }
  15885. if (isElement$5(sibling) && !isBookmarkNode$1(sibling)) {
  15886. return sibling;
  15887. }
  15888. }
  15889. return node;
  15890. };
  15891. var mergeSiblingsNodes = function (dom, prev, next) {
  15892. var elementUtils = ElementUtils(dom);
  15893. if (prev && next) {
  15894. prev = findElementSibling(prev, 'previousSibling');
  15895. next = findElementSibling(next, 'nextSibling');
  15896. if (elementUtils.compare(prev, next)) {
  15897. for (var sibling = prev.nextSibling; sibling && sibling !== next;) {
  15898. var tmpSibling = sibling;
  15899. sibling = sibling.nextSibling;
  15900. prev.appendChild(tmpSibling);
  15901. }
  15902. dom.remove(next);
  15903. Tools.each(Tools.grep(next.childNodes), function (node) {
  15904. prev.appendChild(node);
  15905. });
  15906. return prev;
  15907. }
  15908. }
  15909. return next;
  15910. };
  15911. var mergeSiblings = function (dom, format, vars, node) {
  15912. if (node && format.merge_siblings !== false) {
  15913. var newNode = mergeSiblingsNodes(dom, getNonWhiteSpaceSibling(node), node);
  15914. mergeSiblingsNodes(dom, newNode, getNonWhiteSpaceSibling(newNode, true));
  15915. }
  15916. };
  15917. var clearChildStyles = function (dom, format, node) {
  15918. if (format.clear_child_styles) {
  15919. var selector = format.links ? '*:not(a)' : '*';
  15920. each$b(dom.select(selector, node), function (node) {
  15921. if (isElementNode$1(node)) {
  15922. each$b(format.styles, function (value, name) {
  15923. dom.setStyle(node, name, '');
  15924. });
  15925. }
  15926. });
  15927. }
  15928. };
  15929. var processChildElements = function (node, filter, process) {
  15930. each$b(node.childNodes, function (node) {
  15931. if (isElementNode$1(node)) {
  15932. if (filter(node)) {
  15933. process(node);
  15934. }
  15935. if (node.hasChildNodes()) {
  15936. processChildElements(node, filter, process);
  15937. }
  15938. }
  15939. });
  15940. };
  15941. var unwrapEmptySpan = function (dom, node) {
  15942. if (node.nodeName === 'SPAN' && dom.getAttribs(node).length === 0) {
  15943. dom.remove(node, true);
  15944. }
  15945. };
  15946. var hasStyle = function (dom, name) {
  15947. return function (node) {
  15948. return !!(node && getStyle(dom, node, name));
  15949. };
  15950. };
  15951. var applyStyle = function (dom, name, value) {
  15952. return function (node) {
  15953. dom.setStyle(node, name, value);
  15954. if (node.getAttribute('style') === '') {
  15955. node.removeAttribute('style');
  15956. }
  15957. unwrapEmptySpan(dom, node);
  15958. };
  15959. };
  15960. var removeResult = Adt.generate([
  15961. { keep: [] },
  15962. { rename: ['name'] },
  15963. { removed: [] }
  15964. ]);
  15965. var MCE_ATTR_RE = /^(src|href|style)$/;
  15966. var each$a = Tools.each;
  15967. var isEq$2 = isEq$5;
  15968. var isTableCellOrRow = function (node) {
  15969. return /^(TR|TH|TD)$/.test(node.nodeName);
  15970. };
  15971. var isChildOfInlineParent = function (dom, node, parent) {
  15972. return dom.isChildOf(node, parent) && node !== parent && !dom.isBlock(parent);
  15973. };
  15974. var getContainer = function (ed, rng, start) {
  15975. var container = rng[start ? 'startContainer' : 'endContainer'];
  15976. var offset = rng[start ? 'startOffset' : 'endOffset'];
  15977. if (isElement$5(container)) {
  15978. var lastIdx = container.childNodes.length - 1;
  15979. if (!start && offset) {
  15980. offset--;
  15981. }
  15982. container = container.childNodes[offset > lastIdx ? lastIdx : offset];
  15983. }
  15984. if (isText$7(container) && start && offset >= container.nodeValue.length) {
  15985. container = new DomTreeWalker(container, ed.getBody()).next() || container;
  15986. }
  15987. if (isText$7(container) && !start && offset === 0) {
  15988. container = new DomTreeWalker(container, ed.getBody()).prev() || container;
  15989. }
  15990. return container;
  15991. };
  15992. var normalizeTableSelection = function (node, start) {
  15993. var prop = start ? 'firstChild' : 'lastChild';
  15994. if (isTableCellOrRow(node) && node[prop]) {
  15995. var childNode = node[prop];
  15996. if (node.nodeName === 'TR') {
  15997. return childNode[prop] || childNode;
  15998. } else {
  15999. return childNode;
  16000. }
  16001. }
  16002. return node;
  16003. };
  16004. var wrap$1 = function (dom, node, name, attrs) {
  16005. var wrapper = dom.create(name, attrs);
  16006. node.parentNode.insertBefore(wrapper, node);
  16007. wrapper.appendChild(node);
  16008. return wrapper;
  16009. };
  16010. var wrapWithSiblings = function (dom, node, next, name, attrs) {
  16011. var start = SugarElement.fromDom(node);
  16012. var wrapper = SugarElement.fromDom(dom.create(name, attrs));
  16013. var siblings = next ? nextSiblings(start) : prevSiblings(start);
  16014. append(wrapper, siblings);
  16015. if (next) {
  16016. before$4(start, wrapper);
  16017. prepend(wrapper, start);
  16018. } else {
  16019. after$3(start, wrapper);
  16020. append$1(wrapper, start);
  16021. }
  16022. return wrapper.dom;
  16023. };
  16024. var matchName = function (dom, node, format) {
  16025. if (isInlineFormat(format) && isEq$2(node, format.inline)) {
  16026. return true;
  16027. }
  16028. if (isBlockFormat(format) && isEq$2(node, format.block)) {
  16029. return true;
  16030. }
  16031. if (isSelectorFormat(format)) {
  16032. return isElement$5(node) && dom.is(node, format.selector);
  16033. }
  16034. };
  16035. var isColorFormatAndAnchor = function (node, format) {
  16036. return format.links && node.nodeName === 'A';
  16037. };
  16038. var find = function (dom, node, next, inc) {
  16039. var sibling = getNonWhiteSpaceSibling(node, next, inc);
  16040. return isNullable(sibling) || sibling.nodeName === 'BR' || dom.isBlock(sibling);
  16041. };
  16042. var removeNode = function (ed, node, format) {
  16043. var parentNode = node.parentNode;
  16044. var rootBlockElm;
  16045. var dom = ed.dom, forcedRootBlock = getForcedRootBlock(ed);
  16046. if (isBlockFormat(format)) {
  16047. if (!forcedRootBlock) {
  16048. if (dom.isBlock(node) && !dom.isBlock(parentNode)) {
  16049. if (!find(dom, node, false) && !find(dom, node.firstChild, true, true)) {
  16050. node.insertBefore(dom.create('br'), node.firstChild);
  16051. }
  16052. if (!find(dom, node, true) && !find(dom, node.lastChild, false, true)) {
  16053. node.appendChild(dom.create('br'));
  16054. }
  16055. }
  16056. } else {
  16057. if (parentNode === dom.getRoot()) {
  16058. if (!format.list_block || !isEq$2(node, format.list_block)) {
  16059. each$k(from(node.childNodes), function (node) {
  16060. if (isValid(ed, forcedRootBlock, node.nodeName.toLowerCase())) {
  16061. if (!rootBlockElm) {
  16062. rootBlockElm = wrap$1(dom, node, forcedRootBlock);
  16063. dom.setAttribs(rootBlockElm, ed.settings.forced_root_block_attrs);
  16064. } else {
  16065. rootBlockElm.appendChild(node);
  16066. }
  16067. } else {
  16068. rootBlockElm = null;
  16069. }
  16070. });
  16071. }
  16072. }
  16073. }
  16074. }
  16075. if (isMixedFormat(format) && !isEq$2(format.inline, node)) {
  16076. return;
  16077. }
  16078. dom.remove(node, true);
  16079. };
  16080. var removeFormatInternal = function (ed, format, vars, node, compareNode) {
  16081. var stylesModified;
  16082. var dom = ed.dom;
  16083. if (!matchName(dom, node, format) && !isColorFormatAndAnchor(node, format)) {
  16084. return removeResult.keep();
  16085. }
  16086. var elm = node;
  16087. if (isInlineFormat(format) && format.remove === 'all' && isArray$1(format.preserve_attributes)) {
  16088. var attrsToPreserve = filter$4(dom.getAttribs(elm), function (attr) {
  16089. return contains$3(format.preserve_attributes, attr.name.toLowerCase());
  16090. });
  16091. dom.removeAllAttribs(elm);
  16092. each$k(attrsToPreserve, function (attr) {
  16093. return dom.setAttrib(elm, attr.name, attr.value);
  16094. });
  16095. if (attrsToPreserve.length > 0) {
  16096. return removeResult.rename('span');
  16097. }
  16098. }
  16099. if (format.remove !== 'all') {
  16100. each$a(format.styles, function (value, name) {
  16101. value = normalizeStyleValue(dom, replaceVars(value, vars), name + '');
  16102. if (isNumber(name)) {
  16103. name = value;
  16104. compareNode = null;
  16105. }
  16106. if (format.remove_similar || (!compareNode || isEq$2(getStyle(dom, compareNode, name), value))) {
  16107. dom.setStyle(elm, name, '');
  16108. }
  16109. stylesModified = true;
  16110. });
  16111. if (stylesModified && dom.getAttrib(elm, 'style') === '') {
  16112. elm.removeAttribute('style');
  16113. elm.removeAttribute('data-mce-style');
  16114. }
  16115. each$a(format.attributes, function (value, name) {
  16116. var valueOut;
  16117. value = replaceVars(value, vars);
  16118. if (isNumber(name)) {
  16119. name = value;
  16120. compareNode = null;
  16121. }
  16122. if (format.remove_similar || (!compareNode || isEq$2(dom.getAttrib(compareNode, name), value))) {
  16123. if (name === 'class') {
  16124. value = dom.getAttrib(elm, name);
  16125. if (value) {
  16126. valueOut = '';
  16127. each$k(value.split(/\s+/), function (cls) {
  16128. if (/mce\-\w+/.test(cls)) {
  16129. valueOut += (valueOut ? ' ' : '') + cls;
  16130. }
  16131. });
  16132. if (valueOut) {
  16133. dom.setAttrib(elm, name, valueOut);
  16134. return;
  16135. }
  16136. }
  16137. }
  16138. if (MCE_ATTR_RE.test(name)) {
  16139. elm.removeAttribute('data-mce-' + name);
  16140. }
  16141. if (name === 'style' && matchNodeNames(['li'])(elm) && dom.getStyle(elm, 'list-style-type') === 'none') {
  16142. elm.removeAttribute(name);
  16143. dom.setStyle(elm, 'list-style-type', 'none');
  16144. return;
  16145. }
  16146. if (name === 'class') {
  16147. elm.removeAttribute('className');
  16148. }
  16149. elm.removeAttribute(name);
  16150. }
  16151. });
  16152. each$a(format.classes, function (value) {
  16153. value = replaceVars(value, vars);
  16154. if (!compareNode || dom.hasClass(compareNode, value)) {
  16155. dom.removeClass(elm, value);
  16156. }
  16157. });
  16158. var attrs = dom.getAttribs(elm);
  16159. for (var i = 0; i < attrs.length; i++) {
  16160. var attrName = attrs[i].nodeName;
  16161. if (attrName.indexOf('_') !== 0 && attrName.indexOf('data-') !== 0) {
  16162. return removeResult.keep();
  16163. }
  16164. }
  16165. }
  16166. if (format.remove !== 'none') {
  16167. removeNode(ed, elm, format);
  16168. return removeResult.removed();
  16169. }
  16170. return removeResult.keep();
  16171. };
  16172. var removeFormat$1 = function (ed, format, vars, node, compareNode) {
  16173. return removeFormatInternal(ed, format, vars, node, compareNode).fold(never, function (newName) {
  16174. ed.dom.rename(node, newName);
  16175. return true;
  16176. }, always);
  16177. };
  16178. var findFormatRoot = function (editor, container, name, vars, similar) {
  16179. var formatRoot;
  16180. each$k(getParents$2(editor.dom, container.parentNode).reverse(), function (parent) {
  16181. if (!formatRoot && parent.id !== '_start' && parent.id !== '_end') {
  16182. var format = matchNode(editor, parent, name, vars, similar);
  16183. if (format && format.split !== false) {
  16184. formatRoot = parent;
  16185. }
  16186. }
  16187. });
  16188. return formatRoot;
  16189. };
  16190. var removeFormatFromClone = function (editor, format, vars, clone) {
  16191. return removeFormatInternal(editor, format, vars, clone, clone).fold(constant(clone), function (newName) {
  16192. var fragment = editor.dom.createFragment();
  16193. fragment.appendChild(clone);
  16194. return editor.dom.rename(clone, newName);
  16195. }, constant(null));
  16196. };
  16197. var wrapAndSplit = function (editor, formatList, formatRoot, container, target, split, format, vars) {
  16198. var clone, lastClone, firstClone;
  16199. var dom = editor.dom;
  16200. if (formatRoot) {
  16201. var formatRootParent = formatRoot.parentNode;
  16202. for (var parent_1 = container.parentNode; parent_1 && parent_1 !== formatRootParent; parent_1 = parent_1.parentNode) {
  16203. clone = dom.clone(parent_1, false);
  16204. for (var i = 0; i < formatList.length; i++) {
  16205. clone = removeFormatFromClone(editor, formatList[i], vars, clone);
  16206. if (clone === null) {
  16207. break;
  16208. }
  16209. }
  16210. if (clone) {
  16211. if (lastClone) {
  16212. clone.appendChild(lastClone);
  16213. }
  16214. if (!firstClone) {
  16215. firstClone = clone;
  16216. }
  16217. lastClone = clone;
  16218. }
  16219. }
  16220. if (split && (!format.mixed || !dom.isBlock(formatRoot))) {
  16221. container = dom.split(formatRoot, container);
  16222. }
  16223. if (lastClone) {
  16224. target.parentNode.insertBefore(lastClone, target);
  16225. firstClone.appendChild(target);
  16226. if (isInlineFormat(format)) {
  16227. mergeSiblings(dom, format, vars, lastClone);
  16228. }
  16229. }
  16230. }
  16231. return container;
  16232. };
  16233. var remove$1 = function (ed, name, vars, node, similar) {
  16234. var formatList = ed.formatter.get(name);
  16235. var format = formatList[0];
  16236. var contentEditable = true;
  16237. var dom = ed.dom;
  16238. var selection = ed.selection;
  16239. var splitToFormatRoot = function (container) {
  16240. var formatRoot = findFormatRoot(ed, container, name, vars, similar);
  16241. return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format, vars);
  16242. };
  16243. var isRemoveBookmarkNode = function (node) {
  16244. return isBookmarkNode$1(node) && isElement$5(node) && (node.id === '_start' || node.id === '_end');
  16245. };
  16246. var removeNodeFormat = function (node) {
  16247. return exists(formatList, function (fmt) {
  16248. return removeFormat$1(ed, fmt, vars, node, node);
  16249. });
  16250. };
  16251. var process = function (node) {
  16252. var lastContentEditable = true;
  16253. var hasContentEditableState = false;
  16254. if (isElement$5(node) && dom.getContentEditable(node)) {
  16255. lastContentEditable = contentEditable;
  16256. contentEditable = dom.getContentEditable(node) === 'true';
  16257. hasContentEditableState = true;
  16258. }
  16259. var children = from(node.childNodes);
  16260. if (contentEditable && !hasContentEditableState) {
  16261. var removed = removeNodeFormat(node);
  16262. var parentNode = node.parentNode;
  16263. if (!removed && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  16264. removeNodeFormat(parentNode);
  16265. }
  16266. }
  16267. if (format.deep) {
  16268. if (children.length) {
  16269. for (var i = 0; i < children.length; i++) {
  16270. process(children[i]);
  16271. }
  16272. if (hasContentEditableState) {
  16273. contentEditable = lastContentEditable;
  16274. }
  16275. }
  16276. }
  16277. var textDecorations = [
  16278. 'underline',
  16279. 'line-through',
  16280. 'overline'
  16281. ];
  16282. each$k(textDecorations, function (decoration) {
  16283. if (isElement$5(node) && ed.dom.getStyle(node, 'text-decoration') === decoration && node.parentNode && getTextDecoration(dom, node.parentNode) === decoration) {
  16284. removeFormat$1(ed, {
  16285. deep: false,
  16286. exact: true,
  16287. inline: 'span',
  16288. styles: { textDecoration: decoration }
  16289. }, null, node);
  16290. }
  16291. });
  16292. };
  16293. var unwrap = function (start) {
  16294. var node = dom.get(start ? '_start' : '_end');
  16295. var out = node[start ? 'firstChild' : 'lastChild'];
  16296. if (isRemoveBookmarkNode(out)) {
  16297. out = out[start ? 'firstChild' : 'lastChild'];
  16298. }
  16299. if (isText$7(out) && out.data.length === 0) {
  16300. out = start ? node.previousSibling || node.nextSibling : node.nextSibling || node.previousSibling;
  16301. }
  16302. dom.remove(node, true);
  16303. return out;
  16304. };
  16305. var removeRngStyle = function (rng) {
  16306. var startContainer, endContainer;
  16307. var expandedRng = expandRng(ed, rng, formatList, rng.collapsed);
  16308. if (format.split) {
  16309. expandedRng = split(expandedRng);
  16310. startContainer = getContainer(ed, expandedRng, true);
  16311. endContainer = getContainer(ed, expandedRng);
  16312. if (startContainer !== endContainer) {
  16313. startContainer = normalizeTableSelection(startContainer, true);
  16314. endContainer = normalizeTableSelection(endContainer, false);
  16315. if (isChildOfInlineParent(dom, startContainer, endContainer)) {
  16316. var marker = Optional.from(startContainer.firstChild).getOr(startContainer);
  16317. splitToFormatRoot(wrapWithSiblings(dom, marker, true, 'span', {
  16318. 'id': '_start',
  16319. 'data-mce-type': 'bookmark'
  16320. }));
  16321. unwrap(true);
  16322. return;
  16323. }
  16324. if (isChildOfInlineParent(dom, endContainer, startContainer)) {
  16325. var marker = Optional.from(endContainer.lastChild).getOr(endContainer);
  16326. splitToFormatRoot(wrapWithSiblings(dom, marker, false, 'span', {
  16327. 'id': '_end',
  16328. 'data-mce-type': 'bookmark'
  16329. }));
  16330. unwrap(false);
  16331. return;
  16332. }
  16333. startContainer = wrap$1(dom, startContainer, 'span', {
  16334. 'id': '_start',
  16335. 'data-mce-type': 'bookmark'
  16336. });
  16337. endContainer = wrap$1(dom, endContainer, 'span', {
  16338. 'id': '_end',
  16339. 'data-mce-type': 'bookmark'
  16340. });
  16341. var newRng = dom.createRng();
  16342. newRng.setStartAfter(startContainer);
  16343. newRng.setEndBefore(endContainer);
  16344. walk$2(dom, newRng, function (nodes) {
  16345. each$k(nodes, function (n) {
  16346. if (!isBookmarkNode$1(n) && !isBookmarkNode$1(n.parentNode)) {
  16347. splitToFormatRoot(n);
  16348. }
  16349. });
  16350. });
  16351. splitToFormatRoot(startContainer);
  16352. splitToFormatRoot(endContainer);
  16353. startContainer = unwrap(true);
  16354. endContainer = unwrap();
  16355. } else {
  16356. startContainer = endContainer = splitToFormatRoot(startContainer);
  16357. }
  16358. expandedRng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
  16359. expandedRng.startOffset = dom.nodeIndex(startContainer);
  16360. expandedRng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
  16361. expandedRng.endOffset = dom.nodeIndex(endContainer) + 1;
  16362. }
  16363. walk$2(dom, expandedRng, function (nodes) {
  16364. each$k(nodes, process);
  16365. });
  16366. };
  16367. if (node) {
  16368. if (isNode(node)) {
  16369. var rng = dom.createRng();
  16370. rng.setStartBefore(node);
  16371. rng.setEndAfter(node);
  16372. removeRngStyle(rng);
  16373. } else {
  16374. removeRngStyle(node);
  16375. }
  16376. fireFormatRemove(ed, name, node, vars);
  16377. return;
  16378. }
  16379. if (dom.getContentEditable(selection.getNode()) === 'false') {
  16380. node = selection.getNode();
  16381. for (var i = 0; i < formatList.length; i++) {
  16382. if (formatList[i].ceFalseOverride) {
  16383. if (removeFormat$1(ed, formatList[i], vars, node, node)) {
  16384. break;
  16385. }
  16386. }
  16387. }
  16388. fireFormatRemove(ed, name, node, vars);
  16389. return;
  16390. }
  16391. if (!selection.isCollapsed() || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  16392. preserve(selection, true, function () {
  16393. runOnRanges(ed, removeRngStyle);
  16394. });
  16395. if (isInlineFormat(format) && match$2(ed, name, vars, selection.getStart())) {
  16396. moveStart(dom, selection, selection.getRng());
  16397. }
  16398. ed.nodeChanged();
  16399. } else {
  16400. removeCaretFormat(ed, name, vars, similar);
  16401. }
  16402. fireFormatRemove(ed, name, node, vars);
  16403. };
  16404. var each$9 = Tools.each;
  16405. var mergeTextDecorationsAndColor = function (dom, format, vars, node) {
  16406. var processTextDecorationsAndColor = function (n) {
  16407. if (n.nodeType === 1 && n.parentNode && n.parentNode.nodeType === 1) {
  16408. var textDecoration = getTextDecoration(dom, n.parentNode);
  16409. if (dom.getStyle(n, 'color') && textDecoration) {
  16410. dom.setStyle(n, 'text-decoration', textDecoration);
  16411. } else if (dom.getStyle(n, 'text-decoration') === textDecoration) {
  16412. dom.setStyle(n, 'text-decoration', null);
  16413. }
  16414. }
  16415. };
  16416. if (format.styles && (format.styles.color || format.styles.textDecoration)) {
  16417. Tools.walk(node, processTextDecorationsAndColor, 'childNodes');
  16418. processTextDecorationsAndColor(node);
  16419. }
  16420. };
  16421. var mergeBackgroundColorAndFontSize = function (dom, format, vars, node) {
  16422. if (format.styles && format.styles.backgroundColor) {
  16423. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'backgroundColor', replaceVars(format.styles.backgroundColor, vars)));
  16424. }
  16425. };
  16426. var mergeSubSup = function (dom, format, vars, node) {
  16427. if (isInlineFormat(format) && (format.inline === 'sub' || format.inline === 'sup')) {
  16428. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'fontSize', ''));
  16429. dom.remove(dom.select(format.inline === 'sup' ? 'sub' : 'sup', node), true);
  16430. }
  16431. };
  16432. var mergeWithChildren = function (editor, formatList, vars, node) {
  16433. each$9(formatList, function (format) {
  16434. if (isInlineFormat(format)) {
  16435. each$9(editor.dom.select(format.inline, node), function (child) {
  16436. if (!isElementNode$1(child)) {
  16437. return;
  16438. }
  16439. removeFormat$1(editor, format, vars, child, format.exact ? child : null);
  16440. });
  16441. }
  16442. clearChildStyles(editor.dom, format, node);
  16443. });
  16444. };
  16445. var mergeWithParents = function (editor, format, name, vars, node) {
  16446. if (matchNode(editor, node.parentNode, name, vars)) {
  16447. if (removeFormat$1(editor, format, vars, node)) {
  16448. return;
  16449. }
  16450. }
  16451. if (format.merge_with_parents) {
  16452. editor.dom.getParent(node.parentNode, function (parent) {
  16453. if (matchNode(editor, parent, name, vars)) {
  16454. removeFormat$1(editor, format, vars, node);
  16455. return true;
  16456. }
  16457. });
  16458. }
  16459. };
  16460. var each$8 = Tools.each;
  16461. var isElementNode = function (node) {
  16462. return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  16463. };
  16464. var canFormatBR = function (editor, format, node, parentName) {
  16465. if (canFormatEmptyLines(editor) && isInlineFormat(format)) {
  16466. var validBRParentElements = __assign(__assign({}, editor.schema.getTextBlockElements()), {
  16467. td: {},
  16468. th: {},
  16469. li: {},
  16470. dt: {},
  16471. dd: {},
  16472. figcaption: {},
  16473. caption: {},
  16474. details: {},
  16475. summary: {}
  16476. });
  16477. var hasCaretNodeSibling = sibling(SugarElement.fromDom(node), function (sibling) {
  16478. return isCaretNode(sibling.dom);
  16479. });
  16480. return hasNonNullableKey(validBRParentElements, parentName) && isEmpty$2(SugarElement.fromDom(node.parentNode), false) && !hasCaretNodeSibling;
  16481. } else {
  16482. return false;
  16483. }
  16484. };
  16485. var applyFormat$1 = function (ed, name, vars, node) {
  16486. var formatList = ed.formatter.get(name);
  16487. var format = formatList[0];
  16488. var isCollapsed = !node && ed.selection.isCollapsed();
  16489. var dom = ed.dom;
  16490. var selection = ed.selection;
  16491. var setElementFormat = function (elm, fmt) {
  16492. if (fmt === void 0) {
  16493. fmt = format;
  16494. }
  16495. if (isFunction(fmt.onformat)) {
  16496. fmt.onformat(elm, fmt, vars, node);
  16497. }
  16498. each$8(fmt.styles, function (value, name) {
  16499. dom.setStyle(elm, name, replaceVars(value, vars));
  16500. });
  16501. if (fmt.styles) {
  16502. var styleVal = dom.getAttrib(elm, 'style');
  16503. if (styleVal) {
  16504. dom.setAttrib(elm, 'data-mce-style', styleVal);
  16505. }
  16506. }
  16507. each$8(fmt.attributes, function (value, name) {
  16508. dom.setAttrib(elm, name, replaceVars(value, vars));
  16509. });
  16510. each$8(fmt.classes, function (value) {
  16511. value = replaceVars(value, vars);
  16512. if (!dom.hasClass(elm, value)) {
  16513. dom.addClass(elm, value);
  16514. }
  16515. });
  16516. };
  16517. var applyNodeStyle = function (formatList, node) {
  16518. var found = false;
  16519. each$8(formatList, function (format) {
  16520. if (!isSelectorFormat(format)) {
  16521. return false;
  16522. }
  16523. if (isNonNullable(format.collapsed) && format.collapsed !== isCollapsed) {
  16524. return;
  16525. }
  16526. if (dom.is(node, format.selector) && !isCaretNode(node)) {
  16527. setElementFormat(node, format);
  16528. found = true;
  16529. return false;
  16530. }
  16531. });
  16532. return found;
  16533. };
  16534. var createWrapElement = function (wrapName) {
  16535. if (isString$1(wrapName)) {
  16536. var wrapElm = dom.create(wrapName);
  16537. setElementFormat(wrapElm);
  16538. return wrapElm;
  16539. } else {
  16540. return null;
  16541. }
  16542. };
  16543. var applyRngStyle = function (dom, rng, nodeSpecific) {
  16544. var newWrappers = [];
  16545. var contentEditable = true;
  16546. var wrapName = format.inline || format.block;
  16547. var wrapElm = createWrapElement(wrapName);
  16548. walk$2(dom, rng, function (nodes) {
  16549. var currentWrapElm;
  16550. var process = function (node) {
  16551. var hasContentEditableState = false;
  16552. var lastContentEditable = contentEditable;
  16553. var nodeName = node.nodeName.toLowerCase();
  16554. var parentNode = node.parentNode;
  16555. var parentName = parentNode.nodeName.toLowerCase();
  16556. if (isElement$5(node) && dom.getContentEditable(node)) {
  16557. lastContentEditable = contentEditable;
  16558. contentEditable = dom.getContentEditable(node) === 'true';
  16559. hasContentEditableState = true;
  16560. }
  16561. if (isBr$5(node) && !canFormatBR(ed, format, node, parentName)) {
  16562. currentWrapElm = null;
  16563. if (isBlockFormat(format)) {
  16564. dom.remove(node);
  16565. }
  16566. return;
  16567. }
  16568. if (isBlockFormat(format) && format.wrapper && matchNode(ed, node, name, vars)) {
  16569. currentWrapElm = null;
  16570. return;
  16571. }
  16572. if (contentEditable && !hasContentEditableState && isBlockFormat(format) && !format.wrapper && isTextBlock$1(ed, nodeName) && isValid(ed, parentName, wrapName)) {
  16573. var elm = dom.rename(node, wrapName);
  16574. setElementFormat(elm);
  16575. newWrappers.push(elm);
  16576. currentWrapElm = null;
  16577. return;
  16578. }
  16579. if (isSelectorFormat(format)) {
  16580. var found = applyNodeStyle(formatList, node);
  16581. if (!found && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  16582. found = applyNodeStyle(formatList, parentNode);
  16583. }
  16584. if (!isInlineFormat(format) || found) {
  16585. currentWrapElm = null;
  16586. return;
  16587. }
  16588. }
  16589. 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))) {
  16590. if (!currentWrapElm) {
  16591. currentWrapElm = dom.clone(wrapElm, false);
  16592. node.parentNode.insertBefore(currentWrapElm, node);
  16593. newWrappers.push(currentWrapElm);
  16594. }
  16595. currentWrapElm.appendChild(node);
  16596. } else {
  16597. currentWrapElm = null;
  16598. each$k(from(node.childNodes), process);
  16599. if (hasContentEditableState) {
  16600. contentEditable = lastContentEditable;
  16601. }
  16602. currentWrapElm = null;
  16603. }
  16604. };
  16605. each$k(nodes, process);
  16606. });
  16607. if (format.links === true) {
  16608. each$k(newWrappers, function (node) {
  16609. var process = function (node) {
  16610. if (node.nodeName === 'A') {
  16611. setElementFormat(node, format);
  16612. }
  16613. each$k(from(node.childNodes), process);
  16614. };
  16615. process(node);
  16616. });
  16617. }
  16618. each$k(newWrappers, function (node) {
  16619. var getChildCount = function (node) {
  16620. var count = 0;
  16621. each$k(node.childNodes, function (node) {
  16622. if (!isEmptyTextNode$1(node) && !isBookmarkNode$1(node)) {
  16623. count++;
  16624. }
  16625. });
  16626. return count;
  16627. };
  16628. var mergeStyles = function (node) {
  16629. var childElement = find$3(node.childNodes, isElementNode).filter(function (child) {
  16630. return matchName$1(dom, child, format);
  16631. });
  16632. return childElement.map(function (child) {
  16633. var clone = dom.clone(child, false);
  16634. setElementFormat(clone);
  16635. dom.replace(clone, node, true);
  16636. dom.remove(child, true);
  16637. return clone;
  16638. }).getOr(node);
  16639. };
  16640. var childCount = getChildCount(node);
  16641. if ((newWrappers.length > 1 || !dom.isBlock(node)) && childCount === 0) {
  16642. dom.remove(node, true);
  16643. return;
  16644. }
  16645. if (isInlineFormat(format) || isBlockFormat(format) && format.wrapper) {
  16646. if (!format.exact && childCount === 1) {
  16647. node = mergeStyles(node);
  16648. }
  16649. mergeWithChildren(ed, formatList, vars, node);
  16650. mergeWithParents(ed, format, name, vars, node);
  16651. mergeBackgroundColorAndFontSize(dom, format, vars, node);
  16652. mergeTextDecorationsAndColor(dom, format, vars, node);
  16653. mergeSubSup(dom, format, vars, node);
  16654. mergeSiblings(dom, format, vars, node);
  16655. }
  16656. });
  16657. };
  16658. if (dom.getContentEditable(selection.getNode()) === 'false') {
  16659. node = selection.getNode();
  16660. for (var i = 0, l = formatList.length; i < l; i++) {
  16661. var formatItem = formatList[i];
  16662. if (formatItem.ceFalseOverride && isSelectorFormat(formatItem) && dom.is(node, formatItem.selector)) {
  16663. setElementFormat(node, formatItem);
  16664. break;
  16665. }
  16666. }
  16667. fireFormatApply(ed, name, node, vars);
  16668. return;
  16669. }
  16670. if (format) {
  16671. if (node) {
  16672. if (isNode(node)) {
  16673. if (!applyNodeStyle(formatList, node)) {
  16674. var rng = dom.createRng();
  16675. rng.setStartBefore(node);
  16676. rng.setEndAfter(node);
  16677. applyRngStyle(dom, expandRng(ed, rng, formatList), true);
  16678. }
  16679. } else {
  16680. applyRngStyle(dom, node, true);
  16681. }
  16682. } else {
  16683. if (!isCollapsed || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  16684. var curSelNode = selection.getNode();
  16685. var firstFormat = formatList[0];
  16686. if (!ed.settings.forced_root_block && firstFormat.defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) {
  16687. applyFormat$1(ed, firstFormat.defaultBlock);
  16688. }
  16689. selection.setRng(normalize(selection.getRng()));
  16690. preserve(selection, true, function () {
  16691. runOnRanges(ed, function (selectionRng, fake) {
  16692. var expandedRng = fake ? selectionRng : expandRng(ed, selectionRng, formatList);
  16693. applyRngStyle(dom, expandedRng, false);
  16694. });
  16695. });
  16696. moveStart(dom, selection, selection.getRng());
  16697. ed.nodeChanged();
  16698. } else {
  16699. applyCaretFormat(ed, name, vars);
  16700. }
  16701. }
  16702. postProcess$1(name, ed);
  16703. }
  16704. fireFormatApply(ed, name, node, vars);
  16705. };
  16706. var hasVars = function (value) {
  16707. return has$2(value, 'vars');
  16708. };
  16709. var setup$j = function (registeredFormatListeners, editor) {
  16710. registeredFormatListeners.set({});
  16711. editor.on('NodeChange', function (e) {
  16712. updateAndFireChangeCallbacks(editor, e.element, registeredFormatListeners.get());
  16713. });
  16714. editor.on('FormatApply FormatRemove', function (e) {
  16715. var element = Optional.from(e.node).map(function (nodeOrRange) {
  16716. return isNode(nodeOrRange) ? nodeOrRange : nodeOrRange.startContainer;
  16717. }).bind(function (node) {
  16718. return isElement$5(node) ? Optional.some(node) : Optional.from(node.parentElement);
  16719. }).getOrThunk(function () {
  16720. return fallbackElement(editor);
  16721. });
  16722. updateAndFireChangeCallbacks(editor, element, registeredFormatListeners.get());
  16723. });
  16724. };
  16725. var fallbackElement = function (editor) {
  16726. return editor.selection.getStart();
  16727. };
  16728. var matchingNode = function (editor, parents, format, similar, vars) {
  16729. var isMatchingNode = function (node) {
  16730. var matchingFormat = editor.formatter.matchNode(node, format, vars !== null && vars !== void 0 ? vars : {}, similar);
  16731. return !isUndefined(matchingFormat);
  16732. };
  16733. var isUnableToMatch = function (node) {
  16734. if (matchesUnInheritedFormatSelector(editor, node, format)) {
  16735. return true;
  16736. } else {
  16737. if (!similar) {
  16738. return isNonNullable(editor.formatter.matchNode(node, format, vars, true));
  16739. } else {
  16740. return false;
  16741. }
  16742. }
  16743. };
  16744. return findUntil$1(parents, isMatchingNode, isUnableToMatch);
  16745. };
  16746. var getParents = function (editor, elm) {
  16747. var element = elm !== null && elm !== void 0 ? elm : fallbackElement(editor);
  16748. return filter$4(getParents$2(editor.dom, element), function (node) {
  16749. return isElement$5(node) && !isBogus$2(node);
  16750. });
  16751. };
  16752. var updateAndFireChangeCallbacks = function (editor, elm, registeredCallbacks) {
  16753. var parents = getParents(editor, elm);
  16754. each$j(registeredCallbacks, function (data, format) {
  16755. var runIfChanged = function (spec) {
  16756. var match = matchingNode(editor, parents, format, spec.similar, hasVars(spec) ? spec.vars : undefined);
  16757. var isSet = match.isSome();
  16758. if (spec.state.get() !== isSet) {
  16759. spec.state.set(isSet);
  16760. var node_1 = match.getOr(elm);
  16761. if (hasVars(spec)) {
  16762. spec.callback(isSet, {
  16763. node: node_1,
  16764. format: format,
  16765. parents: parents
  16766. });
  16767. } else {
  16768. each$k(spec.callbacks, function (callback) {
  16769. return callback(isSet, {
  16770. node: node_1,
  16771. format: format,
  16772. parents: parents
  16773. });
  16774. });
  16775. }
  16776. }
  16777. };
  16778. each$k([
  16779. data.withSimilar,
  16780. data.withoutSimilar
  16781. ], runIfChanged);
  16782. each$k(data.withVars, runIfChanged);
  16783. });
  16784. };
  16785. var addListeners = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  16786. var formatChangeItems = registeredFormatListeners.get();
  16787. each$k(formats.split(','), function (format) {
  16788. var group = get$9(formatChangeItems, format).getOrThunk(function () {
  16789. var base = {
  16790. withSimilar: {
  16791. state: Cell(false),
  16792. similar: true,
  16793. callbacks: []
  16794. },
  16795. withoutSimilar: {
  16796. state: Cell(false),
  16797. similar: false,
  16798. callbacks: []
  16799. },
  16800. withVars: []
  16801. };
  16802. formatChangeItems[format] = base;
  16803. return base;
  16804. });
  16805. var getCurrent = function () {
  16806. var parents = getParents(editor);
  16807. return matchingNode(editor, parents, format, similar, vars).isSome();
  16808. };
  16809. if (isUndefined(vars)) {
  16810. var toAppendTo = similar ? group.withSimilar : group.withoutSimilar;
  16811. toAppendTo.callbacks.push(callback);
  16812. if (toAppendTo.callbacks.length === 1) {
  16813. toAppendTo.state.set(getCurrent());
  16814. }
  16815. } else {
  16816. group.withVars.push({
  16817. state: Cell(getCurrent()),
  16818. similar: similar,
  16819. vars: vars,
  16820. callback: callback
  16821. });
  16822. }
  16823. });
  16824. registeredFormatListeners.set(formatChangeItems);
  16825. };
  16826. var removeListeners = function (registeredFormatListeners, formats, callback) {
  16827. var formatChangeItems = registeredFormatListeners.get();
  16828. each$k(formats.split(','), function (format) {
  16829. return get$9(formatChangeItems, format).each(function (group) {
  16830. formatChangeItems[format] = {
  16831. withSimilar: __assign(__assign({}, group.withSimilar), {
  16832. callbacks: filter$4(group.withSimilar.callbacks, function (cb) {
  16833. return cb !== callback;
  16834. })
  16835. }),
  16836. withoutSimilar: __assign(__assign({}, group.withoutSimilar), {
  16837. callbacks: filter$4(group.withoutSimilar.callbacks, function (cb) {
  16838. return cb !== callback;
  16839. })
  16840. }),
  16841. withVars: filter$4(group.withVars, function (item) {
  16842. return item.callback !== callback;
  16843. })
  16844. };
  16845. });
  16846. });
  16847. registeredFormatListeners.set(formatChangeItems);
  16848. };
  16849. var formatChangedInternal = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  16850. if (registeredFormatListeners.get() === null) {
  16851. setup$j(registeredFormatListeners, editor);
  16852. }
  16853. addListeners(editor, registeredFormatListeners, formats, callback, similar, vars);
  16854. return {
  16855. unbind: function () {
  16856. return removeListeners(registeredFormatListeners, formats, callback);
  16857. }
  16858. };
  16859. };
  16860. var toggle = function (editor, name, vars, node) {
  16861. var fmt = editor.formatter.get(name);
  16862. if (match$2(editor, name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) {
  16863. remove$1(editor, name, vars, node);
  16864. } else {
  16865. applyFormat$1(editor, name, vars, node);
  16866. }
  16867. };
  16868. var fromElements = function (elements, scope) {
  16869. var doc = scope || document;
  16870. var fragment = doc.createDocumentFragment();
  16871. each$k(elements, function (element) {
  16872. fragment.appendChild(element.dom);
  16873. });
  16874. return SugarElement.fromDom(fragment);
  16875. };
  16876. var tableModel = function (element, width, rows) {
  16877. return {
  16878. element: element,
  16879. width: width,
  16880. rows: rows
  16881. };
  16882. };
  16883. var tableRow = function (element, cells) {
  16884. return {
  16885. element: element,
  16886. cells: cells
  16887. };
  16888. };
  16889. var cellPosition = function (x, y) {
  16890. return {
  16891. x: x,
  16892. y: y
  16893. };
  16894. };
  16895. var getSpan = function (td, key) {
  16896. var value = parseInt(get$6(td, key), 10);
  16897. return isNaN(value) ? 1 : value;
  16898. };
  16899. var fillout = function (table, x, y, tr, td) {
  16900. var rowspan = getSpan(td, 'rowspan');
  16901. var colspan = getSpan(td, 'colspan');
  16902. var rows = table.rows;
  16903. for (var y2 = y; y2 < y + rowspan; y2++) {
  16904. if (!rows[y2]) {
  16905. rows[y2] = tableRow(deep$1(tr), []);
  16906. }
  16907. for (var x2 = x; x2 < x + colspan; x2++) {
  16908. var cells = rows[y2].cells;
  16909. cells[x2] = y2 === y && x2 === x ? td : shallow(td);
  16910. }
  16911. }
  16912. };
  16913. var cellExists = function (table, x, y) {
  16914. var rows = table.rows;
  16915. var cells = rows[y] ? rows[y].cells : [];
  16916. return !!cells[x];
  16917. };
  16918. var skipCellsX = function (table, x, y) {
  16919. while (cellExists(table, x, y)) {
  16920. x++;
  16921. }
  16922. return x;
  16923. };
  16924. var getWidth = function (rows) {
  16925. return foldl(rows, function (acc, row) {
  16926. return row.cells.length > acc ? row.cells.length : acc;
  16927. }, 0);
  16928. };
  16929. var findElementPos = function (table, element) {
  16930. var rows = table.rows;
  16931. for (var y = 0; y < rows.length; y++) {
  16932. var cells = rows[y].cells;
  16933. for (var x = 0; x < cells.length; x++) {
  16934. if (eq(cells[x], element)) {
  16935. return Optional.some(cellPosition(x, y));
  16936. }
  16937. }
  16938. }
  16939. return Optional.none();
  16940. };
  16941. var extractRows = function (table, sx, sy, ex, ey) {
  16942. var newRows = [];
  16943. var rows = table.rows;
  16944. for (var y = sy; y <= ey; y++) {
  16945. var cells = rows[y].cells;
  16946. var slice = sx < ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
  16947. newRows.push(tableRow(rows[y].element, slice));
  16948. }
  16949. return newRows;
  16950. };
  16951. var subTable = function (table, startPos, endPos) {
  16952. var sx = startPos.x, sy = startPos.y;
  16953. var ex = endPos.x, ey = endPos.y;
  16954. var newRows = sy < ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
  16955. return tableModel(table.element, getWidth(newRows), newRows);
  16956. };
  16957. var createDomTable = function (table, rows) {
  16958. var tableElement = shallow(table.element);
  16959. var tableBody = SugarElement.fromTag('tbody');
  16960. append(tableBody, rows);
  16961. append$1(tableElement, tableBody);
  16962. return tableElement;
  16963. };
  16964. var modelRowsToDomRows = function (table) {
  16965. return map$3(table.rows, function (row) {
  16966. var cells = map$3(row.cells, function (cell) {
  16967. var td = deep$1(cell);
  16968. remove$6(td, 'colspan');
  16969. remove$6(td, 'rowspan');
  16970. return td;
  16971. });
  16972. var tr = shallow(row.element);
  16973. append(tr, cells);
  16974. return tr;
  16975. });
  16976. };
  16977. var fromDom = function (tableElm) {
  16978. var table = tableModel(shallow(tableElm), 0, []);
  16979. each$k(descendants(tableElm, 'tr'), function (tr, y) {
  16980. each$k(descendants(tr, 'td,th'), function (td, x) {
  16981. fillout(table, skipCellsX(table, x, y), y, tr, td);
  16982. });
  16983. });
  16984. return tableModel(table.element, getWidth(table.rows), table.rows);
  16985. };
  16986. var toDom = function (table) {
  16987. return createDomTable(table, modelRowsToDomRows(table));
  16988. };
  16989. var subsection = function (table, startElement, endElement) {
  16990. return findElementPos(table, startElement).bind(function (startPos) {
  16991. return findElementPos(table, endElement).map(function (endPos) {
  16992. return subTable(table, startPos, endPos);
  16993. });
  16994. });
  16995. };
  16996. var findParentListContainer = function (parents) {
  16997. return find$3(parents, function (elm) {
  16998. return name(elm) === 'ul' || name(elm) === 'ol';
  16999. });
  17000. };
  17001. var getFullySelectedListWrappers = function (parents, rng) {
  17002. return find$3(parents, function (elm) {
  17003. return name(elm) === 'li' && hasAllContentsSelected(elm, rng);
  17004. }).fold(constant([]), function (_li) {
  17005. return findParentListContainer(parents).map(function (listCont) {
  17006. var listElm = SugarElement.fromTag(name(listCont));
  17007. var listStyles = filter$3(getAllRaw(listCont), function (_style, name) {
  17008. return startsWith(name, 'list-style');
  17009. });
  17010. setAll(listElm, listStyles);
  17011. return [
  17012. SugarElement.fromTag('li'),
  17013. listElm
  17014. ];
  17015. }).getOr([]);
  17016. });
  17017. };
  17018. var wrap = function (innerElm, elms) {
  17019. var wrapped = foldl(elms, function (acc, elm) {
  17020. append$1(elm, acc);
  17021. return elm;
  17022. }, innerElm);
  17023. return elms.length > 0 ? fromElements([wrapped]) : wrapped;
  17024. };
  17025. var directListWrappers = function (commonAnchorContainer) {
  17026. if (isListItem(commonAnchorContainer)) {
  17027. return parent(commonAnchorContainer).filter(isList).fold(constant([]), function (listElm) {
  17028. return [
  17029. commonAnchorContainer,
  17030. listElm
  17031. ];
  17032. });
  17033. } else {
  17034. return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
  17035. }
  17036. };
  17037. var getWrapElements = function (rootNode, rng) {
  17038. var commonAnchorContainer = SugarElement.fromDom(rng.commonAncestorContainer);
  17039. var parents = parentsAndSelf(commonAnchorContainer, rootNode);
  17040. var wrapElements = filter$4(parents, function (elm) {
  17041. return isInline$1(elm) || isHeading(elm);
  17042. });
  17043. var listWrappers = getFullySelectedListWrappers(parents, rng);
  17044. var allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
  17045. return map$3(allWrappers, shallow);
  17046. };
  17047. var emptyFragment = function () {
  17048. return fromElements([]);
  17049. };
  17050. var getFragmentFromRange = function (rootNode, rng) {
  17051. return wrap(SugarElement.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
  17052. };
  17053. var getParentTable = function (rootElm, cell) {
  17054. return ancestor$2(cell, 'table', curry(eq, rootElm));
  17055. };
  17056. var getTableFragment = function (rootNode, selectedTableCells) {
  17057. return getParentTable(rootNode, selectedTableCells[0]).bind(function (tableElm) {
  17058. var firstCell = selectedTableCells[0];
  17059. var lastCell = selectedTableCells[selectedTableCells.length - 1];
  17060. var fullTableModel = fromDom(tableElm);
  17061. return subsection(fullTableModel, firstCell, lastCell).map(function (sectionedTableModel) {
  17062. return fromElements([toDom(sectionedTableModel)]);
  17063. });
  17064. }).getOrThunk(emptyFragment);
  17065. };
  17066. var getSelectionFragment = function (rootNode, ranges) {
  17067. return ranges.length > 0 && ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
  17068. };
  17069. var read$3 = function (rootNode, ranges) {
  17070. var selectedCells = getCellsFromElementOrRanges(ranges, rootNode);
  17071. return selectedCells.length > 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
  17072. };
  17073. var trimLeadingCollapsibleText = function (text) {
  17074. return text.replace(/^[ \f\n\r\t\v]+/, '');
  17075. };
  17076. var isCollapsibleWhitespace = function (text, index) {
  17077. return index >= 0 && index < text.length && isWhiteSpace(text.charAt(index));
  17078. };
  17079. var getInnerText = function (bin, shouldTrim) {
  17080. var text = trim$2(bin.innerText);
  17081. return shouldTrim ? trimLeadingCollapsibleText(text) : text;
  17082. };
  17083. var getContextNodeName = function (parentBlockOpt) {
  17084. return parentBlockOpt.map(function (block) {
  17085. return block.nodeName;
  17086. }).getOr('div').toLowerCase();
  17087. };
  17088. var getTextContent = function (editor) {
  17089. return Optional.from(editor.selection.getRng()).map(function (rng) {
  17090. var parentBlockOpt = Optional.from(editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock));
  17091. var body = editor.getBody();
  17092. var contextNodeName = getContextNodeName(parentBlockOpt);
  17093. var shouldTrimSpaces = Env.browser.isIE() && contextNodeName !== 'pre';
  17094. var bin = editor.dom.add(body, contextNodeName, {
  17095. 'data-mce-bogus': 'all',
  17096. 'style': 'overflow: hidden; opacity: 0;'
  17097. }, rng.cloneContents());
  17098. var text = getInnerText(bin, shouldTrimSpaces);
  17099. var nonRenderedText = trim$2(bin.textContent);
  17100. editor.dom.remove(bin);
  17101. if (isCollapsibleWhitespace(nonRenderedText, 0) || isCollapsibleWhitespace(nonRenderedText, nonRenderedText.length - 1)) {
  17102. var parentBlock = parentBlockOpt.getOr(body);
  17103. var parentBlockText = getInnerText(parentBlock, shouldTrimSpaces);
  17104. var textIndex = parentBlockText.indexOf(text);
  17105. if (textIndex === -1) {
  17106. return text;
  17107. } else {
  17108. var hasProceedingSpace = isCollapsibleWhitespace(parentBlockText, textIndex - 1);
  17109. var hasTrailingSpace = isCollapsibleWhitespace(parentBlockText, textIndex + text.length);
  17110. return (hasProceedingSpace ? ' ' : '') + text + (hasTrailingSpace ? ' ' : '');
  17111. }
  17112. } else {
  17113. return text;
  17114. }
  17115. }).getOr('');
  17116. };
  17117. var getSerializedContent = function (editor, args) {
  17118. var rng = editor.selection.getRng(), tmpElm = editor.dom.create('body');
  17119. var sel = editor.selection.getSel();
  17120. var ranges = processRanges(editor, getRanges(sel));
  17121. var fragment = args.contextual ? read$3(SugarElement.fromDom(editor.getBody()), ranges).dom : rng.cloneContents();
  17122. if (fragment) {
  17123. tmpElm.appendChild(fragment);
  17124. }
  17125. return editor.selection.serializer.serialize(tmpElm, args);
  17126. };
  17127. var getSelectedContentInternal = function (editor, format, args) {
  17128. if (args === void 0) {
  17129. args = {};
  17130. }
  17131. var updatedArgs = editor.fire('BeforeGetContent', __assign(__assign({}, args), {
  17132. format: format,
  17133. get: true,
  17134. selection: true
  17135. }));
  17136. if (updatedArgs.isDefaultPrevented()) {
  17137. editor.fire('GetContent', updatedArgs);
  17138. return updatedArgs.content;
  17139. }
  17140. if (updatedArgs.format === 'text') {
  17141. return getTextContent(editor);
  17142. } else {
  17143. updatedArgs.getInner = true;
  17144. var content = getSerializedContent(editor, updatedArgs);
  17145. if (updatedArgs.format === 'tree') {
  17146. return content;
  17147. } else {
  17148. updatedArgs.content = editor.selection.isCollapsed() ? '' : content;
  17149. editor.fire('GetContent', updatedArgs);
  17150. return updatedArgs.content;
  17151. }
  17152. }
  17153. };
  17154. var KEEP = 0, INSERT = 1, DELETE = 2;
  17155. var diff = function (left, right) {
  17156. var size = left.length + right.length + 2;
  17157. var vDown = new Array(size);
  17158. var vUp = new Array(size);
  17159. var snake = function (start, end, diag) {
  17160. return {
  17161. start: start,
  17162. end: end,
  17163. diag: diag
  17164. };
  17165. };
  17166. var buildScript = function (start1, end1, start2, end2, script) {
  17167. var middle = getMiddleSnake(start1, end1, start2, end2);
  17168. if (middle === null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) {
  17169. var i = start1;
  17170. var j = start2;
  17171. while (i < end1 || j < end2) {
  17172. if (i < end1 && j < end2 && left[i] === right[j]) {
  17173. script.push([
  17174. KEEP,
  17175. left[i]
  17176. ]);
  17177. ++i;
  17178. ++j;
  17179. } else {
  17180. if (end1 - start1 > end2 - start2) {
  17181. script.push([
  17182. DELETE,
  17183. left[i]
  17184. ]);
  17185. ++i;
  17186. } else {
  17187. script.push([
  17188. INSERT,
  17189. right[j]
  17190. ]);
  17191. ++j;
  17192. }
  17193. }
  17194. }
  17195. } else {
  17196. buildScript(start1, middle.start, start2, middle.start - middle.diag, script);
  17197. for (var i2 = middle.start; i2 < middle.end; ++i2) {
  17198. script.push([
  17199. KEEP,
  17200. left[i2]
  17201. ]);
  17202. }
  17203. buildScript(middle.end, end1, middle.end - middle.diag, end2, script);
  17204. }
  17205. };
  17206. var buildSnake = function (start, diag, end1, end2) {
  17207. var end = start;
  17208. while (end - diag < end2 && end < end1 && left[end] === right[end - diag]) {
  17209. ++end;
  17210. }
  17211. return snake(start, end, diag);
  17212. };
  17213. var getMiddleSnake = function (start1, end1, start2, end2) {
  17214. var m = end1 - start1;
  17215. var n = end2 - start2;
  17216. if (m === 0 || n === 0) {
  17217. return null;
  17218. }
  17219. var delta = m - n;
  17220. var sum = n + m;
  17221. var offset = (sum % 2 === 0 ? sum : sum + 1) / 2;
  17222. vDown[1 + offset] = start1;
  17223. vUp[1 + offset] = end1 + 1;
  17224. var d, k, i, x, y;
  17225. for (d = 0; d <= offset; ++d) {
  17226. for (k = -d; k <= d; k += 2) {
  17227. i = k + offset;
  17228. if (k === -d || k !== d && vDown[i - 1] < vDown[i + 1]) {
  17229. vDown[i] = vDown[i + 1];
  17230. } else {
  17231. vDown[i] = vDown[i - 1] + 1;
  17232. }
  17233. x = vDown[i];
  17234. y = x - start1 + start2 - k;
  17235. while (x < end1 && y < end2 && left[x] === right[y]) {
  17236. vDown[i] = ++x;
  17237. ++y;
  17238. }
  17239. if (delta % 2 !== 0 && delta - d <= k && k <= delta + d) {
  17240. if (vUp[i - delta] <= vDown[i]) {
  17241. return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2);
  17242. }
  17243. }
  17244. }
  17245. for (k = delta - d; k <= delta + d; k += 2) {
  17246. i = k + offset - delta;
  17247. if (k === delta - d || k !== delta + d && vUp[i + 1] <= vUp[i - 1]) {
  17248. vUp[i] = vUp[i + 1] - 1;
  17249. } else {
  17250. vUp[i] = vUp[i - 1];
  17251. }
  17252. x = vUp[i] - 1;
  17253. y = x - start1 + start2 - k;
  17254. while (x >= start1 && y >= start2 && left[x] === right[y]) {
  17255. vUp[i] = x--;
  17256. y--;
  17257. }
  17258. if (delta % 2 === 0 && -d <= k && k <= d) {
  17259. if (vUp[i] <= vDown[i + delta]) {
  17260. return buildSnake(vUp[i], k + start1 - start2, end1, end2);
  17261. }
  17262. }
  17263. }
  17264. }
  17265. };
  17266. var script = [];
  17267. buildScript(0, left.length, 0, right.length, script);
  17268. return script;
  17269. };
  17270. var getOuterHtml = function (elm) {
  17271. if (isElement$5(elm)) {
  17272. return elm.outerHTML;
  17273. } else if (isText$7(elm)) {
  17274. return Entities.encodeRaw(elm.data, false);
  17275. } else if (isComment(elm)) {
  17276. return '<!--' + elm.data + '-->';
  17277. }
  17278. return '';
  17279. };
  17280. var createFragment = function (html) {
  17281. var node;
  17282. var container = document.createElement('div');
  17283. var frag = document.createDocumentFragment();
  17284. if (html) {
  17285. container.innerHTML = html;
  17286. }
  17287. while (node = container.firstChild) {
  17288. frag.appendChild(node);
  17289. }
  17290. return frag;
  17291. };
  17292. var insertAt = function (elm, html, index) {
  17293. var fragment = createFragment(html);
  17294. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  17295. var target = elm.childNodes[index];
  17296. target.parentNode.insertBefore(fragment, target);
  17297. } else {
  17298. elm.appendChild(fragment);
  17299. }
  17300. };
  17301. var removeAt = function (elm, index) {
  17302. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  17303. var target = elm.childNodes[index];
  17304. target.parentNode.removeChild(target);
  17305. }
  17306. };
  17307. var applyDiff = function (diff, elm) {
  17308. var index = 0;
  17309. each$k(diff, function (action) {
  17310. if (action[0] === KEEP) {
  17311. index++;
  17312. } else if (action[0] === INSERT) {
  17313. insertAt(elm, action[1], index);
  17314. index++;
  17315. } else if (action[0] === DELETE) {
  17316. removeAt(elm, index);
  17317. }
  17318. });
  17319. };
  17320. var read$2 = function (elm) {
  17321. return filter$4(map$3(from(elm.childNodes), getOuterHtml), function (item) {
  17322. return item.length > 0;
  17323. });
  17324. };
  17325. var write = function (fragments, elm) {
  17326. var currentFragments = map$3(from(elm.childNodes), getOuterHtml);
  17327. applyDiff(diff(currentFragments, fragments), elm);
  17328. return elm;
  17329. };
  17330. var lazyTempDocument = cached(function () {
  17331. return document.implementation.createHTMLDocument('undo');
  17332. });
  17333. var hasIframes = function (html) {
  17334. return html.indexOf('</iframe>') !== -1;
  17335. };
  17336. var createFragmentedLevel = function (fragments) {
  17337. return {
  17338. type: 'fragmented',
  17339. fragments: fragments,
  17340. content: '',
  17341. bookmark: null,
  17342. beforeBookmark: null
  17343. };
  17344. };
  17345. var createCompleteLevel = function (content) {
  17346. return {
  17347. type: 'complete',
  17348. fragments: null,
  17349. content: content,
  17350. bookmark: null,
  17351. beforeBookmark: null
  17352. };
  17353. };
  17354. var createFromEditor = function (editor) {
  17355. var fragments = read$2(editor.getBody());
  17356. var trimmedFragments = bind(fragments, function (html) {
  17357. var trimmed = trimInternal(editor.serializer, html);
  17358. return trimmed.length > 0 ? [trimmed] : [];
  17359. });
  17360. var content = trimmedFragments.join('');
  17361. return hasIframes(content) ? createFragmentedLevel(trimmedFragments) : createCompleteLevel(content);
  17362. };
  17363. var applyToEditor = function (editor, level, before) {
  17364. var bookmark = before ? level.beforeBookmark : level.bookmark;
  17365. if (level.type === 'fragmented') {
  17366. write(level.fragments, editor.getBody());
  17367. } else {
  17368. editor.setContent(level.content, {
  17369. format: 'raw',
  17370. no_selection: isNonNullable(bookmark) && isPathBookmark(bookmark) ? !bookmark.isFakeCaret : true
  17371. });
  17372. }
  17373. editor.selection.moveToBookmark(bookmark);
  17374. };
  17375. var getLevelContent = function (level) {
  17376. return level.type === 'fragmented' ? level.fragments.join('') : level.content;
  17377. };
  17378. var getCleanLevelContent = function (level) {
  17379. var elm = SugarElement.fromTag('body', lazyTempDocument());
  17380. set(elm, getLevelContent(level));
  17381. each$k(descendants(elm, '*[data-mce-bogus]'), unwrap);
  17382. return get$3(elm);
  17383. };
  17384. var hasEqualContent = function (level1, level2) {
  17385. return getLevelContent(level1) === getLevelContent(level2);
  17386. };
  17387. var hasEqualCleanedContent = function (level1, level2) {
  17388. return getCleanLevelContent(level1) === getCleanLevelContent(level2);
  17389. };
  17390. var isEq$1 = function (level1, level2) {
  17391. if (!level1 || !level2) {
  17392. return false;
  17393. } else if (hasEqualContent(level1, level2)) {
  17394. return true;
  17395. } else {
  17396. return hasEqualCleanedContent(level1, level2);
  17397. }
  17398. };
  17399. var isUnlocked = function (locks) {
  17400. return locks.get() === 0;
  17401. };
  17402. var setTyping = function (undoManager, typing, locks) {
  17403. if (isUnlocked(locks)) {
  17404. undoManager.typing = typing;
  17405. }
  17406. };
  17407. var endTyping = function (undoManager, locks) {
  17408. if (undoManager.typing) {
  17409. setTyping(undoManager, false, locks);
  17410. undoManager.add();
  17411. }
  17412. };
  17413. var endTypingLevelIgnoreLocks = function (undoManager) {
  17414. if (undoManager.typing) {
  17415. undoManager.typing = false;
  17416. undoManager.add();
  17417. }
  17418. };
  17419. var beforeChange$1 = function (editor, locks, beforeBookmark) {
  17420. if (isUnlocked(locks)) {
  17421. beforeBookmark.set(getUndoBookmark(editor.selection));
  17422. }
  17423. };
  17424. var addUndoLevel$1 = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  17425. var currentLevel = createFromEditor(editor);
  17426. level = level || {};
  17427. level = Tools.extend(level, currentLevel);
  17428. if (isUnlocked(locks) === false || editor.removed) {
  17429. return null;
  17430. }
  17431. var lastLevel = undoManager.data[index.get()];
  17432. if (editor.fire('BeforeAddUndo', {
  17433. level: level,
  17434. lastLevel: lastLevel,
  17435. originalEvent: event
  17436. }).isDefaultPrevented()) {
  17437. return null;
  17438. }
  17439. if (lastLevel && isEq$1(lastLevel, level)) {
  17440. return null;
  17441. }
  17442. if (undoManager.data[index.get()]) {
  17443. beforeBookmark.get().each(function (bm) {
  17444. undoManager.data[index.get()].beforeBookmark = bm;
  17445. });
  17446. }
  17447. var customUndoRedoLevels = getCustomUndoRedoLevels(editor);
  17448. if (customUndoRedoLevels) {
  17449. if (undoManager.data.length > customUndoRedoLevels) {
  17450. for (var i = 0; i < undoManager.data.length - 1; i++) {
  17451. undoManager.data[i] = undoManager.data[i + 1];
  17452. }
  17453. undoManager.data.length--;
  17454. index.set(undoManager.data.length);
  17455. }
  17456. }
  17457. level.bookmark = getUndoBookmark(editor.selection);
  17458. if (index.get() < undoManager.data.length - 1) {
  17459. undoManager.data.length = index.get() + 1;
  17460. }
  17461. undoManager.data.push(level);
  17462. index.set(undoManager.data.length - 1);
  17463. var args = {
  17464. level: level,
  17465. lastLevel: lastLevel,
  17466. originalEvent: event
  17467. };
  17468. if (index.get() > 0) {
  17469. editor.setDirty(true);
  17470. editor.fire('AddUndo', args);
  17471. editor.fire('change', args);
  17472. } else {
  17473. editor.fire('AddUndo', args);
  17474. }
  17475. return level;
  17476. };
  17477. var clear$1 = function (editor, undoManager, index) {
  17478. undoManager.data = [];
  17479. index.set(0);
  17480. undoManager.typing = false;
  17481. editor.fire('ClearUndos');
  17482. };
  17483. var extra$1 = function (editor, undoManager, index, callback1, callback2) {
  17484. if (undoManager.transact(callback1)) {
  17485. var bookmark = undoManager.data[index.get()].bookmark;
  17486. var lastLevel = undoManager.data[index.get() - 1];
  17487. applyToEditor(editor, lastLevel, true);
  17488. if (undoManager.transact(callback2)) {
  17489. undoManager.data[index.get() - 1].beforeBookmark = bookmark;
  17490. }
  17491. }
  17492. };
  17493. var redo$1 = function (editor, index, data) {
  17494. var level;
  17495. if (index.get() < data.length - 1) {
  17496. index.set(index.get() + 1);
  17497. level = data[index.get()];
  17498. applyToEditor(editor, level, false);
  17499. editor.setDirty(true);
  17500. editor.fire('Redo', { level: level });
  17501. }
  17502. return level;
  17503. };
  17504. var undo$1 = function (editor, undoManager, locks, index) {
  17505. var level;
  17506. if (undoManager.typing) {
  17507. undoManager.add();
  17508. undoManager.typing = false;
  17509. setTyping(undoManager, false, locks);
  17510. }
  17511. if (index.get() > 0) {
  17512. index.set(index.get() - 1);
  17513. level = undoManager.data[index.get()];
  17514. applyToEditor(editor, level, true);
  17515. editor.setDirty(true);
  17516. editor.fire('Undo', { level: level });
  17517. }
  17518. return level;
  17519. };
  17520. var reset$1 = function (undoManager) {
  17521. undoManager.clear();
  17522. undoManager.add();
  17523. };
  17524. var hasUndo$1 = function (editor, undoManager, index) {
  17525. return index.get() > 0 || undoManager.typing && undoManager.data[0] && !isEq$1(createFromEditor(editor), undoManager.data[0]);
  17526. };
  17527. var hasRedo$1 = function (undoManager, index) {
  17528. return index.get() < undoManager.data.length - 1 && !undoManager.typing;
  17529. };
  17530. var transact$1 = function (undoManager, locks, callback) {
  17531. endTyping(undoManager, locks);
  17532. undoManager.beforeChange();
  17533. undoManager.ignore(callback);
  17534. return undoManager.add();
  17535. };
  17536. var ignore$1 = function (locks, callback) {
  17537. try {
  17538. locks.set(locks.get() + 1);
  17539. callback();
  17540. } finally {
  17541. locks.set(locks.get() - 1);
  17542. }
  17543. };
  17544. var addVisualInternal = function (editor, elm) {
  17545. var dom = editor.dom;
  17546. var scope = isNonNullable(elm) ? elm : editor.getBody();
  17547. if (isUndefined(editor.hasVisual)) {
  17548. editor.hasVisual = isVisualAidsEnabled(editor);
  17549. }
  17550. each$k(dom.select('table,a', scope), function (matchedElm) {
  17551. switch (matchedElm.nodeName) {
  17552. case 'TABLE':
  17553. var cls = getVisualAidsTableClass(editor);
  17554. var value = dom.getAttrib(matchedElm, 'border');
  17555. if ((!value || value === '0') && editor.hasVisual) {
  17556. dom.addClass(matchedElm, cls);
  17557. } else {
  17558. dom.removeClass(matchedElm, cls);
  17559. }
  17560. break;
  17561. case 'A':
  17562. if (!dom.getAttrib(matchedElm, 'href')) {
  17563. var value_1 = dom.getAttrib(matchedElm, 'name') || matchedElm.id;
  17564. var cls_1 = getVisualAidsAnchorClass(editor);
  17565. if (value_1 && editor.hasVisual) {
  17566. dom.addClass(matchedElm, cls_1);
  17567. } else {
  17568. dom.removeClass(matchedElm, cls_1);
  17569. }
  17570. }
  17571. break;
  17572. }
  17573. });
  17574. editor.fire('VisualAid', {
  17575. element: elm,
  17576. hasVisual: editor.hasVisual
  17577. });
  17578. };
  17579. var makePlainAdaptor = function (editor) {
  17580. return {
  17581. undoManager: {
  17582. beforeChange: function (locks, beforeBookmark) {
  17583. return beforeChange$1(editor, locks, beforeBookmark);
  17584. },
  17585. add: function (undoManager, index, locks, beforeBookmark, level, event) {
  17586. return addUndoLevel$1(editor, undoManager, index, locks, beforeBookmark, level, event);
  17587. },
  17588. undo: function (undoManager, locks, index) {
  17589. return undo$1(editor, undoManager, locks, index);
  17590. },
  17591. redo: function (index, data) {
  17592. return redo$1(editor, index, data);
  17593. },
  17594. clear: function (undoManager, index) {
  17595. return clear$1(editor, undoManager, index);
  17596. },
  17597. reset: function (undoManager) {
  17598. return reset$1(undoManager);
  17599. },
  17600. hasUndo: function (undoManager, index) {
  17601. return hasUndo$1(editor, undoManager, index);
  17602. },
  17603. hasRedo: function (undoManager, index) {
  17604. return hasRedo$1(undoManager, index);
  17605. },
  17606. transact: function (undoManager, locks, callback) {
  17607. return transact$1(undoManager, locks, callback);
  17608. },
  17609. ignore: function (locks, callback) {
  17610. return ignore$1(locks, callback);
  17611. },
  17612. extra: function (undoManager, index, callback1, callback2) {
  17613. return extra$1(editor, undoManager, index, callback1, callback2);
  17614. }
  17615. },
  17616. formatter: {
  17617. match: function (name, vars, node, similar) {
  17618. return match$2(editor, name, vars, node, similar);
  17619. },
  17620. matchAll: function (names, vars) {
  17621. return matchAll(editor, names, vars);
  17622. },
  17623. matchNode: function (node, name, vars, similar) {
  17624. return matchNode(editor, node, name, vars, similar);
  17625. },
  17626. canApply: function (name) {
  17627. return canApply(editor, name);
  17628. },
  17629. closest: function (names) {
  17630. return closest(editor, names);
  17631. },
  17632. apply: function (name, vars, node) {
  17633. return applyFormat$1(editor, name, vars, node);
  17634. },
  17635. remove: function (name, vars, node, similar) {
  17636. return remove$1(editor, name, vars, node, similar);
  17637. },
  17638. toggle: function (name, vars, node) {
  17639. return toggle(editor, name, vars, node);
  17640. },
  17641. formatChanged: function (registeredFormatListeners, formats, callback, similar, vars) {
  17642. return formatChangedInternal(editor, registeredFormatListeners, formats, callback, similar, vars);
  17643. }
  17644. },
  17645. editor: {
  17646. getContent: function (args, format) {
  17647. return getContentInternal(editor, args, format);
  17648. },
  17649. setContent: function (content, args) {
  17650. return setContentInternal(editor, content, args);
  17651. },
  17652. insertContent: function (value, details) {
  17653. return insertHtmlAtCaret(editor, value, details);
  17654. },
  17655. addVisual: function (elm) {
  17656. return addVisualInternal(editor, elm);
  17657. }
  17658. },
  17659. selection: {
  17660. getContent: function (format, args) {
  17661. return getSelectedContentInternal(editor, format, args);
  17662. }
  17663. },
  17664. raw: {
  17665. getModel: function () {
  17666. return Optional.none();
  17667. }
  17668. }
  17669. };
  17670. };
  17671. var makeRtcAdaptor = function (rtcEditor) {
  17672. var defaultVars = function (vars) {
  17673. return isObject(vars) ? vars : {};
  17674. };
  17675. var undoManager = rtcEditor.undoManager, formatter = rtcEditor.formatter, editor = rtcEditor.editor, selection = rtcEditor.selection, raw = rtcEditor.raw;
  17676. return {
  17677. undoManager: {
  17678. beforeChange: undoManager.beforeChange,
  17679. add: undoManager.add,
  17680. undo: undoManager.undo,
  17681. redo: undoManager.redo,
  17682. clear: undoManager.clear,
  17683. reset: undoManager.reset,
  17684. hasUndo: undoManager.hasUndo,
  17685. hasRedo: undoManager.hasRedo,
  17686. transact: function (_undoManager, _locks, fn) {
  17687. return undoManager.transact(fn);
  17688. },
  17689. ignore: function (_locks, callback) {
  17690. return undoManager.ignore(callback);
  17691. },
  17692. extra: function (_undoManager, _index, callback1, callback2) {
  17693. return undoManager.extra(callback1, callback2);
  17694. }
  17695. },
  17696. formatter: {
  17697. match: function (name, vars, _node, similar) {
  17698. return formatter.match(name, defaultVars(vars), similar);
  17699. },
  17700. matchAll: formatter.matchAll,
  17701. matchNode: formatter.matchNode,
  17702. canApply: function (name) {
  17703. return formatter.canApply(name);
  17704. },
  17705. closest: function (names) {
  17706. return formatter.closest(names);
  17707. },
  17708. apply: function (name, vars, _node) {
  17709. return formatter.apply(name, defaultVars(vars));
  17710. },
  17711. remove: function (name, vars, _node, _similar) {
  17712. return formatter.remove(name, defaultVars(vars));
  17713. },
  17714. toggle: function (name, vars, _node) {
  17715. return formatter.toggle(name, defaultVars(vars));
  17716. },
  17717. formatChanged: function (_rfl, formats, callback, similar, vars) {
  17718. return formatter.formatChanged(formats, callback, similar, vars);
  17719. }
  17720. },
  17721. editor: {
  17722. getContent: function (args, _format) {
  17723. return editor.getContent(args);
  17724. },
  17725. setContent: function (content, args) {
  17726. return editor.setContent(content, args);
  17727. },
  17728. insertContent: function (content, _details) {
  17729. return editor.insertContent(content);
  17730. },
  17731. addVisual: editor.addVisual
  17732. },
  17733. selection: {
  17734. getContent: function (_format, args) {
  17735. return selection.getContent(args);
  17736. }
  17737. },
  17738. raw: {
  17739. getModel: function () {
  17740. return Optional.some(raw.getRawModel());
  17741. }
  17742. }
  17743. };
  17744. };
  17745. var makeNoopAdaptor = function () {
  17746. var nul = constant(null);
  17747. var empty = constant('');
  17748. return {
  17749. undoManager: {
  17750. beforeChange: noop,
  17751. add: nul,
  17752. undo: nul,
  17753. redo: nul,
  17754. clear: noop,
  17755. reset: noop,
  17756. hasUndo: never,
  17757. hasRedo: never,
  17758. transact: nul,
  17759. ignore: noop,
  17760. extra: noop
  17761. },
  17762. formatter: {
  17763. match: never,
  17764. matchAll: constant([]),
  17765. matchNode: constant(undefined),
  17766. canApply: never,
  17767. closest: empty,
  17768. apply: noop,
  17769. remove: noop,
  17770. toggle: noop,
  17771. formatChanged: constant({ unbind: noop })
  17772. },
  17773. editor: {
  17774. getContent: empty,
  17775. setContent: empty,
  17776. insertContent: noop,
  17777. addVisual: noop
  17778. },
  17779. selection: { getContent: empty },
  17780. raw: { getModel: constant(Optional.none()) }
  17781. };
  17782. };
  17783. var isRtc = function (editor) {
  17784. return has$2(editor.plugins, 'rtc');
  17785. };
  17786. var getRtcSetup = function (editor) {
  17787. return get$9(editor.plugins, 'rtc').bind(function (rtcPlugin) {
  17788. return Optional.from(rtcPlugin.setup);
  17789. });
  17790. };
  17791. var setup$i = function (editor) {
  17792. var editorCast = editor;
  17793. return getRtcSetup(editor).fold(function () {
  17794. editorCast.rtcInstance = makePlainAdaptor(editor);
  17795. return Optional.none();
  17796. }, function (setup) {
  17797. editorCast.rtcInstance = makeNoopAdaptor();
  17798. return Optional.some(function () {
  17799. return setup().then(function (rtcEditor) {
  17800. editorCast.rtcInstance = makeRtcAdaptor(rtcEditor);
  17801. return rtcEditor.rtc.isRemote;
  17802. });
  17803. });
  17804. });
  17805. };
  17806. var getRtcInstanceWithFallback = function (editor) {
  17807. return editor.rtcInstance ? editor.rtcInstance : makePlainAdaptor(editor);
  17808. };
  17809. var getRtcInstanceWithError = function (editor) {
  17810. var rtcInstance = editor.rtcInstance;
  17811. if (!rtcInstance) {
  17812. throw new Error('Failed to get RTC instance not yet initialized.');
  17813. } else {
  17814. return rtcInstance;
  17815. }
  17816. };
  17817. var beforeChange = function (editor, locks, beforeBookmark) {
  17818. getRtcInstanceWithError(editor).undoManager.beforeChange(locks, beforeBookmark);
  17819. };
  17820. var addUndoLevel = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  17821. return getRtcInstanceWithError(editor).undoManager.add(undoManager, index, locks, beforeBookmark, level, event);
  17822. };
  17823. var undo = function (editor, undoManager, locks, index) {
  17824. return getRtcInstanceWithError(editor).undoManager.undo(undoManager, locks, index);
  17825. };
  17826. var redo = function (editor, index, data) {
  17827. return getRtcInstanceWithError(editor).undoManager.redo(index, data);
  17828. };
  17829. var clear = function (editor, undoManager, index) {
  17830. getRtcInstanceWithError(editor).undoManager.clear(undoManager, index);
  17831. };
  17832. var reset = function (editor, undoManager) {
  17833. getRtcInstanceWithError(editor).undoManager.reset(undoManager);
  17834. };
  17835. var hasUndo = function (editor, undoManager, index) {
  17836. return getRtcInstanceWithError(editor).undoManager.hasUndo(undoManager, index);
  17837. };
  17838. var hasRedo = function (editor, undoManager, index) {
  17839. return getRtcInstanceWithError(editor).undoManager.hasRedo(undoManager, index);
  17840. };
  17841. var transact = function (editor, undoManager, locks, callback) {
  17842. return getRtcInstanceWithError(editor).undoManager.transact(undoManager, locks, callback);
  17843. };
  17844. var ignore = function (editor, locks, callback) {
  17845. getRtcInstanceWithError(editor).undoManager.ignore(locks, callback);
  17846. };
  17847. var extra = function (editor, undoManager, index, callback1, callback2) {
  17848. getRtcInstanceWithError(editor).undoManager.extra(undoManager, index, callback1, callback2);
  17849. };
  17850. var matchFormat = function (editor, name, vars, node, similar) {
  17851. return getRtcInstanceWithError(editor).formatter.match(name, vars, node, similar);
  17852. };
  17853. var matchAllFormats = function (editor, names, vars) {
  17854. return getRtcInstanceWithError(editor).formatter.matchAll(names, vars);
  17855. };
  17856. var matchNodeFormat = function (editor, node, name, vars, similar) {
  17857. return getRtcInstanceWithError(editor).formatter.matchNode(node, name, vars, similar);
  17858. };
  17859. var canApplyFormat = function (editor, name) {
  17860. return getRtcInstanceWithError(editor).formatter.canApply(name);
  17861. };
  17862. var closestFormat = function (editor, names) {
  17863. return getRtcInstanceWithError(editor).formatter.closest(names);
  17864. };
  17865. var applyFormat = function (editor, name, vars, node) {
  17866. getRtcInstanceWithError(editor).formatter.apply(name, vars, node);
  17867. };
  17868. var removeFormat = function (editor, name, vars, node, similar) {
  17869. getRtcInstanceWithError(editor).formatter.remove(name, vars, node, similar);
  17870. };
  17871. var toggleFormat = function (editor, name, vars, node) {
  17872. getRtcInstanceWithError(editor).formatter.toggle(name, vars, node);
  17873. };
  17874. var formatChanged = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  17875. return getRtcInstanceWithError(editor).formatter.formatChanged(registeredFormatListeners, formats, callback, similar, vars);
  17876. };
  17877. var getContent$2 = function (editor, args, format) {
  17878. return getRtcInstanceWithFallback(editor).editor.getContent(args, format);
  17879. };
  17880. var setContent$2 = function (editor, content, args) {
  17881. return getRtcInstanceWithFallback(editor).editor.setContent(content, args);
  17882. };
  17883. var insertContent = function (editor, value, details) {
  17884. return getRtcInstanceWithFallback(editor).editor.insertContent(value, details);
  17885. };
  17886. var getSelectedContent = function (editor, format, args) {
  17887. return getRtcInstanceWithError(editor).selection.getContent(format, args);
  17888. };
  17889. var addVisual$1 = function (editor, elm) {
  17890. return getRtcInstanceWithError(editor).editor.addVisual(elm);
  17891. };
  17892. var getContent$1 = function (editor, args) {
  17893. if (args === void 0) {
  17894. args = {};
  17895. }
  17896. var format = args.format ? args.format : 'html';
  17897. return getSelectedContent(editor, format, args);
  17898. };
  17899. var removeEmpty = function (text) {
  17900. if (text.dom.length === 0) {
  17901. remove$7(text);
  17902. return Optional.none();
  17903. } else {
  17904. return Optional.some(text);
  17905. }
  17906. };
  17907. var walkPastBookmark = function (node, start) {
  17908. return node.filter(function (elm) {
  17909. return BookmarkManager.isBookmarkNode(elm.dom);
  17910. }).bind(start ? nextSibling : prevSibling);
  17911. };
  17912. var merge = function (outer, inner, rng, start) {
  17913. var outerElm = outer.dom;
  17914. var innerElm = inner.dom;
  17915. var oldLength = start ? outerElm.length : innerElm.length;
  17916. if (start) {
  17917. mergeTextNodes(outerElm, innerElm, false, !start);
  17918. rng.setStart(innerElm, oldLength);
  17919. } else {
  17920. mergeTextNodes(innerElm, outerElm, false, !start);
  17921. rng.setEnd(innerElm, oldLength);
  17922. }
  17923. };
  17924. var normalizeTextIfRequired = function (inner, start) {
  17925. parent(inner).each(function (root) {
  17926. var text = inner.dom;
  17927. if (start && needsToBeNbspLeft(root, CaretPosition(text, 0))) {
  17928. normalizeWhitespaceAfter(text, 0);
  17929. } else if (!start && needsToBeNbspRight(root, CaretPosition(text, text.length))) {
  17930. normalizeWhitespaceBefore(text, text.length);
  17931. }
  17932. });
  17933. };
  17934. var mergeAndNormalizeText = function (outerNode, innerNode, rng, start) {
  17935. outerNode.bind(function (outer) {
  17936. var normalizer = start ? normalizeWhitespaceBefore : normalizeWhitespaceAfter;
  17937. normalizer(outer.dom, start ? outer.dom.length : 0);
  17938. return innerNode.filter(isText$8).map(function (inner) {
  17939. return merge(outer, inner, rng, start);
  17940. });
  17941. }).orThunk(function () {
  17942. var innerTextNode = walkPastBookmark(innerNode, start).or(innerNode).filter(isText$8);
  17943. return innerTextNode.map(function (inner) {
  17944. return normalizeTextIfRequired(inner, start);
  17945. });
  17946. });
  17947. };
  17948. var rngSetContent = function (rng, fragment) {
  17949. var firstChild = Optional.from(fragment.firstChild).map(SugarElement.fromDom);
  17950. var lastChild = Optional.from(fragment.lastChild).map(SugarElement.fromDom);
  17951. rng.deleteContents();
  17952. rng.insertNode(fragment);
  17953. var prevText = firstChild.bind(prevSibling).filter(isText$8).bind(removeEmpty);
  17954. var nextText = lastChild.bind(nextSibling).filter(isText$8).bind(removeEmpty);
  17955. mergeAndNormalizeText(prevText, firstChild, rng, true);
  17956. mergeAndNormalizeText(nextText, lastChild, rng, false);
  17957. rng.collapse(false);
  17958. };
  17959. var setupArgs = function (args, content) {
  17960. return __assign(__assign({ format: 'html' }, args), {
  17961. set: true,
  17962. selection: true,
  17963. content: content
  17964. });
  17965. };
  17966. var cleanContent = function (editor, args) {
  17967. if (args.format !== 'raw') {
  17968. var rng = editor.selection.getRng();
  17969. var contextBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
  17970. var contextArgs = contextBlock ? { context: contextBlock.nodeName.toLowerCase() } : {};
  17971. var node = editor.parser.parse(args.content, __assign(__assign({
  17972. isRootContent: true,
  17973. forced_root_block: false
  17974. }, contextArgs), args));
  17975. return HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(node);
  17976. } else {
  17977. return args.content;
  17978. }
  17979. };
  17980. var setContent$1 = function (editor, content, args) {
  17981. if (args === void 0) {
  17982. args = {};
  17983. }
  17984. var contentArgs = setupArgs(args, content);
  17985. var updatedArgs = contentArgs;
  17986. if (!contentArgs.no_events) {
  17987. var eventArgs = editor.fire('BeforeSetContent', contentArgs);
  17988. if (eventArgs.isDefaultPrevented()) {
  17989. editor.fire('SetContent', eventArgs);
  17990. return;
  17991. } else {
  17992. updatedArgs = eventArgs;
  17993. }
  17994. }
  17995. updatedArgs.content = cleanContent(editor, updatedArgs);
  17996. var rng = editor.selection.getRng();
  17997. rngSetContent(rng, rng.createContextualFragment(updatedArgs.content));
  17998. editor.selection.setRng(rng);
  17999. scrollRangeIntoView(editor, rng);
  18000. if (!updatedArgs.no_events) {
  18001. editor.fire('SetContent', updatedArgs);
  18002. }
  18003. };
  18004. var deleteFromCallbackMap = function (callbackMap, selector, callback) {
  18005. if (callbackMap && has$2(callbackMap, selector)) {
  18006. var newCallbacks = filter$4(callbackMap[selector], function (cb) {
  18007. return cb !== callback;
  18008. });
  18009. if (newCallbacks.length === 0) {
  18010. delete callbackMap[selector];
  18011. } else {
  18012. callbackMap[selector] = newCallbacks;
  18013. }
  18014. }
  18015. };
  18016. function SelectorChanged (dom, editor) {
  18017. var selectorChangedData;
  18018. var currentSelectors;
  18019. return {
  18020. selectorChangedWithUnbind: function (selector, callback) {
  18021. if (!selectorChangedData) {
  18022. selectorChangedData = {};
  18023. currentSelectors = {};
  18024. editor.on('NodeChange', function (e) {
  18025. var node = e.element, parents = dom.getParents(node, null, dom.getRoot()), matchedSelectors = {};
  18026. Tools.each(selectorChangedData, function (callbacks, selector) {
  18027. Tools.each(parents, function (node) {
  18028. if (dom.is(node, selector)) {
  18029. if (!currentSelectors[selector]) {
  18030. Tools.each(callbacks, function (callback) {
  18031. callback(true, {
  18032. node: node,
  18033. selector: selector,
  18034. parents: parents
  18035. });
  18036. });
  18037. currentSelectors[selector] = callbacks;
  18038. }
  18039. matchedSelectors[selector] = callbacks;
  18040. return false;
  18041. }
  18042. });
  18043. });
  18044. Tools.each(currentSelectors, function (callbacks, selector) {
  18045. if (!matchedSelectors[selector]) {
  18046. delete currentSelectors[selector];
  18047. Tools.each(callbacks, function (callback) {
  18048. callback(false, {
  18049. node: node,
  18050. selector: selector,
  18051. parents: parents
  18052. });
  18053. });
  18054. }
  18055. });
  18056. });
  18057. }
  18058. if (!selectorChangedData[selector]) {
  18059. selectorChangedData[selector] = [];
  18060. }
  18061. selectorChangedData[selector].push(callback);
  18062. return {
  18063. unbind: function () {
  18064. deleteFromCallbackMap(selectorChangedData, selector, callback);
  18065. deleteFromCallbackMap(currentSelectors, selector, callback);
  18066. }
  18067. };
  18068. }
  18069. };
  18070. }
  18071. var isNativeIeSelection = function (rng) {
  18072. return !!rng.select;
  18073. };
  18074. var isAttachedToDom = function (node) {
  18075. return !!(node && node.ownerDocument) && contains$1(SugarElement.fromDom(node.ownerDocument), SugarElement.fromDom(node));
  18076. };
  18077. var isValidRange = function (rng) {
  18078. if (!rng) {
  18079. return false;
  18080. } else if (isNativeIeSelection(rng)) {
  18081. return true;
  18082. } else {
  18083. return isAttachedToDom(rng.startContainer) && isAttachedToDom(rng.endContainer);
  18084. }
  18085. };
  18086. var EditorSelection = function (dom, win, serializer, editor) {
  18087. var selectedRange;
  18088. var explicitRange;
  18089. var selectorChangedWithUnbind = SelectorChanged(dom, editor).selectorChangedWithUnbind;
  18090. var setCursorLocation = function (node, offset) {
  18091. var rng = dom.createRng();
  18092. if (isNonNullable(node) && isNonNullable(offset)) {
  18093. rng.setStart(node, offset);
  18094. rng.setEnd(node, offset);
  18095. setRng(rng);
  18096. collapse(false);
  18097. } else {
  18098. moveEndPoint(dom, rng, editor.getBody(), true);
  18099. setRng(rng);
  18100. }
  18101. };
  18102. var getContent = function (args) {
  18103. return getContent$1(editor, args);
  18104. };
  18105. var setContent = function (content, args) {
  18106. return setContent$1(editor, content, args);
  18107. };
  18108. var getStart$1 = function (real) {
  18109. return getStart(editor.getBody(), getRng$1(), real);
  18110. };
  18111. var getEnd$1 = function (real) {
  18112. return getEnd(editor.getBody(), getRng$1(), real);
  18113. };
  18114. var getBookmark = function (type, normalized) {
  18115. return bookmarkManager.getBookmark(type, normalized);
  18116. };
  18117. var moveToBookmark = function (bookmark) {
  18118. return bookmarkManager.moveToBookmark(bookmark);
  18119. };
  18120. var select$1 = function (node, content) {
  18121. select(dom, node, content).each(setRng);
  18122. return node;
  18123. };
  18124. var isCollapsed = function () {
  18125. var rng = getRng$1(), sel = getSel();
  18126. if (!rng || rng.item) {
  18127. return false;
  18128. }
  18129. if (rng.compareEndPoints) {
  18130. return rng.compareEndPoints('StartToEnd', rng) === 0;
  18131. }
  18132. return !sel || rng.collapsed;
  18133. };
  18134. var collapse = function (toStart) {
  18135. var rng = getRng$1();
  18136. rng.collapse(!!toStart);
  18137. setRng(rng);
  18138. };
  18139. var getSel = function () {
  18140. return win.getSelection ? win.getSelection() : win.document.selection;
  18141. };
  18142. var getRng$1 = function () {
  18143. var selection, rng, elm;
  18144. var tryCompareBoundaryPoints = function (how, sourceRange, destinationRange) {
  18145. try {
  18146. return sourceRange.compareBoundaryPoints(how, destinationRange);
  18147. } catch (ex) {
  18148. return -1;
  18149. }
  18150. };
  18151. var doc = win.document;
  18152. if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  18153. var bookmark = getRng(editor);
  18154. if (bookmark.isSome()) {
  18155. return bookmark.map(function (r) {
  18156. return processRanges(editor, [r])[0];
  18157. }).getOr(doc.createRange());
  18158. }
  18159. }
  18160. try {
  18161. if ((selection = getSel()) && !isRestrictedNode(selection.anchorNode)) {
  18162. if (selection.rangeCount > 0) {
  18163. rng = selection.getRangeAt(0);
  18164. } else {
  18165. rng = selection.createRange ? selection.createRange() : doc.createRange();
  18166. }
  18167. rng = processRanges(editor, [rng])[0];
  18168. }
  18169. } catch (ex) {
  18170. }
  18171. if (!rng) {
  18172. rng = doc.createRange ? doc.createRange() : doc.body.createTextRange();
  18173. }
  18174. if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
  18175. elm = dom.getRoot();
  18176. rng.setStart(elm, 0);
  18177. rng.setEnd(elm, 0);
  18178. }
  18179. if (selectedRange && explicitRange) {
  18180. if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 && tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
  18181. rng = explicitRange;
  18182. } else {
  18183. selectedRange = null;
  18184. explicitRange = null;
  18185. }
  18186. }
  18187. return rng;
  18188. };
  18189. var setRng = function (rng, forward) {
  18190. var node;
  18191. if (!isValidRange(rng)) {
  18192. return;
  18193. }
  18194. var ieRange = isNativeIeSelection(rng) ? rng : null;
  18195. if (ieRange) {
  18196. explicitRange = null;
  18197. try {
  18198. ieRange.select();
  18199. } catch (ex) {
  18200. }
  18201. return;
  18202. }
  18203. var sel = getSel();
  18204. var evt = editor.fire('SetSelectionRange', {
  18205. range: rng,
  18206. forward: forward
  18207. });
  18208. rng = evt.range;
  18209. if (sel) {
  18210. explicitRange = rng;
  18211. try {
  18212. sel.removeAllRanges();
  18213. sel.addRange(rng);
  18214. } catch (ex) {
  18215. }
  18216. if (forward === false && sel.extend) {
  18217. sel.collapse(rng.endContainer, rng.endOffset);
  18218. sel.extend(rng.startContainer, rng.startOffset);
  18219. }
  18220. selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
  18221. }
  18222. if (!rng.collapsed && rng.startContainer === rng.endContainer && sel.setBaseAndExtent && !Env.ie) {
  18223. if (rng.endOffset - rng.startOffset < 2) {
  18224. if (rng.startContainer.hasChildNodes()) {
  18225. node = rng.startContainer.childNodes[rng.startOffset];
  18226. if (node && node.tagName === 'IMG') {
  18227. sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
  18228. if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
  18229. sel.setBaseAndExtent(node, 0, node, 1);
  18230. }
  18231. }
  18232. }
  18233. }
  18234. }
  18235. editor.fire('AfterSetSelectionRange', {
  18236. range: rng,
  18237. forward: forward
  18238. });
  18239. };
  18240. var setNode = function (elm) {
  18241. setContent(dom.getOuterHTML(elm));
  18242. return elm;
  18243. };
  18244. var getNode$1 = function () {
  18245. return getNode(editor.getBody(), getRng$1());
  18246. };
  18247. var getSelectedBlocks$1 = function (startElm, endElm) {
  18248. return getSelectedBlocks(dom, getRng$1(), startElm, endElm);
  18249. };
  18250. var isForward = function () {
  18251. var sel = getSel();
  18252. var anchorNode = sel === null || sel === void 0 ? void 0 : sel.anchorNode;
  18253. var focusNode = sel === null || sel === void 0 ? void 0 : sel.focusNode;
  18254. if (!sel || !anchorNode || !focusNode || isRestrictedNode(anchorNode) || isRestrictedNode(focusNode)) {
  18255. return true;
  18256. }
  18257. var anchorRange = dom.createRng();
  18258. anchorRange.setStart(anchorNode, sel.anchorOffset);
  18259. anchorRange.collapse(true);
  18260. var focusRange = dom.createRng();
  18261. focusRange.setStart(focusNode, sel.focusOffset);
  18262. focusRange.collapse(true);
  18263. return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
  18264. };
  18265. var normalize = function () {
  18266. var rng = getRng$1();
  18267. var sel = getSel();
  18268. if (!hasMultipleRanges(sel) && hasAnyRanges(editor)) {
  18269. var normRng = normalize$2(dom, rng);
  18270. normRng.each(function (normRng) {
  18271. setRng(normRng, isForward());
  18272. });
  18273. return normRng.getOr(rng);
  18274. }
  18275. return rng;
  18276. };
  18277. var selectorChanged = function (selector, callback) {
  18278. selectorChangedWithUnbind(selector, callback);
  18279. return exports;
  18280. };
  18281. var getScrollContainer = function () {
  18282. var scrollContainer;
  18283. var node = dom.getRoot();
  18284. while (node && node.nodeName !== 'BODY') {
  18285. if (node.scrollHeight > node.clientHeight) {
  18286. scrollContainer = node;
  18287. break;
  18288. }
  18289. node = node.parentNode;
  18290. }
  18291. return scrollContainer;
  18292. };
  18293. var scrollIntoView = function (elm, alignToTop) {
  18294. return scrollElementIntoView(editor, elm, alignToTop);
  18295. };
  18296. var placeCaretAt = function (clientX, clientY) {
  18297. return setRng(fromPoint(clientX, clientY, editor.getDoc()));
  18298. };
  18299. var getBoundingClientRect = function () {
  18300. var rng = getRng$1();
  18301. return rng.collapsed ? CaretPosition.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
  18302. };
  18303. var destroy = function () {
  18304. win = selectedRange = explicitRange = null;
  18305. controlSelection.destroy();
  18306. };
  18307. var exports = {
  18308. bookmarkManager: null,
  18309. controlSelection: null,
  18310. dom: dom,
  18311. win: win,
  18312. serializer: serializer,
  18313. editor: editor,
  18314. collapse: collapse,
  18315. setCursorLocation: setCursorLocation,
  18316. getContent: getContent,
  18317. setContent: setContent,
  18318. getBookmark: getBookmark,
  18319. moveToBookmark: moveToBookmark,
  18320. select: select$1,
  18321. isCollapsed: isCollapsed,
  18322. isForward: isForward,
  18323. setNode: setNode,
  18324. getNode: getNode$1,
  18325. getSel: getSel,
  18326. setRng: setRng,
  18327. getRng: getRng$1,
  18328. getStart: getStart$1,
  18329. getEnd: getEnd$1,
  18330. getSelectedBlocks: getSelectedBlocks$1,
  18331. normalize: normalize,
  18332. selectorChanged: selectorChanged,
  18333. selectorChangedWithUnbind: selectorChangedWithUnbind,
  18334. getScrollContainer: getScrollContainer,
  18335. scrollIntoView: scrollIntoView,
  18336. placeCaretAt: placeCaretAt,
  18337. getBoundingClientRect: getBoundingClientRect,
  18338. destroy: destroy
  18339. };
  18340. var bookmarkManager = BookmarkManager(exports);
  18341. var controlSelection = ControlSelection(exports, editor);
  18342. exports.bookmarkManager = bookmarkManager;
  18343. exports.controlSelection = controlSelection;
  18344. return exports;
  18345. };
  18346. var removeAttrs = function (node, names) {
  18347. each$k(names, function (name) {
  18348. node.attr(name, null);
  18349. });
  18350. };
  18351. var addFontToSpansFilter = function (domParser, styles, fontSizes) {
  18352. domParser.addNodeFilter('font', function (nodes) {
  18353. each$k(nodes, function (node) {
  18354. var props = styles.parse(node.attr('style'));
  18355. var color = node.attr('color');
  18356. var face = node.attr('face');
  18357. var size = node.attr('size');
  18358. if (color) {
  18359. props.color = color;
  18360. }
  18361. if (face) {
  18362. props['font-family'] = face;
  18363. }
  18364. if (size) {
  18365. props['font-size'] = fontSizes[parseInt(node.attr('size'), 10) - 1];
  18366. }
  18367. node.name = 'span';
  18368. node.attr('style', styles.serialize(props));
  18369. removeAttrs(node, [
  18370. 'color',
  18371. 'face',
  18372. 'size'
  18373. ]);
  18374. });
  18375. });
  18376. };
  18377. var addStrikeToSpanFilter = function (domParser, styles) {
  18378. domParser.addNodeFilter('strike', function (nodes) {
  18379. each$k(nodes, function (node) {
  18380. var props = styles.parse(node.attr('style'));
  18381. props['text-decoration'] = 'line-through';
  18382. node.name = 'span';
  18383. node.attr('style', styles.serialize(props));
  18384. });
  18385. });
  18386. };
  18387. var addFilters = function (domParser, settings) {
  18388. var styles = Styles();
  18389. if (settings.convert_fonts_to_spans) {
  18390. addFontToSpansFilter(domParser, styles, Tools.explode(settings.font_size_legacy_values));
  18391. }
  18392. addStrikeToSpanFilter(domParser, styles);
  18393. };
  18394. var register$2 = function (domParser, settings) {
  18395. if (settings.inline_styles) {
  18396. addFilters(domParser, settings);
  18397. }
  18398. };
  18399. var blobUriToBlob = function (url) {
  18400. return new promiseObj(function (resolve, reject) {
  18401. var rejectWithError = function () {
  18402. reject('Cannot convert ' + url + ' to Blob. Resource might not exist or is inaccessible.');
  18403. };
  18404. try {
  18405. var xhr_1 = new XMLHttpRequest();
  18406. xhr_1.open('GET', url, true);
  18407. xhr_1.responseType = 'blob';
  18408. xhr_1.onload = function () {
  18409. if (xhr_1.status === 200) {
  18410. resolve(xhr_1.response);
  18411. } else {
  18412. rejectWithError();
  18413. }
  18414. };
  18415. xhr_1.onerror = rejectWithError;
  18416. xhr_1.send();
  18417. } catch (ex) {
  18418. rejectWithError();
  18419. }
  18420. });
  18421. };
  18422. var parseDataUri = function (uri) {
  18423. var type;
  18424. var uriParts = decodeURIComponent(uri).split(',');
  18425. var matches = /data:([^;]+)/.exec(uriParts[0]);
  18426. if (matches) {
  18427. type = matches[1];
  18428. }
  18429. return {
  18430. type: type,
  18431. data: uriParts[1]
  18432. };
  18433. };
  18434. var buildBlob = function (type, data) {
  18435. var str;
  18436. try {
  18437. str = atob(data);
  18438. } catch (e) {
  18439. return Optional.none();
  18440. }
  18441. var arr = new Uint8Array(str.length);
  18442. for (var i = 0; i < arr.length; i++) {
  18443. arr[i] = str.charCodeAt(i);
  18444. }
  18445. return Optional.some(new Blob([arr], { type: type }));
  18446. };
  18447. var dataUriToBlob = function (uri) {
  18448. return new promiseObj(function (resolve) {
  18449. var _a = parseDataUri(uri), type = _a.type, data = _a.data;
  18450. buildBlob(type, data).fold(function () {
  18451. return resolve(new Blob([]));
  18452. }, resolve);
  18453. });
  18454. };
  18455. var uriToBlob = function (url) {
  18456. if (url.indexOf('blob:') === 0) {
  18457. return blobUriToBlob(url);
  18458. }
  18459. if (url.indexOf('data:') === 0) {
  18460. return dataUriToBlob(url);
  18461. }
  18462. return null;
  18463. };
  18464. var blobToDataUri = function (blob) {
  18465. return new promiseObj(function (resolve) {
  18466. var reader = new FileReader();
  18467. reader.onloadend = function () {
  18468. resolve(reader.result);
  18469. };
  18470. reader.readAsDataURL(blob);
  18471. });
  18472. };
  18473. var count$1 = 0;
  18474. var uniqueId = function (prefix) {
  18475. return (prefix || 'blobid') + count$1++;
  18476. };
  18477. var imageToBlobInfo = function (blobCache, img, resolve, reject) {
  18478. var base64, blobInfo;
  18479. if (img.src.indexOf('blob:') === 0) {
  18480. blobInfo = blobCache.getByUri(img.src);
  18481. if (blobInfo) {
  18482. resolve({
  18483. image: img,
  18484. blobInfo: blobInfo
  18485. });
  18486. } else {
  18487. uriToBlob(img.src).then(function (blob) {
  18488. blobToDataUri(blob).then(function (dataUri) {
  18489. base64 = parseDataUri(dataUri).data;
  18490. blobInfo = blobCache.create(uniqueId(), blob, base64);
  18491. blobCache.add(blobInfo);
  18492. resolve({
  18493. image: img,
  18494. blobInfo: blobInfo
  18495. });
  18496. });
  18497. }, function (err) {
  18498. reject(err);
  18499. });
  18500. }
  18501. return;
  18502. }
  18503. var _a = parseDataUri(img.src), data = _a.data, type = _a.type;
  18504. base64 = data;
  18505. blobInfo = blobCache.getByData(base64, type);
  18506. if (blobInfo) {
  18507. resolve({
  18508. image: img,
  18509. blobInfo: blobInfo
  18510. });
  18511. } else {
  18512. uriToBlob(img.src).then(function (blob) {
  18513. blobInfo = blobCache.create(uniqueId(), blob, base64);
  18514. blobCache.add(blobInfo);
  18515. resolve({
  18516. image: img,
  18517. blobInfo: blobInfo
  18518. });
  18519. }, function (err) {
  18520. reject(err);
  18521. });
  18522. }
  18523. };
  18524. var getAllImages = function (elm) {
  18525. return elm ? from(elm.getElementsByTagName('img')) : [];
  18526. };
  18527. var ImageScanner = function (uploadStatus, blobCache) {
  18528. var cachedPromises = {};
  18529. var findAll = function (elm, predicate) {
  18530. if (!predicate) {
  18531. predicate = always;
  18532. }
  18533. var images = filter$4(getAllImages(elm), function (img) {
  18534. var src = img.src;
  18535. if (!Env.fileApi) {
  18536. return false;
  18537. }
  18538. if (img.hasAttribute('data-mce-bogus')) {
  18539. return false;
  18540. }
  18541. if (img.hasAttribute('data-mce-placeholder')) {
  18542. return false;
  18543. }
  18544. if (!src || src === Env.transparentSrc) {
  18545. return false;
  18546. }
  18547. if (src.indexOf('blob:') === 0) {
  18548. return !uploadStatus.isUploaded(src) && predicate(img);
  18549. }
  18550. if (src.indexOf('data:') === 0) {
  18551. return predicate(img);
  18552. }
  18553. return false;
  18554. });
  18555. var promises = map$3(images, function (img) {
  18556. if (cachedPromises[img.src] !== undefined) {
  18557. return new promiseObj(function (resolve) {
  18558. cachedPromises[img.src].then(function (imageInfo) {
  18559. if (typeof imageInfo === 'string') {
  18560. return imageInfo;
  18561. }
  18562. resolve({
  18563. image: img,
  18564. blobInfo: imageInfo.blobInfo
  18565. });
  18566. });
  18567. });
  18568. }
  18569. var newPromise = new promiseObj(function (resolve, reject) {
  18570. imageToBlobInfo(blobCache, img, resolve, reject);
  18571. }).then(function (result) {
  18572. delete cachedPromises[result.image.src];
  18573. return result;
  18574. }).catch(function (error) {
  18575. delete cachedPromises[img.src];
  18576. return error;
  18577. });
  18578. cachedPromises[img.src] = newPromise;
  18579. return newPromise;
  18580. });
  18581. return promiseObj.all(promises);
  18582. };
  18583. return { findAll: findAll };
  18584. };
  18585. var paddEmptyNode = function (settings, args, blockElements, node) {
  18586. var brPreferred = settings.padd_empty_with_br || args.insert;
  18587. if (brPreferred && blockElements[node.name]) {
  18588. node.empty().append(new AstNode('br', 1)).shortEnded = true;
  18589. } else {
  18590. node.empty().append(new AstNode('#text', 3)).value = nbsp;
  18591. }
  18592. };
  18593. var isPaddedWithNbsp = function (node) {
  18594. return hasOnlyChild(node, '#text') && node.firstChild.value === nbsp;
  18595. };
  18596. var hasOnlyChild = function (node, name) {
  18597. return node && node.firstChild && node.firstChild === node.lastChild && node.firstChild.name === name;
  18598. };
  18599. var isPadded = function (schema, node) {
  18600. var rule = schema.getElementRule(node.name);
  18601. return rule && rule.paddEmpty;
  18602. };
  18603. var isEmpty = function (schema, nonEmptyElements, whitespaceElements, node) {
  18604. return node.isEmpty(nonEmptyElements, whitespaceElements, function (node) {
  18605. return isPadded(schema, node);
  18606. });
  18607. };
  18608. var isLineBreakNode = function (node, blockElements) {
  18609. return node && (has$2(blockElements, node.name) || node.name === 'br');
  18610. };
  18611. var isBogusImage = function (img) {
  18612. return isNonNullable(img.attr('data-mce-bogus'));
  18613. };
  18614. var isInternalImageSource = function (img) {
  18615. return img.attr('src') === Env.transparentSrc || isNonNullable(img.attr('data-mce-placeholder'));
  18616. };
  18617. var isValidDataImg = function (img, settings) {
  18618. if (settings.images_dataimg_filter) {
  18619. var imgElem_1 = new Image();
  18620. imgElem_1.src = img.attr('src');
  18621. each$j(img.attributes.map, function (value, key) {
  18622. imgElem_1.setAttribute(key, value);
  18623. });
  18624. return settings.images_dataimg_filter(imgElem_1);
  18625. } else {
  18626. return true;
  18627. }
  18628. };
  18629. var registerBase64ImageFilter = function (parser, settings) {
  18630. var blobCache = settings.blob_cache;
  18631. var processImage = function (img) {
  18632. var inputSrc = img.attr('src');
  18633. if (isInternalImageSource(img) || isBogusImage(img)) {
  18634. return;
  18635. }
  18636. parseDataUri$1(inputSrc).filter(function () {
  18637. return isValidDataImg(img, settings);
  18638. }).bind(function (_a) {
  18639. var type = _a.type, data = _a.data;
  18640. return Optional.from(blobCache.getByData(data, type)).orThunk(function () {
  18641. return buildBlob(type, data).map(function (blob) {
  18642. var blobInfo = blobCache.create(uniqueId(), blob, data);
  18643. blobCache.add(blobInfo);
  18644. return blobInfo;
  18645. });
  18646. });
  18647. }).each(function (blobInfo) {
  18648. img.attr('src', blobInfo.blobUri());
  18649. });
  18650. };
  18651. if (blobCache) {
  18652. parser.addAttributeFilter('src', function (nodes) {
  18653. return each$k(nodes, processImage);
  18654. });
  18655. }
  18656. };
  18657. var register$1 = function (parser, settings) {
  18658. var schema = parser.schema;
  18659. if (settings.remove_trailing_brs) {
  18660. parser.addNodeFilter('br', function (nodes, _, args) {
  18661. var i;
  18662. var l = nodes.length;
  18663. var node;
  18664. var blockElements = Tools.extend({}, schema.getBlockElements());
  18665. var nonEmptyElements = schema.getNonEmptyElements();
  18666. var parent, lastParent, prev, prevName;
  18667. var whiteSpaceElements = schema.getWhiteSpaceElements();
  18668. var elementRule, textNode;
  18669. blockElements.body = 1;
  18670. for (i = 0; i < l; i++) {
  18671. node = nodes[i];
  18672. parent = node.parent;
  18673. if (blockElements[node.parent.name] && node === parent.lastChild) {
  18674. prev = node.prev;
  18675. while (prev) {
  18676. prevName = prev.name;
  18677. if (prevName !== 'span' || prev.attr('data-mce-type') !== 'bookmark') {
  18678. if (prevName === 'br') {
  18679. node = null;
  18680. }
  18681. break;
  18682. }
  18683. prev = prev.prev;
  18684. }
  18685. if (node) {
  18686. node.remove();
  18687. if (isEmpty(schema, nonEmptyElements, whiteSpaceElements, parent)) {
  18688. elementRule = schema.getElementRule(parent.name);
  18689. if (elementRule) {
  18690. if (elementRule.removeEmpty) {
  18691. parent.remove();
  18692. } else if (elementRule.paddEmpty) {
  18693. paddEmptyNode(settings, args, blockElements, parent);
  18694. }
  18695. }
  18696. }
  18697. }
  18698. } else {
  18699. lastParent = node;
  18700. while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) {
  18701. lastParent = parent;
  18702. if (blockElements[parent.name]) {
  18703. break;
  18704. }
  18705. parent = parent.parent;
  18706. }
  18707. if (lastParent === parent && settings.padd_empty_with_br !== true) {
  18708. textNode = new AstNode('#text', 3);
  18709. textNode.value = nbsp;
  18710. node.replace(textNode);
  18711. }
  18712. }
  18713. }
  18714. });
  18715. }
  18716. parser.addAttributeFilter('href', function (nodes) {
  18717. var i = nodes.length;
  18718. var appendRel = function (rel) {
  18719. var parts = rel.split(' ').filter(function (p) {
  18720. return p.length > 0;
  18721. });
  18722. return parts.concat(['noopener']).sort().join(' ');
  18723. };
  18724. var addNoOpener = function (rel) {
  18725. var newRel = rel ? Tools.trim(rel) : '';
  18726. if (!/\b(noopener)\b/g.test(newRel)) {
  18727. return appendRel(newRel);
  18728. } else {
  18729. return newRel;
  18730. }
  18731. };
  18732. if (!settings.allow_unsafe_link_target) {
  18733. while (i--) {
  18734. var node = nodes[i];
  18735. if (node.name === 'a' && node.attr('target') === '_blank') {
  18736. node.attr('rel', addNoOpener(node.attr('rel')));
  18737. }
  18738. }
  18739. }
  18740. });
  18741. if (!settings.allow_html_in_named_anchor) {
  18742. parser.addAttributeFilter('id,name', function (nodes) {
  18743. var i = nodes.length, sibling, prevSibling, parent, node;
  18744. while (i--) {
  18745. node = nodes[i];
  18746. if (node.name === 'a' && node.firstChild && !node.attr('href')) {
  18747. parent = node.parent;
  18748. sibling = node.lastChild;
  18749. do {
  18750. prevSibling = sibling.prev;
  18751. parent.insert(sibling, node);
  18752. sibling = prevSibling;
  18753. } while (sibling);
  18754. }
  18755. }
  18756. });
  18757. }
  18758. if (settings.fix_list_elements) {
  18759. parser.addNodeFilter('ul,ol', function (nodes) {
  18760. var i = nodes.length, node, parentNode;
  18761. while (i--) {
  18762. node = nodes[i];
  18763. parentNode = node.parent;
  18764. if (parentNode.name === 'ul' || parentNode.name === 'ol') {
  18765. if (node.prev && node.prev.name === 'li') {
  18766. node.prev.append(node);
  18767. } else {
  18768. var li = new AstNode('li', 1);
  18769. li.attr('style', 'list-style-type: none');
  18770. node.wrap(li);
  18771. }
  18772. }
  18773. }
  18774. });
  18775. }
  18776. if (settings.validate && schema.getValidClasses()) {
  18777. parser.addAttributeFilter('class', function (nodes) {
  18778. var validClasses = schema.getValidClasses();
  18779. var i = nodes.length;
  18780. while (i--) {
  18781. var node = nodes[i];
  18782. var classList = node.attr('class').split(' ');
  18783. var classValue = '';
  18784. for (var ci = 0; ci < classList.length; ci++) {
  18785. var className = classList[ci];
  18786. var valid = false;
  18787. var validClassesMap = validClasses['*'];
  18788. if (validClassesMap && validClassesMap[className]) {
  18789. valid = true;
  18790. }
  18791. validClassesMap = validClasses[node.name];
  18792. if (!valid && validClassesMap && validClassesMap[className]) {
  18793. valid = true;
  18794. }
  18795. if (valid) {
  18796. if (classValue) {
  18797. classValue += ' ';
  18798. }
  18799. classValue += className;
  18800. }
  18801. }
  18802. if (!classValue.length) {
  18803. classValue = null;
  18804. }
  18805. node.attr('class', classValue);
  18806. }
  18807. });
  18808. }
  18809. registerBase64ImageFilter(parser, settings);
  18810. };
  18811. var makeMap = Tools.makeMap, each$7 = Tools.each, explode$2 = Tools.explode, extend$4 = Tools.extend;
  18812. var DomParser = function (settings, schema) {
  18813. if (schema === void 0) {
  18814. schema = Schema();
  18815. }
  18816. var nodeFilters = {};
  18817. var attributeFilters = [];
  18818. var matchedNodes = {};
  18819. var matchedAttributes = {};
  18820. settings = settings || {};
  18821. settings.validate = 'validate' in settings ? settings.validate : true;
  18822. settings.root_name = settings.root_name || 'body';
  18823. var fixInvalidChildren = function (nodes) {
  18824. var nonSplitableElements = makeMap('tr,td,th,tbody,thead,tfoot,table');
  18825. var nonEmptyElements = schema.getNonEmptyElements();
  18826. var whitespaceElements = schema.getWhiteSpaceElements();
  18827. var textBlockElements = schema.getTextBlockElements();
  18828. var specialElements = schema.getSpecialElements();
  18829. var removeOrUnwrapInvalidNode = function (node, originalNodeParent) {
  18830. if (originalNodeParent === void 0) {
  18831. originalNodeParent = node.parent;
  18832. }
  18833. if (specialElements[node.name]) {
  18834. node.empty().remove();
  18835. } else {
  18836. var children = node.children();
  18837. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  18838. var childNode = children_1[_i];
  18839. if (!schema.isValidChild(originalNodeParent.name, childNode.name)) {
  18840. removeOrUnwrapInvalidNode(childNode, originalNodeParent);
  18841. }
  18842. }
  18843. node.unwrap();
  18844. }
  18845. };
  18846. for (var ni = 0; ni < nodes.length; ni++) {
  18847. var node = nodes[ni];
  18848. var parent_1 = void 0, newParent = void 0, tempNode = void 0;
  18849. if (!node.parent || node.fixed) {
  18850. continue;
  18851. }
  18852. if (textBlockElements[node.name] && node.parent.name === 'li') {
  18853. var sibling = node.next;
  18854. while (sibling) {
  18855. if (textBlockElements[sibling.name]) {
  18856. sibling.name = 'li';
  18857. sibling.fixed = true;
  18858. node.parent.insert(sibling, node.parent);
  18859. } else {
  18860. break;
  18861. }
  18862. sibling = sibling.next;
  18863. }
  18864. node.unwrap();
  18865. continue;
  18866. }
  18867. var parents = [node];
  18868. for (parent_1 = node.parent; parent_1 && !schema.isValidChild(parent_1.name, node.name) && !nonSplitableElements[parent_1.name]; parent_1 = parent_1.parent) {
  18869. parents.push(parent_1);
  18870. }
  18871. if (parent_1 && parents.length > 1) {
  18872. if (schema.isValidChild(parent_1.name, node.name)) {
  18873. parents.reverse();
  18874. newParent = filterNode(parents[0].clone());
  18875. var currentNode = newParent;
  18876. for (var i = 0; i < parents.length - 1; i++) {
  18877. if (schema.isValidChild(currentNode.name, parents[i].name)) {
  18878. tempNode = filterNode(parents[i].clone());
  18879. currentNode.append(tempNode);
  18880. } else {
  18881. tempNode = currentNode;
  18882. }
  18883. for (var childNode = parents[i].firstChild; childNode && childNode !== parents[i + 1];) {
  18884. var nextNode = childNode.next;
  18885. tempNode.append(childNode);
  18886. childNode = nextNode;
  18887. }
  18888. currentNode = tempNode;
  18889. }
  18890. if (!isEmpty(schema, nonEmptyElements, whitespaceElements, newParent)) {
  18891. parent_1.insert(newParent, parents[0], true);
  18892. parent_1.insert(node, newParent);
  18893. } else {
  18894. parent_1.insert(node, parents[0], true);
  18895. }
  18896. parent_1 = parents[0];
  18897. if (isEmpty(schema, nonEmptyElements, whitespaceElements, parent_1) || hasOnlyChild(parent_1, 'br')) {
  18898. parent_1.empty().remove();
  18899. }
  18900. } else {
  18901. removeOrUnwrapInvalidNode(node);
  18902. }
  18903. } else if (node.parent) {
  18904. if (node.name === 'li') {
  18905. var sibling = node.prev;
  18906. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  18907. sibling.append(node);
  18908. continue;
  18909. }
  18910. sibling = node.next;
  18911. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  18912. sibling.insert(node, sibling.firstChild, true);
  18913. continue;
  18914. }
  18915. node.wrap(filterNode(new AstNode('ul', 1)));
  18916. continue;
  18917. }
  18918. if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
  18919. node.wrap(filterNode(new AstNode('div', 1)));
  18920. } else {
  18921. removeOrUnwrapInvalidNode(node);
  18922. }
  18923. }
  18924. }
  18925. };
  18926. var filterNode = function (node) {
  18927. var name = node.name;
  18928. if (name in nodeFilters) {
  18929. var list = matchedNodes[name];
  18930. if (list) {
  18931. list.push(node);
  18932. } else {
  18933. matchedNodes[name] = [node];
  18934. }
  18935. }
  18936. var i = attributeFilters.length;
  18937. while (i--) {
  18938. var attrName = attributeFilters[i].name;
  18939. if (attrName in node.attributes.map) {
  18940. var list = matchedAttributes[attrName];
  18941. if (list) {
  18942. list.push(node);
  18943. } else {
  18944. matchedAttributes[attrName] = [node];
  18945. }
  18946. }
  18947. }
  18948. return node;
  18949. };
  18950. var addNodeFilter = function (name, callback) {
  18951. each$7(explode$2(name), function (name) {
  18952. var list = nodeFilters[name];
  18953. if (!list) {
  18954. nodeFilters[name] = list = [];
  18955. }
  18956. list.push(callback);
  18957. });
  18958. };
  18959. var getNodeFilters = function () {
  18960. var out = [];
  18961. for (var name_1 in nodeFilters) {
  18962. if (has$2(nodeFilters, name_1)) {
  18963. out.push({
  18964. name: name_1,
  18965. callbacks: nodeFilters[name_1]
  18966. });
  18967. }
  18968. }
  18969. return out;
  18970. };
  18971. var addAttributeFilter = function (name, callback) {
  18972. each$7(explode$2(name), function (name) {
  18973. var i;
  18974. for (i = 0; i < attributeFilters.length; i++) {
  18975. if (attributeFilters[i].name === name) {
  18976. attributeFilters[i].callbacks.push(callback);
  18977. return;
  18978. }
  18979. }
  18980. attributeFilters.push({
  18981. name: name,
  18982. callbacks: [callback]
  18983. });
  18984. });
  18985. };
  18986. var getAttributeFilters = function () {
  18987. return [].concat(attributeFilters);
  18988. };
  18989. var parse = function (html, args) {
  18990. var nodes, i, l, fi, fl, list, name;
  18991. var invalidChildren = [];
  18992. var node;
  18993. var getRootBlockName = function (name) {
  18994. if (name === false) {
  18995. return '';
  18996. } else if (name === true) {
  18997. return 'p';
  18998. } else {
  18999. return name;
  19000. }
  19001. };
  19002. args = args || {};
  19003. matchedNodes = {};
  19004. matchedAttributes = {};
  19005. var blockElements = extend$4(makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  19006. var nonEmptyElements = schema.getNonEmptyElements();
  19007. var children = schema.children;
  19008. var validate = settings.validate;
  19009. var forcedRootBlockName = 'forced_root_block' in args ? args.forced_root_block : settings.forced_root_block;
  19010. var rootBlockName = getRootBlockName(forcedRootBlockName);
  19011. var whiteSpaceElements = schema.getWhiteSpaceElements();
  19012. var startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  19013. var endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  19014. var allWhiteSpaceRegExp = /[ \t\r\n]+/g;
  19015. var isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/;
  19016. var isInWhiteSpacePreservedElement = has$2(whiteSpaceElements, args.context) || has$2(whiteSpaceElements, settings.root_name);
  19017. var addRootBlocks = function () {
  19018. var node = rootNode.firstChild, rootBlockNode = null;
  19019. var trim = function (rootBlock) {
  19020. if (rootBlock) {
  19021. node = rootBlock.firstChild;
  19022. if (node && node.type === 3) {
  19023. node.value = node.value.replace(startWhiteSpaceRegExp, '');
  19024. }
  19025. node = rootBlock.lastChild;
  19026. if (node && node.type === 3) {
  19027. node.value = node.value.replace(endWhiteSpaceRegExp, '');
  19028. }
  19029. }
  19030. };
  19031. if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
  19032. return;
  19033. }
  19034. while (node) {
  19035. var next = node.next;
  19036. if (node.type === 3 || node.type === 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type')) {
  19037. if (!rootBlockNode) {
  19038. rootBlockNode = createNode(rootBlockName, 1);
  19039. rootBlockNode.attr(settings.forced_root_block_attrs);
  19040. rootNode.insert(rootBlockNode, node);
  19041. rootBlockNode.append(node);
  19042. } else {
  19043. rootBlockNode.append(node);
  19044. }
  19045. } else {
  19046. trim(rootBlockNode);
  19047. rootBlockNode = null;
  19048. }
  19049. node = next;
  19050. }
  19051. trim(rootBlockNode);
  19052. };
  19053. var createNode = function (name, type) {
  19054. var node = new AstNode(name, type);
  19055. var list;
  19056. if (name in nodeFilters) {
  19057. list = matchedNodes[name];
  19058. if (list) {
  19059. list.push(node);
  19060. } else {
  19061. matchedNodes[name] = [node];
  19062. }
  19063. }
  19064. return node;
  19065. };
  19066. var removeWhitespaceBefore = function (node) {
  19067. var blockElements = schema.getBlockElements();
  19068. for (var textNode = node.prev; textNode && textNode.type === 3;) {
  19069. var textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
  19070. if (textVal.length > 0) {
  19071. textNode.value = textVal;
  19072. return;
  19073. }
  19074. var textNodeNext = textNode.next;
  19075. if (textNodeNext) {
  19076. if (textNodeNext.type === 3 && textNodeNext.value.length) {
  19077. textNode = textNode.prev;
  19078. continue;
  19079. }
  19080. if (!blockElements[textNodeNext.name] && textNodeNext.name !== 'script' && textNodeNext.name !== 'style') {
  19081. textNode = textNode.prev;
  19082. continue;
  19083. }
  19084. }
  19085. var sibling = textNode.prev;
  19086. textNode.remove();
  19087. textNode = sibling;
  19088. }
  19089. };
  19090. var cloneAndExcludeBlocks = function (input) {
  19091. var output = {};
  19092. for (var name_2 in input) {
  19093. if (name_2 !== 'li' && name_2 !== 'p') {
  19094. output[name_2] = input[name_2];
  19095. }
  19096. }
  19097. return output;
  19098. };
  19099. var parser = SaxParser({
  19100. validate: validate,
  19101. document: settings.document,
  19102. allow_html_data_urls: settings.allow_html_data_urls,
  19103. allow_svg_data_urls: settings.allow_svg_data_urls,
  19104. allow_script_urls: settings.allow_script_urls,
  19105. allow_conditional_comments: settings.allow_conditional_comments,
  19106. preserve_cdata: settings.preserve_cdata,
  19107. self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()),
  19108. cdata: function (text) {
  19109. node.append(createNode('#cdata', 4)).value = text;
  19110. },
  19111. text: function (text, raw) {
  19112. var textNode;
  19113. if (!isInWhiteSpacePreservedElement) {
  19114. text = text.replace(allWhiteSpaceRegExp, ' ');
  19115. if (isLineBreakNode(node.lastChild, blockElements)) {
  19116. text = text.replace(startWhiteSpaceRegExp, '');
  19117. }
  19118. }
  19119. if (text.length !== 0) {
  19120. textNode = createNode('#text', 3);
  19121. textNode.raw = !!raw;
  19122. node.append(textNode).value = text;
  19123. }
  19124. },
  19125. comment: function (text) {
  19126. node.append(createNode('#comment', 8)).value = text;
  19127. },
  19128. pi: function (name, text) {
  19129. node.append(createNode(name, 7)).value = text;
  19130. removeWhitespaceBefore(node);
  19131. },
  19132. doctype: function (text) {
  19133. var newNode = node.append(createNode('#doctype', 10));
  19134. newNode.value = text;
  19135. removeWhitespaceBefore(node);
  19136. },
  19137. start: function (name, attrs, empty) {
  19138. var elementRule = validate ? schema.getElementRule(name) : {};
  19139. if (elementRule) {
  19140. var newNode = createNode(elementRule.outputName || name, 1);
  19141. newNode.attributes = attrs;
  19142. newNode.shortEnded = empty;
  19143. node.append(newNode);
  19144. var parent_2 = children[node.name];
  19145. if (parent_2 && children[newNode.name] && !parent_2[newNode.name]) {
  19146. invalidChildren.push(newNode);
  19147. }
  19148. var attrFiltersLen = attributeFilters.length;
  19149. while (attrFiltersLen--) {
  19150. var attrName = attributeFilters[attrFiltersLen].name;
  19151. if (attrName in attrs.map) {
  19152. list = matchedAttributes[attrName];
  19153. if (list) {
  19154. list.push(newNode);
  19155. } else {
  19156. matchedAttributes[attrName] = [newNode];
  19157. }
  19158. }
  19159. }
  19160. if (blockElements[name]) {
  19161. removeWhitespaceBefore(newNode);
  19162. }
  19163. if (!empty) {
  19164. node = newNode;
  19165. }
  19166. if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  19167. isInWhiteSpacePreservedElement = true;
  19168. }
  19169. }
  19170. },
  19171. end: function (name) {
  19172. var textNode, text, sibling, tempNode;
  19173. var elementRule = validate ? schema.getElementRule(name) : {};
  19174. if (elementRule) {
  19175. if (blockElements[name]) {
  19176. if (!isInWhiteSpacePreservedElement) {
  19177. textNode = node.firstChild;
  19178. if (textNode && textNode.type === 3) {
  19179. text = textNode.value.replace(startWhiteSpaceRegExp, '');
  19180. if (text.length > 0) {
  19181. textNode.value = text;
  19182. textNode = textNode.next;
  19183. } else {
  19184. sibling = textNode.next;
  19185. textNode.remove();
  19186. textNode = sibling;
  19187. while (textNode && textNode.type === 3) {
  19188. text = textNode.value;
  19189. sibling = textNode.next;
  19190. if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  19191. textNode.remove();
  19192. textNode = sibling;
  19193. }
  19194. textNode = sibling;
  19195. }
  19196. }
  19197. }
  19198. textNode = node.lastChild;
  19199. if (textNode && textNode.type === 3) {
  19200. text = textNode.value.replace(endWhiteSpaceRegExp, '');
  19201. if (text.length > 0) {
  19202. textNode.value = text;
  19203. textNode = textNode.prev;
  19204. } else {
  19205. sibling = textNode.prev;
  19206. textNode.remove();
  19207. textNode = sibling;
  19208. while (textNode && textNode.type === 3) {
  19209. text = textNode.value;
  19210. sibling = textNode.prev;
  19211. if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  19212. textNode.remove();
  19213. textNode = sibling;
  19214. }
  19215. textNode = sibling;
  19216. }
  19217. }
  19218. }
  19219. }
  19220. }
  19221. if (isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  19222. isInWhiteSpacePreservedElement = false;
  19223. }
  19224. if (elementRule.removeEmpty && isEmpty(schema, nonEmptyElements, whiteSpaceElements, node)) {
  19225. tempNode = node.parent;
  19226. if (blockElements[node.name]) {
  19227. node.empty().remove();
  19228. } else {
  19229. node.unwrap();
  19230. }
  19231. node = tempNode;
  19232. return;
  19233. }
  19234. if (elementRule.paddEmpty && (isPaddedWithNbsp(node) || isEmpty(schema, nonEmptyElements, whiteSpaceElements, node))) {
  19235. paddEmptyNode(settings, args, blockElements, node);
  19236. }
  19237. node = node.parent;
  19238. }
  19239. }
  19240. }, schema);
  19241. var rootNode = node = new AstNode(args.context || settings.root_name, 11);
  19242. parser.parse(html, args.format);
  19243. if (validate && invalidChildren.length) {
  19244. if (!args.context) {
  19245. fixInvalidChildren(invalidChildren);
  19246. } else {
  19247. args.invalid = true;
  19248. }
  19249. }
  19250. if (rootBlockName && (rootNode.name === 'body' || args.isRootContent)) {
  19251. addRootBlocks();
  19252. }
  19253. if (!args.invalid) {
  19254. for (name in matchedNodes) {
  19255. if (!has$2(matchedNodes, name)) {
  19256. continue;
  19257. }
  19258. list = nodeFilters[name];
  19259. nodes = matchedNodes[name];
  19260. fi = nodes.length;
  19261. while (fi--) {
  19262. if (!nodes[fi].parent) {
  19263. nodes.splice(fi, 1);
  19264. }
  19265. }
  19266. for (i = 0, l = list.length; i < l; i++) {
  19267. list[i](nodes, name, args);
  19268. }
  19269. }
  19270. for (i = 0, l = attributeFilters.length; i < l; i++) {
  19271. list = attributeFilters[i];
  19272. if (list.name in matchedAttributes) {
  19273. nodes = matchedAttributes[list.name];
  19274. fi = nodes.length;
  19275. while (fi--) {
  19276. if (!nodes[fi].parent) {
  19277. nodes.splice(fi, 1);
  19278. }
  19279. }
  19280. for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) {
  19281. list.callbacks[fi](nodes, list.name, args);
  19282. }
  19283. }
  19284. }
  19285. }
  19286. return rootNode;
  19287. };
  19288. var exports = {
  19289. schema: schema,
  19290. addAttributeFilter: addAttributeFilter,
  19291. getAttributeFilters: getAttributeFilters,
  19292. addNodeFilter: addNodeFilter,
  19293. getNodeFilters: getNodeFilters,
  19294. filterNode: filterNode,
  19295. parse: parse
  19296. };
  19297. register$1(exports, settings);
  19298. register$2(exports, settings);
  19299. return exports;
  19300. };
  19301. var register = function (htmlParser, settings, dom) {
  19302. htmlParser.addAttributeFilter('data-mce-tabindex', function (nodes, name) {
  19303. var i = nodes.length;
  19304. while (i--) {
  19305. var node = nodes[i];
  19306. node.attr('tabindex', node.attr('data-mce-tabindex'));
  19307. node.attr(name, null);
  19308. }
  19309. });
  19310. htmlParser.addAttributeFilter('src,href,style', function (nodes, name) {
  19311. var internalName = 'data-mce-' + name;
  19312. var urlConverter = settings.url_converter;
  19313. var urlConverterScope = settings.url_converter_scope;
  19314. var i = nodes.length;
  19315. while (i--) {
  19316. var node = nodes[i];
  19317. var value = node.attr(internalName);
  19318. if (value !== undefined) {
  19319. node.attr(name, value.length > 0 ? value : null);
  19320. node.attr(internalName, null);
  19321. } else {
  19322. value = node.attr(name);
  19323. if (name === 'style') {
  19324. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  19325. } else if (urlConverter) {
  19326. value = urlConverter.call(urlConverterScope, value, name, node.name);
  19327. }
  19328. node.attr(name, value.length > 0 ? value : null);
  19329. }
  19330. }
  19331. });
  19332. htmlParser.addAttributeFilter('class', function (nodes) {
  19333. var i = nodes.length;
  19334. while (i--) {
  19335. var node = nodes[i];
  19336. var value = node.attr('class');
  19337. if (value) {
  19338. value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
  19339. node.attr('class', value.length > 0 ? value : null);
  19340. }
  19341. }
  19342. });
  19343. htmlParser.addAttributeFilter('data-mce-type', function (nodes, name, args) {
  19344. var i = nodes.length;
  19345. while (i--) {
  19346. var node = nodes[i];
  19347. if (node.attr('data-mce-type') === 'bookmark' && !args.cleanup) {
  19348. var hasChildren = Optional.from(node.firstChild).exists(function (firstChild) {
  19349. return !isZwsp(firstChild.value);
  19350. });
  19351. if (hasChildren) {
  19352. node.unwrap();
  19353. } else {
  19354. node.remove();
  19355. }
  19356. }
  19357. }
  19358. });
  19359. htmlParser.addNodeFilter('noscript', function (nodes) {
  19360. var i = nodes.length;
  19361. while (i--) {
  19362. var node = nodes[i].firstChild;
  19363. if (node) {
  19364. node.value = Entities.decode(node.value);
  19365. }
  19366. }
  19367. });
  19368. htmlParser.addNodeFilter('script,style', function (nodes, name) {
  19369. var trim = function (value) {
  19370. 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, '');
  19371. };
  19372. var i = nodes.length;
  19373. while (i--) {
  19374. var node = nodes[i];
  19375. var value = node.firstChild ? node.firstChild.value : '';
  19376. if (name === 'script') {
  19377. var type = node.attr('type');
  19378. if (type) {
  19379. node.attr('type', type === 'mce-no/type' ? null : type.replace(/^mce\-/, ''));
  19380. }
  19381. if (settings.element_format === 'xhtml' && value.length > 0) {
  19382. node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
  19383. }
  19384. } else {
  19385. if (settings.element_format === 'xhtml' && value.length > 0) {
  19386. node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
  19387. }
  19388. }
  19389. }
  19390. });
  19391. htmlParser.addNodeFilter('#comment', function (nodes) {
  19392. var i = nodes.length;
  19393. while (i--) {
  19394. var node = nodes[i];
  19395. if (settings.preserve_cdata && node.value.indexOf('[CDATA[') === 0) {
  19396. node.name = '#cdata';
  19397. node.type = 4;
  19398. node.value = dom.decode(node.value.replace(/^\[CDATA\[|\]\]$/g, ''));
  19399. } else if (node.value.indexOf('mce:protected ') === 0) {
  19400. node.name = '#text';
  19401. node.type = 3;
  19402. node.raw = true;
  19403. node.value = unescape(node.value).substr(14);
  19404. }
  19405. }
  19406. });
  19407. htmlParser.addNodeFilter('xml:namespace,input', function (nodes, name) {
  19408. var i = nodes.length;
  19409. while (i--) {
  19410. var node = nodes[i];
  19411. if (node.type === 7) {
  19412. node.remove();
  19413. } else if (node.type === 1) {
  19414. if (name === 'input' && !node.attr('type')) {
  19415. node.attr('type', 'text');
  19416. }
  19417. }
  19418. }
  19419. });
  19420. htmlParser.addAttributeFilter('data-mce-type', function (nodes) {
  19421. each$k(nodes, function (node) {
  19422. if (node.attr('data-mce-type') === 'format-caret') {
  19423. if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
  19424. node.remove();
  19425. } else {
  19426. node.unwrap();
  19427. }
  19428. }
  19429. });
  19430. });
  19431. 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) {
  19432. var i = nodes.length;
  19433. while (i--) {
  19434. nodes[i].attr(name, null);
  19435. }
  19436. });
  19437. };
  19438. var trimTrailingBr = function (rootNode) {
  19439. var isBr = function (node) {
  19440. return node && node.name === 'br';
  19441. };
  19442. var brNode1 = rootNode.lastChild;
  19443. if (isBr(brNode1)) {
  19444. var brNode2 = brNode1.prev;
  19445. if (isBr(brNode2)) {
  19446. brNode1.remove();
  19447. brNode2.remove();
  19448. }
  19449. }
  19450. };
  19451. var preProcess = function (editor, node, args) {
  19452. var oldDoc;
  19453. var dom = editor.dom;
  19454. var clonedNode = node.cloneNode(true);
  19455. var impl = document.implementation;
  19456. if (impl.createHTMLDocument) {
  19457. var doc_1 = impl.createHTMLDocument('');
  19458. Tools.each(clonedNode.nodeName === 'BODY' ? clonedNode.childNodes : [clonedNode], function (node) {
  19459. doc_1.body.appendChild(doc_1.importNode(node, true));
  19460. });
  19461. if (clonedNode.nodeName !== 'BODY') {
  19462. clonedNode = doc_1.body.firstChild;
  19463. } else {
  19464. clonedNode = doc_1.body;
  19465. }
  19466. oldDoc = dom.doc;
  19467. dom.doc = doc_1;
  19468. }
  19469. firePreProcess(editor, __assign(__assign({}, args), { node: clonedNode }));
  19470. if (oldDoc) {
  19471. dom.doc = oldDoc;
  19472. }
  19473. return clonedNode;
  19474. };
  19475. var shouldFireEvent = function (editor, args) {
  19476. return editor && editor.hasEventListeners('PreProcess') && !args.no_events;
  19477. };
  19478. var process = function (editor, node, args) {
  19479. return shouldFireEvent(editor, args) ? preProcess(editor, node, args) : node;
  19480. };
  19481. var addTempAttr = function (htmlParser, tempAttrs, name) {
  19482. if (Tools.inArray(tempAttrs, name) === -1) {
  19483. htmlParser.addAttributeFilter(name, function (nodes, name) {
  19484. var i = nodes.length;
  19485. while (i--) {
  19486. nodes[i].attr(name, null);
  19487. }
  19488. });
  19489. tempAttrs.push(name);
  19490. }
  19491. };
  19492. var postProcess = function (editor, args, content) {
  19493. if (!args.no_events && editor) {
  19494. var outArgs = firePostProcess(editor, __assign(__assign({}, args), { content: content }));
  19495. return outArgs.content;
  19496. } else {
  19497. return content;
  19498. }
  19499. };
  19500. var getHtmlFromNode = function (dom, node, args) {
  19501. var html = trim$2(args.getInner ? node.innerHTML : dom.getOuterHTML(node));
  19502. return args.selection || isWsPreserveElement(SugarElement.fromDom(node)) ? html : Tools.trim(html);
  19503. };
  19504. var parseHtml = function (htmlParser, html, args) {
  19505. var parserArgs = args.selection ? __assign({ forced_root_block: false }, args) : args;
  19506. var rootNode = htmlParser.parse(html, parserArgs);
  19507. trimTrailingBr(rootNode);
  19508. return rootNode;
  19509. };
  19510. var serializeNode = function (settings, schema, node) {
  19511. var htmlSerializer = HtmlSerializer(settings, schema);
  19512. return htmlSerializer.serialize(node);
  19513. };
  19514. var toHtml = function (editor, settings, schema, rootNode, args) {
  19515. var content = serializeNode(settings, schema, rootNode);
  19516. return postProcess(editor, args, content);
  19517. };
  19518. var DomSerializerImpl = function (settings, editor) {
  19519. var tempAttrs = ['data-mce-selected'];
  19520. var dom = editor && editor.dom ? editor.dom : DOMUtils.DOM;
  19521. var schema = editor && editor.schema ? editor.schema : Schema(settings);
  19522. settings.entity_encoding = settings.entity_encoding || 'named';
  19523. settings.remove_trailing_brs = 'remove_trailing_brs' in settings ? settings.remove_trailing_brs : true;
  19524. var htmlParser = DomParser(settings, schema);
  19525. register(htmlParser, settings, dom);
  19526. var serialize = function (node, parserArgs) {
  19527. if (parserArgs === void 0) {
  19528. parserArgs = {};
  19529. }
  19530. var args = __assign({ format: 'html' }, parserArgs);
  19531. var targetNode = process(editor, node, args);
  19532. var html = getHtmlFromNode(dom, targetNode, args);
  19533. var rootNode = parseHtml(htmlParser, html, args);
  19534. return args.format === 'tree' ? rootNode : toHtml(editor, settings, schema, rootNode, args);
  19535. };
  19536. return {
  19537. schema: schema,
  19538. addNodeFilter: htmlParser.addNodeFilter,
  19539. addAttributeFilter: htmlParser.addAttributeFilter,
  19540. serialize: serialize,
  19541. addRules: schema.addValidElements,
  19542. setRules: schema.setValidElements,
  19543. addTempAttr: curry(addTempAttr, htmlParser, tempAttrs),
  19544. getTempAttrs: constant(tempAttrs),
  19545. getNodeFilters: htmlParser.getNodeFilters,
  19546. getAttributeFilters: htmlParser.getAttributeFilters
  19547. };
  19548. };
  19549. var DomSerializer = function (settings, editor) {
  19550. var domSerializer = DomSerializerImpl(settings, editor);
  19551. return {
  19552. schema: domSerializer.schema,
  19553. addNodeFilter: domSerializer.addNodeFilter,
  19554. addAttributeFilter: domSerializer.addAttributeFilter,
  19555. serialize: domSerializer.serialize,
  19556. addRules: domSerializer.addRules,
  19557. setRules: domSerializer.setRules,
  19558. addTempAttr: domSerializer.addTempAttr,
  19559. getTempAttrs: domSerializer.getTempAttrs,
  19560. getNodeFilters: domSerializer.getNodeFilters,
  19561. getAttributeFilters: domSerializer.getAttributeFilters
  19562. };
  19563. };
  19564. var defaultFormat = 'html';
  19565. var getContent = function (editor, args) {
  19566. if (args === void 0) {
  19567. args = {};
  19568. }
  19569. var format = args.format ? args.format : defaultFormat;
  19570. return getContent$2(editor, args, format);
  19571. };
  19572. var setContent = function (editor, content, args) {
  19573. if (args === void 0) {
  19574. args = {};
  19575. }
  19576. return setContent$2(editor, content, args);
  19577. };
  19578. var DOM$7 = DOMUtils.DOM;
  19579. var restoreOriginalStyles = function (editor) {
  19580. DOM$7.setStyle(editor.id, 'display', editor.orgDisplay);
  19581. };
  19582. var safeDestroy = function (x) {
  19583. return Optional.from(x).each(function (x) {
  19584. return x.destroy();
  19585. });
  19586. };
  19587. var clearDomReferences = function (editor) {
  19588. editor.contentAreaContainer = editor.formElement = editor.container = editor.editorContainer = null;
  19589. editor.bodyElement = editor.contentDocument = editor.contentWindow = null;
  19590. editor.iframeElement = editor.targetElm = null;
  19591. if (editor.selection) {
  19592. editor.selection = editor.selection.win = editor.selection.dom = editor.selection.dom.doc = null;
  19593. }
  19594. };
  19595. var restoreForm = function (editor) {
  19596. var form = editor.formElement;
  19597. if (form) {
  19598. if (form._mceOldSubmit) {
  19599. form.submit = form._mceOldSubmit;
  19600. form._mceOldSubmit = null;
  19601. }
  19602. DOM$7.unbind(form, 'submit reset', editor.formEventDelegate);
  19603. }
  19604. };
  19605. var remove = function (editor) {
  19606. if (!editor.removed) {
  19607. var _selectionOverrides = editor._selectionOverrides, editorUpload = editor.editorUpload;
  19608. var body = editor.getBody();
  19609. var element = editor.getElement();
  19610. if (body) {
  19611. editor.save({ is_removing: true });
  19612. }
  19613. editor.removed = true;
  19614. editor.unbindAllNativeEvents();
  19615. if (editor.hasHiddenInput && element) {
  19616. DOM$7.remove(element.nextSibling);
  19617. }
  19618. fireRemove(editor);
  19619. editor.editorManager.remove(editor);
  19620. if (!editor.inline && body) {
  19621. restoreOriginalStyles(editor);
  19622. }
  19623. fireDetach(editor);
  19624. DOM$7.remove(editor.getContainer());
  19625. safeDestroy(_selectionOverrides);
  19626. safeDestroy(editorUpload);
  19627. editor.destroy();
  19628. }
  19629. };
  19630. var destroy = function (editor, automatic) {
  19631. var selection = editor.selection, dom = editor.dom;
  19632. if (editor.destroyed) {
  19633. return;
  19634. }
  19635. if (!automatic && !editor.removed) {
  19636. editor.remove();
  19637. return;
  19638. }
  19639. if (!automatic) {
  19640. editor.editorManager.off('beforeunload', editor._beforeUnload);
  19641. if (editor.theme && editor.theme.destroy) {
  19642. editor.theme.destroy();
  19643. }
  19644. safeDestroy(selection);
  19645. safeDestroy(dom);
  19646. }
  19647. restoreForm(editor);
  19648. clearDomReferences(editor);
  19649. editor.destroyed = true;
  19650. };
  19651. var deep = function (old, nu) {
  19652. var bothObjects = isObject(old) && isObject(nu);
  19653. return bothObjects ? deepMerge(old, nu) : nu;
  19654. };
  19655. var baseMerge = function (merger) {
  19656. return function () {
  19657. var objects = [];
  19658. for (var _i = 0; _i < arguments.length; _i++) {
  19659. objects[_i] = arguments[_i];
  19660. }
  19661. if (objects.length === 0) {
  19662. throw new Error('Can\'t merge zero objects');
  19663. }
  19664. var ret = {};
  19665. for (var j = 0; j < objects.length; j++) {
  19666. var curObject = objects[j];
  19667. for (var key in curObject) {
  19668. if (has$2(curObject, key)) {
  19669. ret[key] = merger(ret[key], curObject[key]);
  19670. }
  19671. }
  19672. }
  19673. return ret;
  19674. };
  19675. };
  19676. var deepMerge = baseMerge(deep);
  19677. var sectionResult = function (sections, settings) {
  19678. return {
  19679. sections: constant(sections),
  19680. settings: constant(settings)
  19681. };
  19682. };
  19683. var deviceDetection = detect().deviceType;
  19684. var isTouch = deviceDetection.isTouch();
  19685. var isPhone = deviceDetection.isPhone();
  19686. var isTablet = deviceDetection.isTablet();
  19687. var legacyMobilePlugins = [
  19688. 'lists',
  19689. 'autolink',
  19690. 'autosave'
  19691. ];
  19692. var defaultTouchSettings = {
  19693. table_grid: false,
  19694. object_resizing: false,
  19695. resize: false
  19696. };
  19697. var normalizePlugins = function (plugins) {
  19698. var pluginNames = isArray$1(plugins) ? plugins.join(' ') : plugins;
  19699. var trimmedPlugins = map$3(isString$1(pluginNames) ? pluginNames.split(' ') : [], trim$4);
  19700. return filter$4(trimmedPlugins, function (item) {
  19701. return item.length > 0;
  19702. });
  19703. };
  19704. var filterLegacyMobilePlugins = function (plugins) {
  19705. return filter$4(plugins, curry(contains$3, legacyMobilePlugins));
  19706. };
  19707. var extractSections = function (keys, settings) {
  19708. var result = bifilter(settings, function (value, key) {
  19709. return contains$3(keys, key);
  19710. });
  19711. return sectionResult(result.t, result.f);
  19712. };
  19713. var getSection = function (sectionResult, name, defaults) {
  19714. if (defaults === void 0) {
  19715. defaults = {};
  19716. }
  19717. var sections = sectionResult.sections();
  19718. var sectionSettings = get$9(sections, name).getOr({});
  19719. return Tools.extend({}, defaults, sectionSettings);
  19720. };
  19721. var hasSection = function (sectionResult, name) {
  19722. return has$2(sectionResult.sections(), name);
  19723. };
  19724. var isSectionTheme = function (sectionResult, name, theme) {
  19725. var section = sectionResult.sections();
  19726. return hasSection(sectionResult, name) && section[name].theme === theme;
  19727. };
  19728. var getSectionConfig = function (sectionResult, name) {
  19729. return hasSection(sectionResult, name) ? sectionResult.sections()[name] : {};
  19730. };
  19731. var getToolbarMode = function (settings, defaultVal) {
  19732. return get$9(settings, 'toolbar_mode').orThunk(function () {
  19733. return get$9(settings, 'toolbar_drawer').map(function (val) {
  19734. return val === false ? 'wrap' : val;
  19735. });
  19736. }).getOr(defaultVal);
  19737. };
  19738. var getDefaultSettings = function (settings, id, documentBaseUrl, isTouch, editor) {
  19739. var baseDefaults = {
  19740. id: id,
  19741. theme: 'silver',
  19742. toolbar_mode: getToolbarMode(settings, 'floating'),
  19743. plugins: '',
  19744. document_base_url: documentBaseUrl,
  19745. add_form_submit_trigger: true,
  19746. submit_patch: true,
  19747. add_unload_trigger: true,
  19748. convert_urls: true,
  19749. relative_urls: true,
  19750. remove_script_host: true,
  19751. object_resizing: true,
  19752. doctype: '<!DOCTYPE html>',
  19753. visual: true,
  19754. font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%',
  19755. forced_root_block: 'p',
  19756. hidden_input: true,
  19757. inline_styles: true,
  19758. convert_fonts_to_spans: true,
  19759. indent: true,
  19760. 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',
  19761. 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',
  19762. entity_encoding: 'named',
  19763. url_converter: editor.convertURL,
  19764. url_converter_scope: editor
  19765. };
  19766. return __assign(__assign({}, baseDefaults), isTouch ? defaultTouchSettings : {});
  19767. };
  19768. var getDefaultMobileSettings = function (mobileSettings, isPhone) {
  19769. var defaultMobileSettings = {
  19770. resize: false,
  19771. toolbar_mode: getToolbarMode(mobileSettings, 'scrolling'),
  19772. toolbar_sticky: false
  19773. };
  19774. var defaultPhoneSettings = { menubar: false };
  19775. return __assign(__assign(__assign({}, defaultTouchSettings), defaultMobileSettings), isPhone ? defaultPhoneSettings : {});
  19776. };
  19777. var getExternalPlugins = function (overrideSettings, settings) {
  19778. var userDefinedExternalPlugins = settings.external_plugins ? settings.external_plugins : {};
  19779. if (overrideSettings && overrideSettings.external_plugins) {
  19780. return Tools.extend({}, overrideSettings.external_plugins, userDefinedExternalPlugins);
  19781. } else {
  19782. return userDefinedExternalPlugins;
  19783. }
  19784. };
  19785. var combinePlugins = function (forcedPlugins, plugins) {
  19786. return [].concat(normalizePlugins(forcedPlugins)).concat(normalizePlugins(plugins));
  19787. };
  19788. var getPlatformPlugins = function (isMobileDevice, sectionResult, desktopPlugins, mobilePlugins) {
  19789. if (isMobileDevice && isSectionTheme(sectionResult, 'mobile', 'mobile')) {
  19790. return filterLegacyMobilePlugins(mobilePlugins);
  19791. } else if (isMobileDevice && hasSection(sectionResult, 'mobile')) {
  19792. return mobilePlugins;
  19793. } else {
  19794. return desktopPlugins;
  19795. }
  19796. };
  19797. var processPlugins = function (isMobileDevice, sectionResult, defaultOverrideSettings, settings) {
  19798. var forcedPlugins = normalizePlugins(defaultOverrideSettings.forced_plugins);
  19799. var desktopPlugins = normalizePlugins(settings.plugins);
  19800. var mobileConfig = getSectionConfig(sectionResult, 'mobile');
  19801. var mobilePlugins = mobileConfig.plugins ? normalizePlugins(mobileConfig.plugins) : desktopPlugins;
  19802. var platformPlugins = getPlatformPlugins(isMobileDevice, sectionResult, desktopPlugins, mobilePlugins);
  19803. var combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
  19804. if (Env.browser.isIE() && contains$3(combinedPlugins, 'rtc')) {
  19805. throw new Error('RTC plugin is not supported on IE 11.');
  19806. }
  19807. return Tools.extend(settings, { plugins: combinedPlugins.join(' ') });
  19808. };
  19809. var isOnMobile = function (isMobileDevice, sectionResult) {
  19810. return isMobileDevice && hasSection(sectionResult, 'mobile');
  19811. };
  19812. var combineSettings = function (isMobileDevice, isPhone, defaultSettings, defaultOverrideSettings, settings) {
  19813. var defaultDeviceSettings = isMobileDevice ? { mobile: getDefaultMobileSettings(settings.mobile || {}, isPhone) } : {};
  19814. var sectionResult = extractSections(['mobile'], deepMerge(defaultDeviceSettings, settings));
  19815. var extendedSettings = Tools.extend(defaultSettings, defaultOverrideSettings, sectionResult.settings(), isOnMobile(isMobileDevice, sectionResult) ? getSection(sectionResult, 'mobile') : {}, {
  19816. validate: true,
  19817. external_plugins: getExternalPlugins(defaultOverrideSettings, sectionResult.settings())
  19818. });
  19819. return processPlugins(isMobileDevice, sectionResult, defaultOverrideSettings, extendedSettings);
  19820. };
  19821. var getEditorSettings = function (editor, id, documentBaseUrl, defaultOverrideSettings, settings) {
  19822. var defaultSettings = getDefaultSettings(settings, id, documentBaseUrl, isTouch, editor);
  19823. return combineSettings(isPhone || isTablet, isPhone, defaultSettings, defaultOverrideSettings, settings);
  19824. };
  19825. var getFiltered = function (predicate, editor, name) {
  19826. return Optional.from(editor.settings[name]).filter(predicate);
  19827. };
  19828. var getParamObject = function (value) {
  19829. var output = {};
  19830. if (typeof value === 'string') {
  19831. each$k(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function (val) {
  19832. var arr = val.split('=');
  19833. if (arr.length > 1) {
  19834. output[Tools.trim(arr[0])] = Tools.trim(arr[1]);
  19835. } else {
  19836. output[Tools.trim(arr[0])] = Tools.trim(arr[0]);
  19837. }
  19838. });
  19839. } else {
  19840. output = value;
  19841. }
  19842. return output;
  19843. };
  19844. var isArrayOf = function (p) {
  19845. return function (a) {
  19846. return isArray$1(a) && forall(a, p);
  19847. };
  19848. };
  19849. var getParam = function (editor, name, defaultVal, type) {
  19850. var value = name in editor.settings ? editor.settings[name] : defaultVal;
  19851. if (type === 'hash') {
  19852. return getParamObject(value);
  19853. } else if (type === 'string') {
  19854. return getFiltered(isString$1, editor, name).getOr(defaultVal);
  19855. } else if (type === 'number') {
  19856. return getFiltered(isNumber, editor, name).getOr(defaultVal);
  19857. } else if (type === 'boolean') {
  19858. return getFiltered(isBoolean, editor, name).getOr(defaultVal);
  19859. } else if (type === 'object') {
  19860. return getFiltered(isObject, editor, name).getOr(defaultVal);
  19861. } else if (type === 'array') {
  19862. return getFiltered(isArray$1, editor, name).getOr(defaultVal);
  19863. } else if (type === 'string[]') {
  19864. return getFiltered(isArrayOf(isString$1), editor, name).getOr(defaultVal);
  19865. } else if (type === 'function') {
  19866. return getFiltered(isFunction, editor, name).getOr(defaultVal);
  19867. } else {
  19868. return value;
  19869. }
  19870. };
  19871. var CreateIconManager = function () {
  19872. var lookup = {};
  19873. var add = function (id, iconPack) {
  19874. lookup[id] = iconPack;
  19875. };
  19876. var get = function (id) {
  19877. if (lookup[id]) {
  19878. return lookup[id];
  19879. }
  19880. return { icons: {} };
  19881. };
  19882. var has = function (id) {
  19883. return has$2(lookup, id);
  19884. };
  19885. return {
  19886. add: add,
  19887. get: get,
  19888. has: has
  19889. };
  19890. };
  19891. var IconManager = CreateIconManager();
  19892. var getProp = function (propName, elm) {
  19893. var rawElm = elm.dom;
  19894. return rawElm[propName];
  19895. };
  19896. var getComputedSizeProp = function (propName, elm) {
  19897. return parseInt(get$5(elm, propName), 10);
  19898. };
  19899. var getClientWidth = curry(getProp, 'clientWidth');
  19900. var getClientHeight = curry(getProp, 'clientHeight');
  19901. var getMarginTop = curry(getComputedSizeProp, 'margin-top');
  19902. var getMarginLeft = curry(getComputedSizeProp, 'margin-left');
  19903. var getBoundingClientRect = function (elm) {
  19904. return elm.dom.getBoundingClientRect();
  19905. };
  19906. var isInsideElementContentArea = function (bodyElm, clientX, clientY) {
  19907. var clientWidth = getClientWidth(bodyElm);
  19908. var clientHeight = getClientHeight(bodyElm);
  19909. return clientX >= 0 && clientY >= 0 && clientX <= clientWidth && clientY <= clientHeight;
  19910. };
  19911. var transpose = function (inline, elm, clientX, clientY) {
  19912. var clientRect = getBoundingClientRect(elm);
  19913. var deltaX = inline ? clientRect.left + elm.dom.clientLeft + getMarginLeft(elm) : 0;
  19914. var deltaY = inline ? clientRect.top + elm.dom.clientTop + getMarginTop(elm) : 0;
  19915. var x = clientX - deltaX;
  19916. var y = clientY - deltaY;
  19917. return {
  19918. x: x,
  19919. y: y
  19920. };
  19921. };
  19922. var isXYInContentArea = function (editor, clientX, clientY) {
  19923. var bodyElm = SugarElement.fromDom(editor.getBody());
  19924. var targetElm = editor.inline ? bodyElm : documentElement(bodyElm);
  19925. var transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
  19926. return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
  19927. };
  19928. var fromDomSafe = function (node) {
  19929. return Optional.from(node).map(SugarElement.fromDom);
  19930. };
  19931. var isEditorAttachedToDom = function (editor) {
  19932. var rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
  19933. return fromDomSafe(rawContainer).map(inBody).getOr(false);
  19934. };
  19935. var NotificationManagerImpl = function () {
  19936. var unimplemented = function () {
  19937. throw new Error('Theme did not provide a NotificationManager implementation.');
  19938. };
  19939. return {
  19940. open: unimplemented,
  19941. close: unimplemented,
  19942. reposition: unimplemented,
  19943. getArgs: unimplemented
  19944. };
  19945. };
  19946. var NotificationManager = function (editor) {
  19947. var notifications = [];
  19948. var getImplementation = function () {
  19949. var theme = editor.theme;
  19950. return theme && theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
  19951. };
  19952. var getTopNotification = function () {
  19953. return Optional.from(notifications[0]);
  19954. };
  19955. var isEqual = function (a, b) {
  19956. return a.type === b.type && a.text === b.text && !a.progressBar && !a.timeout && !b.progressBar && !b.timeout;
  19957. };
  19958. var reposition = function () {
  19959. if (notifications.length > 0) {
  19960. getImplementation().reposition(notifications);
  19961. }
  19962. };
  19963. var addNotification = function (notification) {
  19964. notifications.push(notification);
  19965. };
  19966. var closeNotification = function (notification) {
  19967. findIndex$2(notifications, function (otherNotification) {
  19968. return otherNotification === notification;
  19969. }).each(function (index) {
  19970. notifications.splice(index, 1);
  19971. });
  19972. };
  19973. var open = function (spec, fireEvent) {
  19974. if (fireEvent === void 0) {
  19975. fireEvent = true;
  19976. }
  19977. if (editor.removed || !isEditorAttachedToDom(editor)) {
  19978. return;
  19979. }
  19980. if (fireEvent) {
  19981. editor.fire('BeforeOpenNotification', { notification: spec });
  19982. }
  19983. return find$3(notifications, function (notification) {
  19984. return isEqual(getImplementation().getArgs(notification), spec);
  19985. }).getOrThunk(function () {
  19986. editor.editorManager.setActive(editor);
  19987. var notification = getImplementation().open(spec, function () {
  19988. closeNotification(notification);
  19989. reposition();
  19990. getTopNotification().fold(function () {
  19991. return editor.focus();
  19992. }, function (top) {
  19993. return focus$1(SugarElement.fromDom(top.getEl()));
  19994. });
  19995. });
  19996. addNotification(notification);
  19997. reposition();
  19998. editor.fire('OpenNotification', { notification: __assign({}, notification) });
  19999. return notification;
  20000. });
  20001. };
  20002. var close = function () {
  20003. getTopNotification().each(function (notification) {
  20004. getImplementation().close(notification);
  20005. closeNotification(notification);
  20006. reposition();
  20007. });
  20008. };
  20009. var getNotifications = constant(notifications);
  20010. var registerEvents = function (editor) {
  20011. editor.on('SkinLoaded', function () {
  20012. var serviceMessage = getServiceMessage(editor);
  20013. if (serviceMessage) {
  20014. open({
  20015. text: serviceMessage,
  20016. type: 'warning',
  20017. timeout: 0
  20018. }, false);
  20019. }
  20020. });
  20021. editor.on('ResizeEditor ResizeWindow NodeChange', function () {
  20022. Delay.requestAnimationFrame(reposition);
  20023. });
  20024. editor.on('remove', function () {
  20025. each$k(notifications.slice(), function (notification) {
  20026. getImplementation().close(notification);
  20027. });
  20028. });
  20029. };
  20030. registerEvents(editor);
  20031. return {
  20032. open: open,
  20033. close: close,
  20034. getNotifications: getNotifications
  20035. };
  20036. };
  20037. var PluginManager = AddOnManager.PluginManager;
  20038. var ThemeManager = AddOnManager.ThemeManager;
  20039. function WindowManagerImpl () {
  20040. var unimplemented = function () {
  20041. throw new Error('Theme did not provide a WindowManager implementation.');
  20042. };
  20043. return {
  20044. open: unimplemented,
  20045. openUrl: unimplemented,
  20046. alert: unimplemented,
  20047. confirm: unimplemented,
  20048. close: unimplemented,
  20049. getParams: unimplemented,
  20050. setParams: unimplemented
  20051. };
  20052. }
  20053. var WindowManager = function (editor) {
  20054. var dialogs = [];
  20055. var getImplementation = function () {
  20056. var theme = editor.theme;
  20057. return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
  20058. };
  20059. var funcBind = function (scope, f) {
  20060. return function () {
  20061. var args = [];
  20062. for (var _i = 0; _i < arguments.length; _i++) {
  20063. args[_i] = arguments[_i];
  20064. }
  20065. return f ? f.apply(scope, args) : undefined;
  20066. };
  20067. };
  20068. var fireOpenEvent = function (dialog) {
  20069. editor.fire('OpenWindow', { dialog: dialog });
  20070. };
  20071. var fireCloseEvent = function (dialog) {
  20072. editor.fire('CloseWindow', { dialog: dialog });
  20073. };
  20074. var addDialog = function (dialog) {
  20075. dialogs.push(dialog);
  20076. fireOpenEvent(dialog);
  20077. };
  20078. var closeDialog = function (dialog) {
  20079. fireCloseEvent(dialog);
  20080. dialogs = filter$4(dialogs, function (otherDialog) {
  20081. return otherDialog !== dialog;
  20082. });
  20083. if (dialogs.length === 0) {
  20084. editor.focus();
  20085. }
  20086. };
  20087. var getTopDialog = function () {
  20088. return Optional.from(dialogs[dialogs.length - 1]);
  20089. };
  20090. var storeSelectionAndOpenDialog = function (openDialog) {
  20091. editor.editorManager.setActive(editor);
  20092. store(editor);
  20093. var dialog = openDialog();
  20094. addDialog(dialog);
  20095. return dialog;
  20096. };
  20097. var open = function (args, params) {
  20098. return storeSelectionAndOpenDialog(function () {
  20099. return getImplementation().open(args, params, closeDialog);
  20100. });
  20101. };
  20102. var openUrl = function (args) {
  20103. return storeSelectionAndOpenDialog(function () {
  20104. return getImplementation().openUrl(args, closeDialog);
  20105. });
  20106. };
  20107. var alert = function (message, callback, scope) {
  20108. var windowManagerImpl = getImplementation();
  20109. windowManagerImpl.alert(message, funcBind(scope ? scope : windowManagerImpl, callback));
  20110. };
  20111. var confirm = function (message, callback, scope) {
  20112. var windowManagerImpl = getImplementation();
  20113. windowManagerImpl.confirm(message, funcBind(scope ? scope : windowManagerImpl, callback));
  20114. };
  20115. var close = function () {
  20116. getTopDialog().each(function (dialog) {
  20117. getImplementation().close(dialog);
  20118. closeDialog(dialog);
  20119. });
  20120. };
  20121. editor.on('remove', function () {
  20122. each$k(dialogs, function (dialog) {
  20123. getImplementation().close(dialog);
  20124. });
  20125. });
  20126. return {
  20127. open: open,
  20128. openUrl: openUrl,
  20129. alert: alert,
  20130. confirm: confirm,
  20131. close: close
  20132. };
  20133. };
  20134. var displayNotification = function (editor, message) {
  20135. editor.notificationManager.open({
  20136. type: 'error',
  20137. text: message
  20138. });
  20139. };
  20140. var displayError = function (editor, message) {
  20141. if (editor._skinLoaded) {
  20142. displayNotification(editor, message);
  20143. } else {
  20144. editor.on('SkinLoaded', function () {
  20145. displayNotification(editor, message);
  20146. });
  20147. }
  20148. };
  20149. var uploadError = function (editor, message) {
  20150. displayError(editor, I18n.translate([
  20151. 'Failed to upload image: {0}',
  20152. message
  20153. ]));
  20154. };
  20155. var logError = function (editor, errorType, msg) {
  20156. fireError(editor, errorType, { message: msg });
  20157. console.error(msg);
  20158. };
  20159. var createLoadError = function (type, url, name) {
  20160. return name ? 'Failed to load ' + type + ': ' + name + ' from url ' + url : 'Failed to load ' + type + ' url: ' + url;
  20161. };
  20162. var pluginLoadError = function (editor, url, name) {
  20163. logError(editor, 'PluginLoadError', createLoadError('plugin', url, name));
  20164. };
  20165. var iconsLoadError = function (editor, url, name) {
  20166. logError(editor, 'IconsLoadError', createLoadError('icons', url, name));
  20167. };
  20168. var languageLoadError = function (editor, url, name) {
  20169. logError(editor, 'LanguageLoadError', createLoadError('language', url, name));
  20170. };
  20171. var pluginInitError = function (editor, name, err) {
  20172. var message = I18n.translate([
  20173. 'Failed to initialize plugin: {0}',
  20174. name
  20175. ]);
  20176. fireError(editor, 'PluginLoadError', { message: message });
  20177. initError(message, err);
  20178. displayError(editor, message);
  20179. };
  20180. var initError = function (message) {
  20181. var x = [];
  20182. for (var _i = 1; _i < arguments.length; _i++) {
  20183. x[_i - 1] = arguments[_i];
  20184. }
  20185. var console = window.console;
  20186. if (console) {
  20187. if (console.error) {
  20188. console.error.apply(console, __spreadArray([message], x));
  20189. } else {
  20190. console.log.apply(console, __spreadArray([message], x));
  20191. }
  20192. }
  20193. };
  20194. var isContentCssSkinName = function (url) {
  20195. return /^[a-z0-9\-]+$/i.test(url);
  20196. };
  20197. var getContentCssUrls = function (editor) {
  20198. return transformToUrls(editor, getContentCss(editor));
  20199. };
  20200. var getFontCssUrls = function (editor) {
  20201. return transformToUrls(editor, getFontCss(editor));
  20202. };
  20203. var transformToUrls = function (editor, cssLinks) {
  20204. var skinUrl = editor.editorManager.baseURL + '/skins/content';
  20205. var suffix = editor.editorManager.suffix;
  20206. var contentCssFile = 'content' + suffix + '.css';
  20207. var inline = editor.inline === true;
  20208. return map$3(cssLinks, function (url) {
  20209. if (isContentCssSkinName(url) && !inline) {
  20210. return skinUrl + '/' + url + '/' + contentCssFile;
  20211. } else {
  20212. return editor.documentBaseURI.toAbsolute(url);
  20213. }
  20214. });
  20215. };
  20216. var appendContentCssFromSettings = function (editor) {
  20217. editor.contentCSS = editor.contentCSS.concat(getContentCssUrls(editor), getFontCssUrls(editor));
  20218. };
  20219. var UploadStatus = function () {
  20220. var PENDING = 1, UPLOADED = 2;
  20221. var blobUriStatuses = {};
  20222. var createStatus = function (status, resultUri) {
  20223. return {
  20224. status: status,
  20225. resultUri: resultUri
  20226. };
  20227. };
  20228. var hasBlobUri = function (blobUri) {
  20229. return blobUri in blobUriStatuses;
  20230. };
  20231. var getResultUri = function (blobUri) {
  20232. var result = blobUriStatuses[blobUri];
  20233. return result ? result.resultUri : null;
  20234. };
  20235. var isPending = function (blobUri) {
  20236. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
  20237. };
  20238. var isUploaded = function (blobUri) {
  20239. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
  20240. };
  20241. var markPending = function (blobUri) {
  20242. blobUriStatuses[blobUri] = createStatus(PENDING, null);
  20243. };
  20244. var markUploaded = function (blobUri, resultUri) {
  20245. blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
  20246. };
  20247. var removeFailed = function (blobUri) {
  20248. delete blobUriStatuses[blobUri];
  20249. };
  20250. var destroy = function () {
  20251. blobUriStatuses = {};
  20252. };
  20253. return {
  20254. hasBlobUri: hasBlobUri,
  20255. getResultUri: getResultUri,
  20256. isPending: isPending,
  20257. isUploaded: isUploaded,
  20258. markPending: markPending,
  20259. markUploaded: markUploaded,
  20260. removeFailed: removeFailed,
  20261. destroy: destroy
  20262. };
  20263. };
  20264. var count = 0;
  20265. var seed = function () {
  20266. var rnd = function () {
  20267. return Math.round(Math.random() * 4294967295).toString(36);
  20268. };
  20269. var now = new Date().getTime();
  20270. return 's' + now.toString(36) + rnd() + rnd() + rnd();
  20271. };
  20272. var uuid = function (prefix) {
  20273. return prefix + count++ + seed();
  20274. };
  20275. var BlobCache = function () {
  20276. var cache = [];
  20277. var mimeToExt = function (mime) {
  20278. var mimes = {
  20279. 'image/jpeg': 'jpg',
  20280. 'image/jpg': 'jpg',
  20281. 'image/gif': 'gif',
  20282. 'image/png': 'png',
  20283. 'image/apng': 'apng',
  20284. 'image/avif': 'avif',
  20285. 'image/svg+xml': 'svg',
  20286. 'image/webp': 'webp',
  20287. 'image/bmp': 'bmp',
  20288. 'image/tiff': 'tiff'
  20289. };
  20290. return mimes[mime.toLowerCase()] || 'dat';
  20291. };
  20292. var create = function (o, blob, base64, name, filename) {
  20293. if (isString$1(o)) {
  20294. var id = o;
  20295. return toBlobInfo({
  20296. id: id,
  20297. name: name,
  20298. filename: filename,
  20299. blob: blob,
  20300. base64: base64
  20301. });
  20302. } else if (isObject(o)) {
  20303. return toBlobInfo(o);
  20304. } else {
  20305. throw new Error('Unknown input type');
  20306. }
  20307. };
  20308. var toBlobInfo = function (o) {
  20309. if (!o.blob || !o.base64) {
  20310. throw new Error('blob and base64 representations of the image are required for BlobInfo to be created');
  20311. }
  20312. var id = o.id || uuid('blobid');
  20313. var name = o.name || id;
  20314. var blob = o.blob;
  20315. return {
  20316. id: constant(id),
  20317. name: constant(name),
  20318. filename: constant(o.filename || name + '.' + mimeToExt(blob.type)),
  20319. blob: constant(blob),
  20320. base64: constant(o.base64),
  20321. blobUri: constant(o.blobUri || URL.createObjectURL(blob)),
  20322. uri: constant(o.uri)
  20323. };
  20324. };
  20325. var add = function (blobInfo) {
  20326. if (!get(blobInfo.id())) {
  20327. cache.push(blobInfo);
  20328. }
  20329. };
  20330. var findFirst = function (predicate) {
  20331. return find$3(cache, predicate).getOrUndefined();
  20332. };
  20333. var get = function (id) {
  20334. return findFirst(function (cachedBlobInfo) {
  20335. return cachedBlobInfo.id() === id;
  20336. });
  20337. };
  20338. var getByUri = function (blobUri) {
  20339. return findFirst(function (blobInfo) {
  20340. return blobInfo.blobUri() === blobUri;
  20341. });
  20342. };
  20343. var getByData = function (base64, type) {
  20344. return findFirst(function (blobInfo) {
  20345. return blobInfo.base64() === base64 && blobInfo.blob().type === type;
  20346. });
  20347. };
  20348. var removeByUri = function (blobUri) {
  20349. cache = filter$4(cache, function (blobInfo) {
  20350. if (blobInfo.blobUri() === blobUri) {
  20351. URL.revokeObjectURL(blobInfo.blobUri());
  20352. return false;
  20353. }
  20354. return true;
  20355. });
  20356. };
  20357. var destroy = function () {
  20358. each$k(cache, function (cachedBlobInfo) {
  20359. URL.revokeObjectURL(cachedBlobInfo.blobUri());
  20360. });
  20361. cache = [];
  20362. };
  20363. return {
  20364. create: create,
  20365. add: add,
  20366. get: get,
  20367. getByUri: getByUri,
  20368. getByData: getByData,
  20369. findFirst: findFirst,
  20370. removeByUri: removeByUri,
  20371. destroy: destroy
  20372. };
  20373. };
  20374. var Uploader = function (uploadStatus, settings) {
  20375. var pendingPromises = {};
  20376. var pathJoin = function (path1, path2) {
  20377. if (path1) {
  20378. return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
  20379. }
  20380. return path2;
  20381. };
  20382. var defaultHandler = function (blobInfo, success, failure, progress) {
  20383. var xhr = new XMLHttpRequest();
  20384. xhr.open('POST', settings.url);
  20385. xhr.withCredentials = settings.credentials;
  20386. xhr.upload.onprogress = function (e) {
  20387. progress(e.loaded / e.total * 100);
  20388. };
  20389. xhr.onerror = function () {
  20390. failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  20391. };
  20392. xhr.onload = function () {
  20393. if (xhr.status < 200 || xhr.status >= 300) {
  20394. failure('HTTP Error: ' + xhr.status);
  20395. return;
  20396. }
  20397. var json = JSON.parse(xhr.responseText);
  20398. if (!json || typeof json.location !== 'string') {
  20399. failure('Invalid JSON: ' + xhr.responseText);
  20400. return;
  20401. }
  20402. success(pathJoin(settings.basePath, json.location));
  20403. };
  20404. var formData = new FormData();
  20405. formData.append('file', blobInfo.blob(), blobInfo.filename());
  20406. xhr.send(formData);
  20407. };
  20408. var noUpload = function () {
  20409. return new promiseObj(function (resolve) {
  20410. resolve([]);
  20411. });
  20412. };
  20413. var handlerSuccess = function (blobInfo, url) {
  20414. return {
  20415. url: url,
  20416. blobInfo: blobInfo,
  20417. status: true
  20418. };
  20419. };
  20420. var handlerFailure = function (blobInfo, message, options) {
  20421. return {
  20422. url: '',
  20423. blobInfo: blobInfo,
  20424. status: false,
  20425. error: {
  20426. message: message,
  20427. options: options
  20428. }
  20429. };
  20430. };
  20431. var resolvePending = function (blobUri, result) {
  20432. Tools.each(pendingPromises[blobUri], function (resolve) {
  20433. resolve(result);
  20434. });
  20435. delete pendingPromises[blobUri];
  20436. };
  20437. var uploadBlobInfo = function (blobInfo, handler, openNotification) {
  20438. uploadStatus.markPending(blobInfo.blobUri());
  20439. return new promiseObj(function (resolve) {
  20440. var notification, progress;
  20441. try {
  20442. var closeNotification_1 = function () {
  20443. if (notification) {
  20444. notification.close();
  20445. progress = noop;
  20446. }
  20447. };
  20448. var success = function (url) {
  20449. closeNotification_1();
  20450. uploadStatus.markUploaded(blobInfo.blobUri(), url);
  20451. resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
  20452. resolve(handlerSuccess(blobInfo, url));
  20453. };
  20454. var failure = function (error, options) {
  20455. var failureOptions = options ? options : {};
  20456. closeNotification_1();
  20457. uploadStatus.removeFailed(blobInfo.blobUri());
  20458. resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error, failureOptions));
  20459. resolve(handlerFailure(blobInfo, error, failureOptions));
  20460. };
  20461. progress = function (percent) {
  20462. if (percent < 0 || percent > 100) {
  20463. return;
  20464. }
  20465. Optional.from(notification).orThunk(function () {
  20466. return Optional.from(openNotification).map(apply);
  20467. }).each(function (n) {
  20468. notification = n;
  20469. n.progressBar.value(percent);
  20470. });
  20471. };
  20472. handler(blobInfo, success, failure, progress);
  20473. } catch (ex) {
  20474. resolve(handlerFailure(blobInfo, ex.message, {}));
  20475. }
  20476. });
  20477. };
  20478. var isDefaultHandler = function (handler) {
  20479. return handler === defaultHandler;
  20480. };
  20481. var pendingUploadBlobInfo = function (blobInfo) {
  20482. var blobUri = blobInfo.blobUri();
  20483. return new promiseObj(function (resolve) {
  20484. pendingPromises[blobUri] = pendingPromises[blobUri] || [];
  20485. pendingPromises[blobUri].push(resolve);
  20486. });
  20487. };
  20488. var uploadBlobs = function (blobInfos, openNotification) {
  20489. blobInfos = Tools.grep(blobInfos, function (blobInfo) {
  20490. return !uploadStatus.isUploaded(blobInfo.blobUri());
  20491. });
  20492. return promiseObj.all(Tools.map(blobInfos, function (blobInfo) {
  20493. return uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification);
  20494. }));
  20495. };
  20496. var upload = function (blobInfos, openNotification) {
  20497. return !settings.url && isDefaultHandler(settings.handler) ? noUpload() : uploadBlobs(blobInfos, openNotification);
  20498. };
  20499. if (isFunction(settings.handler) === false) {
  20500. settings.handler = defaultHandler;
  20501. }
  20502. return { upload: upload };
  20503. };
  20504. var openNotification = function (editor) {
  20505. return function () {
  20506. return editor.notificationManager.open({
  20507. text: editor.translate('Image uploading...'),
  20508. type: 'info',
  20509. timeout: -1,
  20510. progressBar: true
  20511. });
  20512. };
  20513. };
  20514. var createUploader = function (editor, uploadStatus) {
  20515. return Uploader(uploadStatus, {
  20516. url: getImageUploadUrl(editor),
  20517. basePath: getImageUploadBasePath(editor),
  20518. credentials: getImagesUploadCredentials(editor),
  20519. handler: getImagesUploadHandler(editor)
  20520. });
  20521. };
  20522. var ImageUploader = function (editor) {
  20523. var uploadStatus = UploadStatus();
  20524. var uploader = createUploader(editor, uploadStatus);
  20525. return {
  20526. upload: function (blobInfos, showNotification) {
  20527. if (showNotification === void 0) {
  20528. showNotification = true;
  20529. }
  20530. return uploader.upload(blobInfos, showNotification ? openNotification(editor) : undefined);
  20531. }
  20532. };
  20533. };
  20534. var UploadChangeHandler = function (editor) {
  20535. var lastChangedLevel = Cell(null);
  20536. editor.on('change AddUndo', function (e) {
  20537. lastChangedLevel.set(__assign({}, e.level));
  20538. });
  20539. var fireIfChanged = function () {
  20540. var data = editor.undoManager.data;
  20541. last$2(data).filter(function (level) {
  20542. return !isEq$1(lastChangedLevel.get(), level);
  20543. }).each(function (level) {
  20544. editor.setDirty(true);
  20545. editor.fire('change', {
  20546. level: level,
  20547. lastLevel: get$a(data, data.length - 2).getOrNull()
  20548. });
  20549. });
  20550. };
  20551. return { fireIfChanged: fireIfChanged };
  20552. };
  20553. var EditorUpload = function (editor) {
  20554. var blobCache = BlobCache();
  20555. var uploader, imageScanner;
  20556. var uploadStatus = UploadStatus();
  20557. var urlFilters = [];
  20558. var changeHandler = UploadChangeHandler(editor);
  20559. var aliveGuard = function (callback) {
  20560. return function (result) {
  20561. if (editor.selection) {
  20562. return callback(result);
  20563. }
  20564. return [];
  20565. };
  20566. };
  20567. var cacheInvalidator = function (url) {
  20568. return url + (url.indexOf('?') === -1 ? '?' : '&') + new Date().getTime();
  20569. };
  20570. var replaceString = function (content, search, replace) {
  20571. var index = 0;
  20572. do {
  20573. index = content.indexOf(search, index);
  20574. if (index !== -1) {
  20575. content = content.substring(0, index) + replace + content.substr(index + search.length);
  20576. index += replace.length - search.length + 1;
  20577. }
  20578. } while (index !== -1);
  20579. return content;
  20580. };
  20581. var replaceImageUrl = function (content, targetUrl, replacementUrl) {
  20582. var replacementString = 'src="' + replacementUrl + '"' + (replacementUrl === Env.transparentSrc ? ' data-mce-placeholder="1"' : '');
  20583. content = replaceString(content, 'src="' + targetUrl + '"', replacementString);
  20584. content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
  20585. return content;
  20586. };
  20587. var replaceUrlInUndoStack = function (targetUrl, replacementUrl) {
  20588. each$k(editor.undoManager.data, function (level) {
  20589. if (level.type === 'fragmented') {
  20590. level.fragments = map$3(level.fragments, function (fragment) {
  20591. return replaceImageUrl(fragment, targetUrl, replacementUrl);
  20592. });
  20593. } else {
  20594. level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
  20595. }
  20596. });
  20597. };
  20598. var replaceImageUriInView = function (image, resultUri) {
  20599. var src = editor.convertURL(resultUri, 'src');
  20600. replaceUrlInUndoStack(image.src, resultUri);
  20601. editor.$(image).attr({
  20602. 'src': shouldReuseFileName(editor) ? cacheInvalidator(resultUri) : resultUri,
  20603. 'data-mce-src': src
  20604. });
  20605. };
  20606. var uploadImages = function (callback) {
  20607. if (!uploader) {
  20608. uploader = createUploader(editor, uploadStatus);
  20609. }
  20610. return scanForImages().then(aliveGuard(function (imageInfos) {
  20611. var blobInfos = map$3(imageInfos, function (imageInfo) {
  20612. return imageInfo.blobInfo;
  20613. });
  20614. return uploader.upload(blobInfos, openNotification(editor)).then(aliveGuard(function (result) {
  20615. var imagesToRemove = [];
  20616. var filteredResult = map$3(result, function (uploadInfo, index) {
  20617. var blobInfo = imageInfos[index].blobInfo;
  20618. var image = imageInfos[index].image;
  20619. if (uploadInfo.status && shouldReplaceBlobUris(editor)) {
  20620. blobCache.removeByUri(image.src);
  20621. if (isRtc(editor)) ; else {
  20622. replaceImageUriInView(image, uploadInfo.url);
  20623. }
  20624. } else if (uploadInfo.error) {
  20625. if (uploadInfo.error.options.remove) {
  20626. replaceUrlInUndoStack(image.getAttribute('src'), Env.transparentSrc);
  20627. imagesToRemove.push(image);
  20628. }
  20629. uploadError(editor, uploadInfo.error.message);
  20630. }
  20631. return {
  20632. element: image,
  20633. status: uploadInfo.status,
  20634. uploadUri: uploadInfo.url,
  20635. blobInfo: blobInfo
  20636. };
  20637. });
  20638. if (filteredResult.length > 0) {
  20639. changeHandler.fireIfChanged();
  20640. }
  20641. if (imagesToRemove.length > 0) {
  20642. if (isRtc(editor)) {
  20643. console.error('Removing images on failed uploads is currently unsupported for RTC');
  20644. } else {
  20645. editor.undoManager.transact(function () {
  20646. each$k(imagesToRemove, function (element) {
  20647. editor.dom.remove(element);
  20648. blobCache.removeByUri(element.src);
  20649. });
  20650. });
  20651. }
  20652. }
  20653. if (callback) {
  20654. callback(filteredResult);
  20655. }
  20656. return filteredResult;
  20657. }));
  20658. }));
  20659. };
  20660. var uploadImagesAuto = function (callback) {
  20661. if (isAutomaticUploadsEnabled(editor)) {
  20662. return uploadImages(callback);
  20663. }
  20664. };
  20665. var isValidDataUriImage = function (imgElm) {
  20666. if (forall(urlFilters, function (filter) {
  20667. return filter(imgElm);
  20668. }) === false) {
  20669. return false;
  20670. }
  20671. if (imgElm.getAttribute('src').indexOf('data:') === 0) {
  20672. var dataImgFilter = getImagesDataImgFilter(editor);
  20673. return dataImgFilter(imgElm);
  20674. }
  20675. return true;
  20676. };
  20677. var addFilter = function (filter) {
  20678. urlFilters.push(filter);
  20679. };
  20680. var scanForImages = function () {
  20681. if (!imageScanner) {
  20682. imageScanner = ImageScanner(uploadStatus, blobCache);
  20683. }
  20684. return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(function (result) {
  20685. result = filter$4(result, function (resultItem) {
  20686. if (typeof resultItem === 'string') {
  20687. displayError(editor, resultItem);
  20688. return false;
  20689. }
  20690. return true;
  20691. });
  20692. if (isRtc(editor)) ; else {
  20693. each$k(result, function (resultItem) {
  20694. replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
  20695. resultItem.image.src = resultItem.blobInfo.blobUri();
  20696. resultItem.image.removeAttribute('data-mce-src');
  20697. });
  20698. }
  20699. return result;
  20700. }));
  20701. };
  20702. var destroy = function () {
  20703. blobCache.destroy();
  20704. uploadStatus.destroy();
  20705. imageScanner = uploader = null;
  20706. };
  20707. var replaceBlobUris = function (content) {
  20708. return content.replace(/src="(blob:[^"]+)"/g, function (match, blobUri) {
  20709. var resultUri = uploadStatus.getResultUri(blobUri);
  20710. if (resultUri) {
  20711. return 'src="' + resultUri + '"';
  20712. }
  20713. var blobInfo = blobCache.getByUri(blobUri);
  20714. if (!blobInfo) {
  20715. blobInfo = foldl(editor.editorManager.get(), function (result, editor) {
  20716. return result || editor.editorUpload && editor.editorUpload.blobCache.getByUri(blobUri);
  20717. }, null);
  20718. }
  20719. if (blobInfo) {
  20720. var blob = blobInfo.blob();
  20721. return 'src="data:' + blob.type + ';base64,' + blobInfo.base64() + '"';
  20722. }
  20723. return match;
  20724. });
  20725. };
  20726. editor.on('SetContent', function () {
  20727. if (isAutomaticUploadsEnabled(editor)) {
  20728. uploadImagesAuto();
  20729. } else {
  20730. scanForImages();
  20731. }
  20732. });
  20733. editor.on('RawSaveContent', function (e) {
  20734. e.content = replaceBlobUris(e.content);
  20735. });
  20736. editor.on('GetContent', function (e) {
  20737. if (e.source_view || e.format === 'raw' || e.format === 'tree') {
  20738. return;
  20739. }
  20740. e.content = replaceBlobUris(e.content);
  20741. });
  20742. editor.on('PostRender', function () {
  20743. editor.parser.addNodeFilter('img', function (images) {
  20744. each$k(images, function (img) {
  20745. var src = img.attr('src');
  20746. if (blobCache.getByUri(src)) {
  20747. return;
  20748. }
  20749. var resultUri = uploadStatus.getResultUri(src);
  20750. if (resultUri) {
  20751. img.attr('src', resultUri);
  20752. }
  20753. });
  20754. });
  20755. });
  20756. return {
  20757. blobCache: blobCache,
  20758. addFilter: addFilter,
  20759. uploadImages: uploadImages,
  20760. uploadImagesAuto: uploadImagesAuto,
  20761. scanForImages: scanForImages,
  20762. destroy: destroy
  20763. };
  20764. };
  20765. var get = function (dom) {
  20766. var formats = {
  20767. valigntop: [{
  20768. selector: 'td,th',
  20769. styles: { verticalAlign: 'top' }
  20770. }],
  20771. valignmiddle: [{
  20772. selector: 'td,th',
  20773. styles: { verticalAlign: 'middle' }
  20774. }],
  20775. valignbottom: [{
  20776. selector: 'td,th',
  20777. styles: { verticalAlign: 'bottom' }
  20778. }],
  20779. alignleft: [
  20780. {
  20781. selector: 'figure.image',
  20782. collapsed: false,
  20783. classes: 'align-left',
  20784. ceFalseOverride: true,
  20785. preview: 'font-family font-size'
  20786. },
  20787. {
  20788. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20789. styles: { textAlign: 'left' },
  20790. inherit: false,
  20791. preview: false,
  20792. defaultBlock: 'div'
  20793. },
  20794. {
  20795. selector: 'img,table,audio,video',
  20796. collapsed: false,
  20797. styles: { float: 'left' },
  20798. preview: 'font-family font-size'
  20799. }
  20800. ],
  20801. aligncenter: [
  20802. {
  20803. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20804. styles: { textAlign: 'center' },
  20805. inherit: false,
  20806. preview: 'font-family font-size',
  20807. defaultBlock: 'div'
  20808. },
  20809. {
  20810. selector: 'figure.image',
  20811. collapsed: false,
  20812. classes: 'align-center',
  20813. ceFalseOverride: true,
  20814. preview: 'font-family font-size'
  20815. },
  20816. {
  20817. selector: 'img,audio,video',
  20818. collapsed: false,
  20819. styles: {
  20820. display: 'block',
  20821. marginLeft: 'auto',
  20822. marginRight: 'auto'
  20823. },
  20824. preview: false
  20825. },
  20826. {
  20827. selector: 'table',
  20828. collapsed: false,
  20829. styles: {
  20830. marginLeft: 'auto',
  20831. marginRight: 'auto'
  20832. },
  20833. preview: 'font-family font-size'
  20834. }
  20835. ],
  20836. alignright: [
  20837. {
  20838. selector: 'figure.image',
  20839. collapsed: false,
  20840. classes: 'align-right',
  20841. ceFalseOverride: true,
  20842. preview: 'font-family font-size'
  20843. },
  20844. {
  20845. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20846. styles: { textAlign: 'right' },
  20847. inherit: false,
  20848. preview: 'font-family font-size',
  20849. defaultBlock: 'div'
  20850. },
  20851. {
  20852. selector: 'img,table,audio,video',
  20853. collapsed: false,
  20854. styles: { float: 'right' },
  20855. preview: 'font-family font-size'
  20856. }
  20857. ],
  20858. alignjustify: [{
  20859. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20860. styles: { textAlign: 'justify' },
  20861. inherit: false,
  20862. defaultBlock: 'div',
  20863. preview: 'font-family font-size'
  20864. }],
  20865. bold: [
  20866. {
  20867. inline: 'strong',
  20868. remove: 'all',
  20869. preserve_attributes: [
  20870. 'class',
  20871. 'style'
  20872. ]
  20873. },
  20874. {
  20875. inline: 'span',
  20876. styles: { fontWeight: 'bold' }
  20877. },
  20878. {
  20879. inline: 'b',
  20880. remove: 'all',
  20881. preserve_attributes: [
  20882. 'class',
  20883. 'style'
  20884. ]
  20885. }
  20886. ],
  20887. italic: [
  20888. {
  20889. inline: 'em',
  20890. remove: 'all',
  20891. preserve_attributes: [
  20892. 'class',
  20893. 'style'
  20894. ]
  20895. },
  20896. {
  20897. inline: 'span',
  20898. styles: { fontStyle: 'italic' }
  20899. },
  20900. {
  20901. inline: 'i',
  20902. remove: 'all',
  20903. preserve_attributes: [
  20904. 'class',
  20905. 'style'
  20906. ]
  20907. }
  20908. ],
  20909. underline: [
  20910. {
  20911. inline: 'span',
  20912. styles: { textDecoration: 'underline' },
  20913. exact: true
  20914. },
  20915. {
  20916. inline: 'u',
  20917. remove: 'all',
  20918. preserve_attributes: [
  20919. 'class',
  20920. 'style'
  20921. ]
  20922. }
  20923. ],
  20924. strikethrough: [
  20925. {
  20926. inline: 'span',
  20927. styles: { textDecoration: 'line-through' },
  20928. exact: true
  20929. },
  20930. {
  20931. inline: 'strike',
  20932. remove: 'all',
  20933. preserve_attributes: [
  20934. 'class',
  20935. 'style'
  20936. ]
  20937. },
  20938. {
  20939. inline: 's',
  20940. remove: 'all',
  20941. preserve_attributes: [
  20942. 'class',
  20943. 'style'
  20944. ]
  20945. }
  20946. ],
  20947. forecolor: {
  20948. inline: 'span',
  20949. styles: { color: '%value' },
  20950. links: true,
  20951. remove_similar: true,
  20952. clear_child_styles: true
  20953. },
  20954. hilitecolor: {
  20955. inline: 'span',
  20956. styles: { backgroundColor: '%value' },
  20957. links: true,
  20958. remove_similar: true,
  20959. clear_child_styles: true
  20960. },
  20961. fontname: {
  20962. inline: 'span',
  20963. toggle: false,
  20964. styles: { fontFamily: '%value' },
  20965. clear_child_styles: true
  20966. },
  20967. fontsize: {
  20968. inline: 'span',
  20969. toggle: false,
  20970. styles: { fontSize: '%value' },
  20971. clear_child_styles: true
  20972. },
  20973. lineheight: {
  20974. selector: 'h1,h2,h3,h4,h5,h6,p,li,td,th,div',
  20975. defaultBlock: 'p',
  20976. styles: { lineHeight: '%value' }
  20977. },
  20978. fontsize_class: {
  20979. inline: 'span',
  20980. attributes: { class: '%value' }
  20981. },
  20982. blockquote: {
  20983. block: 'blockquote',
  20984. wrapper: true,
  20985. remove: 'all'
  20986. },
  20987. subscript: { inline: 'sub' },
  20988. superscript: { inline: 'sup' },
  20989. code: { inline: 'code' },
  20990. link: {
  20991. inline: 'a',
  20992. selector: 'a',
  20993. remove: 'all',
  20994. split: true,
  20995. deep: true,
  20996. onmatch: function (node, _fmt, _itemName) {
  20997. return isElement$5(node) && node.hasAttribute('href');
  20998. },
  20999. onformat: function (elm, _fmt, vars) {
  21000. Tools.each(vars, function (value, key) {
  21001. dom.setAttrib(elm, key, value);
  21002. });
  21003. }
  21004. },
  21005. lang: {
  21006. inline: 'span',
  21007. clear_child_styles: true,
  21008. remove_similar: true,
  21009. attributes: {
  21010. 'lang': '%value',
  21011. 'data-mce-lang': function (vars) {
  21012. var _a;
  21013. return (_a = vars === null || vars === void 0 ? void 0 : vars.customValue) !== null && _a !== void 0 ? _a : null;
  21014. }
  21015. }
  21016. },
  21017. removeformat: [
  21018. {
  21019. selector: 'b,strong,em,i,font,u,strike,s,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins,small',
  21020. remove: 'all',
  21021. split: true,
  21022. expand: false,
  21023. block_expand: true,
  21024. deep: true
  21025. },
  21026. {
  21027. selector: 'span',
  21028. attributes: [
  21029. 'style',
  21030. 'class'
  21031. ],
  21032. remove: 'empty',
  21033. split: true,
  21034. expand: false,
  21035. deep: true
  21036. },
  21037. {
  21038. selector: '*',
  21039. attributes: [
  21040. 'style',
  21041. 'class'
  21042. ],
  21043. split: false,
  21044. expand: false,
  21045. deep: true
  21046. }
  21047. ]
  21048. };
  21049. Tools.each('p h1 h2 h3 h4 h5 h6 div address pre dt dd samp'.split(/\s/), function (name) {
  21050. formats[name] = {
  21051. block: name,
  21052. remove: 'all'
  21053. };
  21054. });
  21055. return formats;
  21056. };
  21057. var FormatRegistry = function (editor) {
  21058. var formats = {};
  21059. var get$1 = function (name) {
  21060. return isNonNullable(name) ? formats[name] : formats;
  21061. };
  21062. var has = function (name) {
  21063. return has$2(formats, name);
  21064. };
  21065. var register = function (name, format) {
  21066. if (name) {
  21067. if (!isString$1(name)) {
  21068. each$j(name, function (format, name) {
  21069. register(name, format);
  21070. });
  21071. } else {
  21072. if (!isArray$1(format)) {
  21073. format = [format];
  21074. }
  21075. each$k(format, function (format) {
  21076. if (isUndefined(format.deep)) {
  21077. format.deep = !isSelectorFormat(format);
  21078. }
  21079. if (isUndefined(format.split)) {
  21080. format.split = !isSelectorFormat(format) || isInlineFormat(format);
  21081. }
  21082. if (isUndefined(format.remove) && isSelectorFormat(format) && !isInlineFormat(format)) {
  21083. format.remove = 'none';
  21084. }
  21085. if (isSelectorFormat(format) && isInlineFormat(format)) {
  21086. format.mixed = true;
  21087. format.block_expand = true;
  21088. }
  21089. if (isString$1(format.classes)) {
  21090. format.classes = format.classes.split(/\s+/);
  21091. }
  21092. });
  21093. formats[name] = format;
  21094. }
  21095. }
  21096. };
  21097. var unregister = function (name) {
  21098. if (name && formats[name]) {
  21099. delete formats[name];
  21100. }
  21101. return formats;
  21102. };
  21103. register(get(editor.dom));
  21104. register(getFormats(editor));
  21105. return {
  21106. get: get$1,
  21107. has: has,
  21108. register: register,
  21109. unregister: unregister
  21110. };
  21111. };
  21112. var each$6 = Tools.each;
  21113. var dom = DOMUtils.DOM;
  21114. var parsedSelectorToHtml = function (ancestry, editor) {
  21115. var elm, item, fragment;
  21116. var schema = editor && editor.schema || Schema({});
  21117. var decorate = function (elm, item) {
  21118. if (item.classes.length) {
  21119. dom.addClass(elm, item.classes.join(' '));
  21120. }
  21121. dom.setAttribs(elm, item.attrs);
  21122. };
  21123. var createElement = function (sItem) {
  21124. item = typeof sItem === 'string' ? {
  21125. name: sItem,
  21126. classes: [],
  21127. attrs: {}
  21128. } : sItem;
  21129. var elm = dom.create(item.name);
  21130. decorate(elm, item);
  21131. return elm;
  21132. };
  21133. var getRequiredParent = function (elm, candidate) {
  21134. var name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm;
  21135. var elmRule = schema.getElementRule(name);
  21136. var parentsRequired = elmRule && elmRule.parentsRequired;
  21137. if (parentsRequired && parentsRequired.length) {
  21138. return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
  21139. } else {
  21140. return false;
  21141. }
  21142. };
  21143. var wrapInHtml = function (elm, ancestry, siblings) {
  21144. var parent, parentCandidate;
  21145. var ancestor = ancestry.length > 0 && ancestry[0];
  21146. var ancestorName = ancestor && ancestor.name;
  21147. var parentRequired = getRequiredParent(elm, ancestorName);
  21148. if (parentRequired) {
  21149. if (ancestorName === parentRequired) {
  21150. parentCandidate = ancestry[0];
  21151. ancestry = ancestry.slice(1);
  21152. } else {
  21153. parentCandidate = parentRequired;
  21154. }
  21155. } else if (ancestor) {
  21156. parentCandidate = ancestry[0];
  21157. ancestry = ancestry.slice(1);
  21158. } else if (!siblings) {
  21159. return elm;
  21160. }
  21161. if (parentCandidate) {
  21162. parent = createElement(parentCandidate);
  21163. parent.appendChild(elm);
  21164. }
  21165. if (siblings) {
  21166. if (!parent) {
  21167. parent = dom.create('div');
  21168. parent.appendChild(elm);
  21169. }
  21170. Tools.each(siblings, function (sibling) {
  21171. var siblingElm = createElement(sibling);
  21172. parent.insertBefore(siblingElm, elm);
  21173. });
  21174. }
  21175. return wrapInHtml(parent, ancestry, parentCandidate && parentCandidate.siblings);
  21176. };
  21177. if (ancestry && ancestry.length) {
  21178. item = ancestry[0];
  21179. elm = createElement(item);
  21180. fragment = dom.create('div');
  21181. fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
  21182. return fragment;
  21183. } else {
  21184. return '';
  21185. }
  21186. };
  21187. var parseSelectorItem = function (item) {
  21188. var tagName;
  21189. var obj = {
  21190. classes: [],
  21191. attrs: {}
  21192. };
  21193. item = obj.selector = Tools.trim(item);
  21194. if (item !== '*') {
  21195. tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function ($0, $1, $2, $3, $4) {
  21196. switch ($1) {
  21197. case '#':
  21198. obj.attrs.id = $2;
  21199. break;
  21200. case '.':
  21201. obj.classes.push($2);
  21202. break;
  21203. case ':':
  21204. if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
  21205. obj.attrs[$2] = $2;
  21206. }
  21207. break;
  21208. }
  21209. if ($3 === '[') {
  21210. var m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
  21211. if (m) {
  21212. obj.attrs[m[1]] = m[2];
  21213. }
  21214. }
  21215. return '';
  21216. });
  21217. }
  21218. obj.name = tagName || 'div';
  21219. return obj;
  21220. };
  21221. var parseSelector = function (selector) {
  21222. if (!selector || typeof selector !== 'string') {
  21223. return [];
  21224. }
  21225. selector = selector.split(/\s*,\s*/)[0];
  21226. selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1');
  21227. return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), function (item) {
  21228. var siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
  21229. var obj = siblings.pop();
  21230. if (siblings.length) {
  21231. obj.siblings = siblings;
  21232. }
  21233. return obj;
  21234. }).reverse();
  21235. };
  21236. var getCssText = function (editor, format) {
  21237. var name, previewFrag;
  21238. var previewCss = '', parentFontSize;
  21239. var previewStyles = getPreviewStyles(editor);
  21240. if (previewStyles === '') {
  21241. return '';
  21242. }
  21243. var removeVars = function (val) {
  21244. return val.replace(/%(\w+)/g, '');
  21245. };
  21246. if (typeof format === 'string') {
  21247. format = editor.formatter.get(format);
  21248. if (!format) {
  21249. return;
  21250. }
  21251. format = format[0];
  21252. }
  21253. if ('preview' in format) {
  21254. var previewOpt = get$9(format, 'preview');
  21255. if (is$1(previewOpt, false)) {
  21256. return '';
  21257. } else {
  21258. previewStyles = previewOpt.getOr(previewStyles);
  21259. }
  21260. }
  21261. name = format.block || format.inline || 'span';
  21262. var items = parseSelector(format.selector);
  21263. if (items.length) {
  21264. if (!items[0].name) {
  21265. items[0].name = name;
  21266. }
  21267. name = format.selector;
  21268. previewFrag = parsedSelectorToHtml(items, editor);
  21269. } else {
  21270. previewFrag = parsedSelectorToHtml([name], editor);
  21271. }
  21272. var previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;
  21273. each$6(format.styles, function (value, name) {
  21274. var newValue = removeVars(value);
  21275. if (newValue) {
  21276. dom.setStyle(previewElm, name, newValue);
  21277. }
  21278. });
  21279. each$6(format.attributes, function (value, name) {
  21280. var newValue = removeVars(value);
  21281. if (newValue) {
  21282. dom.setAttrib(previewElm, name, newValue);
  21283. }
  21284. });
  21285. each$6(format.classes, function (value) {
  21286. var newValue = removeVars(value);
  21287. if (!dom.hasClass(previewElm, newValue)) {
  21288. dom.addClass(previewElm, newValue);
  21289. }
  21290. });
  21291. editor.fire('PreviewFormats');
  21292. dom.setStyles(previewFrag, {
  21293. position: 'absolute',
  21294. left: -65535
  21295. });
  21296. editor.getBody().appendChild(previewFrag);
  21297. parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
  21298. parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
  21299. each$6(previewStyles.split(' '), function (name) {
  21300. var value = dom.getStyle(previewElm, name, true);
  21301. if (name === 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
  21302. value = dom.getStyle(editor.getBody(), name, true);
  21303. if (dom.toHex(value).toLowerCase() === '#ffffff') {
  21304. return;
  21305. }
  21306. }
  21307. if (name === 'color') {
  21308. if (dom.toHex(value).toLowerCase() === '#000000') {
  21309. return;
  21310. }
  21311. }
  21312. if (name === 'font-size') {
  21313. if (/em|%$/.test(value)) {
  21314. if (parentFontSize === 0) {
  21315. return;
  21316. }
  21317. var numValue = parseFloat(value) / (/%$/.test(value) ? 100 : 1);
  21318. value = numValue * parentFontSize + 'px';
  21319. }
  21320. }
  21321. if (name === 'border' && value) {
  21322. previewCss += 'padding:0 2px;';
  21323. }
  21324. previewCss += name + ':' + value + ';';
  21325. });
  21326. editor.fire('AfterPreviewFormats');
  21327. dom.remove(previewFrag);
  21328. return previewCss;
  21329. };
  21330. var setup$h = function (editor) {
  21331. editor.addShortcut('meta+b', '', 'Bold');
  21332. editor.addShortcut('meta+i', '', 'Italic');
  21333. editor.addShortcut('meta+u', '', 'Underline');
  21334. for (var i = 1; i <= 6; i++) {
  21335. editor.addShortcut('access+' + i, '', [
  21336. 'FormatBlock',
  21337. false,
  21338. 'h' + i
  21339. ]);
  21340. }
  21341. editor.addShortcut('access+7', '', [
  21342. 'FormatBlock',
  21343. false,
  21344. 'p'
  21345. ]);
  21346. editor.addShortcut('access+8', '', [
  21347. 'FormatBlock',
  21348. false,
  21349. 'div'
  21350. ]);
  21351. editor.addShortcut('access+9', '', [
  21352. 'FormatBlock',
  21353. false,
  21354. 'address'
  21355. ]);
  21356. };
  21357. var Formatter = function (editor) {
  21358. var formats = FormatRegistry(editor);
  21359. var formatChangeState = Cell(null);
  21360. setup$h(editor);
  21361. setup$k(editor);
  21362. return {
  21363. get: formats.get,
  21364. has: formats.has,
  21365. register: formats.register,
  21366. unregister: formats.unregister,
  21367. apply: function (name, vars, node) {
  21368. applyFormat(editor, name, vars, node);
  21369. },
  21370. remove: function (name, vars, node, similar) {
  21371. removeFormat(editor, name, vars, node, similar);
  21372. },
  21373. toggle: function (name, vars, node) {
  21374. toggleFormat(editor, name, vars, node);
  21375. },
  21376. match: function (name, vars, node, similar) {
  21377. return matchFormat(editor, name, vars, node, similar);
  21378. },
  21379. closest: function (names) {
  21380. return closestFormat(editor, names);
  21381. },
  21382. matchAll: function (names, vars) {
  21383. return matchAllFormats(editor, names, vars);
  21384. },
  21385. matchNode: function (node, name, vars, similar) {
  21386. return matchNodeFormat(editor, node, name, vars, similar);
  21387. },
  21388. canApply: function (name) {
  21389. return canApplyFormat(editor, name);
  21390. },
  21391. formatChanged: function (formats, callback, similar, vars) {
  21392. return formatChanged(editor, formatChangeState, formats, callback, similar, vars);
  21393. },
  21394. getCssText: curry(getCssText, editor)
  21395. };
  21396. };
  21397. var shouldIgnoreCommand = function (cmd) {
  21398. switch (cmd.toLowerCase()) {
  21399. case 'undo':
  21400. case 'redo':
  21401. case 'mcerepaint':
  21402. case 'mcefocus':
  21403. return true;
  21404. default:
  21405. return false;
  21406. }
  21407. };
  21408. var registerEvents = function (editor, undoManager, locks) {
  21409. var isFirstTypedCharacter = Cell(false);
  21410. var addNonTypingUndoLevel = function (e) {
  21411. setTyping(undoManager, false, locks);
  21412. undoManager.add({}, e);
  21413. };
  21414. editor.on('init', function () {
  21415. undoManager.add();
  21416. });
  21417. editor.on('BeforeExecCommand', function (e) {
  21418. var cmd = e.command;
  21419. if (!shouldIgnoreCommand(cmd)) {
  21420. endTyping(undoManager, locks);
  21421. undoManager.beforeChange();
  21422. }
  21423. });
  21424. editor.on('ExecCommand', function (e) {
  21425. var cmd = e.command;
  21426. if (!shouldIgnoreCommand(cmd)) {
  21427. addNonTypingUndoLevel(e);
  21428. }
  21429. });
  21430. editor.on('ObjectResizeStart cut', function () {
  21431. undoManager.beforeChange();
  21432. });
  21433. editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
  21434. editor.on('dragend', addNonTypingUndoLevel);
  21435. editor.on('keyup', function (e) {
  21436. var keyCode = e.keyCode;
  21437. if (e.isDefaultPrevented()) {
  21438. return;
  21439. }
  21440. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45 || e.ctrlKey) {
  21441. addNonTypingUndoLevel();
  21442. editor.nodeChanged();
  21443. }
  21444. if (keyCode === 46 || keyCode === 8) {
  21445. editor.nodeChanged();
  21446. }
  21447. if (isFirstTypedCharacter.get() && undoManager.typing && isEq$1(createFromEditor(editor), undoManager.data[0]) === false) {
  21448. if (editor.isDirty() === false) {
  21449. editor.setDirty(true);
  21450. editor.fire('change', {
  21451. level: undoManager.data[0],
  21452. lastLevel: null
  21453. });
  21454. }
  21455. editor.fire('TypingUndo');
  21456. isFirstTypedCharacter.set(false);
  21457. editor.nodeChanged();
  21458. }
  21459. });
  21460. editor.on('keydown', function (e) {
  21461. var keyCode = e.keyCode;
  21462. if (e.isDefaultPrevented()) {
  21463. return;
  21464. }
  21465. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45) {
  21466. if (undoManager.typing) {
  21467. addNonTypingUndoLevel(e);
  21468. }
  21469. return;
  21470. }
  21471. var modKey = e.ctrlKey && !e.altKey || e.metaKey;
  21472. if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !undoManager.typing && !modKey) {
  21473. undoManager.beforeChange();
  21474. setTyping(undoManager, true, locks);
  21475. undoManager.add({}, e);
  21476. isFirstTypedCharacter.set(true);
  21477. }
  21478. });
  21479. editor.on('mousedown', function (e) {
  21480. if (undoManager.typing) {
  21481. addNonTypingUndoLevel(e);
  21482. }
  21483. });
  21484. var isInsertReplacementText = function (event) {
  21485. return event.inputType === 'insertReplacementText';
  21486. };
  21487. var isInsertTextDataNull = function (event) {
  21488. return event.inputType === 'insertText' && event.data === null;
  21489. };
  21490. var isInsertFromPasteOrDrop = function (event) {
  21491. return event.inputType === 'insertFromPaste' || event.inputType === 'insertFromDrop';
  21492. };
  21493. editor.on('input', function (e) {
  21494. if (e.inputType && (isInsertReplacementText(e) || isInsertTextDataNull(e) || isInsertFromPasteOrDrop(e))) {
  21495. addNonTypingUndoLevel(e);
  21496. }
  21497. });
  21498. editor.on('AddUndo Undo Redo ClearUndos', function (e) {
  21499. if (!e.isDefaultPrevented()) {
  21500. editor.nodeChanged();
  21501. }
  21502. });
  21503. };
  21504. var addKeyboardShortcuts = function (editor) {
  21505. editor.addShortcut('meta+z', '', 'Undo');
  21506. editor.addShortcut('meta+y,meta+shift+z', '', 'Redo');
  21507. };
  21508. var UndoManager = function (editor) {
  21509. var beforeBookmark = value();
  21510. var locks = Cell(0);
  21511. var index = Cell(0);
  21512. var undoManager = {
  21513. data: [],
  21514. typing: false,
  21515. beforeChange: function () {
  21516. beforeChange(editor, locks, beforeBookmark);
  21517. },
  21518. add: function (level, event) {
  21519. return addUndoLevel(editor, undoManager, index, locks, beforeBookmark, level, event);
  21520. },
  21521. undo: function () {
  21522. return undo(editor, undoManager, locks, index);
  21523. },
  21524. redo: function () {
  21525. return redo(editor, index, undoManager.data);
  21526. },
  21527. clear: function () {
  21528. clear(editor, undoManager, index);
  21529. },
  21530. reset: function () {
  21531. reset(editor, undoManager);
  21532. },
  21533. hasUndo: function () {
  21534. return hasUndo(editor, undoManager, index);
  21535. },
  21536. hasRedo: function () {
  21537. return hasRedo(editor, undoManager, index);
  21538. },
  21539. transact: function (callback) {
  21540. return transact(editor, undoManager, locks, callback);
  21541. },
  21542. ignore: function (callback) {
  21543. ignore(editor, locks, callback);
  21544. },
  21545. extra: function (callback1, callback2) {
  21546. extra(editor, undoManager, index, callback1, callback2);
  21547. }
  21548. };
  21549. if (!isRtc(editor)) {
  21550. registerEvents(editor, undoManager, locks);
  21551. }
  21552. addKeyboardShortcuts(editor);
  21553. return undoManager;
  21554. };
  21555. var nonTypingKeycodes = [
  21556. 9,
  21557. 27,
  21558. VK.HOME,
  21559. VK.END,
  21560. 19,
  21561. 20,
  21562. 44,
  21563. 144,
  21564. 145,
  21565. 33,
  21566. 34,
  21567. 45,
  21568. 16,
  21569. 17,
  21570. 18,
  21571. 91,
  21572. 92,
  21573. 93,
  21574. VK.DOWN,
  21575. VK.UP,
  21576. VK.LEFT,
  21577. VK.RIGHT
  21578. ].concat(Env.browser.isFirefox() ? [224] : []);
  21579. var placeholderAttr = 'data-mce-placeholder';
  21580. var isKeyboardEvent = function (e) {
  21581. return e.type === 'keydown' || e.type === 'keyup';
  21582. };
  21583. var isDeleteEvent = function (e) {
  21584. var keyCode = e.keyCode;
  21585. return keyCode === VK.BACKSPACE || keyCode === VK.DELETE;
  21586. };
  21587. var isNonTypingKeyboardEvent = function (e) {
  21588. if (isKeyboardEvent(e)) {
  21589. var keyCode = e.keyCode;
  21590. return !isDeleteEvent(e) && (VK.metaKeyPressed(e) || e.altKey || keyCode >= 112 && keyCode <= 123 || contains$3(nonTypingKeycodes, keyCode));
  21591. } else {
  21592. return false;
  21593. }
  21594. };
  21595. var isTypingKeyboardEvent = function (e) {
  21596. return isKeyboardEvent(e) && !(isDeleteEvent(e) || e.type === 'keyup' && e.keyCode === 229);
  21597. };
  21598. var isVisuallyEmpty = function (dom, rootElm, forcedRootBlock) {
  21599. if (isEmpty$2(SugarElement.fromDom(rootElm), false)) {
  21600. var isForcedRootBlockFalse = forcedRootBlock === '';
  21601. var firstElement = rootElm.firstElementChild;
  21602. if (!firstElement) {
  21603. return true;
  21604. } else if (dom.getStyle(rootElm.firstElementChild, 'padding-left') || dom.getStyle(rootElm.firstElementChild, 'padding-right')) {
  21605. return false;
  21606. } else {
  21607. return isForcedRootBlockFalse ? !dom.isBlock(firstElement) : forcedRootBlock === firstElement.nodeName.toLowerCase();
  21608. }
  21609. } else {
  21610. return false;
  21611. }
  21612. };
  21613. var setup$g = function (editor) {
  21614. var dom = editor.dom;
  21615. var rootBlock = getForcedRootBlock(editor);
  21616. var placeholder = getPlaceholder(editor);
  21617. var updatePlaceholder = function (e, initial) {
  21618. if (isNonTypingKeyboardEvent(e)) {
  21619. return;
  21620. }
  21621. var body = editor.getBody();
  21622. var showPlaceholder = isTypingKeyboardEvent(e) ? false : isVisuallyEmpty(dom, body, rootBlock);
  21623. var isPlaceholderShown = dom.getAttrib(body, placeholderAttr) !== '';
  21624. if (isPlaceholderShown !== showPlaceholder || initial) {
  21625. dom.setAttrib(body, placeholderAttr, showPlaceholder ? placeholder : null);
  21626. dom.setAttrib(body, 'aria-placeholder', showPlaceholder ? placeholder : null);
  21627. firePlaceholderToggle(editor, showPlaceholder);
  21628. editor.on(showPlaceholder ? 'keydown' : 'keyup', updatePlaceholder);
  21629. editor.off(showPlaceholder ? 'keyup' : 'keydown', updatePlaceholder);
  21630. }
  21631. };
  21632. if (placeholder) {
  21633. editor.on('init', function (e) {
  21634. updatePlaceholder(e, true);
  21635. editor.on('change SetContent ExecCommand', updatePlaceholder);
  21636. editor.on('paste', function (e) {
  21637. return Delay.setEditorTimeout(editor, function () {
  21638. return updatePlaceholder(e);
  21639. });
  21640. });
  21641. });
  21642. }
  21643. };
  21644. var strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
  21645. var hasStrongRtl = function (text) {
  21646. return strongRtl.test(text);
  21647. };
  21648. var isInlineTarget = function (editor, elm) {
  21649. return is$2(SugarElement.fromDom(elm), getInlineBoundarySelector(editor));
  21650. };
  21651. var isRtl = function (element) {
  21652. return DOMUtils.DOM.getStyle(element, 'direction', true) === 'rtl' || hasStrongRtl(element.textContent);
  21653. };
  21654. var findInlineParents = function (isInlineTarget, rootNode, pos) {
  21655. return filter$4(DOMUtils.DOM.getParents(pos.container(), '*', rootNode), isInlineTarget);
  21656. };
  21657. var findRootInline = function (isInlineTarget, rootNode, pos) {
  21658. var parents = findInlineParents(isInlineTarget, rootNode, pos);
  21659. return Optional.from(parents[parents.length - 1]);
  21660. };
  21661. var hasSameParentBlock = function (rootNode, node1, node2) {
  21662. var block1 = getParentBlock$2(node1, rootNode);
  21663. var block2 = getParentBlock$2(node2, rootNode);
  21664. return block1 && block1 === block2;
  21665. };
  21666. var isAtZwsp = function (pos) {
  21667. return isBeforeInline(pos) || isAfterInline(pos);
  21668. };
  21669. var normalizePosition = function (forward, pos) {
  21670. if (!pos) {
  21671. return pos;
  21672. }
  21673. var container = pos.container(), offset = pos.offset();
  21674. if (forward) {
  21675. if (isCaretContainerInline(container)) {
  21676. if (isText$7(container.nextSibling)) {
  21677. return CaretPosition(container.nextSibling, 0);
  21678. } else {
  21679. return CaretPosition.after(container);
  21680. }
  21681. } else {
  21682. return isBeforeInline(pos) ? CaretPosition(container, offset + 1) : pos;
  21683. }
  21684. } else {
  21685. if (isCaretContainerInline(container)) {
  21686. if (isText$7(container.previousSibling)) {
  21687. return CaretPosition(container.previousSibling, container.previousSibling.data.length);
  21688. } else {
  21689. return CaretPosition.before(container);
  21690. }
  21691. } else {
  21692. return isAfterInline(pos) ? CaretPosition(container, offset - 1) : pos;
  21693. }
  21694. }
  21695. };
  21696. var normalizeForwards = curry(normalizePosition, true);
  21697. var normalizeBackwards = curry(normalizePosition, false);
  21698. var isBeforeRoot = function (rootNode) {
  21699. return function (elm) {
  21700. return eq(rootNode, SugarElement.fromDom(elm.dom.parentNode));
  21701. };
  21702. };
  21703. var isTextBlockOrListItem = function (element) {
  21704. return isTextBlock$2(element) || isListItem(element);
  21705. };
  21706. var getParentBlock$1 = function (rootNode, elm) {
  21707. if (contains$1(rootNode, elm)) {
  21708. return closest$3(elm, isTextBlockOrListItem, isBeforeRoot(rootNode));
  21709. } else {
  21710. return Optional.none();
  21711. }
  21712. };
  21713. var placeCaretInEmptyBody = function (editor) {
  21714. var body = editor.getBody();
  21715. var node = body.firstChild && editor.dom.isBlock(body.firstChild) ? body.firstChild : body;
  21716. editor.selection.setCursorLocation(node, 0);
  21717. };
  21718. var paddEmptyBody = function (editor) {
  21719. if (editor.dom.isEmpty(editor.getBody())) {
  21720. editor.setContent('');
  21721. placeCaretInEmptyBody(editor);
  21722. }
  21723. };
  21724. var willDeleteLastPositionInElement = function (forward, fromPos, elm) {
  21725. return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  21726. var normalizedFirstPos = normalizePosition(true, firstPos);
  21727. var normalizedLastPos = normalizePosition(false, lastPos);
  21728. var normalizedFromPos = normalizePosition(false, fromPos);
  21729. if (forward) {
  21730. return nextPosition(elm, normalizedFromPos).exists(function (nextPos) {
  21731. return nextPos.isEqual(normalizedLastPos) && fromPos.isEqual(normalizedFirstPos);
  21732. });
  21733. } else {
  21734. return prevPosition(elm, normalizedFromPos).exists(function (prevPos) {
  21735. return prevPos.isEqual(normalizedFirstPos) && fromPos.isEqual(normalizedLastPos);
  21736. });
  21737. }
  21738. }).getOr(true);
  21739. };
  21740. var blockPosition = function (block, position) {
  21741. return {
  21742. block: block,
  21743. position: position
  21744. };
  21745. };
  21746. var blockBoundary = function (from, to) {
  21747. return {
  21748. from: from,
  21749. to: to
  21750. };
  21751. };
  21752. var getBlockPosition = function (rootNode, pos) {
  21753. var rootElm = SugarElement.fromDom(rootNode);
  21754. var containerElm = SugarElement.fromDom(pos.container());
  21755. return getParentBlock$1(rootElm, containerElm).map(function (block) {
  21756. return blockPosition(block, pos);
  21757. });
  21758. };
  21759. var isDifferentBlocks = function (blockBoundary) {
  21760. return eq(blockBoundary.from.block, blockBoundary.to.block) === false;
  21761. };
  21762. var hasSameParent = function (blockBoundary) {
  21763. return parent(blockBoundary.from.block).bind(function (parent1) {
  21764. return parent(blockBoundary.to.block).filter(function (parent2) {
  21765. return eq(parent1, parent2);
  21766. });
  21767. }).isSome();
  21768. };
  21769. var isEditable$1 = function (blockBoundary) {
  21770. return isContentEditableFalse$b(blockBoundary.from.block.dom) === false && isContentEditableFalse$b(blockBoundary.to.block.dom) === false;
  21771. };
  21772. var skipLastBr = function (rootNode, forward, blockPosition) {
  21773. if (isBr$5(blockPosition.position.getNode()) && isEmpty$2(blockPosition.block) === false) {
  21774. return positionIn(false, blockPosition.block.dom).bind(function (lastPositionInBlock) {
  21775. if (lastPositionInBlock.isEqual(blockPosition.position)) {
  21776. return fromPosition(forward, rootNode, lastPositionInBlock).bind(function (to) {
  21777. return getBlockPosition(rootNode, to);
  21778. });
  21779. } else {
  21780. return Optional.some(blockPosition);
  21781. }
  21782. }).getOr(blockPosition);
  21783. } else {
  21784. return blockPosition;
  21785. }
  21786. };
  21787. var readFromRange = function (rootNode, forward, rng) {
  21788. var fromBlockPos = getBlockPosition(rootNode, CaretPosition.fromRangeStart(rng));
  21789. var toBlockPos = fromBlockPos.bind(function (blockPos) {
  21790. return fromPosition(forward, rootNode, blockPos.position).bind(function (to) {
  21791. return getBlockPosition(rootNode, to).map(function (blockPos) {
  21792. return skipLastBr(rootNode, forward, blockPos);
  21793. });
  21794. });
  21795. });
  21796. return lift2(fromBlockPos, toBlockPos, blockBoundary).filter(function (blockBoundary) {
  21797. return isDifferentBlocks(blockBoundary) && hasSameParent(blockBoundary) && isEditable$1(blockBoundary);
  21798. });
  21799. };
  21800. var read$1 = function (rootNode, forward, rng) {
  21801. return rng.collapsed ? readFromRange(rootNode, forward, rng) : Optional.none();
  21802. };
  21803. var getChildrenUntilBlockBoundary = function (block) {
  21804. var children$1 = children(block);
  21805. return findIndex$2(children$1, isBlock$2).fold(constant(children$1), function (index) {
  21806. return children$1.slice(0, index);
  21807. });
  21808. };
  21809. var extractChildren = function (block) {
  21810. var children = getChildrenUntilBlockBoundary(block);
  21811. each$k(children, remove$7);
  21812. return children;
  21813. };
  21814. var removeEmptyRoot = function (rootNode, block) {
  21815. var parents = parentsAndSelf(block, rootNode);
  21816. return find$3(parents.reverse(), function (element) {
  21817. return isEmpty$2(element);
  21818. }).each(remove$7);
  21819. };
  21820. var isEmptyBefore = function (el) {
  21821. return filter$4(prevSiblings(el), function (el) {
  21822. return !isEmpty$2(el);
  21823. }).length === 0;
  21824. };
  21825. var nestedBlockMerge = function (rootNode, fromBlock, toBlock, insertionPoint) {
  21826. if (isEmpty$2(toBlock)) {
  21827. fillWithPaddingBr(toBlock);
  21828. return firstPositionIn(toBlock.dom);
  21829. }
  21830. if (isEmptyBefore(insertionPoint) && isEmpty$2(fromBlock)) {
  21831. before$4(insertionPoint, SugarElement.fromTag('br'));
  21832. }
  21833. var position = prevPosition(toBlock.dom, CaretPosition.before(insertionPoint.dom));
  21834. each$k(extractChildren(fromBlock), function (child) {
  21835. before$4(insertionPoint, child);
  21836. });
  21837. removeEmptyRoot(rootNode, fromBlock);
  21838. return position;
  21839. };
  21840. var sidelongBlockMerge = function (rootNode, fromBlock, toBlock) {
  21841. if (isEmpty$2(toBlock)) {
  21842. remove$7(toBlock);
  21843. if (isEmpty$2(fromBlock)) {
  21844. fillWithPaddingBr(fromBlock);
  21845. }
  21846. return firstPositionIn(fromBlock.dom);
  21847. }
  21848. var position = lastPositionIn(toBlock.dom);
  21849. each$k(extractChildren(fromBlock), function (child) {
  21850. append$1(toBlock, child);
  21851. });
  21852. removeEmptyRoot(rootNode, fromBlock);
  21853. return position;
  21854. };
  21855. var findInsertionPoint = function (toBlock, block) {
  21856. var parentsAndSelf$1 = parentsAndSelf(block, toBlock);
  21857. return Optional.from(parentsAndSelf$1[parentsAndSelf$1.length - 1]);
  21858. };
  21859. var getInsertionPoint = function (fromBlock, toBlock) {
  21860. return contains$1(toBlock, fromBlock) ? findInsertionPoint(toBlock, fromBlock) : Optional.none();
  21861. };
  21862. var trimBr = function (first, block) {
  21863. positionIn(first, block.dom).map(function (position) {
  21864. return position.getNode();
  21865. }).map(SugarElement.fromDom).filter(isBr$4).each(remove$7);
  21866. };
  21867. var mergeBlockInto = function (rootNode, fromBlock, toBlock) {
  21868. trimBr(true, fromBlock);
  21869. trimBr(false, toBlock);
  21870. return getInsertionPoint(fromBlock, toBlock).fold(curry(sidelongBlockMerge, rootNode, fromBlock, toBlock), curry(nestedBlockMerge, rootNode, fromBlock, toBlock));
  21871. };
  21872. var mergeBlocks = function (rootNode, forward, block1, block2) {
  21873. return forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
  21874. };
  21875. var backspaceDelete$8 = function (editor, forward) {
  21876. var rootNode = SugarElement.fromDom(editor.getBody());
  21877. var position = read$1(rootNode.dom, forward, editor.selection.getRng()).bind(function (blockBoundary) {
  21878. return mergeBlocks(rootNode, forward, blockBoundary.from.block, blockBoundary.to.block);
  21879. });
  21880. position.each(function (pos) {
  21881. editor.selection.setRng(pos.toRange());
  21882. });
  21883. return position.isSome();
  21884. };
  21885. var deleteRangeMergeBlocks = function (rootNode, selection) {
  21886. var rng = selection.getRng();
  21887. return lift2(getParentBlock$1(rootNode, SugarElement.fromDom(rng.startContainer)), getParentBlock$1(rootNode, SugarElement.fromDom(rng.endContainer)), function (block1, block2) {
  21888. if (eq(block1, block2) === false) {
  21889. rng.deleteContents();
  21890. mergeBlocks(rootNode, true, block1, block2).each(function (pos) {
  21891. selection.setRng(pos.toRange());
  21892. });
  21893. return true;
  21894. } else {
  21895. return false;
  21896. }
  21897. }).getOr(false);
  21898. };
  21899. var isRawNodeInTable = function (root, rawNode) {
  21900. var node = SugarElement.fromDom(rawNode);
  21901. var isRoot = curry(eq, root);
  21902. return ancestor$3(node, isTableCell$4, isRoot).isSome();
  21903. };
  21904. var isSelectionInTable = function (root, rng) {
  21905. return isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
  21906. };
  21907. var isEverythingSelected = function (root, rng) {
  21908. var noPrevious = prevPosition(root.dom, CaretPosition.fromRangeStart(rng)).isNone();
  21909. var noNext = nextPosition(root.dom, CaretPosition.fromRangeEnd(rng)).isNone();
  21910. return !isSelectionInTable(root, rng) && noPrevious && noNext;
  21911. };
  21912. var emptyEditor = function (editor) {
  21913. editor.setContent('');
  21914. editor.selection.setCursorLocation();
  21915. return true;
  21916. };
  21917. var deleteRange$1 = function (editor) {
  21918. var rootNode = SugarElement.fromDom(editor.getBody());
  21919. var rng = editor.selection.getRng();
  21920. return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
  21921. };
  21922. var backspaceDelete$7 = function (editor, _forward) {
  21923. return editor.selection.isCollapsed() ? false : deleteRange$1(editor);
  21924. };
  21925. var isContentEditableTrue$2 = isContentEditableTrue$4;
  21926. var isContentEditableFalse$4 = isContentEditableFalse$b;
  21927. var showCaret = function (direction, editor, node, before, scrollIntoView) {
  21928. return Optional.from(editor._selectionOverrides.showCaret(direction, node, before, scrollIntoView));
  21929. };
  21930. var getNodeRange = function (node) {
  21931. var rng = node.ownerDocument.createRange();
  21932. rng.selectNode(node);
  21933. return rng;
  21934. };
  21935. var selectNode = function (editor, node) {
  21936. var e = editor.fire('BeforeObjectSelected', { target: node });
  21937. if (e.isDefaultPrevented()) {
  21938. return Optional.none();
  21939. }
  21940. return Optional.some(getNodeRange(node));
  21941. };
  21942. var renderCaretAtRange = function (editor, range, scrollIntoView) {
  21943. var normalizedRange = normalizeRange(1, editor.getBody(), range);
  21944. var caretPosition = CaretPosition.fromRangeStart(normalizedRange);
  21945. var caretPositionNode = caretPosition.getNode();
  21946. if (isInlineFakeCaretTarget(caretPositionNode)) {
  21947. return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
  21948. }
  21949. var caretPositionBeforeNode = caretPosition.getNode(true);
  21950. if (isInlineFakeCaretTarget(caretPositionBeforeNode)) {
  21951. return showCaret(1, editor, caretPositionBeforeNode, false, false);
  21952. }
  21953. var ceRoot = editor.dom.getParent(caretPosition.getNode(), function (node) {
  21954. return isContentEditableFalse$4(node) || isContentEditableTrue$2(node);
  21955. });
  21956. if (isInlineFakeCaretTarget(ceRoot)) {
  21957. return showCaret(1, editor, ceRoot, false, scrollIntoView);
  21958. }
  21959. return Optional.none();
  21960. };
  21961. var renderRangeCaret = function (editor, range, scrollIntoView) {
  21962. return range.collapsed ? renderCaretAtRange(editor, range, scrollIntoView).getOr(range) : range;
  21963. };
  21964. var isBeforeBoundary = function (pos) {
  21965. return isBeforeContentEditableFalse(pos) || isBeforeMedia(pos);
  21966. };
  21967. var isAfterBoundary = function (pos) {
  21968. return isAfterContentEditableFalse(pos) || isAfterMedia(pos);
  21969. };
  21970. var trimEmptyTextNode = function (dom, node) {
  21971. if (isText$7(node) && node.data.length === 0) {
  21972. dom.remove(node);
  21973. }
  21974. };
  21975. var deleteContentAndShowCaret = function (editor, range, node, direction, forward, peekCaretPosition) {
  21976. showCaret(direction, editor, peekCaretPosition.getNode(!forward), forward, true).each(function (caretRange) {
  21977. if (range.collapsed) {
  21978. var deleteRange = range.cloneRange();
  21979. if (forward) {
  21980. deleteRange.setEnd(caretRange.startContainer, caretRange.startOffset);
  21981. } else {
  21982. deleteRange.setStart(caretRange.endContainer, caretRange.endOffset);
  21983. }
  21984. deleteRange.deleteContents();
  21985. } else {
  21986. range.deleteContents();
  21987. }
  21988. editor.selection.setRng(caretRange);
  21989. });
  21990. trimEmptyTextNode(editor.dom, node);
  21991. return true;
  21992. };
  21993. var deleteBoundaryText = function (editor, forward) {
  21994. var range = editor.selection.getRng();
  21995. if (!isText$7(range.commonAncestorContainer)) {
  21996. return false;
  21997. }
  21998. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  21999. var caretWalker = CaretWalker(editor.getBody());
  22000. var getNextPosFn = curry(getVisualCaretPosition, forward ? caretWalker.next : caretWalker.prev);
  22001. var isBeforeFn = forward ? isBeforeBoundary : isAfterBoundary;
  22002. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22003. var nextCaretPosition = normalizePosition(forward, getNextPosFn(caretPosition));
  22004. if (!nextCaretPosition || !isMoveInsideSameBlock(caretPosition, nextCaretPosition)) {
  22005. return false;
  22006. } else if (isBeforeFn(nextCaretPosition)) {
  22007. return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, nextCaretPosition);
  22008. }
  22009. var peekCaretPosition = getNextPosFn(nextCaretPosition);
  22010. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  22011. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  22012. return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, peekCaretPosition);
  22013. }
  22014. }
  22015. return false;
  22016. };
  22017. var backspaceDelete$6 = function (editor, forward) {
  22018. return deleteBoundaryText(editor, forward);
  22019. };
  22020. var isCompoundElement = function (node) {
  22021. return isTableCell$4(SugarElement.fromDom(node)) || isListItem(SugarElement.fromDom(node));
  22022. };
  22023. var DeleteAction = Adt.generate([
  22024. { remove: ['element'] },
  22025. { moveToElement: ['element'] },
  22026. { moveToPosition: ['position'] }
  22027. ]);
  22028. var isAtContentEditableBlockCaret = function (forward, from) {
  22029. var elm = from.getNode(forward === false);
  22030. var caretLocation = forward ? 'after' : 'before';
  22031. return isElement$5(elm) && elm.getAttribute('data-mce-caret') === caretLocation;
  22032. };
  22033. var isDeleteFromCefDifferentBlocks = function (root, forward, from, to) {
  22034. var inSameBlock = function (elm) {
  22035. return isInline$1(SugarElement.fromDom(elm)) && !isInSameBlock(from, to, root);
  22036. };
  22037. return getRelativeCefElm(!forward, from).fold(function () {
  22038. return getRelativeCefElm(forward, to).fold(never, inSameBlock);
  22039. }, inSameBlock);
  22040. };
  22041. var deleteEmptyBlockOrMoveToCef = function (root, forward, from, to) {
  22042. var toCefElm = to.getNode(forward === false);
  22043. return getParentBlock$1(SugarElement.fromDom(root), SugarElement.fromDom(from.getNode())).map(function (blockElm) {
  22044. return isEmpty$2(blockElm) ? DeleteAction.remove(blockElm.dom) : DeleteAction.moveToElement(toCefElm);
  22045. }).orThunk(function () {
  22046. return Optional.some(DeleteAction.moveToElement(toCefElm));
  22047. });
  22048. };
  22049. var findCefPosition = function (root, forward, from) {
  22050. return fromPosition(forward, root, from).bind(function (to) {
  22051. if (isCompoundElement(to.getNode())) {
  22052. return Optional.none();
  22053. } else if (isDeleteFromCefDifferentBlocks(root, forward, from, to)) {
  22054. return Optional.none();
  22055. } else if (forward && isContentEditableFalse$b(to.getNode())) {
  22056. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  22057. } else if (forward === false && isContentEditableFalse$b(to.getNode(true))) {
  22058. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  22059. } else if (forward && isAfterContentEditableFalse(from)) {
  22060. return Optional.some(DeleteAction.moveToPosition(to));
  22061. } else if (forward === false && isBeforeContentEditableFalse(from)) {
  22062. return Optional.some(DeleteAction.moveToPosition(to));
  22063. } else {
  22064. return Optional.none();
  22065. }
  22066. });
  22067. };
  22068. var getContentEditableBlockAction = function (forward, elm) {
  22069. if (forward && isContentEditableFalse$b(elm.nextSibling)) {
  22070. return Optional.some(DeleteAction.moveToElement(elm.nextSibling));
  22071. } else if (forward === false && isContentEditableFalse$b(elm.previousSibling)) {
  22072. return Optional.some(DeleteAction.moveToElement(elm.previousSibling));
  22073. } else {
  22074. return Optional.none();
  22075. }
  22076. };
  22077. var skipMoveToActionFromInlineCefToContent = function (root, from, deleteAction) {
  22078. return deleteAction.fold(function (elm) {
  22079. return Optional.some(DeleteAction.remove(elm));
  22080. }, function (elm) {
  22081. return Optional.some(DeleteAction.moveToElement(elm));
  22082. }, function (to) {
  22083. if (isInSameBlock(from, to, root)) {
  22084. return Optional.none();
  22085. } else {
  22086. return Optional.some(DeleteAction.moveToPosition(to));
  22087. }
  22088. });
  22089. };
  22090. var getContentEditableAction = function (root, forward, from) {
  22091. if (isAtContentEditableBlockCaret(forward, from)) {
  22092. return getContentEditableBlockAction(forward, from.getNode(forward === false)).fold(function () {
  22093. return findCefPosition(root, forward, from);
  22094. }, Optional.some);
  22095. } else {
  22096. return findCefPosition(root, forward, from).bind(function (deleteAction) {
  22097. return skipMoveToActionFromInlineCefToContent(root, from, deleteAction);
  22098. });
  22099. }
  22100. };
  22101. var read = function (root, forward, rng) {
  22102. var normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
  22103. var from = CaretPosition.fromRangeStart(normalizedRange);
  22104. var rootElement = SugarElement.fromDom(root);
  22105. if (forward === false && isAfterContentEditableFalse(from)) {
  22106. return Optional.some(DeleteAction.remove(from.getNode(true)));
  22107. } else if (forward && isBeforeContentEditableFalse(from)) {
  22108. return Optional.some(DeleteAction.remove(from.getNode()));
  22109. } else if (forward === false && isBeforeContentEditableFalse(from) && isAfterBr(rootElement, from)) {
  22110. return findPreviousBr(rootElement, from).map(function (br) {
  22111. return DeleteAction.remove(br.getNode());
  22112. });
  22113. } else if (forward && isAfterContentEditableFalse(from) && isBeforeBr$1(rootElement, from)) {
  22114. return findNextBr(rootElement, from).map(function (br) {
  22115. return DeleteAction.remove(br.getNode());
  22116. });
  22117. } else {
  22118. return getContentEditableAction(root, forward, from);
  22119. }
  22120. };
  22121. var deleteElement$1 = function (editor, forward) {
  22122. return function (element) {
  22123. editor._selectionOverrides.hideFakeCaret();
  22124. deleteElement$2(editor, forward, SugarElement.fromDom(element));
  22125. return true;
  22126. };
  22127. };
  22128. var moveToElement = function (editor, forward) {
  22129. return function (element) {
  22130. var pos = forward ? CaretPosition.before(element) : CaretPosition.after(element);
  22131. editor.selection.setRng(pos.toRange());
  22132. return true;
  22133. };
  22134. };
  22135. var moveToPosition = function (editor) {
  22136. return function (pos) {
  22137. editor.selection.setRng(pos.toRange());
  22138. return true;
  22139. };
  22140. };
  22141. var getAncestorCe = function (editor, node) {
  22142. return Optional.from(getContentEditableRoot$1(editor.getBody(), node));
  22143. };
  22144. var backspaceDeleteCaret = function (editor, forward) {
  22145. var selectedNode = editor.selection.getNode();
  22146. return getAncestorCe(editor, selectedNode).filter(isContentEditableFalse$b).fold(function () {
  22147. return read(editor.getBody(), forward, editor.selection.getRng()).exists(function (deleteAction) {
  22148. return deleteAction.fold(deleteElement$1(editor, forward), moveToElement(editor, forward), moveToPosition(editor));
  22149. });
  22150. }, always);
  22151. };
  22152. var deleteOffscreenSelection = function (rootElement) {
  22153. each$k(descendants(rootElement, '.mce-offscreen-selection'), remove$7);
  22154. };
  22155. var backspaceDeleteRange = function (editor, forward) {
  22156. var selectedNode = editor.selection.getNode();
  22157. if (isContentEditableFalse$b(selectedNode) && !isTableCell$5(selectedNode)) {
  22158. var hasCefAncestor = getAncestorCe(editor, selectedNode.parentNode).filter(isContentEditableFalse$b);
  22159. return hasCefAncestor.fold(function () {
  22160. deleteOffscreenSelection(SugarElement.fromDom(editor.getBody()));
  22161. deleteElement$2(editor, forward, SugarElement.fromDom(editor.selection.getNode()));
  22162. paddEmptyBody(editor);
  22163. return true;
  22164. }, always);
  22165. }
  22166. return false;
  22167. };
  22168. var paddEmptyElement = function (editor) {
  22169. var dom = editor.dom, selection = editor.selection;
  22170. var ceRoot = getContentEditableRoot$1(editor.getBody(), selection.getNode());
  22171. if (isContentEditableTrue$4(ceRoot) && dom.isBlock(ceRoot) && dom.isEmpty(ceRoot)) {
  22172. var br = dom.create('br', { 'data-mce-bogus': '1' });
  22173. dom.setHTML(ceRoot, '');
  22174. ceRoot.appendChild(br);
  22175. selection.setRng(CaretPosition.before(br).toRange());
  22176. }
  22177. return true;
  22178. };
  22179. var backspaceDelete$5 = function (editor, forward) {
  22180. if (editor.selection.isCollapsed()) {
  22181. return backspaceDeleteCaret(editor, forward);
  22182. } else {
  22183. return backspaceDeleteRange(editor, forward);
  22184. }
  22185. };
  22186. var deleteCaret$2 = function (editor, forward) {
  22187. var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22188. return fromPosition(forward, editor.getBody(), fromPos).filter(function (pos) {
  22189. return forward ? isBeforeImageBlock(pos) : isAfterImageBlock(pos);
  22190. }).bind(function (pos) {
  22191. return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, pos));
  22192. }).exists(function (elm) {
  22193. editor.selection.select(elm);
  22194. return true;
  22195. });
  22196. };
  22197. var backspaceDelete$4 = function (editor, forward) {
  22198. return editor.selection.isCollapsed() ? deleteCaret$2(editor, forward) : false;
  22199. };
  22200. var isText = isText$7;
  22201. var startsWithCaretContainer = function (node) {
  22202. return isText(node) && node.data[0] === ZWSP$1;
  22203. };
  22204. var endsWithCaretContainer = function (node) {
  22205. return isText(node) && node.data[node.data.length - 1] === ZWSP$1;
  22206. };
  22207. var createZwsp = function (node) {
  22208. return node.ownerDocument.createTextNode(ZWSP$1);
  22209. };
  22210. var insertBefore = function (node) {
  22211. if (isText(node.previousSibling)) {
  22212. if (endsWithCaretContainer(node.previousSibling)) {
  22213. return node.previousSibling;
  22214. } else {
  22215. node.previousSibling.appendData(ZWSP$1);
  22216. return node.previousSibling;
  22217. }
  22218. } else if (isText(node)) {
  22219. if (startsWithCaretContainer(node)) {
  22220. return node;
  22221. } else {
  22222. node.insertData(0, ZWSP$1);
  22223. return node;
  22224. }
  22225. } else {
  22226. var newNode = createZwsp(node);
  22227. node.parentNode.insertBefore(newNode, node);
  22228. return newNode;
  22229. }
  22230. };
  22231. var insertAfter = function (node) {
  22232. if (isText(node.nextSibling)) {
  22233. if (startsWithCaretContainer(node.nextSibling)) {
  22234. return node.nextSibling;
  22235. } else {
  22236. node.nextSibling.insertData(0, ZWSP$1);
  22237. return node.nextSibling;
  22238. }
  22239. } else if (isText(node)) {
  22240. if (endsWithCaretContainer(node)) {
  22241. return node;
  22242. } else {
  22243. node.appendData(ZWSP$1);
  22244. return node;
  22245. }
  22246. } else {
  22247. var newNode = createZwsp(node);
  22248. if (node.nextSibling) {
  22249. node.parentNode.insertBefore(newNode, node.nextSibling);
  22250. } else {
  22251. node.parentNode.appendChild(newNode);
  22252. }
  22253. return newNode;
  22254. }
  22255. };
  22256. var insertInline = function (before, node) {
  22257. return before ? insertBefore(node) : insertAfter(node);
  22258. };
  22259. var insertInlineBefore = curry(insertInline, true);
  22260. var insertInlineAfter = curry(insertInline, false);
  22261. var insertInlinePos = function (pos, before) {
  22262. if (isText$7(pos.container())) {
  22263. return insertInline(before, pos.container());
  22264. } else {
  22265. return insertInline(before, pos.getNode());
  22266. }
  22267. };
  22268. var isPosCaretContainer = function (pos, caret) {
  22269. var caretNode = caret.get();
  22270. return caretNode && pos.container() === caretNode && isCaretContainerInline(caretNode);
  22271. };
  22272. var renderCaret = function (caret, location) {
  22273. return location.fold(function (element) {
  22274. remove$2(caret.get());
  22275. var text = insertInlineBefore(element);
  22276. caret.set(text);
  22277. return Optional.some(CaretPosition(text, text.length - 1));
  22278. }, function (element) {
  22279. return firstPositionIn(element).map(function (pos) {
  22280. if (!isPosCaretContainer(pos, caret)) {
  22281. remove$2(caret.get());
  22282. var text = insertInlinePos(pos, true);
  22283. caret.set(text);
  22284. return CaretPosition(text, 1);
  22285. } else {
  22286. return CaretPosition(caret.get(), 1);
  22287. }
  22288. });
  22289. }, function (element) {
  22290. return lastPositionIn(element).map(function (pos) {
  22291. if (!isPosCaretContainer(pos, caret)) {
  22292. remove$2(caret.get());
  22293. var text = insertInlinePos(pos, false);
  22294. caret.set(text);
  22295. return CaretPosition(text, text.length - 1);
  22296. } else {
  22297. return CaretPosition(caret.get(), caret.get().length - 1);
  22298. }
  22299. });
  22300. }, function (element) {
  22301. remove$2(caret.get());
  22302. var text = insertInlineAfter(element);
  22303. caret.set(text);
  22304. return Optional.some(CaretPosition(text, 1));
  22305. });
  22306. };
  22307. var evaluateUntil = function (fns, args) {
  22308. for (var i = 0; i < fns.length; i++) {
  22309. var result = fns[i].apply(null, args);
  22310. if (result.isSome()) {
  22311. return result;
  22312. }
  22313. }
  22314. return Optional.none();
  22315. };
  22316. var Location = Adt.generate([
  22317. { before: ['element'] },
  22318. { start: ['element'] },
  22319. { end: ['element'] },
  22320. { after: ['element'] }
  22321. ]);
  22322. var rescope$1 = function (rootNode, node) {
  22323. var parentBlock = getParentBlock$2(node, rootNode);
  22324. return parentBlock ? parentBlock : rootNode;
  22325. };
  22326. var before = function (isInlineTarget, rootNode, pos) {
  22327. var nPos = normalizeForwards(pos);
  22328. var scope = rescope$1(rootNode, nPos.container());
  22329. return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  22330. return nextPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  22331. return Location.before(inline);
  22332. });
  22333. }, Optional.none);
  22334. };
  22335. var isNotInsideFormatCaretContainer = function (rootNode, elm) {
  22336. return getParentCaretContainer(rootNode, elm) === null;
  22337. };
  22338. var findInsideRootInline = function (isInlineTarget, rootNode, pos) {
  22339. return findRootInline(isInlineTarget, rootNode, pos).filter(curry(isNotInsideFormatCaretContainer, rootNode));
  22340. };
  22341. var start$1 = function (isInlineTarget, rootNode, pos) {
  22342. var nPos = normalizeBackwards(pos);
  22343. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  22344. var prevPos = prevPosition(inline, nPos);
  22345. return prevPos.isNone() ? Optional.some(Location.start(inline)) : Optional.none();
  22346. });
  22347. };
  22348. var end = function (isInlineTarget, rootNode, pos) {
  22349. var nPos = normalizeForwards(pos);
  22350. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  22351. var nextPos = nextPosition(inline, nPos);
  22352. return nextPos.isNone() ? Optional.some(Location.end(inline)) : Optional.none();
  22353. });
  22354. };
  22355. var after = function (isInlineTarget, rootNode, pos) {
  22356. var nPos = normalizeBackwards(pos);
  22357. var scope = rescope$1(rootNode, nPos.container());
  22358. return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  22359. return prevPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  22360. return Location.after(inline);
  22361. });
  22362. }, Optional.none);
  22363. };
  22364. var isValidLocation = function (location) {
  22365. return isRtl(getElement(location)) === false;
  22366. };
  22367. var readLocation = function (isInlineTarget, rootNode, pos) {
  22368. var location = evaluateUntil([
  22369. before,
  22370. start$1,
  22371. end,
  22372. after
  22373. ], [
  22374. isInlineTarget,
  22375. rootNode,
  22376. pos
  22377. ]);
  22378. return location.filter(isValidLocation);
  22379. };
  22380. var getElement = function (location) {
  22381. return location.fold(identity, identity, identity, identity);
  22382. };
  22383. var getName = function (location) {
  22384. return location.fold(constant('before'), constant('start'), constant('end'), constant('after'));
  22385. };
  22386. var outside = function (location) {
  22387. return location.fold(Location.before, Location.before, Location.after, Location.after);
  22388. };
  22389. var inside = function (location) {
  22390. return location.fold(Location.start, Location.start, Location.end, Location.end);
  22391. };
  22392. var isEq = function (location1, location2) {
  22393. return getName(location1) === getName(location2) && getElement(location1) === getElement(location2);
  22394. };
  22395. var betweenInlines = function (forward, isInlineTarget, rootNode, from, to, location) {
  22396. return lift2(findRootInline(isInlineTarget, rootNode, from), findRootInline(isInlineTarget, rootNode, to), function (fromInline, toInline) {
  22397. if (fromInline !== toInline && hasSameParentBlock(rootNode, fromInline, toInline)) {
  22398. return Location.after(forward ? fromInline : toInline);
  22399. } else {
  22400. return location;
  22401. }
  22402. }).getOr(location);
  22403. };
  22404. var skipNoMovement = function (fromLocation, toLocation) {
  22405. return fromLocation.fold(always, function (fromLocation) {
  22406. return !isEq(fromLocation, toLocation);
  22407. });
  22408. };
  22409. var findLocationTraverse = function (forward, isInlineTarget, rootNode, fromLocation, pos) {
  22410. var from = normalizePosition(forward, pos);
  22411. var to = fromPosition(forward, rootNode, from).map(curry(normalizePosition, forward));
  22412. var location = to.fold(function () {
  22413. return fromLocation.map(outside);
  22414. }, function (to) {
  22415. return readLocation(isInlineTarget, rootNode, to).map(curry(betweenInlines, forward, isInlineTarget, rootNode, from, to)).filter(curry(skipNoMovement, fromLocation));
  22416. });
  22417. return location.filter(isValidLocation);
  22418. };
  22419. var findLocationSimple = function (forward, location) {
  22420. if (forward) {
  22421. return location.fold(compose(Optional.some, Location.start), Optional.none, compose(Optional.some, Location.after), Optional.none);
  22422. } else {
  22423. return location.fold(Optional.none, compose(Optional.some, Location.before), Optional.none, compose(Optional.some, Location.end));
  22424. }
  22425. };
  22426. var findLocation$1 = function (forward, isInlineTarget, rootNode, pos) {
  22427. var from = normalizePosition(forward, pos);
  22428. var fromLocation = readLocation(isInlineTarget, rootNode, from);
  22429. return readLocation(isInlineTarget, rootNode, from).bind(curry(findLocationSimple, forward)).orThunk(function () {
  22430. return findLocationTraverse(forward, isInlineTarget, rootNode, fromLocation, pos);
  22431. });
  22432. };
  22433. curry(findLocation$1, false);
  22434. curry(findLocation$1, true);
  22435. var hasSelectionModifyApi = function (editor) {
  22436. return isFunction(editor.selection.getSel().modify);
  22437. };
  22438. var moveRel = function (forward, selection, pos) {
  22439. var delta = forward ? 1 : -1;
  22440. selection.setRng(CaretPosition(pos.container(), pos.offset() + delta).toRange());
  22441. selection.getSel().modify('move', forward ? 'forward' : 'backward', 'word');
  22442. return true;
  22443. };
  22444. var moveByWord = function (forward, editor) {
  22445. var rng = editor.selection.getRng();
  22446. var pos = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  22447. if (!hasSelectionModifyApi(editor)) {
  22448. return false;
  22449. } else if (forward && isBeforeInline(pos)) {
  22450. return moveRel(true, editor.selection, pos);
  22451. } else if (!forward && isAfterInline(pos)) {
  22452. return moveRel(false, editor.selection, pos);
  22453. } else {
  22454. return false;
  22455. }
  22456. };
  22457. var BreakType;
  22458. (function (BreakType) {
  22459. BreakType[BreakType['Br'] = 0] = 'Br';
  22460. BreakType[BreakType['Block'] = 1] = 'Block';
  22461. BreakType[BreakType['Wrap'] = 2] = 'Wrap';
  22462. BreakType[BreakType['Eol'] = 3] = 'Eol';
  22463. }(BreakType || (BreakType = {})));
  22464. var flip = function (direction, positions) {
  22465. return direction === HDirection.Backwards ? reverse(positions) : positions;
  22466. };
  22467. var walk = function (direction, caretWalker, pos) {
  22468. return direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
  22469. };
  22470. var getBreakType = function (scope, direction, currentPos, nextPos) {
  22471. if (isBr$5(nextPos.getNode(direction === HDirection.Forwards))) {
  22472. return BreakType.Br;
  22473. } else if (isInSameBlock(currentPos, nextPos) === false) {
  22474. return BreakType.Block;
  22475. } else {
  22476. return BreakType.Wrap;
  22477. }
  22478. };
  22479. var getPositionsUntil = function (predicate, direction, scope, start) {
  22480. var caretWalker = CaretWalker(scope);
  22481. var currentPos = start;
  22482. var positions = [];
  22483. while (currentPos) {
  22484. var nextPos = walk(direction, caretWalker, currentPos);
  22485. if (!nextPos) {
  22486. break;
  22487. }
  22488. if (isBr$5(nextPos.getNode(false))) {
  22489. if (direction === HDirection.Forwards) {
  22490. return {
  22491. positions: flip(direction, positions).concat([nextPos]),
  22492. breakType: BreakType.Br,
  22493. breakAt: Optional.some(nextPos)
  22494. };
  22495. } else {
  22496. return {
  22497. positions: flip(direction, positions),
  22498. breakType: BreakType.Br,
  22499. breakAt: Optional.some(nextPos)
  22500. };
  22501. }
  22502. }
  22503. if (!nextPos.isVisible()) {
  22504. currentPos = nextPos;
  22505. continue;
  22506. }
  22507. if (predicate(currentPos, nextPos)) {
  22508. var breakType = getBreakType(scope, direction, currentPos, nextPos);
  22509. return {
  22510. positions: flip(direction, positions),
  22511. breakType: breakType,
  22512. breakAt: Optional.some(nextPos)
  22513. };
  22514. }
  22515. positions.push(nextPos);
  22516. currentPos = nextPos;
  22517. }
  22518. return {
  22519. positions: flip(direction, positions),
  22520. breakType: BreakType.Eol,
  22521. breakAt: Optional.none()
  22522. };
  22523. };
  22524. var getAdjacentLinePositions = function (direction, getPositionsUntilBreak, scope, start) {
  22525. return getPositionsUntilBreak(scope, start).breakAt.map(function (pos) {
  22526. var positions = getPositionsUntilBreak(scope, pos).positions;
  22527. return direction === HDirection.Backwards ? positions.concat(pos) : [pos].concat(positions);
  22528. }).getOr([]);
  22529. };
  22530. var findClosestHorizontalPositionFromPoint = function (positions, x) {
  22531. return foldl(positions, function (acc, newPos) {
  22532. return acc.fold(function () {
  22533. return Optional.some(newPos);
  22534. }, function (lastPos) {
  22535. return lift2(head(lastPos.getClientRects()), head(newPos.getClientRects()), function (lastRect, newRect) {
  22536. var lastDist = Math.abs(x - lastRect.left);
  22537. var newDist = Math.abs(x - newRect.left);
  22538. return newDist <= lastDist ? newPos : lastPos;
  22539. }).or(acc);
  22540. });
  22541. }, Optional.none());
  22542. };
  22543. var findClosestHorizontalPosition = function (positions, pos) {
  22544. return head(pos.getClientRects()).bind(function (targetRect) {
  22545. return findClosestHorizontalPositionFromPoint(positions, targetRect.left);
  22546. });
  22547. };
  22548. var getPositionsUntilPreviousLine = curry(getPositionsUntil, CaretPosition.isAbove, -1);
  22549. var getPositionsUntilNextLine = curry(getPositionsUntil, CaretPosition.isBelow, 1);
  22550. var getPositionsAbove = curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
  22551. var getPositionsBelow = curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
  22552. var isAtFirstLine = function (scope, pos) {
  22553. return getPositionsUntilPreviousLine(scope, pos).breakAt.isNone();
  22554. };
  22555. var isAtLastLine = function (scope, pos) {
  22556. return getPositionsUntilNextLine(scope, pos).breakAt.isNone();
  22557. };
  22558. var getFirstLinePositions = function (scope) {
  22559. return firstPositionIn(scope).map(function (pos) {
  22560. return [pos].concat(getPositionsUntilNextLine(scope, pos).positions);
  22561. }).getOr([]);
  22562. };
  22563. var getLastLinePositions = function (scope) {
  22564. return lastPositionIn(scope).map(function (pos) {
  22565. return getPositionsUntilPreviousLine(scope, pos).positions.concat(pos);
  22566. }).getOr([]);
  22567. };
  22568. var getNodeClientRects = function (node) {
  22569. var toArrayWithNode = function (clientRects) {
  22570. return map$3(clientRects, function (rect) {
  22571. var clientRect = clone(rect);
  22572. clientRect.node = node;
  22573. return clientRect;
  22574. });
  22575. };
  22576. if (isElement$5(node)) {
  22577. return toArrayWithNode(node.getClientRects());
  22578. }
  22579. if (isText$7(node)) {
  22580. var rng = node.ownerDocument.createRange();
  22581. rng.setStart(node, 0);
  22582. rng.setEnd(node, node.data.length);
  22583. return toArrayWithNode(rng.getClientRects());
  22584. }
  22585. };
  22586. var getClientRects = function (nodes) {
  22587. return bind(nodes, getNodeClientRects);
  22588. };
  22589. var VDirection;
  22590. (function (VDirection) {
  22591. VDirection[VDirection['Up'] = -1] = 'Up';
  22592. VDirection[VDirection['Down'] = 1] = 'Down';
  22593. }(VDirection || (VDirection = {})));
  22594. var findUntil = function (direction, root, predicateFn, node) {
  22595. while (node = findNode$1(node, direction, isEditableCaretCandidate$1, root)) {
  22596. if (predicateFn(node)) {
  22597. return;
  22598. }
  22599. }
  22600. };
  22601. var walkUntil$1 = function (direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) {
  22602. var line = 0;
  22603. var result = [];
  22604. var add = function (node) {
  22605. var clientRects = getClientRects([node]);
  22606. if (direction === -1) {
  22607. clientRects = clientRects.reverse();
  22608. }
  22609. for (var i = 0; i < clientRects.length; i++) {
  22610. var clientRect = clientRects[i];
  22611. if (isBeflowFn(clientRect, targetClientRect)) {
  22612. continue;
  22613. }
  22614. if (result.length > 0 && isAboveFn(clientRect, last$1(result))) {
  22615. line++;
  22616. }
  22617. clientRect.line = line;
  22618. if (predicateFn(clientRect)) {
  22619. return true;
  22620. }
  22621. result.push(clientRect);
  22622. }
  22623. };
  22624. var targetClientRect = last$1(caretPosition.getClientRects());
  22625. if (!targetClientRect) {
  22626. return result;
  22627. }
  22628. var node = caretPosition.getNode();
  22629. add(node);
  22630. findUntil(direction, root, add, node);
  22631. return result;
  22632. };
  22633. var aboveLineNumber = function (lineNumber, clientRect) {
  22634. return clientRect.line > lineNumber;
  22635. };
  22636. var isLineNumber = function (lineNumber, clientRect) {
  22637. return clientRect.line === lineNumber;
  22638. };
  22639. var upUntil = curry(walkUntil$1, VDirection.Up, isAbove$1, isBelow$1);
  22640. var downUntil = curry(walkUntil$1, VDirection.Down, isBelow$1, isAbove$1);
  22641. var positionsUntil = function (direction, root, predicateFn, node) {
  22642. var caretWalker = CaretWalker(root);
  22643. var walkFn;
  22644. var isBelowFn;
  22645. var isAboveFn;
  22646. var caretPosition;
  22647. var result = [];
  22648. var line = 0;
  22649. var getClientRect = function (caretPosition) {
  22650. if (direction === 1) {
  22651. return last$1(caretPosition.getClientRects());
  22652. }
  22653. return last$1(caretPosition.getClientRects());
  22654. };
  22655. if (direction === 1) {
  22656. walkFn = caretWalker.next;
  22657. isBelowFn = isBelow$1;
  22658. isAboveFn = isAbove$1;
  22659. caretPosition = CaretPosition.after(node);
  22660. } else {
  22661. walkFn = caretWalker.prev;
  22662. isBelowFn = isAbove$1;
  22663. isAboveFn = isBelow$1;
  22664. caretPosition = CaretPosition.before(node);
  22665. }
  22666. var targetClientRect = getClientRect(caretPosition);
  22667. do {
  22668. if (!caretPosition.isVisible()) {
  22669. continue;
  22670. }
  22671. var rect = getClientRect(caretPosition);
  22672. if (isAboveFn(rect, targetClientRect)) {
  22673. continue;
  22674. }
  22675. if (result.length > 0 && isBelowFn(rect, last$1(result))) {
  22676. line++;
  22677. }
  22678. var clientRect = clone(rect);
  22679. clientRect.position = caretPosition;
  22680. clientRect.line = line;
  22681. if (predicateFn(clientRect)) {
  22682. return result;
  22683. }
  22684. result.push(clientRect);
  22685. } while (caretPosition = walkFn(caretPosition));
  22686. return result;
  22687. };
  22688. var isAboveLine = function (lineNumber) {
  22689. return function (clientRect) {
  22690. return aboveLineNumber(lineNumber, clientRect);
  22691. };
  22692. };
  22693. var isLine = function (lineNumber) {
  22694. return function (clientRect) {
  22695. return isLineNumber(lineNumber, clientRect);
  22696. };
  22697. };
  22698. var isContentEditableFalse$3 = isContentEditableFalse$b;
  22699. var findNode = findNode$1;
  22700. var distanceToRectLeft = function (clientRect, clientX) {
  22701. return Math.abs(clientRect.left - clientX);
  22702. };
  22703. var distanceToRectRight = function (clientRect, clientX) {
  22704. return Math.abs(clientRect.right - clientX);
  22705. };
  22706. var isInsideX = function (clientX, clientRect) {
  22707. return clientX >= clientRect.left && clientX <= clientRect.right;
  22708. };
  22709. var isInsideY = function (clientY, clientRect) {
  22710. return clientY >= clientRect.top && clientY <= clientRect.bottom;
  22711. };
  22712. var findClosestClientRect = function (clientRects, clientX) {
  22713. return reduce(clientRects, function (oldClientRect, clientRect) {
  22714. var oldDistance = Math.min(distanceToRectLeft(oldClientRect, clientX), distanceToRectRight(oldClientRect, clientX));
  22715. var newDistance = Math.min(distanceToRectLeft(clientRect, clientX), distanceToRectRight(clientRect, clientX));
  22716. if (isInsideX(clientX, clientRect)) {
  22717. return clientRect;
  22718. }
  22719. if (isInsideX(clientX, oldClientRect)) {
  22720. return oldClientRect;
  22721. }
  22722. if (newDistance === oldDistance && isContentEditableFalse$3(clientRect.node)) {
  22723. return clientRect;
  22724. }
  22725. if (newDistance < oldDistance) {
  22726. return clientRect;
  22727. }
  22728. return oldClientRect;
  22729. });
  22730. };
  22731. var walkUntil = function (direction, root, predicateFn, startNode, includeChildren) {
  22732. var node = findNode(startNode, direction, isEditableCaretCandidate$1, root, !includeChildren);
  22733. do {
  22734. if (!node || predicateFn(node)) {
  22735. return;
  22736. }
  22737. } while (node = findNode(node, direction, isEditableCaretCandidate$1, root));
  22738. };
  22739. var findLineNodeRects = function (root, targetNodeRect, includeChildren) {
  22740. if (includeChildren === void 0) {
  22741. includeChildren = true;
  22742. }
  22743. var clientRects = [];
  22744. var collect = function (checkPosFn, node) {
  22745. var lineRects = filter$4(getClientRects([node]), function (clientRect) {
  22746. return !checkPosFn(clientRect, targetNodeRect);
  22747. });
  22748. clientRects = clientRects.concat(lineRects);
  22749. return lineRects.length === 0;
  22750. };
  22751. clientRects.push(targetNodeRect);
  22752. walkUntil(VDirection.Up, root, curry(collect, isAbove$1), targetNodeRect.node, includeChildren);
  22753. walkUntil(VDirection.Down, root, curry(collect, isBelow$1), targetNodeRect.node, includeChildren);
  22754. return clientRects;
  22755. };
  22756. var getFakeCaretTargets = function (root) {
  22757. return filter$4(from(root.getElementsByTagName('*')), isFakeCaretTarget);
  22758. };
  22759. var caretInfo = function (clientRect, clientX) {
  22760. return {
  22761. node: clientRect.node,
  22762. before: distanceToRectLeft(clientRect, clientX) < distanceToRectRight(clientRect, clientX)
  22763. };
  22764. };
  22765. var closestFakeCaret = function (root, clientX, clientY) {
  22766. var fakeTargetNodeRects = getClientRects(getFakeCaretTargets(root));
  22767. var targetNodeRects = filter$4(fakeTargetNodeRects, curry(isInsideY, clientY));
  22768. var closestNodeRect = findClosestClientRect(targetNodeRects, clientX);
  22769. if (closestNodeRect) {
  22770. var includeChildren = !isTable$3(closestNodeRect.node) && !isMedia$2(closestNodeRect.node);
  22771. closestNodeRect = findClosestClientRect(findLineNodeRects(root, closestNodeRect, includeChildren), clientX);
  22772. if (closestNodeRect && isFakeCaretTarget(closestNodeRect.node)) {
  22773. return caretInfo(closestNodeRect, clientX);
  22774. }
  22775. }
  22776. return null;
  22777. };
  22778. var moveToRange = function (editor, rng) {
  22779. editor.selection.setRng(rng);
  22780. scrollRangeIntoView(editor, editor.selection.getRng());
  22781. };
  22782. var renderRangeCaretOpt = function (editor, range, scrollIntoView) {
  22783. return Optional.some(renderRangeCaret(editor, range, scrollIntoView));
  22784. };
  22785. var moveHorizontally = function (editor, direction, range, isBefore, isAfter, isElement) {
  22786. var forwards = direction === HDirection.Forwards;
  22787. var caretWalker = CaretWalker(editor.getBody());
  22788. var getNextPosFn = curry(getVisualCaretPosition, forwards ? caretWalker.next : caretWalker.prev);
  22789. var isBeforeFn = forwards ? isBefore : isAfter;
  22790. if (!range.collapsed) {
  22791. var node = getSelectedNode(range);
  22792. if (isElement(node)) {
  22793. return showCaret(direction, editor, node, direction === HDirection.Backwards, false);
  22794. }
  22795. }
  22796. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22797. if (isBeforeFn(caretPosition)) {
  22798. return selectNode(editor, caretPosition.getNode(!forwards));
  22799. }
  22800. var nextCaretPosition = normalizePosition(forwards, getNextPosFn(caretPosition));
  22801. var rangeIsInContainerBlock = isRangeInCaretContainerBlock(range);
  22802. if (!nextCaretPosition) {
  22803. return rangeIsInContainerBlock ? Optional.some(range) : Optional.none();
  22804. }
  22805. if (isBeforeFn(nextCaretPosition)) {
  22806. return showCaret(direction, editor, nextCaretPosition.getNode(!forwards), forwards, false);
  22807. }
  22808. var peekCaretPosition = getNextPosFn(nextCaretPosition);
  22809. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  22810. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  22811. return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, false);
  22812. }
  22813. }
  22814. if (rangeIsInContainerBlock) {
  22815. return renderRangeCaretOpt(editor, nextCaretPosition.toRange(), false);
  22816. }
  22817. return Optional.none();
  22818. };
  22819. var moveVertically = function (editor, direction, range, isBefore, isAfter, isElement) {
  22820. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22821. var caretClientRect = last$1(caretPosition.getClientRects());
  22822. var forwards = direction === VDirection.Down;
  22823. if (!caretClientRect) {
  22824. return Optional.none();
  22825. }
  22826. var walkerFn = forwards ? downUntil : upUntil;
  22827. var linePositions = walkerFn(editor.getBody(), isAboveLine(1), caretPosition);
  22828. var nextLinePositions = filter$4(linePositions, isLine(1));
  22829. var clientX = caretClientRect.left;
  22830. var nextLineRect = findClosestClientRect(nextLinePositions, clientX);
  22831. if (nextLineRect && isElement(nextLineRect.node)) {
  22832. var dist1 = Math.abs(clientX - nextLineRect.left);
  22833. var dist2 = Math.abs(clientX - nextLineRect.right);
  22834. return showCaret(direction, editor, nextLineRect.node, dist1 < dist2, false);
  22835. }
  22836. var currentNode;
  22837. if (isBefore(caretPosition)) {
  22838. currentNode = caretPosition.getNode();
  22839. } else if (isAfter(caretPosition)) {
  22840. currentNode = caretPosition.getNode(true);
  22841. } else {
  22842. currentNode = getSelectedNode(range);
  22843. }
  22844. if (currentNode) {
  22845. var caretPositions = positionsUntil(direction, editor.getBody(), isAboveLine(1), currentNode);
  22846. var closestNextLineRect = findClosestClientRect(filter$4(caretPositions, isLine(1)), clientX);
  22847. if (closestNextLineRect) {
  22848. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  22849. }
  22850. closestNextLineRect = last$1(filter$4(caretPositions, isLine(0)));
  22851. if (closestNextLineRect) {
  22852. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  22853. }
  22854. }
  22855. if (nextLinePositions.length === 0) {
  22856. return getLineEndPoint(editor, forwards).filter(forwards ? isAfter : isBefore).map(function (pos) {
  22857. return renderRangeCaret(editor, pos.toRange(), false);
  22858. });
  22859. }
  22860. return Optional.none();
  22861. };
  22862. var getLineEndPoint = function (editor, forward) {
  22863. var rng = editor.selection.getRng();
  22864. var body = editor.getBody();
  22865. if (forward) {
  22866. var from = CaretPosition.fromRangeEnd(rng);
  22867. var result = getPositionsUntilNextLine(body, from);
  22868. return last$2(result.positions);
  22869. } else {
  22870. var from = CaretPosition.fromRangeStart(rng);
  22871. var result = getPositionsUntilPreviousLine(body, from);
  22872. return head(result.positions);
  22873. }
  22874. };
  22875. var moveToLineEndPoint$3 = function (editor, forward, isElementPosition) {
  22876. return getLineEndPoint(editor, forward).filter(isElementPosition).exists(function (pos) {
  22877. editor.selection.setRng(pos.toRange());
  22878. return true;
  22879. });
  22880. };
  22881. var setCaretPosition = function (editor, pos) {
  22882. var rng = editor.dom.createRng();
  22883. rng.setStart(pos.container(), pos.offset());
  22884. rng.setEnd(pos.container(), pos.offset());
  22885. editor.selection.setRng(rng);
  22886. };
  22887. var setSelected = function (state, elm) {
  22888. if (state) {
  22889. elm.setAttribute('data-mce-selected', 'inline-boundary');
  22890. } else {
  22891. elm.removeAttribute('data-mce-selected');
  22892. }
  22893. };
  22894. var renderCaretLocation = function (editor, caret, location) {
  22895. return renderCaret(caret, location).map(function (pos) {
  22896. setCaretPosition(editor, pos);
  22897. return location;
  22898. });
  22899. };
  22900. var findLocation = function (editor, caret, forward) {
  22901. var rootNode = editor.getBody();
  22902. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  22903. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22904. var location = findLocation$1(forward, isInlineTarget$1, rootNode, from);
  22905. return location.bind(function (location) {
  22906. return renderCaretLocation(editor, caret, location);
  22907. });
  22908. };
  22909. var toggleInlines = function (isInlineTarget, dom, elms) {
  22910. var inlineBoundaries = map$3(descendants(SugarElement.fromDom(dom.getRoot()), '*[data-mce-selected="inline-boundary"]'), function (e) {
  22911. return e.dom;
  22912. });
  22913. var selectedInlines = filter$4(inlineBoundaries, isInlineTarget);
  22914. var targetInlines = filter$4(elms, isInlineTarget);
  22915. each$k(difference(selectedInlines, targetInlines), curry(setSelected, false));
  22916. each$k(difference(targetInlines, selectedInlines), curry(setSelected, true));
  22917. };
  22918. var safeRemoveCaretContainer = function (editor, caret) {
  22919. if (editor.selection.isCollapsed() && editor.composing !== true && caret.get()) {
  22920. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22921. if (CaretPosition.isTextPosition(pos) && isAtZwsp(pos) === false) {
  22922. setCaretPosition(editor, removeAndReposition(caret.get(), pos));
  22923. caret.set(null);
  22924. }
  22925. }
  22926. };
  22927. var renderInsideInlineCaret = function (isInlineTarget, editor, caret, elms) {
  22928. if (editor.selection.isCollapsed()) {
  22929. var inlines = filter$4(elms, isInlineTarget);
  22930. each$k(inlines, function (_inline) {
  22931. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22932. readLocation(isInlineTarget, editor.getBody(), pos).bind(function (location) {
  22933. return renderCaretLocation(editor, caret, location);
  22934. });
  22935. });
  22936. }
  22937. };
  22938. var move$2 = function (editor, caret, forward) {
  22939. return isInlineBoundariesEnabled(editor) ? findLocation(editor, caret, forward).isSome() : false;
  22940. };
  22941. var moveWord = function (forward, editor, _caret) {
  22942. return isInlineBoundariesEnabled(editor) ? moveByWord(forward, editor) : false;
  22943. };
  22944. var setupSelectedState = function (editor) {
  22945. var caret = Cell(null);
  22946. var isInlineTarget$1 = curry(isInlineTarget, editor);
  22947. editor.on('NodeChange', function (e) {
  22948. if (isInlineBoundariesEnabled(editor) && !(Env.browser.isIE() && e.initial)) {
  22949. toggleInlines(isInlineTarget$1, editor.dom, e.parents);
  22950. safeRemoveCaretContainer(editor, caret);
  22951. renderInsideInlineCaret(isInlineTarget$1, editor, caret, e.parents);
  22952. }
  22953. });
  22954. return caret;
  22955. };
  22956. var moveNextWord = curry(moveWord, true);
  22957. var movePrevWord = curry(moveWord, false);
  22958. var moveToLineEndPoint$2 = function (editor, forward, caret) {
  22959. if (isInlineBoundariesEnabled(editor)) {
  22960. var linePoint = getLineEndPoint(editor, forward).getOrThunk(function () {
  22961. var rng = editor.selection.getRng();
  22962. return forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  22963. });
  22964. return readLocation(curry(isInlineTarget, editor), editor.getBody(), linePoint).exists(function (loc) {
  22965. var outsideLoc = outside(loc);
  22966. return renderCaret(caret, outsideLoc).exists(function (pos) {
  22967. setCaretPosition(editor, pos);
  22968. return true;
  22969. });
  22970. });
  22971. } else {
  22972. return false;
  22973. }
  22974. };
  22975. var rangeFromPositions = function (from, to) {
  22976. var range = document.createRange();
  22977. range.setStart(from.container(), from.offset());
  22978. range.setEnd(to.container(), to.offset());
  22979. return range;
  22980. };
  22981. var hasOnlyTwoOrLessPositionsLeft = function (elm) {
  22982. return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  22983. var normalizedFirstPos = normalizePosition(true, firstPos);
  22984. var normalizedLastPos = normalizePosition(false, lastPos);
  22985. return nextPosition(elm, normalizedFirstPos).forall(function (pos) {
  22986. return pos.isEqual(normalizedLastPos);
  22987. });
  22988. }).getOr(true);
  22989. };
  22990. var setCaretLocation = function (editor, caret) {
  22991. return function (location) {
  22992. return renderCaret(caret, location).exists(function (pos) {
  22993. setCaretPosition(editor, pos);
  22994. return true;
  22995. });
  22996. };
  22997. };
  22998. var deleteFromTo = function (editor, caret, from, to) {
  22999. var rootNode = editor.getBody();
  23000. var isInlineTarget$1 = curry(isInlineTarget, editor);
  23001. editor.undoManager.ignore(function () {
  23002. editor.selection.setRng(rangeFromPositions(from, to));
  23003. editor.execCommand('Delete');
  23004. readLocation(isInlineTarget$1, rootNode, CaretPosition.fromRangeStart(editor.selection.getRng())).map(inside).map(setCaretLocation(editor, caret));
  23005. });
  23006. editor.nodeChanged();
  23007. };
  23008. var rescope = function (rootNode, node) {
  23009. var parentBlock = getParentBlock$2(node, rootNode);
  23010. return parentBlock ? parentBlock : rootNode;
  23011. };
  23012. var backspaceDeleteCollapsed = function (editor, caret, forward, from) {
  23013. var rootNode = rescope(editor.getBody(), from.container());
  23014. var isInlineTarget$1 = curry(isInlineTarget, editor);
  23015. var fromLocation = readLocation(isInlineTarget$1, rootNode, from);
  23016. return fromLocation.bind(function (location) {
  23017. if (forward) {
  23018. return location.fold(constant(Optional.some(inside(location))), Optional.none, constant(Optional.some(outside(location))), Optional.none);
  23019. } else {
  23020. return location.fold(Optional.none, constant(Optional.some(outside(location))), Optional.none, constant(Optional.some(inside(location))));
  23021. }
  23022. }).map(setCaretLocation(editor, caret)).getOrThunk(function () {
  23023. var toPosition = navigate(forward, rootNode, from);
  23024. var toLocation = toPosition.bind(function (pos) {
  23025. return readLocation(isInlineTarget$1, rootNode, pos);
  23026. });
  23027. return lift2(fromLocation, toLocation, function () {
  23028. return findRootInline(isInlineTarget$1, rootNode, from).exists(function (elm) {
  23029. if (hasOnlyTwoOrLessPositionsLeft(elm)) {
  23030. deleteElement$2(editor, forward, SugarElement.fromDom(elm));
  23031. return true;
  23032. } else {
  23033. return false;
  23034. }
  23035. });
  23036. }).orThunk(function () {
  23037. return toLocation.bind(function (_) {
  23038. return toPosition.map(function (to) {
  23039. if (forward) {
  23040. deleteFromTo(editor, caret, from, to);
  23041. } else {
  23042. deleteFromTo(editor, caret, to, from);
  23043. }
  23044. return true;
  23045. });
  23046. });
  23047. }).getOr(false);
  23048. });
  23049. };
  23050. var backspaceDelete$3 = function (editor, caret, forward) {
  23051. if (editor.selection.isCollapsed() && isInlineBoundariesEnabled(editor)) {
  23052. var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  23053. return backspaceDeleteCollapsed(editor, caret, forward, from);
  23054. }
  23055. return false;
  23056. };
  23057. var getParentInlines = function (rootElm, startElm) {
  23058. var parents = parentsAndSelf(startElm, rootElm);
  23059. return findIndex$2(parents, isBlock$2).fold(constant(parents), function (index) {
  23060. return parents.slice(0, index);
  23061. });
  23062. };
  23063. var hasOnlyOneChild = function (elm) {
  23064. return childNodesCount(elm) === 1;
  23065. };
  23066. var deleteLastPosition = function (forward, editor, target, parentInlines) {
  23067. var isFormatElement$1 = curry(isFormatElement, editor);
  23068. var formatNodes = map$3(filter$4(parentInlines, isFormatElement$1), function (elm) {
  23069. return elm.dom;
  23070. });
  23071. if (formatNodes.length === 0) {
  23072. deleteElement$2(editor, forward, target);
  23073. } else {
  23074. var pos = replaceWithCaretFormat(target.dom, formatNodes);
  23075. editor.selection.setRng(pos.toRange());
  23076. }
  23077. };
  23078. var deleteCaret$1 = function (editor, forward) {
  23079. var rootElm = SugarElement.fromDom(editor.getBody());
  23080. var startElm = SugarElement.fromDom(editor.selection.getStart());
  23081. var parentInlines = filter$4(getParentInlines(rootElm, startElm), hasOnlyOneChild);
  23082. return last$2(parentInlines).exists(function (target) {
  23083. var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23084. if (willDeleteLastPositionInElement(forward, fromPos, target.dom) && !isEmptyCaretFormatElement(target)) {
  23085. deleteLastPosition(forward, editor, target, parentInlines);
  23086. return true;
  23087. } else {
  23088. return false;
  23089. }
  23090. });
  23091. };
  23092. var backspaceDelete$2 = function (editor, forward) {
  23093. return editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : false;
  23094. };
  23095. var deleteElement = function (editor, forward, element) {
  23096. editor._selectionOverrides.hideFakeCaret();
  23097. deleteElement$2(editor, forward, SugarElement.fromDom(element));
  23098. return true;
  23099. };
  23100. var deleteCaret = function (editor, forward) {
  23101. var isNearMedia = forward ? isBeforeMedia : isAfterMedia;
  23102. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23103. var fromPos = getNormalizedRangeEndPoint(direction, editor.getBody(), editor.selection.getRng());
  23104. if (isNearMedia(fromPos)) {
  23105. return deleteElement(editor, forward, fromPos.getNode(!forward));
  23106. } else {
  23107. return Optional.from(normalizePosition(forward, fromPos)).filter(function (pos) {
  23108. return isNearMedia(pos) && isMoveInsideSameBlock(fromPos, pos);
  23109. }).exists(function (pos) {
  23110. return deleteElement(editor, forward, pos.getNode(!forward));
  23111. });
  23112. }
  23113. };
  23114. var deleteRange = function (editor, forward) {
  23115. var selectedNode = editor.selection.getNode();
  23116. return isMedia$2(selectedNode) ? deleteElement(editor, forward, selectedNode) : false;
  23117. };
  23118. var backspaceDelete$1 = function (editor, forward) {
  23119. return editor.selection.isCollapsed() ? deleteCaret(editor, forward) : deleteRange(editor, forward);
  23120. };
  23121. var isEditable = function (target) {
  23122. return closest$3(target, function (elm) {
  23123. return isContentEditableTrue$4(elm.dom) || isContentEditableFalse$b(elm.dom);
  23124. }).exists(function (elm) {
  23125. return isContentEditableTrue$4(elm.dom);
  23126. });
  23127. };
  23128. var parseIndentValue = function (value) {
  23129. var number = parseInt(value, 10);
  23130. return isNaN(number) ? 0 : number;
  23131. };
  23132. var getIndentStyleName = function (useMargin, element) {
  23133. var indentStyleName = useMargin || isTable$2(element) ? 'margin' : 'padding';
  23134. var suffix = get$5(element, 'direction') === 'rtl' ? '-right' : '-left';
  23135. return indentStyleName + suffix;
  23136. };
  23137. var indentElement = function (dom, command, useMargin, value, unit, element) {
  23138. var indentStyleName = getIndentStyleName(useMargin, SugarElement.fromDom(element));
  23139. if (command === 'outdent') {
  23140. var styleValue = Math.max(0, parseIndentValue(element.style[indentStyleName]) - value);
  23141. dom.setStyle(element, indentStyleName, styleValue ? styleValue + unit : '');
  23142. } else {
  23143. var styleValue = parseIndentValue(element.style[indentStyleName]) + value + unit;
  23144. dom.setStyle(element, indentStyleName, styleValue);
  23145. }
  23146. };
  23147. var validateBlocks = function (editor, blocks) {
  23148. return forall(blocks, function (block) {
  23149. var indentStyleName = getIndentStyleName(shouldIndentUseMargin(editor), block);
  23150. var intentValue = getRaw(block, indentStyleName).map(parseIndentValue).getOr(0);
  23151. var contentEditable = editor.dom.getContentEditable(block.dom);
  23152. return contentEditable !== 'false' && intentValue > 0;
  23153. });
  23154. };
  23155. var canOutdent = function (editor) {
  23156. var blocks = getBlocksToIndent(editor);
  23157. return !editor.mode.isReadOnly() && (blocks.length > 1 || validateBlocks(editor, blocks));
  23158. };
  23159. var isListComponent = function (el) {
  23160. return isList(el) || isListItem(el);
  23161. };
  23162. var parentIsListComponent = function (el) {
  23163. return parent(el).exists(isListComponent);
  23164. };
  23165. var getBlocksToIndent = function (editor) {
  23166. return filter$4(fromDom$1(editor.selection.getSelectedBlocks()), function (el) {
  23167. return !isListComponent(el) && !parentIsListComponent(el) && isEditable(el);
  23168. });
  23169. };
  23170. var handle = function (editor, command) {
  23171. var dom = editor.dom, selection = editor.selection, formatter = editor.formatter;
  23172. var indentation = getIndentation(editor);
  23173. var indentUnit = /[a-z%]+$/i.exec(indentation)[0];
  23174. var indentValue = parseInt(indentation, 10);
  23175. var useMargin = shouldIndentUseMargin(editor);
  23176. var forcedRootBlock = getForcedRootBlock(editor);
  23177. if (!editor.queryCommandState('InsertUnorderedList') && !editor.queryCommandState('InsertOrderedList')) {
  23178. if (forcedRootBlock === '' && !dom.getParent(selection.getNode(), dom.isBlock)) {
  23179. formatter.apply('div');
  23180. }
  23181. }
  23182. each$k(getBlocksToIndent(editor), function (block) {
  23183. indentElement(dom, command, useMargin, indentValue, indentUnit, block.dom);
  23184. });
  23185. };
  23186. var backspaceDelete = function (editor, _forward) {
  23187. if (editor.selection.isCollapsed() && canOutdent(editor)) {
  23188. var dom = editor.dom;
  23189. var rng = editor.selection.getRng();
  23190. var pos = CaretPosition.fromRangeStart(rng);
  23191. var block = dom.getParent(rng.startContainer, dom.isBlock);
  23192. if (block !== null && isAtStartOfBlock(SugarElement.fromDom(block), pos)) {
  23193. handle(editor, 'outdent');
  23194. return true;
  23195. }
  23196. }
  23197. return false;
  23198. };
  23199. var nativeCommand = function (editor, command) {
  23200. editor.getDoc().execCommand(command, false, null);
  23201. };
  23202. var deleteCommand = function (editor, caret) {
  23203. if (backspaceDelete(editor)) {
  23204. return;
  23205. } else if (backspaceDelete$5(editor, false)) {
  23206. return;
  23207. } else if (backspaceDelete$6(editor, false)) {
  23208. return;
  23209. } else if (backspaceDelete$3(editor, caret, false)) {
  23210. return;
  23211. } else if (backspaceDelete$8(editor, false)) {
  23212. return;
  23213. } else if (backspaceDelete$9(editor)) {
  23214. return;
  23215. } else if (backspaceDelete$4(editor, false)) {
  23216. return;
  23217. } else if (backspaceDelete$1(editor, false)) {
  23218. return;
  23219. } else if (backspaceDelete$7(editor)) {
  23220. return;
  23221. } else if (backspaceDelete$2(editor, false)) {
  23222. return;
  23223. } else {
  23224. nativeCommand(editor, 'Delete');
  23225. paddEmptyBody(editor);
  23226. }
  23227. };
  23228. var forwardDeleteCommand = function (editor, caret) {
  23229. if (backspaceDelete$5(editor, true)) {
  23230. return;
  23231. } else if (backspaceDelete$6(editor, true)) {
  23232. return;
  23233. } else if (backspaceDelete$3(editor, caret, true)) {
  23234. return;
  23235. } else if (backspaceDelete$8(editor, true)) {
  23236. return;
  23237. } else if (backspaceDelete$9(editor)) {
  23238. return;
  23239. } else if (backspaceDelete$4(editor, true)) {
  23240. return;
  23241. } else if (backspaceDelete$1(editor, true)) {
  23242. return;
  23243. } else if (backspaceDelete$7(editor)) {
  23244. return;
  23245. } else if (backspaceDelete$2(editor, true)) {
  23246. return;
  23247. } else {
  23248. nativeCommand(editor, 'ForwardDelete');
  23249. }
  23250. };
  23251. var setup$f = function (editor, caret) {
  23252. editor.addCommand('delete', function () {
  23253. deleteCommand(editor, caret);
  23254. });
  23255. editor.addCommand('forwardDelete', function () {
  23256. forwardDeleteCommand(editor, caret);
  23257. });
  23258. };
  23259. var SIGNIFICANT_MOVE = 5;
  23260. var LONGPRESS_DELAY = 400;
  23261. var getTouch = function (event) {
  23262. if (event.touches === undefined || event.touches.length !== 1) {
  23263. return Optional.none();
  23264. }
  23265. return Optional.some(event.touches[0]);
  23266. };
  23267. var isFarEnough = function (touch, data) {
  23268. var distX = Math.abs(touch.clientX - data.x);
  23269. var distY = Math.abs(touch.clientY - data.y);
  23270. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  23271. };
  23272. var setup$e = function (editor) {
  23273. var startData = value();
  23274. var longpressFired = Cell(false);
  23275. var debounceLongpress = last(function (e) {
  23276. editor.fire('longpress', __assign(__assign({}, e), { type: 'longpress' }));
  23277. longpressFired.set(true);
  23278. }, LONGPRESS_DELAY);
  23279. editor.on('touchstart', function (e) {
  23280. getTouch(e).each(function (touch) {
  23281. debounceLongpress.cancel();
  23282. var data = {
  23283. x: touch.clientX,
  23284. y: touch.clientY,
  23285. target: e.target
  23286. };
  23287. debounceLongpress.throttle(e);
  23288. longpressFired.set(false);
  23289. startData.set(data);
  23290. });
  23291. }, true);
  23292. editor.on('touchmove', function (e) {
  23293. debounceLongpress.cancel();
  23294. getTouch(e).each(function (touch) {
  23295. startData.on(function (data) {
  23296. if (isFarEnough(touch, data)) {
  23297. startData.clear();
  23298. longpressFired.set(false);
  23299. editor.fire('longpresscancel');
  23300. }
  23301. });
  23302. });
  23303. }, true);
  23304. editor.on('touchend touchcancel', function (e) {
  23305. debounceLongpress.cancel();
  23306. if (e.type === 'touchcancel') {
  23307. return;
  23308. }
  23309. startData.get().filter(function (data) {
  23310. return data.target.isEqualNode(e.target);
  23311. }).each(function () {
  23312. if (longpressFired.get()) {
  23313. e.preventDefault();
  23314. } else {
  23315. editor.fire('tap', __assign(__assign({}, e), { type: 'tap' }));
  23316. }
  23317. });
  23318. }, true);
  23319. };
  23320. var isBlockElement = function (blockElements, node) {
  23321. return has$2(blockElements, node.nodeName);
  23322. };
  23323. var isValidTarget = function (blockElements, node) {
  23324. if (isText$7(node)) {
  23325. return true;
  23326. } else if (isElement$5(node)) {
  23327. return !isBlockElement(blockElements, node) && !isBookmarkNode$1(node);
  23328. } else {
  23329. return false;
  23330. }
  23331. };
  23332. var hasBlockParent = function (blockElements, root, node) {
  23333. return exists(parents(SugarElement.fromDom(node), SugarElement.fromDom(root)), function (elm) {
  23334. return isBlockElement(blockElements, elm.dom);
  23335. });
  23336. };
  23337. var shouldRemoveTextNode = function (blockElements, node) {
  23338. if (isText$7(node)) {
  23339. if (node.nodeValue.length === 0) {
  23340. return true;
  23341. } else if (/^\s+$/.test(node.nodeValue) && (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
  23342. return true;
  23343. }
  23344. }
  23345. return false;
  23346. };
  23347. var addRootBlocks = function (editor) {
  23348. var dom = editor.dom, selection = editor.selection;
  23349. var schema = editor.schema, blockElements = schema.getBlockElements();
  23350. var node = selection.getStart();
  23351. var rootNode = editor.getBody();
  23352. var rootBlockNode, tempNode, wrapped;
  23353. var forcedRootBlock = getForcedRootBlock(editor);
  23354. if (!node || !isElement$5(node) || !forcedRootBlock) {
  23355. return;
  23356. }
  23357. var rootNodeName = rootNode.nodeName.toLowerCase();
  23358. if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, node)) {
  23359. return;
  23360. }
  23361. var rng = selection.getRng();
  23362. var startContainer = rng.startContainer;
  23363. var startOffset = rng.startOffset;
  23364. var endContainer = rng.endContainer;
  23365. var endOffset = rng.endOffset;
  23366. var restoreSelection = hasFocus(editor);
  23367. node = rootNode.firstChild;
  23368. while (node) {
  23369. if (isValidTarget(blockElements, node)) {
  23370. if (shouldRemoveTextNode(blockElements, node)) {
  23371. tempNode = node;
  23372. node = node.nextSibling;
  23373. dom.remove(tempNode);
  23374. continue;
  23375. }
  23376. if (!rootBlockNode) {
  23377. rootBlockNode = dom.create(forcedRootBlock, getForcedRootBlockAttrs(editor));
  23378. node.parentNode.insertBefore(rootBlockNode, node);
  23379. wrapped = true;
  23380. }
  23381. tempNode = node;
  23382. node = node.nextSibling;
  23383. rootBlockNode.appendChild(tempNode);
  23384. } else {
  23385. rootBlockNode = null;
  23386. node = node.nextSibling;
  23387. }
  23388. }
  23389. if (wrapped && restoreSelection) {
  23390. rng.setStart(startContainer, startOffset);
  23391. rng.setEnd(endContainer, endOffset);
  23392. selection.setRng(rng);
  23393. editor.nodeChanged();
  23394. }
  23395. };
  23396. var setup$d = function (editor) {
  23397. if (getForcedRootBlock(editor)) {
  23398. editor.on('NodeChange', curry(addRootBlocks, editor));
  23399. }
  23400. };
  23401. var findBlockCaretContainer = function (editor) {
  23402. return descendant(SugarElement.fromDom(editor.getBody()), '*[data-mce-caret]').map(function (elm) {
  23403. return elm.dom;
  23404. }).getOrNull();
  23405. };
  23406. var removeIeControlRect = function (editor) {
  23407. editor.selection.setRng(editor.selection.getRng());
  23408. };
  23409. var showBlockCaretContainer = function (editor, blockCaretContainer) {
  23410. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  23411. showCaretContainerBlock(blockCaretContainer);
  23412. removeIeControlRect(editor);
  23413. editor.selection.scrollIntoView(blockCaretContainer);
  23414. }
  23415. };
  23416. var handleBlockContainer = function (editor, e) {
  23417. var blockCaretContainer = findBlockCaretContainer(editor);
  23418. if (!blockCaretContainer) {
  23419. return;
  23420. }
  23421. if (e.type === 'compositionstart') {
  23422. e.preventDefault();
  23423. e.stopPropagation();
  23424. showBlockCaretContainer(editor, blockCaretContainer);
  23425. return;
  23426. }
  23427. if (hasContent(blockCaretContainer)) {
  23428. showBlockCaretContainer(editor, blockCaretContainer);
  23429. editor.undoManager.add();
  23430. }
  23431. };
  23432. var setup$c = function (editor) {
  23433. editor.on('keyup compositionstart', curry(handleBlockContainer, editor));
  23434. };
  23435. var isContentEditableFalse$2 = isContentEditableFalse$b;
  23436. var moveToCeFalseHorizontally = function (direction, editor, range) {
  23437. return moveHorizontally(editor, direction, range, isBeforeContentEditableFalse, isAfterContentEditableFalse, isContentEditableFalse$2);
  23438. };
  23439. var moveToCeFalseVertically = function (direction, editor, range) {
  23440. var isBefore = function (caretPosition) {
  23441. return isBeforeContentEditableFalse(caretPosition) || isBeforeTable(caretPosition);
  23442. };
  23443. var isAfter = function (caretPosition) {
  23444. return isAfterContentEditableFalse(caretPosition) || isAfterTable(caretPosition);
  23445. };
  23446. return moveVertically(editor, direction, range, isBefore, isAfter, isContentEditableFalse$2);
  23447. };
  23448. var createTextBlock = function (editor) {
  23449. var textBlock = editor.dom.create(getForcedRootBlock(editor));
  23450. if (!Env.ie || Env.ie >= 11) {
  23451. textBlock.innerHTML = '<br data-mce-bogus="1">';
  23452. }
  23453. return textBlock;
  23454. };
  23455. var exitPreBlock = function (editor, direction, range) {
  23456. var caretWalker = CaretWalker(editor.getBody());
  23457. var getVisualCaretPosition$1 = curry(getVisualCaretPosition, direction === 1 ? caretWalker.next : caretWalker.prev);
  23458. if (range.collapsed && hasForcedRootBlock(editor)) {
  23459. var pre = editor.dom.getParent(range.startContainer, 'PRE');
  23460. if (!pre) {
  23461. return;
  23462. }
  23463. var caretPos = getVisualCaretPosition$1(CaretPosition.fromRangeStart(range));
  23464. if (!caretPos) {
  23465. var newBlock = createTextBlock(editor);
  23466. if (direction === 1) {
  23467. editor.$(pre).after(newBlock);
  23468. } else {
  23469. editor.$(pre).before(newBlock);
  23470. }
  23471. editor.selection.select(newBlock, true);
  23472. editor.selection.collapse();
  23473. }
  23474. }
  23475. };
  23476. var getHorizontalRange = function (editor, forward) {
  23477. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23478. var range = editor.selection.getRng();
  23479. return moveToCeFalseHorizontally(direction, editor, range).orThunk(function () {
  23480. exitPreBlock(editor, direction, range);
  23481. return Optional.none();
  23482. });
  23483. };
  23484. var getVerticalRange = function (editor, down) {
  23485. var direction = down ? 1 : -1;
  23486. var range = editor.selection.getRng();
  23487. return moveToCeFalseVertically(direction, editor, range).orThunk(function () {
  23488. exitPreBlock(editor, direction, range);
  23489. return Optional.none();
  23490. });
  23491. };
  23492. var moveH$2 = function (editor, forward) {
  23493. return getHorizontalRange(editor, forward).exists(function (newRange) {
  23494. moveToRange(editor, newRange);
  23495. return true;
  23496. });
  23497. };
  23498. var moveV$3 = function (editor, down) {
  23499. return getVerticalRange(editor, down).exists(function (newRange) {
  23500. moveToRange(editor, newRange);
  23501. return true;
  23502. });
  23503. };
  23504. var moveToLineEndPoint$1 = function (editor, forward) {
  23505. var isCefPosition = forward ? isAfterContentEditableFalse : isBeforeContentEditableFalse;
  23506. return moveToLineEndPoint$3(editor, forward, isCefPosition);
  23507. };
  23508. var isTarget = function (node) {
  23509. return contains$3(['figcaption'], name(node));
  23510. };
  23511. var rangeBefore = function (target) {
  23512. var rng = document.createRange();
  23513. rng.setStartBefore(target.dom);
  23514. rng.setEndBefore(target.dom);
  23515. return rng;
  23516. };
  23517. var insertElement = function (root, elm, forward) {
  23518. if (forward) {
  23519. append$1(root, elm);
  23520. } else {
  23521. prepend(root, elm);
  23522. }
  23523. };
  23524. var insertBr = function (root, forward) {
  23525. var br = SugarElement.fromTag('br');
  23526. insertElement(root, br, forward);
  23527. return rangeBefore(br);
  23528. };
  23529. var insertBlock = function (root, forward, blockName, attrs) {
  23530. var block = SugarElement.fromTag(blockName);
  23531. var br = SugarElement.fromTag('br');
  23532. setAll$1(block, attrs);
  23533. append$1(block, br);
  23534. insertElement(root, block, forward);
  23535. return rangeBefore(br);
  23536. };
  23537. var insertEmptyLine = function (root, rootBlockName, attrs, forward) {
  23538. if (rootBlockName === '') {
  23539. return insertBr(root, forward);
  23540. } else {
  23541. return insertBlock(root, forward, rootBlockName, attrs);
  23542. }
  23543. };
  23544. var getClosestTargetBlock = function (pos, root) {
  23545. var isRoot = curry(eq, root);
  23546. return closest$3(SugarElement.fromDom(pos.container()), isBlock$2, isRoot).filter(isTarget);
  23547. };
  23548. var isAtFirstOrLastLine = function (root, forward, pos) {
  23549. return forward ? isAtLastLine(root.dom, pos) : isAtFirstLine(root.dom, pos);
  23550. };
  23551. var moveCaretToNewEmptyLine = function (editor, forward) {
  23552. var root = SugarElement.fromDom(editor.getBody());
  23553. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23554. var rootBlock = getForcedRootBlock(editor);
  23555. var rootBlockAttrs = getForcedRootBlockAttrs(editor);
  23556. return getClosestTargetBlock(pos, root).exists(function () {
  23557. if (isAtFirstOrLastLine(root, forward, pos)) {
  23558. var rng = insertEmptyLine(root, rootBlock, rootBlockAttrs, forward);
  23559. editor.selection.setRng(rng);
  23560. return true;
  23561. } else {
  23562. return false;
  23563. }
  23564. });
  23565. };
  23566. var moveV$2 = function (editor, forward) {
  23567. if (editor.selection.isCollapsed()) {
  23568. return moveCaretToNewEmptyLine(editor, forward);
  23569. } else {
  23570. return false;
  23571. }
  23572. };
  23573. var defaultPatterns = function (patterns) {
  23574. return map$3(patterns, function (pattern) {
  23575. return __assign({
  23576. shiftKey: false,
  23577. altKey: false,
  23578. ctrlKey: false,
  23579. metaKey: false,
  23580. keyCode: 0,
  23581. action: noop
  23582. }, pattern);
  23583. });
  23584. };
  23585. var matchesEvent = function (pattern, evt) {
  23586. return evt.keyCode === pattern.keyCode && evt.shiftKey === pattern.shiftKey && evt.altKey === pattern.altKey && evt.ctrlKey === pattern.ctrlKey && evt.metaKey === pattern.metaKey;
  23587. };
  23588. var match$1 = function (patterns, evt) {
  23589. return bind(defaultPatterns(patterns), function (pattern) {
  23590. return matchesEvent(pattern, evt) ? [pattern] : [];
  23591. });
  23592. };
  23593. var action = function (f) {
  23594. var x = [];
  23595. for (var _i = 1; _i < arguments.length; _i++) {
  23596. x[_i - 1] = arguments[_i];
  23597. }
  23598. return function () {
  23599. return f.apply(null, x);
  23600. };
  23601. };
  23602. var execute = function (patterns, evt) {
  23603. return find$3(match$1(patterns, evt), function (pattern) {
  23604. return pattern.action();
  23605. });
  23606. };
  23607. var moveH$1 = function (editor, forward) {
  23608. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23609. var range = editor.selection.getRng();
  23610. return moveHorizontally(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(function (newRange) {
  23611. moveToRange(editor, newRange);
  23612. return true;
  23613. });
  23614. };
  23615. var moveV$1 = function (editor, down) {
  23616. var direction = down ? 1 : -1;
  23617. var range = editor.selection.getRng();
  23618. return moveVertically(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(function (newRange) {
  23619. moveToRange(editor, newRange);
  23620. return true;
  23621. });
  23622. };
  23623. var moveToLineEndPoint = function (editor, forward) {
  23624. var isNearMedia = forward ? isAfterMedia : isBeforeMedia;
  23625. return moveToLineEndPoint$3(editor, forward, isNearMedia);
  23626. };
  23627. var deflate = function (rect, delta) {
  23628. return {
  23629. left: rect.left - delta,
  23630. top: rect.top - delta,
  23631. right: rect.right + delta * 2,
  23632. bottom: rect.bottom + delta * 2,
  23633. width: rect.width + delta,
  23634. height: rect.height + delta
  23635. };
  23636. };
  23637. var getCorners = function (getYAxisValue, tds) {
  23638. return bind(tds, function (td) {
  23639. var rect = deflate(clone(td.getBoundingClientRect()), -1);
  23640. return [
  23641. {
  23642. x: rect.left,
  23643. y: getYAxisValue(rect),
  23644. cell: td
  23645. },
  23646. {
  23647. x: rect.right,
  23648. y: getYAxisValue(rect),
  23649. cell: td
  23650. }
  23651. ];
  23652. });
  23653. };
  23654. var findClosestCorner = function (corners, x, y) {
  23655. return foldl(corners, function (acc, newCorner) {
  23656. return acc.fold(function () {
  23657. return Optional.some(newCorner);
  23658. }, function (oldCorner) {
  23659. var oldDist = Math.sqrt(Math.abs(oldCorner.x - x) + Math.abs(oldCorner.y - y));
  23660. var newDist = Math.sqrt(Math.abs(newCorner.x - x) + Math.abs(newCorner.y - y));
  23661. return Optional.some(newDist < oldDist ? newCorner : oldCorner);
  23662. });
  23663. }, Optional.none());
  23664. };
  23665. var getClosestCell = function (getYAxisValue, isTargetCorner, table, x, y) {
  23666. var cells = descendants(SugarElement.fromDom(table), 'td,th,caption').map(function (e) {
  23667. return e.dom;
  23668. });
  23669. var corners = filter$4(getCorners(getYAxisValue, cells), function (corner) {
  23670. return isTargetCorner(corner, y);
  23671. });
  23672. return findClosestCorner(corners, x, y).map(function (corner) {
  23673. return corner.cell;
  23674. });
  23675. };
  23676. var getBottomValue = function (rect) {
  23677. return rect.bottom;
  23678. };
  23679. var getTopValue = function (rect) {
  23680. return rect.top;
  23681. };
  23682. var isAbove = function (corner, y) {
  23683. return corner.y < y;
  23684. };
  23685. var isBelow = function (corner, y) {
  23686. return corner.y > y;
  23687. };
  23688. var getClosestCellAbove = curry(getClosestCell, getBottomValue, isAbove);
  23689. var getClosestCellBelow = curry(getClosestCell, getTopValue, isBelow);
  23690. var findClosestPositionInAboveCell = function (table, pos) {
  23691. return head(pos.getClientRects()).bind(function (rect) {
  23692. return getClosestCellAbove(table, rect.left, rect.top);
  23693. }).bind(function (cell) {
  23694. return findClosestHorizontalPosition(getLastLinePositions(cell), pos);
  23695. });
  23696. };
  23697. var findClosestPositionInBelowCell = function (table, pos) {
  23698. return last$2(pos.getClientRects()).bind(function (rect) {
  23699. return getClosestCellBelow(table, rect.left, rect.top);
  23700. }).bind(function (cell) {
  23701. return findClosestHorizontalPosition(getFirstLinePositions(cell), pos);
  23702. });
  23703. };
  23704. var hasNextBreak = function (getPositionsUntil, scope, lineInfo) {
  23705. return lineInfo.breakAt.exists(function (breakPos) {
  23706. return getPositionsUntil(scope, breakPos).breakAt.isSome();
  23707. });
  23708. };
  23709. var startsWithWrapBreak = function (lineInfo) {
  23710. return lineInfo.breakType === BreakType.Wrap && lineInfo.positions.length === 0;
  23711. };
  23712. var startsWithBrBreak = function (lineInfo) {
  23713. return lineInfo.breakType === BreakType.Br && lineInfo.positions.length === 1;
  23714. };
  23715. var isAtTableCellLine = function (getPositionsUntil, scope, pos) {
  23716. var lineInfo = getPositionsUntil(scope, pos);
  23717. if (startsWithWrapBreak(lineInfo) || !isBr$5(pos.getNode()) && startsWithBrBreak(lineInfo)) {
  23718. return !hasNextBreak(getPositionsUntil, scope, lineInfo);
  23719. } else {
  23720. return lineInfo.breakAt.isNone();
  23721. }
  23722. };
  23723. var isAtFirstTableCellLine = curry(isAtTableCellLine, getPositionsUntilPreviousLine);
  23724. var isAtLastTableCellLine = curry(isAtTableCellLine, getPositionsUntilNextLine);
  23725. var isCaretAtStartOrEndOfTable = function (forward, rng, table) {
  23726. var caretPos = CaretPosition.fromRangeStart(rng);
  23727. return positionIn(!forward, table).exists(function (pos) {
  23728. return pos.isEqual(caretPos);
  23729. });
  23730. };
  23731. var navigateHorizontally = function (editor, forward, table, _td) {
  23732. var rng = editor.selection.getRng();
  23733. var direction = forward ? 1 : -1;
  23734. if (isFakeCaretTableBrowser() && isCaretAtStartOrEndOfTable(forward, rng, table)) {
  23735. showCaret(direction, editor, table, !forward, false).each(function (newRng) {
  23736. moveToRange(editor, newRng);
  23737. });
  23738. return true;
  23739. }
  23740. return false;
  23741. };
  23742. var getClosestAbovePosition = function (root, table, start) {
  23743. return findClosestPositionInAboveCell(table, start).orThunk(function () {
  23744. return head(start.getClientRects()).bind(function (rect) {
  23745. return findClosestHorizontalPositionFromPoint(getPositionsAbove(root, CaretPosition.before(table)), rect.left);
  23746. });
  23747. }).getOr(CaretPosition.before(table));
  23748. };
  23749. var getClosestBelowPosition = function (root, table, start) {
  23750. return findClosestPositionInBelowCell(table, start).orThunk(function () {
  23751. return head(start.getClientRects()).bind(function (rect) {
  23752. return findClosestHorizontalPositionFromPoint(getPositionsBelow(root, CaretPosition.after(table)), rect.left);
  23753. });
  23754. }).getOr(CaretPosition.after(table));
  23755. };
  23756. var getTable = function (previous, pos) {
  23757. var node = pos.getNode(previous);
  23758. return isElement$5(node) && node.nodeName === 'TABLE' ? Optional.some(node) : Optional.none();
  23759. };
  23760. var renderBlock = function (down, editor, table, pos) {
  23761. var forcedRootBlock = getForcedRootBlock(editor);
  23762. if (forcedRootBlock) {
  23763. editor.undoManager.transact(function () {
  23764. var element = SugarElement.fromTag(forcedRootBlock);
  23765. setAll$1(element, getForcedRootBlockAttrs(editor));
  23766. append$1(element, SugarElement.fromTag('br'));
  23767. if (down) {
  23768. after$3(SugarElement.fromDom(table), element);
  23769. } else {
  23770. before$4(SugarElement.fromDom(table), element);
  23771. }
  23772. var rng = editor.dom.createRng();
  23773. rng.setStart(element.dom, 0);
  23774. rng.setEnd(element.dom, 0);
  23775. moveToRange(editor, rng);
  23776. });
  23777. } else {
  23778. moveToRange(editor, pos.toRange());
  23779. }
  23780. };
  23781. var moveCaret = function (editor, down, pos) {
  23782. var table = down ? getTable(true, pos) : getTable(false, pos);
  23783. var last = down === false;
  23784. table.fold(function () {
  23785. return moveToRange(editor, pos.toRange());
  23786. }, function (table) {
  23787. return positionIn(last, editor.getBody()).filter(function (lastPos) {
  23788. return lastPos.isEqual(pos);
  23789. }).fold(function () {
  23790. return moveToRange(editor, pos.toRange());
  23791. }, function (_) {
  23792. return renderBlock(down, editor, table, pos);
  23793. });
  23794. });
  23795. };
  23796. var navigateVertically = function (editor, down, table, td) {
  23797. var rng = editor.selection.getRng();
  23798. var pos = CaretPosition.fromRangeStart(rng);
  23799. var root = editor.getBody();
  23800. if (!down && isAtFirstTableCellLine(td, pos)) {
  23801. var newPos = getClosestAbovePosition(root, table, pos);
  23802. moveCaret(editor, down, newPos);
  23803. return true;
  23804. } else if (down && isAtLastTableCellLine(td, pos)) {
  23805. var newPos = getClosestBelowPosition(root, table, pos);
  23806. moveCaret(editor, down, newPos);
  23807. return true;
  23808. } else {
  23809. return false;
  23810. }
  23811. };
  23812. var move$1 = function (editor, forward, mover) {
  23813. return Optional.from(editor.dom.getParent(editor.selection.getNode(), 'td,th')).bind(function (td) {
  23814. return Optional.from(editor.dom.getParent(td, 'table')).map(function (table) {
  23815. return mover(editor, forward, table, td);
  23816. });
  23817. }).getOr(false);
  23818. };
  23819. var moveH = function (editor, forward) {
  23820. return move$1(editor, forward, navigateHorizontally);
  23821. };
  23822. var moveV = function (editor, forward) {
  23823. return move$1(editor, forward, navigateVertically);
  23824. };
  23825. var executeKeydownOverride$3 = function (editor, caret, evt) {
  23826. var os = detect().os;
  23827. execute([
  23828. {
  23829. keyCode: VK.RIGHT,
  23830. action: action(moveH$2, editor, true)
  23831. },
  23832. {
  23833. keyCode: VK.LEFT,
  23834. action: action(moveH$2, editor, false)
  23835. },
  23836. {
  23837. keyCode: VK.UP,
  23838. action: action(moveV$3, editor, false)
  23839. },
  23840. {
  23841. keyCode: VK.DOWN,
  23842. action: action(moveV$3, editor, true)
  23843. },
  23844. {
  23845. keyCode: VK.RIGHT,
  23846. action: action(moveH, editor, true)
  23847. },
  23848. {
  23849. keyCode: VK.LEFT,
  23850. action: action(moveH, editor, false)
  23851. },
  23852. {
  23853. keyCode: VK.UP,
  23854. action: action(moveV, editor, false)
  23855. },
  23856. {
  23857. keyCode: VK.DOWN,
  23858. action: action(moveV, editor, true)
  23859. },
  23860. {
  23861. keyCode: VK.RIGHT,
  23862. action: action(moveH$1, editor, true)
  23863. },
  23864. {
  23865. keyCode: VK.LEFT,
  23866. action: action(moveH$1, editor, false)
  23867. },
  23868. {
  23869. keyCode: VK.UP,
  23870. action: action(moveV$1, editor, false)
  23871. },
  23872. {
  23873. keyCode: VK.DOWN,
  23874. action: action(moveV$1, editor, true)
  23875. },
  23876. {
  23877. keyCode: VK.RIGHT,
  23878. action: action(move$2, editor, caret, true)
  23879. },
  23880. {
  23881. keyCode: VK.LEFT,
  23882. action: action(move$2, editor, caret, false)
  23883. },
  23884. {
  23885. keyCode: VK.RIGHT,
  23886. ctrlKey: !os.isOSX(),
  23887. altKey: os.isOSX(),
  23888. action: action(moveNextWord, editor, caret)
  23889. },
  23890. {
  23891. keyCode: VK.LEFT,
  23892. ctrlKey: !os.isOSX(),
  23893. altKey: os.isOSX(),
  23894. action: action(movePrevWord, editor, caret)
  23895. },
  23896. {
  23897. keyCode: VK.UP,
  23898. action: action(moveV$2, editor, false)
  23899. },
  23900. {
  23901. keyCode: VK.DOWN,
  23902. action: action(moveV$2, editor, true)
  23903. }
  23904. ], evt).each(function (_) {
  23905. evt.preventDefault();
  23906. });
  23907. };
  23908. var setup$b = function (editor, caret) {
  23909. editor.on('keydown', function (evt) {
  23910. if (evt.isDefaultPrevented() === false) {
  23911. executeKeydownOverride$3(editor, caret, evt);
  23912. }
  23913. });
  23914. };
  23915. var executeKeydownOverride$2 = function (editor, caret, evt) {
  23916. execute([
  23917. {
  23918. keyCode: VK.BACKSPACE,
  23919. action: action(backspaceDelete, editor, false)
  23920. },
  23921. {
  23922. keyCode: VK.BACKSPACE,
  23923. action: action(backspaceDelete$5, editor, false)
  23924. },
  23925. {
  23926. keyCode: VK.DELETE,
  23927. action: action(backspaceDelete$5, editor, true)
  23928. },
  23929. {
  23930. keyCode: VK.BACKSPACE,
  23931. action: action(backspaceDelete$6, editor, false)
  23932. },
  23933. {
  23934. keyCode: VK.DELETE,
  23935. action: action(backspaceDelete$6, editor, true)
  23936. },
  23937. {
  23938. keyCode: VK.BACKSPACE,
  23939. action: action(backspaceDelete$3, editor, caret, false)
  23940. },
  23941. {
  23942. keyCode: VK.DELETE,
  23943. action: action(backspaceDelete$3, editor, caret, true)
  23944. },
  23945. {
  23946. keyCode: VK.BACKSPACE,
  23947. action: action(backspaceDelete$9, editor, false)
  23948. },
  23949. {
  23950. keyCode: VK.DELETE,
  23951. action: action(backspaceDelete$9, editor, true)
  23952. },
  23953. {
  23954. keyCode: VK.BACKSPACE,
  23955. action: action(backspaceDelete$4, editor, false)
  23956. },
  23957. {
  23958. keyCode: VK.DELETE,
  23959. action: action(backspaceDelete$4, editor, true)
  23960. },
  23961. {
  23962. keyCode: VK.BACKSPACE,
  23963. action: action(backspaceDelete$1, editor, false)
  23964. },
  23965. {
  23966. keyCode: VK.DELETE,
  23967. action: action(backspaceDelete$1, editor, true)
  23968. },
  23969. {
  23970. keyCode: VK.BACKSPACE,
  23971. action: action(backspaceDelete$7, editor, false)
  23972. },
  23973. {
  23974. keyCode: VK.DELETE,
  23975. action: action(backspaceDelete$7, editor, true)
  23976. },
  23977. {
  23978. keyCode: VK.BACKSPACE,
  23979. action: action(backspaceDelete$8, editor, false)
  23980. },
  23981. {
  23982. keyCode: VK.DELETE,
  23983. action: action(backspaceDelete$8, editor, true)
  23984. },
  23985. {
  23986. keyCode: VK.BACKSPACE,
  23987. action: action(backspaceDelete$2, editor, false)
  23988. },
  23989. {
  23990. keyCode: VK.DELETE,
  23991. action: action(backspaceDelete$2, editor, true)
  23992. }
  23993. ], evt).each(function (_) {
  23994. evt.preventDefault();
  23995. });
  23996. };
  23997. var executeKeyupOverride = function (editor, evt) {
  23998. execute([
  23999. {
  24000. keyCode: VK.BACKSPACE,
  24001. action: action(paddEmptyElement, editor)
  24002. },
  24003. {
  24004. keyCode: VK.DELETE,
  24005. action: action(paddEmptyElement, editor)
  24006. }
  24007. ], evt);
  24008. };
  24009. var setup$a = function (editor, caret) {
  24010. editor.on('keydown', function (evt) {
  24011. if (evt.isDefaultPrevented() === false) {
  24012. executeKeydownOverride$2(editor, caret, evt);
  24013. }
  24014. });
  24015. editor.on('keyup', function (evt) {
  24016. if (evt.isDefaultPrevented() === false) {
  24017. executeKeyupOverride(editor, evt);
  24018. }
  24019. });
  24020. };
  24021. var firstNonWhiteSpaceNodeSibling = function (node) {
  24022. while (node) {
  24023. if (node.nodeType === 1 || node.nodeType === 3 && node.data && /[\r\n\s]/.test(node.data)) {
  24024. return node;
  24025. }
  24026. node = node.nextSibling;
  24027. }
  24028. };
  24029. var moveToCaretPosition = function (editor, root) {
  24030. var node, lastNode = root;
  24031. var dom = editor.dom;
  24032. var moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
  24033. if (!root) {
  24034. return;
  24035. }
  24036. if (/^(LI|DT|DD)$/.test(root.nodeName)) {
  24037. var firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild);
  24038. if (firstChild && /^(UL|OL|DL)$/.test(firstChild.nodeName)) {
  24039. root.insertBefore(dom.doc.createTextNode(nbsp), root.firstChild);
  24040. }
  24041. }
  24042. var rng = dom.createRng();
  24043. root.normalize();
  24044. if (root.hasChildNodes()) {
  24045. var walker = new DomTreeWalker(root, root);
  24046. while (node = walker.current()) {
  24047. if (isText$7(node)) {
  24048. rng.setStart(node, 0);
  24049. rng.setEnd(node, 0);
  24050. break;
  24051. }
  24052. if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) {
  24053. rng.setStartBefore(node);
  24054. rng.setEndBefore(node);
  24055. break;
  24056. }
  24057. lastNode = node;
  24058. node = walker.next();
  24059. }
  24060. if (!node) {
  24061. rng.setStart(lastNode, 0);
  24062. rng.setEnd(lastNode, 0);
  24063. }
  24064. } else {
  24065. if (isBr$5(root)) {
  24066. if (root.nextSibling && dom.isBlock(root.nextSibling)) {
  24067. rng.setStartBefore(root);
  24068. rng.setEndBefore(root);
  24069. } else {
  24070. rng.setStartAfter(root);
  24071. rng.setEndAfter(root);
  24072. }
  24073. } else {
  24074. rng.setStart(root, 0);
  24075. rng.setEnd(root, 0);
  24076. }
  24077. }
  24078. editor.selection.setRng(rng);
  24079. scrollRangeIntoView(editor, rng);
  24080. };
  24081. var getEditableRoot$1 = function (dom, node) {
  24082. var root = dom.getRoot();
  24083. var parent, editableRoot;
  24084. parent = node;
  24085. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  24086. if (dom.getContentEditable(parent) === 'true') {
  24087. editableRoot = parent;
  24088. }
  24089. parent = parent.parentNode;
  24090. }
  24091. return parent !== root ? editableRoot : root;
  24092. };
  24093. var getParentBlock = function (editor) {
  24094. return Optional.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
  24095. };
  24096. var getParentBlockName = function (editor) {
  24097. return getParentBlock(editor).fold(constant(''), function (parentBlock) {
  24098. return parentBlock.nodeName.toUpperCase();
  24099. });
  24100. };
  24101. var isListItemParentBlock = function (editor) {
  24102. return getParentBlock(editor).filter(function (elm) {
  24103. return isListItem(SugarElement.fromDom(elm));
  24104. }).isSome();
  24105. };
  24106. var hasFirstChild = function (elm, name) {
  24107. return elm.firstChild && elm.firstChild.nodeName === name;
  24108. };
  24109. var isFirstChild = function (elm) {
  24110. var _a;
  24111. return ((_a = elm.parentNode) === null || _a === void 0 ? void 0 : _a.firstChild) === elm;
  24112. };
  24113. var hasParent = function (elm, parentName) {
  24114. return elm && elm.parentNode && elm.parentNode.nodeName === parentName;
  24115. };
  24116. var isListBlock = function (elm) {
  24117. return elm && /^(OL|UL|LI)$/.test(elm.nodeName);
  24118. };
  24119. var isNestedList = function (elm) {
  24120. return isListBlock(elm) && isListBlock(elm.parentNode);
  24121. };
  24122. var getContainerBlock = function (containerBlock) {
  24123. var containerBlockParent = containerBlock.parentNode;
  24124. if (/^(LI|DT|DD)$/.test(containerBlockParent.nodeName)) {
  24125. return containerBlockParent;
  24126. }
  24127. return containerBlock;
  24128. };
  24129. var isFirstOrLastLi = function (containerBlock, parentBlock, first) {
  24130. var node = containerBlock[first ? 'firstChild' : 'lastChild'];
  24131. while (node) {
  24132. if (isElement$5(node)) {
  24133. break;
  24134. }
  24135. node = node[first ? 'nextSibling' : 'previousSibling'];
  24136. }
  24137. return node === parentBlock;
  24138. };
  24139. var insert$3 = function (editor, createNewBlock, containerBlock, parentBlock, newBlockName) {
  24140. var dom = editor.dom;
  24141. var rng = editor.selection.getRng();
  24142. if (containerBlock === editor.getBody()) {
  24143. return;
  24144. }
  24145. if (isNestedList(containerBlock)) {
  24146. newBlockName = 'LI';
  24147. }
  24148. var newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR');
  24149. if (isFirstOrLastLi(containerBlock, parentBlock, true) && isFirstOrLastLi(containerBlock, parentBlock, false)) {
  24150. if (hasParent(containerBlock, 'LI')) {
  24151. var containerBlockParent = getContainerBlock(containerBlock);
  24152. dom.insertAfter(newBlock, containerBlockParent);
  24153. if (isFirstChild(containerBlock)) {
  24154. dom.remove(containerBlockParent);
  24155. } else {
  24156. dom.remove(containerBlock);
  24157. }
  24158. } else {
  24159. dom.replace(newBlock, containerBlock);
  24160. }
  24161. } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
  24162. if (hasParent(containerBlock, 'LI')) {
  24163. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  24164. newBlock.appendChild(dom.doc.createTextNode(' '));
  24165. newBlock.appendChild(containerBlock);
  24166. } else {
  24167. containerBlock.parentNode.insertBefore(newBlock, containerBlock);
  24168. }
  24169. dom.remove(parentBlock);
  24170. } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
  24171. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  24172. dom.remove(parentBlock);
  24173. } else {
  24174. containerBlock = getContainerBlock(containerBlock);
  24175. var tmpRng = rng.cloneRange();
  24176. tmpRng.setStartAfter(parentBlock);
  24177. tmpRng.setEndAfter(containerBlock);
  24178. var fragment = tmpRng.extractContents();
  24179. if (newBlockName === 'LI' && hasFirstChild(fragment, 'LI')) {
  24180. newBlock = fragment.firstChild;
  24181. dom.insertAfter(fragment, containerBlock);
  24182. } else {
  24183. dom.insertAfter(fragment, containerBlock);
  24184. dom.insertAfter(newBlock, containerBlock);
  24185. }
  24186. dom.remove(parentBlock);
  24187. }
  24188. moveToCaretPosition(editor, newBlock);
  24189. };
  24190. var trimZwsp = function (fragment) {
  24191. each$k(descendants$1(SugarElement.fromDom(fragment), isText$8), function (text) {
  24192. var rawNode = text.dom;
  24193. rawNode.nodeValue = trim$2(rawNode.nodeValue);
  24194. });
  24195. };
  24196. var isEmptyAnchor = function (dom, elm) {
  24197. return elm && elm.nodeName === 'A' && dom.isEmpty(elm);
  24198. };
  24199. var isTableCell = function (node) {
  24200. return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  24201. };
  24202. var emptyBlock = function (elm) {
  24203. elm.innerHTML = '<br data-mce-bogus="1">';
  24204. };
  24205. var containerAndSiblingName = function (container, nodeName) {
  24206. return container.nodeName === nodeName || container.previousSibling && container.previousSibling.nodeName === nodeName;
  24207. };
  24208. var canSplitBlock = function (dom, node) {
  24209. return node && dom.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.getContentEditable(node) !== 'true';
  24210. };
  24211. var trimInlineElementsOnLeftSideOfBlock = function (dom, nonEmptyElementsMap, block) {
  24212. var node = block;
  24213. var firstChilds = [];
  24214. var i;
  24215. if (!node) {
  24216. return;
  24217. }
  24218. while (node = node.firstChild) {
  24219. if (dom.isBlock(node)) {
  24220. return;
  24221. }
  24222. if (isElement$5(node) && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  24223. firstChilds.push(node);
  24224. }
  24225. }
  24226. i = firstChilds.length;
  24227. while (i--) {
  24228. node = firstChilds[i];
  24229. if (!node.hasChildNodes() || node.firstChild === node.lastChild && node.firstChild.nodeValue === '') {
  24230. dom.remove(node);
  24231. } else {
  24232. if (isEmptyAnchor(dom, node)) {
  24233. dom.remove(node);
  24234. }
  24235. }
  24236. }
  24237. };
  24238. var normalizeZwspOffset = function (start, container, offset) {
  24239. if (isText$7(container) === false) {
  24240. return offset;
  24241. } else if (start) {
  24242. return offset === 1 && container.data.charAt(offset - 1) === ZWSP$1 ? 0 : offset;
  24243. } else {
  24244. return offset === container.data.length - 1 && container.data.charAt(offset) === ZWSP$1 ? container.data.length : offset;
  24245. }
  24246. };
  24247. var includeZwspInRange = function (rng) {
  24248. var newRng = rng.cloneRange();
  24249. newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
  24250. newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
  24251. return newRng;
  24252. };
  24253. var trimLeadingLineBreaks = function (node) {
  24254. do {
  24255. if (isText$7(node)) {
  24256. node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
  24257. }
  24258. node = node.firstChild;
  24259. } while (node);
  24260. };
  24261. var getEditableRoot = function (dom, node) {
  24262. var root = dom.getRoot();
  24263. var parent, editableRoot;
  24264. parent = node;
  24265. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  24266. if (dom.getContentEditable(parent) === 'true') {
  24267. editableRoot = parent;
  24268. }
  24269. parent = parent.parentNode;
  24270. }
  24271. return parent !== root ? editableRoot : root;
  24272. };
  24273. var applyAttributes = function (editor, node, forcedRootBlockAttrs) {
  24274. var dom = editor.dom;
  24275. Optional.from(forcedRootBlockAttrs.style).map(dom.parseStyle).each(function (attrStyles) {
  24276. var currentStyles = getAllRaw(SugarElement.fromDom(node));
  24277. var newStyles = __assign(__assign({}, currentStyles), attrStyles);
  24278. dom.setStyles(node, newStyles);
  24279. });
  24280. var attrClassesOpt = Optional.from(forcedRootBlockAttrs.class).map(function (attrClasses) {
  24281. return attrClasses.split(/\s+/);
  24282. });
  24283. var currentClassesOpt = Optional.from(node.className).map(function (currentClasses) {
  24284. return filter$4(currentClasses.split(/\s+/), function (clazz) {
  24285. return clazz !== '';
  24286. });
  24287. });
  24288. lift2(attrClassesOpt, currentClassesOpt, function (attrClasses, currentClasses) {
  24289. var filteredClasses = filter$4(currentClasses, function (clazz) {
  24290. return !contains$3(attrClasses, clazz);
  24291. });
  24292. var newClasses = __spreadArray(__spreadArray([], attrClasses), filteredClasses);
  24293. dom.setAttrib(node, 'class', newClasses.join(' '));
  24294. });
  24295. var appliedAttrs = [
  24296. 'style',
  24297. 'class'
  24298. ];
  24299. var remainingAttrs = filter$3(forcedRootBlockAttrs, function (_, attrs) {
  24300. return !contains$3(appliedAttrs, attrs);
  24301. });
  24302. dom.setAttribs(node, remainingAttrs);
  24303. };
  24304. var setForcedBlockAttrs = function (editor, node) {
  24305. var forcedRootBlockName = getForcedRootBlock(editor);
  24306. if (forcedRootBlockName && forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
  24307. var forcedRootBlockAttrs = getForcedRootBlockAttrs(editor);
  24308. applyAttributes(editor, node, forcedRootBlockAttrs);
  24309. }
  24310. };
  24311. var wrapSelfAndSiblingsInDefaultBlock = function (editor, newBlockName, rng, container, offset) {
  24312. var newBlock, parentBlock, startNode, node, next, rootBlockName;
  24313. var blockName = newBlockName || 'P';
  24314. var dom = editor.dom, editableRoot = getEditableRoot(dom, container);
  24315. parentBlock = dom.getParent(container, dom.isBlock);
  24316. if (!parentBlock || !canSplitBlock(dom, parentBlock)) {
  24317. parentBlock = parentBlock || editableRoot;
  24318. if (parentBlock === editor.getBody() || isTableCell(parentBlock)) {
  24319. rootBlockName = parentBlock.nodeName.toLowerCase();
  24320. } else {
  24321. rootBlockName = parentBlock.parentNode.nodeName.toLowerCase();
  24322. }
  24323. if (!parentBlock.hasChildNodes()) {
  24324. newBlock = dom.create(blockName);
  24325. setForcedBlockAttrs(editor, newBlock);
  24326. parentBlock.appendChild(newBlock);
  24327. rng.setStart(newBlock, 0);
  24328. rng.setEnd(newBlock, 0);
  24329. return newBlock;
  24330. }
  24331. node = container;
  24332. while (node.parentNode !== parentBlock) {
  24333. node = node.parentNode;
  24334. }
  24335. while (node && !dom.isBlock(node)) {
  24336. startNode = node;
  24337. node = node.previousSibling;
  24338. }
  24339. if (startNode && editor.schema.isValidChild(rootBlockName, blockName.toLowerCase())) {
  24340. newBlock = dom.create(blockName);
  24341. setForcedBlockAttrs(editor, newBlock);
  24342. startNode.parentNode.insertBefore(newBlock, startNode);
  24343. node = startNode;
  24344. while (node && !dom.isBlock(node)) {
  24345. next = node.nextSibling;
  24346. newBlock.appendChild(node);
  24347. node = next;
  24348. }
  24349. rng.setStart(container, offset);
  24350. rng.setEnd(container, offset);
  24351. }
  24352. }
  24353. return container;
  24354. };
  24355. var addBrToBlockIfNeeded = function (dom, block) {
  24356. block.normalize();
  24357. var lastChild = block.lastChild;
  24358. if (!lastChild || /^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true))) {
  24359. dom.add(block, 'br');
  24360. }
  24361. };
  24362. var insert$2 = function (editor, evt) {
  24363. var tmpRng, container, offset, parentBlock;
  24364. var newBlock, fragment, containerBlock, parentBlockName, newBlockName, isAfterLastNodeInContainer;
  24365. var dom = editor.dom;
  24366. var schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
  24367. var rng = editor.selection.getRng();
  24368. var createNewBlock = function (name) {
  24369. var node = container, block, clonedNode, caretNode;
  24370. var textInlineElements = schema.getTextInlineElements();
  24371. if (name || parentBlockName === 'TABLE' || parentBlockName === 'HR') {
  24372. block = dom.create(name || newBlockName);
  24373. } else {
  24374. block = parentBlock.cloneNode(false);
  24375. }
  24376. caretNode = block;
  24377. if (shouldKeepStyles(editor) === false) {
  24378. dom.setAttrib(block, 'style', null);
  24379. dom.setAttrib(block, 'class', null);
  24380. } else {
  24381. do {
  24382. if (textInlineElements[node.nodeName]) {
  24383. if (isCaretNode(node) || isBookmarkNode$1(node)) {
  24384. continue;
  24385. }
  24386. clonedNode = node.cloneNode(false);
  24387. dom.setAttrib(clonedNode, 'id', '');
  24388. if (block.hasChildNodes()) {
  24389. clonedNode.appendChild(block.firstChild);
  24390. block.appendChild(clonedNode);
  24391. } else {
  24392. caretNode = clonedNode;
  24393. block.appendChild(clonedNode);
  24394. }
  24395. }
  24396. } while ((node = node.parentNode) && node !== editableRoot);
  24397. }
  24398. setForcedBlockAttrs(editor, block);
  24399. emptyBlock(caretNode);
  24400. return block;
  24401. };
  24402. var isCaretAtStartOrEndOfBlock = function (start) {
  24403. var node, name;
  24404. var normalizedOffset = normalizeZwspOffset(start, container, offset);
  24405. if (isText$7(container) && (start ? normalizedOffset > 0 : normalizedOffset < container.nodeValue.length)) {
  24406. return false;
  24407. }
  24408. if (container.parentNode === parentBlock && isAfterLastNodeInContainer && !start) {
  24409. return true;
  24410. }
  24411. if (start && isElement$5(container) && container === parentBlock.firstChild) {
  24412. return true;
  24413. }
  24414. if (containerAndSiblingName(container, 'TABLE') || containerAndSiblingName(container, 'HR')) {
  24415. return isAfterLastNodeInContainer && !start || !isAfterLastNodeInContainer && start;
  24416. }
  24417. var walker = new DomTreeWalker(container, parentBlock);
  24418. if (isText$7(container)) {
  24419. if (start && normalizedOffset === 0) {
  24420. walker.prev();
  24421. } else if (!start && normalizedOffset === container.nodeValue.length) {
  24422. walker.next();
  24423. }
  24424. }
  24425. while (node = walker.current()) {
  24426. if (isElement$5(node)) {
  24427. if (!node.getAttribute('data-mce-bogus')) {
  24428. name = node.nodeName.toLowerCase();
  24429. if (nonEmptyElementsMap[name] && name !== 'br') {
  24430. return false;
  24431. }
  24432. }
  24433. } else if (isText$7(node) && !isWhitespaceText(node.nodeValue)) {
  24434. return false;
  24435. }
  24436. if (start) {
  24437. walker.prev();
  24438. } else {
  24439. walker.next();
  24440. }
  24441. }
  24442. return true;
  24443. };
  24444. var insertNewBlockAfter = function () {
  24445. if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName !== 'HGROUP') {
  24446. newBlock = createNewBlock(newBlockName);
  24447. } else {
  24448. newBlock = createNewBlock();
  24449. }
  24450. if (shouldEndContainerOnEmptyBlock(editor) && canSplitBlock(dom, containerBlock) && dom.isEmpty(parentBlock)) {
  24451. newBlock = dom.split(containerBlock, parentBlock);
  24452. } else {
  24453. dom.insertAfter(newBlock, parentBlock);
  24454. }
  24455. moveToCaretPosition(editor, newBlock);
  24456. };
  24457. normalize$2(dom, rng).each(function (normRng) {
  24458. rng.setStart(normRng.startContainer, normRng.startOffset);
  24459. rng.setEnd(normRng.endContainer, normRng.endOffset);
  24460. });
  24461. container = rng.startContainer;
  24462. offset = rng.startOffset;
  24463. newBlockName = getForcedRootBlock(editor);
  24464. var shiftKey = !!(evt && evt.shiftKey);
  24465. var ctrlKey = !!(evt && evt.ctrlKey);
  24466. if (isElement$5(container) && container.hasChildNodes()) {
  24467. isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  24468. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  24469. if (isAfterLastNodeInContainer && isText$7(container)) {
  24470. offset = container.nodeValue.length;
  24471. } else {
  24472. offset = 0;
  24473. }
  24474. }
  24475. var editableRoot = getEditableRoot(dom, container);
  24476. if (!editableRoot) {
  24477. return;
  24478. }
  24479. if (newBlockName && !shiftKey || !newBlockName && shiftKey) {
  24480. container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset);
  24481. }
  24482. parentBlock = dom.getParent(container, dom.isBlock);
  24483. containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  24484. parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : '';
  24485. var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  24486. if (containerBlockName === 'LI' && !ctrlKey) {
  24487. parentBlock = containerBlock;
  24488. containerBlock = containerBlock.parentNode;
  24489. parentBlockName = containerBlockName;
  24490. }
  24491. if (/^(LI|DT|DD)$/.test(parentBlockName)) {
  24492. if (dom.isEmpty(parentBlock)) {
  24493. insert$3(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
  24494. return;
  24495. }
  24496. }
  24497. if (newBlockName && parentBlock === editor.getBody()) {
  24498. return;
  24499. }
  24500. newBlockName = newBlockName || 'P';
  24501. if (isCaretContainerBlock$1(parentBlock)) {
  24502. newBlock = showCaretContainerBlock(parentBlock);
  24503. if (dom.isEmpty(parentBlock)) {
  24504. emptyBlock(parentBlock);
  24505. }
  24506. setForcedBlockAttrs(editor, newBlock);
  24507. moveToCaretPosition(editor, newBlock);
  24508. } else if (isCaretAtStartOrEndOfBlock()) {
  24509. insertNewBlockAfter();
  24510. } else if (isCaretAtStartOrEndOfBlock(true)) {
  24511. newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
  24512. moveToCaretPosition(editor, containerAndSiblingName(parentBlock, 'HR') ? newBlock : parentBlock);
  24513. } else {
  24514. tmpRng = includeZwspInRange(rng).cloneRange();
  24515. tmpRng.setEndAfter(parentBlock);
  24516. fragment = tmpRng.extractContents();
  24517. trimZwsp(fragment);
  24518. trimLeadingLineBreaks(fragment);
  24519. newBlock = fragment.firstChild;
  24520. dom.insertAfter(fragment, parentBlock);
  24521. trimInlineElementsOnLeftSideOfBlock(dom, nonEmptyElementsMap, newBlock);
  24522. addBrToBlockIfNeeded(dom, parentBlock);
  24523. if (dom.isEmpty(parentBlock)) {
  24524. emptyBlock(parentBlock);
  24525. }
  24526. newBlock.normalize();
  24527. if (dom.isEmpty(newBlock)) {
  24528. dom.remove(newBlock);
  24529. insertNewBlockAfter();
  24530. } else {
  24531. setForcedBlockAttrs(editor, newBlock);
  24532. moveToCaretPosition(editor, newBlock);
  24533. }
  24534. }
  24535. dom.setAttrib(newBlock, 'id', '');
  24536. editor.fire('NewBlock', { newBlock: newBlock });
  24537. };
  24538. var hasRightSideContent = function (schema, container, parentBlock) {
  24539. var walker = new DomTreeWalker(container, parentBlock);
  24540. var node;
  24541. var nonEmptyElementsMap = schema.getNonEmptyElements();
  24542. while (node = walker.next()) {
  24543. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
  24544. return true;
  24545. }
  24546. }
  24547. };
  24548. var moveSelectionToBr = function (editor, brElm, extraBr) {
  24549. var rng = editor.dom.createRng();
  24550. if (!extraBr) {
  24551. rng.setStartAfter(brElm);
  24552. rng.setEndAfter(brElm);
  24553. } else {
  24554. rng.setStartBefore(brElm);
  24555. rng.setEndBefore(brElm);
  24556. }
  24557. editor.selection.setRng(rng);
  24558. scrollRangeIntoView(editor, rng);
  24559. };
  24560. var insertBrAtCaret = function (editor, evt) {
  24561. var selection = editor.selection;
  24562. var dom = editor.dom;
  24563. var rng = selection.getRng();
  24564. var brElm;
  24565. var extraBr;
  24566. normalize$2(dom, rng).each(function (normRng) {
  24567. rng.setStart(normRng.startContainer, normRng.startOffset);
  24568. rng.setEnd(normRng.endContainer, normRng.endOffset);
  24569. });
  24570. var offset = rng.startOffset;
  24571. var container = rng.startContainer;
  24572. if (container.nodeType === 1 && container.hasChildNodes()) {
  24573. var isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  24574. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  24575. if (isAfterLastNodeInContainer && container.nodeType === 3) {
  24576. offset = container.nodeValue.length;
  24577. } else {
  24578. offset = 0;
  24579. }
  24580. }
  24581. var parentBlock = dom.getParent(container, dom.isBlock);
  24582. var containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  24583. var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  24584. var isControlKey = !!(evt && evt.ctrlKey);
  24585. if (containerBlockName === 'LI' && !isControlKey) {
  24586. parentBlock = containerBlock;
  24587. }
  24588. if (container && container.nodeType === 3 && offset >= container.nodeValue.length) {
  24589. if (!hasRightSideContent(editor.schema, container, parentBlock)) {
  24590. brElm = dom.create('br');
  24591. rng.insertNode(brElm);
  24592. rng.setStartAfter(brElm);
  24593. rng.setEndAfter(brElm);
  24594. extraBr = true;
  24595. }
  24596. }
  24597. brElm = dom.create('br');
  24598. rangeInsertNode(dom, rng, brElm);
  24599. moveSelectionToBr(editor, brElm, extraBr);
  24600. editor.undoManager.add();
  24601. };
  24602. var insertBrBefore = function (editor, inline) {
  24603. var br = SugarElement.fromTag('br');
  24604. before$4(SugarElement.fromDom(inline), br);
  24605. editor.undoManager.add();
  24606. };
  24607. var insertBrAfter = function (editor, inline) {
  24608. if (!hasBrAfter(editor.getBody(), inline)) {
  24609. after$3(SugarElement.fromDom(inline), SugarElement.fromTag('br'));
  24610. }
  24611. var br = SugarElement.fromTag('br');
  24612. after$3(SugarElement.fromDom(inline), br);
  24613. moveSelectionToBr(editor, br.dom, false);
  24614. editor.undoManager.add();
  24615. };
  24616. var isBeforeBr = function (pos) {
  24617. return isBr$5(pos.getNode());
  24618. };
  24619. var hasBrAfter = function (rootNode, startNode) {
  24620. if (isBeforeBr(CaretPosition.after(startNode))) {
  24621. return true;
  24622. } else {
  24623. return nextPosition(rootNode, CaretPosition.after(startNode)).map(function (pos) {
  24624. return isBr$5(pos.getNode());
  24625. }).getOr(false);
  24626. }
  24627. };
  24628. var isAnchorLink = function (elm) {
  24629. return elm && elm.nodeName === 'A' && 'href' in elm;
  24630. };
  24631. var isInsideAnchor = function (location) {
  24632. return location.fold(never, isAnchorLink, isAnchorLink, never);
  24633. };
  24634. var readInlineAnchorLocation = function (editor) {
  24635. var isInlineTarget$1 = curry(isInlineTarget, editor);
  24636. var position = CaretPosition.fromRangeStart(editor.selection.getRng());
  24637. return readLocation(isInlineTarget$1, editor.getBody(), position).filter(isInsideAnchor);
  24638. };
  24639. var insertBrOutsideAnchor = function (editor, location) {
  24640. location.fold(noop, curry(insertBrBefore, editor), curry(insertBrAfter, editor), noop);
  24641. };
  24642. var insert$1 = function (editor, evt) {
  24643. var anchorLocation = readInlineAnchorLocation(editor);
  24644. if (anchorLocation.isSome()) {
  24645. anchorLocation.each(curry(insertBrOutsideAnchor, editor));
  24646. } else {
  24647. insertBrAtCaret(editor, evt);
  24648. }
  24649. };
  24650. var matchesSelector = function (editor, selector) {
  24651. return getParentBlock(editor).filter(function (parentBlock) {
  24652. return selector.length > 0 && is$2(SugarElement.fromDom(parentBlock), selector);
  24653. }).isSome();
  24654. };
  24655. var shouldInsertBr = function (editor) {
  24656. return matchesSelector(editor, getBrNewLineSelector(editor));
  24657. };
  24658. var shouldBlockNewLine$1 = function (editor) {
  24659. return matchesSelector(editor, getNoNewLineSelector(editor));
  24660. };
  24661. var newLineAction = Adt.generate([
  24662. { br: [] },
  24663. { block: [] },
  24664. { none: [] }
  24665. ]);
  24666. var shouldBlockNewLine = function (editor, _shiftKey) {
  24667. return shouldBlockNewLine$1(editor);
  24668. };
  24669. var isBrMode = function (requiredState) {
  24670. return function (editor, _shiftKey) {
  24671. var brMode = getForcedRootBlock(editor) === '';
  24672. return brMode === requiredState;
  24673. };
  24674. };
  24675. var inListBlock = function (requiredState) {
  24676. return function (editor, _shiftKey) {
  24677. return isListItemParentBlock(editor) === requiredState;
  24678. };
  24679. };
  24680. var inBlock = function (blockName, requiredState) {
  24681. return function (editor, _shiftKey) {
  24682. var state = getParentBlockName(editor) === blockName.toUpperCase();
  24683. return state === requiredState;
  24684. };
  24685. };
  24686. var inPreBlock = function (requiredState) {
  24687. return inBlock('pre', requiredState);
  24688. };
  24689. var inSummaryBlock = function () {
  24690. return inBlock('summary', true);
  24691. };
  24692. var shouldPutBrInPre = function (requiredState) {
  24693. return function (editor, _shiftKey) {
  24694. return shouldPutBrInPre$1(editor) === requiredState;
  24695. };
  24696. };
  24697. var inBrContext = function (editor, _shiftKey) {
  24698. return shouldInsertBr(editor);
  24699. };
  24700. var hasShiftKey = function (_editor, shiftKey) {
  24701. return shiftKey;
  24702. };
  24703. var canInsertIntoEditableRoot = function (editor) {
  24704. var forcedRootBlock = getForcedRootBlock(editor);
  24705. var rootEditable = getEditableRoot$1(editor.dom, editor.selection.getStart());
  24706. return rootEditable && editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock ? forcedRootBlock : 'P');
  24707. };
  24708. var match = function (predicates, action) {
  24709. return function (editor, shiftKey) {
  24710. var isMatch = foldl(predicates, function (res, p) {
  24711. return res && p(editor, shiftKey);
  24712. }, true);
  24713. return isMatch ? Optional.some(action) : Optional.none();
  24714. };
  24715. };
  24716. var getAction = function (editor, evt) {
  24717. return evaluateUntil([
  24718. match([shouldBlockNewLine], newLineAction.none()),
  24719. match([inSummaryBlock()], newLineAction.br()),
  24720. match([
  24721. inPreBlock(true),
  24722. shouldPutBrInPre(false),
  24723. hasShiftKey
  24724. ], newLineAction.br()),
  24725. match([
  24726. inPreBlock(true),
  24727. shouldPutBrInPre(false)
  24728. ], newLineAction.block()),
  24729. match([
  24730. inPreBlock(true),
  24731. shouldPutBrInPre(true),
  24732. hasShiftKey
  24733. ], newLineAction.block()),
  24734. match([
  24735. inPreBlock(true),
  24736. shouldPutBrInPre(true)
  24737. ], newLineAction.br()),
  24738. match([
  24739. inListBlock(true),
  24740. hasShiftKey
  24741. ], newLineAction.br()),
  24742. match([inListBlock(true)], newLineAction.block()),
  24743. match([
  24744. isBrMode(true),
  24745. hasShiftKey,
  24746. canInsertIntoEditableRoot
  24747. ], newLineAction.block()),
  24748. match([isBrMode(true)], newLineAction.br()),
  24749. match([inBrContext], newLineAction.br()),
  24750. match([
  24751. isBrMode(false),
  24752. hasShiftKey
  24753. ], newLineAction.br()),
  24754. match([canInsertIntoEditableRoot], newLineAction.block())
  24755. ], [
  24756. editor,
  24757. !!(evt && evt.shiftKey)
  24758. ]).getOr(newLineAction.none());
  24759. };
  24760. var insert = function (editor, evt) {
  24761. getAction(editor, evt).fold(function () {
  24762. insert$1(editor, evt);
  24763. }, function () {
  24764. insert$2(editor, evt);
  24765. }, noop);
  24766. };
  24767. var handleEnterKeyEvent = function (editor, event) {
  24768. if (event.isDefaultPrevented()) {
  24769. return;
  24770. }
  24771. event.preventDefault();
  24772. endTypingLevelIgnoreLocks(editor.undoManager);
  24773. editor.undoManager.transact(function () {
  24774. if (editor.selection.isCollapsed() === false) {
  24775. editor.execCommand('Delete');
  24776. }
  24777. insert(editor, event);
  24778. });
  24779. };
  24780. var setup$9 = function (editor) {
  24781. editor.on('keydown', function (event) {
  24782. if (event.keyCode === VK.ENTER) {
  24783. handleEnterKeyEvent(editor, event);
  24784. }
  24785. });
  24786. };
  24787. var executeKeydownOverride$1 = function (editor, caret, evt) {
  24788. execute([
  24789. {
  24790. keyCode: VK.END,
  24791. action: action(moveToLineEndPoint$1, editor, true)
  24792. },
  24793. {
  24794. keyCode: VK.HOME,
  24795. action: action(moveToLineEndPoint$1, editor, false)
  24796. },
  24797. {
  24798. keyCode: VK.END,
  24799. action: action(moveToLineEndPoint, editor, true)
  24800. },
  24801. {
  24802. keyCode: VK.HOME,
  24803. action: action(moveToLineEndPoint, editor, false)
  24804. },
  24805. {
  24806. keyCode: VK.END,
  24807. action: action(moveToLineEndPoint$2, editor, true, caret)
  24808. },
  24809. {
  24810. keyCode: VK.HOME,
  24811. action: action(moveToLineEndPoint$2, editor, false, caret)
  24812. }
  24813. ], evt).each(function (_) {
  24814. evt.preventDefault();
  24815. });
  24816. };
  24817. var setup$8 = function (editor, caret) {
  24818. editor.on('keydown', function (evt) {
  24819. if (evt.isDefaultPrevented() === false) {
  24820. executeKeydownOverride$1(editor, caret, evt);
  24821. }
  24822. });
  24823. };
  24824. var browser = detect().browser;
  24825. var setupIeInput = function (editor) {
  24826. var keypressThrotter = first(function () {
  24827. if (!editor.composing) {
  24828. normalizeNbspsInEditor(editor);
  24829. }
  24830. }, 0);
  24831. if (browser.isIE()) {
  24832. editor.on('keypress', function (_e) {
  24833. keypressThrotter.throttle();
  24834. });
  24835. editor.on('remove', function (_e) {
  24836. keypressThrotter.cancel();
  24837. });
  24838. }
  24839. };
  24840. var setup$7 = function (editor) {
  24841. setupIeInput(editor);
  24842. editor.on('input', function (e) {
  24843. if (e.isComposing === false) {
  24844. normalizeNbspsInEditor(editor);
  24845. }
  24846. });
  24847. };
  24848. var platform = detect();
  24849. var executeKeyupAction = function (editor, caret, evt) {
  24850. execute([
  24851. {
  24852. keyCode: VK.PAGE_UP,
  24853. action: action(moveToLineEndPoint$2, editor, false, caret)
  24854. },
  24855. {
  24856. keyCode: VK.PAGE_DOWN,
  24857. action: action(moveToLineEndPoint$2, editor, true, caret)
  24858. }
  24859. ], evt);
  24860. };
  24861. var stopImmediatePropagation = function (e) {
  24862. return e.stopImmediatePropagation();
  24863. };
  24864. var isPageUpDown = function (evt) {
  24865. return evt.keyCode === VK.PAGE_UP || evt.keyCode === VK.PAGE_DOWN;
  24866. };
  24867. var setNodeChangeBlocker = function (blocked, editor, block) {
  24868. if (block && !blocked.get()) {
  24869. editor.on('NodeChange', stopImmediatePropagation, true);
  24870. } else if (!block && blocked.get()) {
  24871. editor.off('NodeChange', stopImmediatePropagation);
  24872. }
  24873. blocked.set(block);
  24874. };
  24875. var setup$6 = function (editor, caret) {
  24876. if (platform.os.isOSX()) {
  24877. return;
  24878. }
  24879. var blocked = Cell(false);
  24880. editor.on('keydown', function (evt) {
  24881. if (isPageUpDown(evt)) {
  24882. setNodeChangeBlocker(blocked, editor, true);
  24883. }
  24884. });
  24885. editor.on('keyup', function (evt) {
  24886. if (evt.isDefaultPrevented() === false) {
  24887. executeKeyupAction(editor, caret, evt);
  24888. }
  24889. if (isPageUpDown(evt) && blocked.get()) {
  24890. setNodeChangeBlocker(blocked, editor, false);
  24891. editor.nodeChanged();
  24892. }
  24893. });
  24894. };
  24895. var insertTextAtPosition = function (text, pos) {
  24896. var container = pos.container();
  24897. var offset = pos.offset();
  24898. if (isText$7(container)) {
  24899. container.insertData(offset, text);
  24900. return Optional.some(CaretPosition(container, offset + text.length));
  24901. } else {
  24902. return getElementFromPosition(pos).map(function (elm) {
  24903. var textNode = SugarElement.fromText(text);
  24904. if (pos.isAtEnd()) {
  24905. after$3(elm, textNode);
  24906. } else {
  24907. before$4(elm, textNode);
  24908. }
  24909. return CaretPosition(textNode.dom, text.length);
  24910. });
  24911. }
  24912. };
  24913. var insertNbspAtPosition = curry(insertTextAtPosition, nbsp);
  24914. var insertSpaceAtPosition = curry(insertTextAtPosition, ' ');
  24915. var locationToCaretPosition = function (root) {
  24916. return function (location) {
  24917. return location.fold(function (element) {
  24918. return prevPosition(root.dom, CaretPosition.before(element));
  24919. }, function (element) {
  24920. return firstPositionIn(element);
  24921. }, function (element) {
  24922. return lastPositionIn(element);
  24923. }, function (element) {
  24924. return nextPosition(root.dom, CaretPosition.after(element));
  24925. });
  24926. };
  24927. };
  24928. var insertInlineBoundarySpaceOrNbsp = function (root, pos) {
  24929. return function (checkPos) {
  24930. return needsToHaveNbsp(root, checkPos) ? insertNbspAtPosition(pos) : insertSpaceAtPosition(pos);
  24931. };
  24932. };
  24933. var setSelection = function (editor) {
  24934. return function (pos) {
  24935. editor.selection.setRng(pos.toRange());
  24936. editor.nodeChanged();
  24937. return true;
  24938. };
  24939. };
  24940. var insertSpaceOrNbspAtSelection = function (editor) {
  24941. var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  24942. var root = SugarElement.fromDom(editor.getBody());
  24943. if (editor.selection.isCollapsed()) {
  24944. var isInlineTarget$1 = curry(isInlineTarget, editor);
  24945. var caretPosition = CaretPosition.fromRangeStart(editor.selection.getRng());
  24946. return readLocation(isInlineTarget$1, editor.getBody(), caretPosition).bind(locationToCaretPosition(root)).bind(insertInlineBoundarySpaceOrNbsp(root, pos)).exists(setSelection(editor));
  24947. } else {
  24948. return false;
  24949. }
  24950. };
  24951. var executeKeydownOverride = function (editor, evt) {
  24952. execute([{
  24953. keyCode: VK.SPACEBAR,
  24954. action: action(insertSpaceOrNbspAtSelection, editor)
  24955. }], evt).each(function (_) {
  24956. evt.preventDefault();
  24957. });
  24958. };
  24959. var setup$5 = function (editor) {
  24960. editor.on('keydown', function (evt) {
  24961. if (evt.isDefaultPrevented() === false) {
  24962. executeKeydownOverride(editor, evt);
  24963. }
  24964. });
  24965. };
  24966. var registerKeyboardOverrides = function (editor) {
  24967. var caret = setupSelectedState(editor);
  24968. setup$c(editor);
  24969. setup$b(editor, caret);
  24970. setup$a(editor, caret);
  24971. setup$9(editor);
  24972. setup$5(editor);
  24973. setup$7(editor);
  24974. setup$8(editor, caret);
  24975. setup$6(editor, caret);
  24976. return caret;
  24977. };
  24978. var setup$4 = function (editor) {
  24979. if (!isRtc(editor)) {
  24980. return registerKeyboardOverrides(editor);
  24981. } else {
  24982. return Cell(null);
  24983. }
  24984. };
  24985. var NodeChange = function () {
  24986. function NodeChange(editor) {
  24987. this.lastPath = [];
  24988. this.editor = editor;
  24989. var lastRng;
  24990. var self = this;
  24991. if (!('onselectionchange' in editor.getDoc())) {
  24992. editor.on('NodeChange click mouseup keyup focus', function (e) {
  24993. var nativeRng = editor.selection.getRng();
  24994. var fakeRng = {
  24995. startContainer: nativeRng.startContainer,
  24996. startOffset: nativeRng.startOffset,
  24997. endContainer: nativeRng.endContainer,
  24998. endOffset: nativeRng.endOffset
  24999. };
  25000. if (e.type === 'nodechange' || !isEq$4(fakeRng, lastRng)) {
  25001. editor.fire('SelectionChange');
  25002. }
  25003. lastRng = fakeRng;
  25004. });
  25005. }
  25006. editor.on('contextmenu', function () {
  25007. editor.fire('SelectionChange');
  25008. });
  25009. editor.on('SelectionChange', function () {
  25010. var startElm = editor.selection.getStart(true);
  25011. if (!startElm || !Env.range && editor.selection.isCollapsed()) {
  25012. return;
  25013. }
  25014. if (hasAnyRanges(editor) && !self.isSameElementPath(startElm) && editor.dom.isChildOf(startElm, editor.getBody())) {
  25015. editor.nodeChanged({ selectionChange: true });
  25016. }
  25017. });
  25018. editor.on('mouseup', function (e) {
  25019. if (!e.isDefaultPrevented() && hasAnyRanges(editor)) {
  25020. if (editor.selection.getNode().nodeName === 'IMG') {
  25021. Delay.setEditorTimeout(editor, function () {
  25022. editor.nodeChanged();
  25023. });
  25024. } else {
  25025. editor.nodeChanged();
  25026. }
  25027. }
  25028. });
  25029. }
  25030. NodeChange.prototype.nodeChanged = function (args) {
  25031. var selection = this.editor.selection;
  25032. var node, parents, root;
  25033. if (this.editor.initialized && selection && !shouldDisableNodeChange(this.editor) && !this.editor.mode.isReadOnly()) {
  25034. root = this.editor.getBody();
  25035. node = selection.getStart(true) || root;
  25036. if (node.ownerDocument !== this.editor.getDoc() || !this.editor.dom.isChildOf(node, root)) {
  25037. node = root;
  25038. }
  25039. parents = [];
  25040. this.editor.dom.getParent(node, function (node) {
  25041. if (node === root) {
  25042. return true;
  25043. }
  25044. parents.push(node);
  25045. });
  25046. args = args || {};
  25047. args.element = node;
  25048. args.parents = parents;
  25049. this.editor.fire('NodeChange', args);
  25050. }
  25051. };
  25052. NodeChange.prototype.isSameElementPath = function (startElm) {
  25053. var i;
  25054. var currentPath = this.editor.$(startElm).parentsUntil(this.editor.getBody()).add(startElm);
  25055. if (currentPath.length === this.lastPath.length) {
  25056. for (i = currentPath.length; i >= 0; i--) {
  25057. if (currentPath[i] !== this.lastPath[i]) {
  25058. break;
  25059. }
  25060. }
  25061. if (i === -1) {
  25062. this.lastPath = currentPath;
  25063. return true;
  25064. }
  25065. }
  25066. this.lastPath = currentPath;
  25067. return false;
  25068. };
  25069. return NodeChange;
  25070. }();
  25071. var preventSummaryToggle = function (editor) {
  25072. editor.on('click', function (e) {
  25073. if (editor.dom.getParent(e.target, 'details')) {
  25074. e.preventDefault();
  25075. }
  25076. });
  25077. };
  25078. var filterDetails = function (editor) {
  25079. editor.parser.addNodeFilter('details', function (elms) {
  25080. each$k(elms, function (details) {
  25081. details.attr('data-mce-open', details.attr('open'));
  25082. details.attr('open', 'open');
  25083. });
  25084. });
  25085. editor.serializer.addNodeFilter('details', function (elms) {
  25086. each$k(elms, function (details) {
  25087. var open = details.attr('data-mce-open');
  25088. details.attr('open', isString$1(open) ? open : null);
  25089. details.attr('data-mce-open', null);
  25090. });
  25091. });
  25092. };
  25093. var setup$3 = function (editor) {
  25094. preventSummaryToggle(editor);
  25095. filterDetails(editor);
  25096. };
  25097. var isTextBlockNode = function (node) {
  25098. return isElement$5(node) && isTextBlock$2(SugarElement.fromDom(node));
  25099. };
  25100. var normalizeSelection = function (editor) {
  25101. var rng = editor.selection.getRng();
  25102. var startPos = CaretPosition.fromRangeStart(rng);
  25103. var endPos = CaretPosition.fromRangeEnd(rng);
  25104. if (CaretPosition.isElementPosition(startPos)) {
  25105. var container = startPos.container();
  25106. if (isTextBlockNode(container)) {
  25107. firstPositionIn(container).each(function (pos) {
  25108. return rng.setStart(pos.container(), pos.offset());
  25109. });
  25110. }
  25111. }
  25112. if (CaretPosition.isElementPosition(endPos)) {
  25113. var container = startPos.container();
  25114. if (isTextBlockNode(container)) {
  25115. lastPositionIn(container).each(function (pos) {
  25116. return rng.setEnd(pos.container(), pos.offset());
  25117. });
  25118. }
  25119. }
  25120. editor.selection.setRng(normalize(rng));
  25121. };
  25122. var setup$2 = function (editor) {
  25123. editor.on('click', function (e) {
  25124. if (e.detail >= 3) {
  25125. normalizeSelection(editor);
  25126. }
  25127. });
  25128. };
  25129. var getAbsolutePosition = function (elm) {
  25130. var clientRect = elm.getBoundingClientRect();
  25131. var doc = elm.ownerDocument;
  25132. var docElem = doc.documentElement;
  25133. var win = doc.defaultView;
  25134. return {
  25135. top: clientRect.top + win.pageYOffset - docElem.clientTop,
  25136. left: clientRect.left + win.pageXOffset - docElem.clientLeft
  25137. };
  25138. };
  25139. var getBodyPosition = function (editor) {
  25140. return editor.inline ? getAbsolutePosition(editor.getBody()) : {
  25141. left: 0,
  25142. top: 0
  25143. };
  25144. };
  25145. var getScrollPosition = function (editor) {
  25146. var body = editor.getBody();
  25147. return editor.inline ? {
  25148. left: body.scrollLeft,
  25149. top: body.scrollTop
  25150. } : {
  25151. left: 0,
  25152. top: 0
  25153. };
  25154. };
  25155. var getBodyScroll = function (editor) {
  25156. var body = editor.getBody(), docElm = editor.getDoc().documentElement;
  25157. var inlineScroll = {
  25158. left: body.scrollLeft,
  25159. top: body.scrollTop
  25160. };
  25161. var iframeScroll = {
  25162. left: body.scrollLeft || docElm.scrollLeft,
  25163. top: body.scrollTop || docElm.scrollTop
  25164. };
  25165. return editor.inline ? inlineScroll : iframeScroll;
  25166. };
  25167. var getMousePosition = function (editor, event) {
  25168. if (event.target.ownerDocument !== editor.getDoc()) {
  25169. var iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
  25170. var scrollPosition = getBodyScroll(editor);
  25171. return {
  25172. left: event.pageX - iframePosition.left + scrollPosition.left,
  25173. top: event.pageY - iframePosition.top + scrollPosition.top
  25174. };
  25175. }
  25176. return {
  25177. left: event.pageX,
  25178. top: event.pageY
  25179. };
  25180. };
  25181. var calculatePosition = function (bodyPosition, scrollPosition, mousePosition) {
  25182. return {
  25183. pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
  25184. pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
  25185. };
  25186. };
  25187. var calc = function (editor, event) {
  25188. return calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
  25189. };
  25190. var isContentEditableFalse$1 = isContentEditableFalse$b, isContentEditableTrue$1 = isContentEditableTrue$4;
  25191. var isDraggable = function (rootElm, elm) {
  25192. return isContentEditableFalse$1(elm) && elm !== rootElm;
  25193. };
  25194. var isValidDropTarget = function (editor, targetElement, dragElement) {
  25195. if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
  25196. return false;
  25197. }
  25198. return !isContentEditableFalse$1(targetElement);
  25199. };
  25200. var cloneElement = function (elm) {
  25201. var cloneElm = elm.cloneNode(true);
  25202. cloneElm.removeAttribute('data-mce-selected');
  25203. return cloneElm;
  25204. };
  25205. var createGhost = function (editor, elm, width, height) {
  25206. var dom = editor.dom;
  25207. var clonedElm = elm.cloneNode(true);
  25208. dom.setStyles(clonedElm, {
  25209. width: width,
  25210. height: height
  25211. });
  25212. dom.setAttrib(clonedElm, 'data-mce-selected', null);
  25213. var ghostElm = dom.create('div', {
  25214. 'class': 'mce-drag-container',
  25215. 'data-mce-bogus': 'all',
  25216. 'unselectable': 'on',
  25217. 'contenteditable': 'false'
  25218. });
  25219. dom.setStyles(ghostElm, {
  25220. position: 'absolute',
  25221. opacity: 0.5,
  25222. overflow: 'hidden',
  25223. border: 0,
  25224. padding: 0,
  25225. margin: 0,
  25226. width: width,
  25227. height: height
  25228. });
  25229. dom.setStyles(clonedElm, {
  25230. margin: 0,
  25231. boxSizing: 'border-box'
  25232. });
  25233. ghostElm.appendChild(clonedElm);
  25234. return ghostElm;
  25235. };
  25236. var appendGhostToBody = function (ghostElm, bodyElm) {
  25237. if (ghostElm.parentNode !== bodyElm) {
  25238. bodyElm.appendChild(ghostElm);
  25239. }
  25240. };
  25241. var moveGhost = function (ghostElm, position, width, height, maxX, maxY) {
  25242. var overflowX = 0, overflowY = 0;
  25243. ghostElm.style.left = position.pageX + 'px';
  25244. ghostElm.style.top = position.pageY + 'px';
  25245. if (position.pageX + width > maxX) {
  25246. overflowX = position.pageX + width - maxX;
  25247. }
  25248. if (position.pageY + height > maxY) {
  25249. overflowY = position.pageY + height - maxY;
  25250. }
  25251. ghostElm.style.width = width - overflowX + 'px';
  25252. ghostElm.style.height = height - overflowY + 'px';
  25253. };
  25254. var removeElement = function (elm) {
  25255. if (elm && elm.parentNode) {
  25256. elm.parentNode.removeChild(elm);
  25257. }
  25258. };
  25259. var isLeftMouseButtonPressed = function (e) {
  25260. return e.button === 0;
  25261. };
  25262. var applyRelPos = function (state, position) {
  25263. return {
  25264. pageX: position.pageX - state.relX,
  25265. pageY: position.pageY + 5
  25266. };
  25267. };
  25268. var start = function (state, editor) {
  25269. return function (e) {
  25270. if (isLeftMouseButtonPressed(e)) {
  25271. var ceElm = find$3(editor.dom.getParents(e.target), or(isContentEditableFalse$1, isContentEditableTrue$1)).getOr(null);
  25272. if (isDraggable(editor.getBody(), ceElm)) {
  25273. var elmPos = editor.dom.getPos(ceElm);
  25274. var bodyElm = editor.getBody();
  25275. var docElm = editor.getDoc().documentElement;
  25276. state.set({
  25277. element: ceElm,
  25278. dragging: false,
  25279. screenX: e.screenX,
  25280. screenY: e.screenY,
  25281. maxX: (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2,
  25282. maxY: (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2,
  25283. relX: e.pageX - elmPos.x,
  25284. relY: e.pageY - elmPos.y,
  25285. width: ceElm.offsetWidth,
  25286. height: ceElm.offsetHeight,
  25287. ghost: createGhost(editor, ceElm, ceElm.offsetWidth, ceElm.offsetHeight)
  25288. });
  25289. }
  25290. }
  25291. };
  25292. };
  25293. var move = function (state, editor) {
  25294. var throttledPlaceCaretAt = Delay.throttle(function (clientX, clientY) {
  25295. editor._selectionOverrides.hideFakeCaret();
  25296. editor.selection.placeCaretAt(clientX, clientY);
  25297. }, 0);
  25298. editor.on('remove', throttledPlaceCaretAt.stop);
  25299. return function (e) {
  25300. return state.on(function (state) {
  25301. var movement = Math.max(Math.abs(e.screenX - state.screenX), Math.abs(e.screenY - state.screenY));
  25302. if (!state.dragging && movement > 10) {
  25303. var args = editor.fire('dragstart', { target: state.element });
  25304. if (args.isDefaultPrevented()) {
  25305. return;
  25306. }
  25307. state.dragging = true;
  25308. editor.focus();
  25309. }
  25310. if (state.dragging) {
  25311. var targetPos = applyRelPos(state, calc(editor, e));
  25312. appendGhostToBody(state.ghost, editor.getBody());
  25313. moveGhost(state.ghost, targetPos, state.width, state.height, state.maxX, state.maxY);
  25314. throttledPlaceCaretAt(e.clientX, e.clientY);
  25315. }
  25316. });
  25317. };
  25318. };
  25319. var getRawTarget = function (selection) {
  25320. var rng = selection.getSel().getRangeAt(0);
  25321. var startContainer = rng.startContainer;
  25322. return startContainer.nodeType === 3 ? startContainer.parentNode : startContainer;
  25323. };
  25324. var drop = function (state, editor) {
  25325. return function (e) {
  25326. state.on(function (state) {
  25327. if (state.dragging) {
  25328. if (isValidDropTarget(editor, getRawTarget(editor.selection), state.element)) {
  25329. var targetClone_1 = cloneElement(state.element);
  25330. var args = editor.fire('drop', {
  25331. clientX: e.clientX,
  25332. clientY: e.clientY
  25333. });
  25334. if (!args.isDefaultPrevented()) {
  25335. editor.undoManager.transact(function () {
  25336. removeElement(state.element);
  25337. editor.insertContent(editor.dom.getOuterHTML(targetClone_1));
  25338. editor._selectionOverrides.hideFakeCaret();
  25339. });
  25340. }
  25341. }
  25342. }
  25343. });
  25344. removeDragState(state);
  25345. };
  25346. };
  25347. var stop = function (state, editor) {
  25348. return function () {
  25349. state.on(function (state) {
  25350. if (state.dragging) {
  25351. editor.fire('dragend');
  25352. }
  25353. });
  25354. removeDragState(state);
  25355. };
  25356. };
  25357. var removeDragState = function (state) {
  25358. state.on(function (state) {
  25359. removeElement(state.ghost);
  25360. });
  25361. state.clear();
  25362. };
  25363. var bindFakeDragEvents = function (editor) {
  25364. var state = value();
  25365. var pageDom = DOMUtils.DOM;
  25366. var rootDocument = document;
  25367. var dragStartHandler = start(state, editor);
  25368. var dragHandler = move(state, editor);
  25369. var dropHandler = drop(state, editor);
  25370. var dragEndHandler = stop(state, editor);
  25371. editor.on('mousedown', dragStartHandler);
  25372. editor.on('mousemove', dragHandler);
  25373. editor.on('mouseup', dropHandler);
  25374. pageDom.bind(rootDocument, 'mousemove', dragHandler);
  25375. pageDom.bind(rootDocument, 'mouseup', dragEndHandler);
  25376. editor.on('remove', function () {
  25377. pageDom.unbind(rootDocument, 'mousemove', dragHandler);
  25378. pageDom.unbind(rootDocument, 'mouseup', dragEndHandler);
  25379. });
  25380. };
  25381. var blockIeDrop = function (editor) {
  25382. editor.on('drop', function (e) {
  25383. var realTarget = typeof e.clientX !== 'undefined' ? editor.getDoc().elementFromPoint(e.clientX, e.clientY) : null;
  25384. if (isContentEditableFalse$1(realTarget) || editor.dom.getContentEditableParent(realTarget) === 'false') {
  25385. e.preventDefault();
  25386. }
  25387. });
  25388. };
  25389. var blockUnsupportedFileDrop = function (editor) {
  25390. var preventFileDrop = function (e) {
  25391. if (!e.isDefaultPrevented()) {
  25392. var dataTransfer = e.dataTransfer;
  25393. if (dataTransfer && (contains$3(dataTransfer.types, 'Files') || dataTransfer.files.length > 0)) {
  25394. e.preventDefault();
  25395. if (e.type === 'drop') {
  25396. displayError(editor, 'Dropped file type is not supported');
  25397. }
  25398. }
  25399. }
  25400. };
  25401. var preventFileDropIfUIElement = function (e) {
  25402. if (isUIElement(editor, e.target)) {
  25403. preventFileDrop(e);
  25404. }
  25405. };
  25406. var setup = function () {
  25407. var pageDom = DOMUtils.DOM;
  25408. var dom = editor.dom;
  25409. var doc = document;
  25410. var editorRoot = editor.inline ? editor.getBody() : editor.getDoc();
  25411. var eventNames = [
  25412. 'drop',
  25413. 'dragover'
  25414. ];
  25415. each$k(eventNames, function (name) {
  25416. pageDom.bind(doc, name, preventFileDropIfUIElement);
  25417. dom.bind(editorRoot, name, preventFileDrop);
  25418. });
  25419. editor.on('remove', function () {
  25420. each$k(eventNames, function (name) {
  25421. pageDom.unbind(doc, name, preventFileDropIfUIElement);
  25422. dom.unbind(editorRoot, name, preventFileDrop);
  25423. });
  25424. });
  25425. };
  25426. editor.on('init', function () {
  25427. Delay.setEditorTimeout(editor, setup, 0);
  25428. });
  25429. };
  25430. var init$2 = function (editor) {
  25431. bindFakeDragEvents(editor);
  25432. blockIeDrop(editor);
  25433. if (shouldBlockUnsupportedDrop(editor)) {
  25434. blockUnsupportedFileDrop(editor);
  25435. }
  25436. };
  25437. var setup$1 = function (editor) {
  25438. var renderFocusCaret = first(function () {
  25439. if (!editor.removed && editor.getBody().contains(document.activeElement)) {
  25440. var rng = editor.selection.getRng();
  25441. if (rng.collapsed) {
  25442. var caretRange = renderRangeCaret(editor, rng, false);
  25443. editor.selection.setRng(caretRange);
  25444. }
  25445. }
  25446. }, 0);
  25447. editor.on('focus', function () {
  25448. renderFocusCaret.throttle();
  25449. });
  25450. editor.on('blur', function () {
  25451. renderFocusCaret.cancel();
  25452. });
  25453. };
  25454. var setup = function (editor) {
  25455. editor.on('init', function () {
  25456. editor.on('focusin', function (e) {
  25457. var target = e.target;
  25458. if (isMedia$2(target)) {
  25459. var ceRoot = getContentEditableRoot$1(editor.getBody(), target);
  25460. var node = isContentEditableFalse$b(ceRoot) ? ceRoot : target;
  25461. if (editor.selection.getNode() !== node) {
  25462. selectNode(editor, node).each(function (rng) {
  25463. return editor.selection.setRng(rng);
  25464. });
  25465. }
  25466. }
  25467. });
  25468. });
  25469. };
  25470. var isContentEditableTrue = isContentEditableTrue$4;
  25471. var isContentEditableFalse = isContentEditableFalse$b;
  25472. var getContentEditableRoot = function (editor, node) {
  25473. return getContentEditableRoot$1(editor.getBody(), node);
  25474. };
  25475. var SelectionOverrides = function (editor) {
  25476. var selection = editor.selection, dom = editor.dom;
  25477. var isBlock = dom.isBlock;
  25478. var rootNode = editor.getBody();
  25479. var fakeCaret = FakeCaret(editor, rootNode, isBlock, function () {
  25480. return hasFocus(editor);
  25481. });
  25482. var realSelectionId = 'sel-' + dom.uniqueId();
  25483. var elementSelectionAttr = 'data-mce-selected';
  25484. var selectedElement;
  25485. var isFakeSelectionElement = function (node) {
  25486. return dom.hasClass(node, 'mce-offscreen-selection');
  25487. };
  25488. var isFakeSelectionTargetElement = function (node) {
  25489. return node !== rootNode && (isContentEditableFalse(node) || isMedia$2(node)) && dom.isChildOf(node, rootNode);
  25490. };
  25491. var isNearFakeSelectionElement = function (pos) {
  25492. return isBeforeContentEditableFalse(pos) || isAfterContentEditableFalse(pos) || isBeforeMedia(pos) || isAfterMedia(pos);
  25493. };
  25494. var getRealSelectionElement = function () {
  25495. var container = dom.get(realSelectionId);
  25496. return container ? container.getElementsByTagName('*')[0] : container;
  25497. };
  25498. var setRange = function (range) {
  25499. if (range) {
  25500. selection.setRng(range);
  25501. }
  25502. };
  25503. var getRange = selection.getRng;
  25504. var showCaret = function (direction, node, before, scrollIntoView) {
  25505. if (scrollIntoView === void 0) {
  25506. scrollIntoView = true;
  25507. }
  25508. var e = editor.fire('ShowCaret', {
  25509. target: node,
  25510. direction: direction,
  25511. before: before
  25512. });
  25513. if (e.isDefaultPrevented()) {
  25514. return null;
  25515. }
  25516. if (scrollIntoView) {
  25517. selection.scrollIntoView(node, direction === -1);
  25518. }
  25519. return fakeCaret.show(before, node);
  25520. };
  25521. var showBlockCaretContainer = function (blockCaretContainer) {
  25522. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  25523. showCaretContainerBlock(blockCaretContainer);
  25524. setRange(getRange());
  25525. selection.scrollIntoView(blockCaretContainer);
  25526. }
  25527. };
  25528. var registerEvents = function () {
  25529. editor.on('mouseup', function (e) {
  25530. var range = getRange();
  25531. if (range.collapsed && isXYInContentArea(editor, e.clientX, e.clientY)) {
  25532. renderCaretAtRange(editor, range, false).each(setRange);
  25533. }
  25534. });
  25535. editor.on('click', function (e) {
  25536. var contentEditableRoot = getContentEditableRoot(editor, e.target);
  25537. if (contentEditableRoot) {
  25538. if (isContentEditableFalse(contentEditableRoot)) {
  25539. e.preventDefault();
  25540. editor.focus();
  25541. }
  25542. if (isContentEditableTrue(contentEditableRoot)) {
  25543. if (dom.isChildOf(contentEditableRoot, selection.getNode())) {
  25544. removeElementSelection();
  25545. }
  25546. }
  25547. }
  25548. });
  25549. editor.on('blur NewBlock', removeElementSelection);
  25550. editor.on('ResizeWindow FullscreenStateChanged', fakeCaret.reposition);
  25551. var hasNormalCaretPosition = function (elm) {
  25552. var caretWalker = CaretWalker(elm);
  25553. if (!elm.firstChild) {
  25554. return false;
  25555. }
  25556. var startPos = CaretPosition.before(elm.firstChild);
  25557. var newPos = caretWalker.next(startPos);
  25558. return newPos && !isNearFakeSelectionElement(newPos);
  25559. };
  25560. var isInSameBlock = function (node1, node2) {
  25561. var block1 = dom.getParent(node1, isBlock);
  25562. var block2 = dom.getParent(node2, isBlock);
  25563. return block1 === block2;
  25564. };
  25565. var hasBetterMouseTarget = function (targetNode, caretNode) {
  25566. var targetBlock = dom.getParent(targetNode, isBlock);
  25567. var caretBlock = dom.getParent(caretNode, isBlock);
  25568. if (targetBlock && targetNode !== caretBlock && dom.isChildOf(targetBlock, caretBlock) && isContentEditableFalse(getContentEditableRoot(editor, targetBlock)) === false) {
  25569. return true;
  25570. }
  25571. return targetBlock && !isInSameBlock(targetBlock, caretBlock) && hasNormalCaretPosition(targetBlock);
  25572. };
  25573. editor.on('tap', function (e) {
  25574. var targetElm = e.target;
  25575. var contentEditableRoot = getContentEditableRoot(editor, targetElm);
  25576. if (isContentEditableFalse(contentEditableRoot)) {
  25577. e.preventDefault();
  25578. selectNode(editor, contentEditableRoot).each(setElementSelection);
  25579. } else if (isFakeSelectionTargetElement(targetElm)) {
  25580. selectNode(editor, targetElm).each(setElementSelection);
  25581. }
  25582. }, true);
  25583. editor.on('mousedown', function (e) {
  25584. var targetElm = e.target;
  25585. if (targetElm !== rootNode && targetElm.nodeName !== 'HTML' && !dom.isChildOf(targetElm, rootNode)) {
  25586. return;
  25587. }
  25588. if (isXYInContentArea(editor, e.clientX, e.clientY) === false) {
  25589. return;
  25590. }
  25591. var contentEditableRoot = getContentEditableRoot(editor, targetElm);
  25592. if (contentEditableRoot) {
  25593. if (isContentEditableFalse(contentEditableRoot)) {
  25594. e.preventDefault();
  25595. selectNode(editor, contentEditableRoot).each(setElementSelection);
  25596. } else {
  25597. removeElementSelection();
  25598. if (!(isContentEditableTrue(contentEditableRoot) && e.shiftKey) && !isXYWithinRange(e.clientX, e.clientY, selection.getRng())) {
  25599. hideFakeCaret();
  25600. selection.placeCaretAt(e.clientX, e.clientY);
  25601. }
  25602. }
  25603. } else if (isFakeSelectionTargetElement(targetElm)) {
  25604. selectNode(editor, targetElm).each(setElementSelection);
  25605. } else if (isFakeCaretTarget(targetElm) === false) {
  25606. removeElementSelection();
  25607. hideFakeCaret();
  25608. var fakeCaretInfo = closestFakeCaret(rootNode, e.clientX, e.clientY);
  25609. if (fakeCaretInfo) {
  25610. if (!hasBetterMouseTarget(targetElm, fakeCaretInfo.node)) {
  25611. e.preventDefault();
  25612. var range = showCaret(1, fakeCaretInfo.node, fakeCaretInfo.before, false);
  25613. editor.getBody().focus();
  25614. setRange(range);
  25615. }
  25616. }
  25617. }
  25618. });
  25619. editor.on('keypress', function (e) {
  25620. if (VK.modifierPressed(e)) {
  25621. return;
  25622. }
  25623. if (isContentEditableFalse(selection.getNode())) {
  25624. e.preventDefault();
  25625. }
  25626. });
  25627. editor.on('GetSelectionRange', function (e) {
  25628. var rng = e.range;
  25629. if (selectedElement) {
  25630. if (!selectedElement.parentNode) {
  25631. selectedElement = null;
  25632. return;
  25633. }
  25634. rng = rng.cloneRange();
  25635. rng.selectNode(selectedElement);
  25636. e.range = rng;
  25637. }
  25638. });
  25639. editor.on('SetSelectionRange', function (e) {
  25640. e.range = normalizeShortEndedElementSelection(e.range);
  25641. var rng = setElementSelection(e.range, e.forward);
  25642. if (rng) {
  25643. e.range = rng;
  25644. }
  25645. });
  25646. var isPasteBin = function (node) {
  25647. return node.id === 'mcepastebin';
  25648. };
  25649. editor.on('AfterSetSelectionRange', function (e) {
  25650. var rng = e.range;
  25651. var parentNode = rng.startContainer.parentNode;
  25652. if (!isRangeInCaretContainer(rng) && !isPasteBin(parentNode)) {
  25653. hideFakeCaret();
  25654. }
  25655. if (!isFakeSelectionElement(parentNode)) {
  25656. removeElementSelection();
  25657. }
  25658. });
  25659. editor.on('copy', function (e) {
  25660. var clipboardData = e.clipboardData;
  25661. if (!e.isDefaultPrevented() && e.clipboardData && !Env.ie) {
  25662. var realSelectionElement = getRealSelectionElement();
  25663. if (realSelectionElement) {
  25664. e.preventDefault();
  25665. clipboardData.clearData();
  25666. clipboardData.setData('text/html', realSelectionElement.outerHTML);
  25667. clipboardData.setData('text/plain', realSelectionElement.outerText || realSelectionElement.innerText);
  25668. }
  25669. }
  25670. });
  25671. init$2(editor);
  25672. setup$1(editor);
  25673. setup(editor);
  25674. };
  25675. var isWithinCaretContainer = function (node) {
  25676. return isCaretContainer$2(node) || startsWithCaretContainer$1(node) || endsWithCaretContainer$1(node);
  25677. };
  25678. var isRangeInCaretContainer = function (rng) {
  25679. return isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
  25680. };
  25681. var normalizeShortEndedElementSelection = function (rng) {
  25682. var shortEndedElements = editor.schema.getShortEndedElements();
  25683. var newRng = dom.createRng();
  25684. var startContainer = rng.startContainer;
  25685. var startOffset = rng.startOffset;
  25686. var endContainer = rng.endContainer;
  25687. var endOffset = rng.endOffset;
  25688. if (has$2(shortEndedElements, startContainer.nodeName.toLowerCase())) {
  25689. if (startOffset === 0) {
  25690. newRng.setStartBefore(startContainer);
  25691. } else {
  25692. newRng.setStartAfter(startContainer);
  25693. }
  25694. } else {
  25695. newRng.setStart(startContainer, startOffset);
  25696. }
  25697. if (has$2(shortEndedElements, endContainer.nodeName.toLowerCase())) {
  25698. if (endOffset === 0) {
  25699. newRng.setEndBefore(endContainer);
  25700. } else {
  25701. newRng.setEndAfter(endContainer);
  25702. }
  25703. } else {
  25704. newRng.setEnd(endContainer, endOffset);
  25705. }
  25706. return newRng;
  25707. };
  25708. var setupOffscreenSelection = function (node, targetClone, origTargetClone) {
  25709. var $ = editor.$;
  25710. var $realSelectionContainer = descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).fold(function () {
  25711. return $([]);
  25712. }, function (elm) {
  25713. return $([elm.dom]);
  25714. });
  25715. if ($realSelectionContainer.length === 0) {
  25716. $realSelectionContainer = $('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>').attr('id', realSelectionId);
  25717. $realSelectionContainer.appendTo(editor.getBody());
  25718. }
  25719. var newRange = dom.createRng();
  25720. if (targetClone === origTargetClone && Env.ie) {
  25721. $realSelectionContainer.empty().append('<p style="font-size: 0" data-mce-bogus="all">\xA0</p>').append(targetClone);
  25722. newRange.setStartAfter($realSelectionContainer[0].firstChild.firstChild);
  25723. newRange.setEndAfter(targetClone);
  25724. } else {
  25725. $realSelectionContainer.empty().append(nbsp).append(targetClone).append(nbsp);
  25726. newRange.setStart($realSelectionContainer[0].firstChild, 1);
  25727. newRange.setEnd($realSelectionContainer[0].lastChild, 0);
  25728. }
  25729. $realSelectionContainer.css({ top: dom.getPos(node, editor.getBody()).y });
  25730. $realSelectionContainer[0].focus();
  25731. var sel = selection.getSel();
  25732. sel.removeAllRanges();
  25733. sel.addRange(newRange);
  25734. return newRange;
  25735. };
  25736. var selectElement = function (elm) {
  25737. var targetClone = elm.cloneNode(true);
  25738. var e = editor.fire('ObjectSelected', {
  25739. target: elm,
  25740. targetClone: targetClone
  25741. });
  25742. if (e.isDefaultPrevented()) {
  25743. return null;
  25744. }
  25745. var range = setupOffscreenSelection(elm, e.targetClone, targetClone);
  25746. var nodeElm = SugarElement.fromDom(elm);
  25747. each$k(descendants(SugarElement.fromDom(editor.getBody()), '*[data-mce-selected]'), function (elm) {
  25748. if (!eq(nodeElm, elm)) {
  25749. remove$6(elm, elementSelectionAttr);
  25750. }
  25751. });
  25752. if (!dom.getAttrib(elm, elementSelectionAttr)) {
  25753. elm.setAttribute(elementSelectionAttr, '1');
  25754. }
  25755. selectedElement = elm;
  25756. hideFakeCaret();
  25757. return range;
  25758. };
  25759. var setElementSelection = function (range, forward) {
  25760. if (!range) {
  25761. return null;
  25762. }
  25763. if (range.collapsed) {
  25764. if (!isRangeInCaretContainer(range)) {
  25765. var dir = forward ? 1 : -1;
  25766. var caretPosition = getNormalizedRangeEndPoint(dir, rootNode, range);
  25767. var beforeNode = caretPosition.getNode(!forward);
  25768. if (isFakeCaretTarget(beforeNode)) {
  25769. return showCaret(dir, beforeNode, forward ? !caretPosition.isAtEnd() : false, false);
  25770. }
  25771. var afterNode = caretPosition.getNode(forward);
  25772. if (isFakeCaretTarget(afterNode)) {
  25773. return showCaret(dir, afterNode, forward ? false : !caretPosition.isAtEnd(), false);
  25774. }
  25775. }
  25776. return null;
  25777. }
  25778. var startContainer = range.startContainer;
  25779. var startOffset = range.startOffset;
  25780. var endOffset = range.endOffset;
  25781. if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse(startContainer.parentNode)) {
  25782. startContainer = startContainer.parentNode;
  25783. startOffset = dom.nodeIndex(startContainer);
  25784. startContainer = startContainer.parentNode;
  25785. }
  25786. if (startContainer.nodeType !== 1) {
  25787. return null;
  25788. }
  25789. if (endOffset === startOffset + 1 && startContainer === range.endContainer) {
  25790. var node = startContainer.childNodes[startOffset];
  25791. if (isFakeSelectionTargetElement(node)) {
  25792. return selectElement(node);
  25793. }
  25794. }
  25795. return null;
  25796. };
  25797. var removeElementSelection = function () {
  25798. if (selectedElement) {
  25799. selectedElement.removeAttribute(elementSelectionAttr);
  25800. }
  25801. descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).each(remove$7);
  25802. selectedElement = null;
  25803. };
  25804. var destroy = function () {
  25805. fakeCaret.destroy();
  25806. selectedElement = null;
  25807. };
  25808. var hideFakeCaret = function () {
  25809. fakeCaret.hide();
  25810. };
  25811. if (Env.ceFalse && !isRtc(editor)) {
  25812. registerEvents();
  25813. }
  25814. return {
  25815. showCaret: showCaret,
  25816. showBlockCaretContainer: showBlockCaretContainer,
  25817. hideFakeCaret: hideFakeCaret,
  25818. destroy: destroy
  25819. };
  25820. };
  25821. var Quirks = function (editor) {
  25822. var each = Tools.each;
  25823. var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, parser = editor.parser;
  25824. var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit;
  25825. var mceInternalUrlPrefix = 'data:text/mce-internal,';
  25826. var mceInternalDataType = isIE ? 'Text' : 'URL';
  25827. var setEditorCommandState = function (cmd, state) {
  25828. try {
  25829. editor.getDoc().execCommand(cmd, false, state);
  25830. } catch (ex) {
  25831. }
  25832. };
  25833. var isDefaultPrevented = function (e) {
  25834. return e.isDefaultPrevented();
  25835. };
  25836. var setMceInternalContent = function (e) {
  25837. var selectionHtml, internalContent;
  25838. if (e.dataTransfer) {
  25839. if (editor.selection.isCollapsed() && e.target.tagName === 'IMG') {
  25840. selection.select(e.target);
  25841. }
  25842. selectionHtml = editor.selection.getContent();
  25843. if (selectionHtml.length > 0) {
  25844. internalContent = mceInternalUrlPrefix + escape(editor.id) + ',' + escape(selectionHtml);
  25845. e.dataTransfer.setData(mceInternalDataType, internalContent);
  25846. }
  25847. }
  25848. };
  25849. var getMceInternalContent = function (e) {
  25850. var internalContent;
  25851. if (e.dataTransfer) {
  25852. internalContent = e.dataTransfer.getData(mceInternalDataType);
  25853. if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) {
  25854. internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(',');
  25855. return {
  25856. id: unescape(internalContent[0]),
  25857. html: unescape(internalContent[1])
  25858. };
  25859. }
  25860. }
  25861. return null;
  25862. };
  25863. var insertClipboardContents = function (content, internal) {
  25864. if (editor.queryCommandSupported('mceInsertClipboardContent')) {
  25865. editor.execCommand('mceInsertClipboardContent', false, {
  25866. content: content,
  25867. internal: internal
  25868. });
  25869. } else {
  25870. editor.execCommand('mceInsertContent', false, content);
  25871. }
  25872. };
  25873. var emptyEditorWhenDeleting = function () {
  25874. var serializeRng = function (rng) {
  25875. var body = dom.create('body');
  25876. var contents = rng.cloneContents();
  25877. body.appendChild(contents);
  25878. return selection.serializer.serialize(body, { format: 'html' });
  25879. };
  25880. var allContentsSelected = function (rng) {
  25881. var selection = serializeRng(rng);
  25882. var allRng = dom.createRng();
  25883. allRng.selectNode(editor.getBody());
  25884. var allSelection = serializeRng(allRng);
  25885. return selection === allSelection;
  25886. };
  25887. editor.on('keydown', function (e) {
  25888. var keyCode = e.keyCode;
  25889. var isCollapsed, body;
  25890. if (!isDefaultPrevented(e) && (keyCode === DELETE || keyCode === BACKSPACE)) {
  25891. isCollapsed = editor.selection.isCollapsed();
  25892. body = editor.getBody();
  25893. if (isCollapsed && !dom.isEmpty(body)) {
  25894. return;
  25895. }
  25896. if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
  25897. return;
  25898. }
  25899. e.preventDefault();
  25900. editor.setContent('');
  25901. if (body.firstChild && dom.isBlock(body.firstChild)) {
  25902. editor.selection.setCursorLocation(body.firstChild, 0);
  25903. } else {
  25904. editor.selection.setCursorLocation(body, 0);
  25905. }
  25906. editor.nodeChanged();
  25907. }
  25908. });
  25909. };
  25910. var selectAll = function () {
  25911. editor.shortcuts.add('meta+a', null, 'SelectAll');
  25912. };
  25913. var documentElementEditingFocus = function () {
  25914. if (!editor.inline) {
  25915. dom.bind(editor.getDoc(), 'mousedown mouseup', function (e) {
  25916. var rng;
  25917. if (e.target === editor.getDoc().documentElement) {
  25918. rng = selection.getRng();
  25919. editor.getBody().focus();
  25920. if (e.type === 'mousedown') {
  25921. if (isCaretContainer$2(rng.startContainer)) {
  25922. return;
  25923. }
  25924. selection.placeCaretAt(e.clientX, e.clientY);
  25925. } else {
  25926. selection.setRng(rng);
  25927. }
  25928. }
  25929. });
  25930. }
  25931. };
  25932. var removeHrOnBackspace = function () {
  25933. editor.on('keydown', function (e) {
  25934. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25935. if (!editor.getBody().getElementsByTagName('hr').length) {
  25936. return;
  25937. }
  25938. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25939. var node = selection.getNode();
  25940. var previousSibling = node.previousSibling;
  25941. if (node.nodeName === 'HR') {
  25942. dom.remove(node);
  25943. e.preventDefault();
  25944. return;
  25945. }
  25946. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'hr') {
  25947. dom.remove(previousSibling);
  25948. e.preventDefault();
  25949. }
  25950. }
  25951. }
  25952. });
  25953. };
  25954. var focusBody = function () {
  25955. if (!Range.prototype.getClientRects) {
  25956. editor.on('mousedown', function (e) {
  25957. if (!isDefaultPrevented(e) && e.target.nodeName === 'HTML') {
  25958. var body_1 = editor.getBody();
  25959. body_1.blur();
  25960. Delay.setEditorTimeout(editor, function () {
  25961. body_1.focus();
  25962. });
  25963. }
  25964. });
  25965. }
  25966. };
  25967. var selectControlElements = function () {
  25968. editor.on('click', function (e) {
  25969. var target = e.target;
  25970. if (/^(IMG|HR)$/.test(target.nodeName) && dom.getContentEditableParent(target) !== 'false') {
  25971. e.preventDefault();
  25972. editor.selection.select(target);
  25973. editor.nodeChanged();
  25974. }
  25975. if (target.nodeName === 'A' && dom.hasClass(target, 'mce-item-anchor')) {
  25976. e.preventDefault();
  25977. selection.select(target);
  25978. }
  25979. });
  25980. };
  25981. var removeStylesWhenDeletingAcrossBlockElements = function () {
  25982. var getAttributeApplyFunction = function () {
  25983. var template = dom.getAttribs(selection.getStart().cloneNode(false));
  25984. return function () {
  25985. var target = selection.getStart();
  25986. if (target !== editor.getBody()) {
  25987. dom.setAttrib(target, 'style', null);
  25988. each(template, function (attr) {
  25989. target.setAttributeNode(attr.cloneNode(true));
  25990. });
  25991. }
  25992. };
  25993. };
  25994. var isSelectionAcrossElements = function () {
  25995. return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock);
  25996. };
  25997. editor.on('keypress', function (e) {
  25998. var applyAttributes;
  25999. if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) {
  26000. applyAttributes = getAttributeApplyFunction();
  26001. editor.getDoc().execCommand('delete', false, null);
  26002. applyAttributes();
  26003. e.preventDefault();
  26004. return false;
  26005. }
  26006. });
  26007. dom.bind(editor.getDoc(), 'cut', function (e) {
  26008. var applyAttributes;
  26009. if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
  26010. applyAttributes = getAttributeApplyFunction();
  26011. Delay.setEditorTimeout(editor, function () {
  26012. applyAttributes();
  26013. });
  26014. }
  26015. });
  26016. };
  26017. var disableBackspaceIntoATable = function () {
  26018. editor.on('keydown', function (e) {
  26019. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  26020. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  26021. var previousSibling = selection.getNode().previousSibling;
  26022. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'table') {
  26023. e.preventDefault();
  26024. return false;
  26025. }
  26026. }
  26027. }
  26028. });
  26029. };
  26030. var removeBlockQuoteOnBackSpace = function () {
  26031. editor.on('keydown', function (e) {
  26032. var rng, parent;
  26033. if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) {
  26034. return;
  26035. }
  26036. rng = selection.getRng();
  26037. var container = rng.startContainer;
  26038. var offset = rng.startOffset;
  26039. var root = dom.getRoot();
  26040. parent = container;
  26041. if (!rng.collapsed || offset !== 0) {
  26042. return;
  26043. }
  26044. while (parent && parent.parentNode && parent.parentNode.firstChild === parent && parent.parentNode !== root) {
  26045. parent = parent.parentNode;
  26046. }
  26047. if (parent.tagName === 'BLOCKQUOTE') {
  26048. editor.formatter.toggle('blockquote', null, parent);
  26049. rng = dom.createRng();
  26050. rng.setStart(container, 0);
  26051. rng.setEnd(container, 0);
  26052. selection.setRng(rng);
  26053. }
  26054. });
  26055. };
  26056. var setGeckoEditingOptions = function () {
  26057. var setOpts = function () {
  26058. setEditorCommandState('StyleWithCSS', false);
  26059. setEditorCommandState('enableInlineTableEditing', false);
  26060. if (!getObjectResizing(editor)) {
  26061. setEditorCommandState('enableObjectResizing', false);
  26062. }
  26063. };
  26064. if (!isReadOnly$1(editor)) {
  26065. editor.on('BeforeExecCommand mousedown', setOpts);
  26066. }
  26067. };
  26068. var addBrAfterLastLinks = function () {
  26069. var fixLinks = function () {
  26070. each(dom.select('a'), function (node) {
  26071. var parentNode = node.parentNode;
  26072. var root = dom.getRoot();
  26073. if (parentNode.lastChild === node) {
  26074. while (parentNode && !dom.isBlock(parentNode)) {
  26075. if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
  26076. return;
  26077. }
  26078. parentNode = parentNode.parentNode;
  26079. }
  26080. dom.add(parentNode, 'br', { 'data-mce-bogus': 1 });
  26081. }
  26082. });
  26083. };
  26084. editor.on('SetContent ExecCommand', function (e) {
  26085. if (e.type === 'setcontent' || e.command === 'mceInsertLink') {
  26086. fixLinks();
  26087. }
  26088. });
  26089. };
  26090. var setDefaultBlockType = function () {
  26091. if (getForcedRootBlock(editor)) {
  26092. editor.on('init', function () {
  26093. setEditorCommandState('DefaultParagraphSeparator', getForcedRootBlock(editor));
  26094. });
  26095. }
  26096. };
  26097. var normalizeSelection = function () {
  26098. editor.on('keyup focusin mouseup', function (e) {
  26099. if (!VK.modifierPressed(e)) {
  26100. selection.normalize();
  26101. }
  26102. }, true);
  26103. };
  26104. var showBrokenImageIcon = function () {
  26105. editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}');
  26106. };
  26107. var restoreFocusOnKeyDown = function () {
  26108. if (!editor.inline) {
  26109. editor.on('keydown', function () {
  26110. if (document.activeElement === document.body) {
  26111. editor.getWin().focus();
  26112. }
  26113. });
  26114. }
  26115. };
  26116. var bodyHeight = function () {
  26117. if (!editor.inline) {
  26118. editor.contentStyles.push('body {min-height: 150px}');
  26119. editor.on('click', function (e) {
  26120. var rng;
  26121. if (e.target.nodeName === 'HTML') {
  26122. if (Env.ie > 11) {
  26123. editor.getBody().focus();
  26124. return;
  26125. }
  26126. rng = editor.selection.getRng();
  26127. editor.getBody().focus();
  26128. editor.selection.setRng(rng);
  26129. editor.selection.normalize();
  26130. editor.nodeChanged();
  26131. }
  26132. });
  26133. }
  26134. };
  26135. var blockCmdArrowNavigation = function () {
  26136. if (Env.mac) {
  26137. editor.on('keydown', function (e) {
  26138. if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) {
  26139. e.preventDefault();
  26140. var selection_1 = editor.selection.getSel();
  26141. selection_1.modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary');
  26142. }
  26143. });
  26144. }
  26145. };
  26146. var disableAutoUrlDetect = function () {
  26147. setEditorCommandState('AutoUrlDetect', false);
  26148. };
  26149. var tapLinksAndImages = function () {
  26150. editor.on('click', function (e) {
  26151. var elm = e.target;
  26152. do {
  26153. if (elm.tagName === 'A') {
  26154. e.preventDefault();
  26155. return;
  26156. }
  26157. } while (elm = elm.parentNode);
  26158. });
  26159. editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
  26160. };
  26161. var blockFormSubmitInsideEditor = function () {
  26162. editor.on('init', function () {
  26163. editor.dom.bind(editor.getBody(), 'submit', function (e) {
  26164. e.preventDefault();
  26165. });
  26166. });
  26167. };
  26168. var removeAppleInterchangeBrs = function () {
  26169. parser.addNodeFilter('br', function (nodes) {
  26170. var i = nodes.length;
  26171. while (i--) {
  26172. if (nodes[i].attr('class') === 'Apple-interchange-newline') {
  26173. nodes[i].remove();
  26174. }
  26175. }
  26176. });
  26177. };
  26178. var ieInternalDragAndDrop = function () {
  26179. editor.on('dragstart', function (e) {
  26180. setMceInternalContent(e);
  26181. });
  26182. editor.on('drop', function (e) {
  26183. if (!isDefaultPrevented(e)) {
  26184. var internalContent = getMceInternalContent(e);
  26185. if (internalContent && internalContent.id !== editor.id) {
  26186. e.preventDefault();
  26187. var rng = fromPoint(e.x, e.y, editor.getDoc());
  26188. selection.setRng(rng);
  26189. insertClipboardContents(internalContent.html, true);
  26190. }
  26191. }
  26192. });
  26193. };
  26194. var refreshContentEditable = noop;
  26195. var isHidden = function () {
  26196. if (!isGecko || editor.removed) {
  26197. return false;
  26198. }
  26199. var sel = editor.selection.getSel();
  26200. return !sel || !sel.rangeCount || sel.rangeCount === 0;
  26201. };
  26202. var setupRtc = function () {
  26203. if (isWebKit) {
  26204. documentElementEditingFocus();
  26205. selectControlElements();
  26206. blockFormSubmitInsideEditor();
  26207. selectAll();
  26208. if (Env.iOS) {
  26209. restoreFocusOnKeyDown();
  26210. bodyHeight();
  26211. tapLinksAndImages();
  26212. }
  26213. }
  26214. if (isGecko) {
  26215. focusBody();
  26216. setGeckoEditingOptions();
  26217. showBrokenImageIcon();
  26218. blockCmdArrowNavigation();
  26219. }
  26220. };
  26221. var setup = function () {
  26222. removeBlockQuoteOnBackSpace();
  26223. emptyEditorWhenDeleting();
  26224. if (!Env.windowsPhone) {
  26225. normalizeSelection();
  26226. }
  26227. if (isWebKit) {
  26228. documentElementEditingFocus();
  26229. selectControlElements();
  26230. setDefaultBlockType();
  26231. blockFormSubmitInsideEditor();
  26232. disableBackspaceIntoATable();
  26233. removeAppleInterchangeBrs();
  26234. if (Env.iOS) {
  26235. restoreFocusOnKeyDown();
  26236. bodyHeight();
  26237. tapLinksAndImages();
  26238. } else {
  26239. selectAll();
  26240. }
  26241. }
  26242. if (Env.ie >= 11) {
  26243. bodyHeight();
  26244. disableBackspaceIntoATable();
  26245. }
  26246. if (Env.ie) {
  26247. selectAll();
  26248. disableAutoUrlDetect();
  26249. ieInternalDragAndDrop();
  26250. }
  26251. if (isGecko) {
  26252. removeHrOnBackspace();
  26253. focusBody();
  26254. removeStylesWhenDeletingAcrossBlockElements();
  26255. setGeckoEditingOptions();
  26256. addBrAfterLastLinks();
  26257. showBrokenImageIcon();
  26258. blockCmdArrowNavigation();
  26259. disableBackspaceIntoATable();
  26260. }
  26261. };
  26262. if (isRtc(editor)) {
  26263. setupRtc();
  26264. } else {
  26265. setup();
  26266. }
  26267. return {
  26268. refreshContentEditable: refreshContentEditable,
  26269. isHidden: isHidden
  26270. };
  26271. };
  26272. var DOM$6 = DOMUtils.DOM;
  26273. var appendStyle = function (editor, text) {
  26274. var body = SugarElement.fromDom(editor.getBody());
  26275. var container = getStyleContainer(getRootNode(body));
  26276. var style = SugarElement.fromTag('style');
  26277. set$1(style, 'type', 'text/css');
  26278. append$1(style, SugarElement.fromText(text));
  26279. append$1(container, style);
  26280. editor.on('remove', function () {
  26281. remove$7(style);
  26282. });
  26283. };
  26284. var getRootName = function (editor) {
  26285. return editor.inline ? editor.getElement().nodeName.toLowerCase() : undefined;
  26286. };
  26287. var removeUndefined = function (obj) {
  26288. return filter$3(obj, function (v) {
  26289. return isUndefined(v) === false;
  26290. });
  26291. };
  26292. var mkParserSettings = function (editor) {
  26293. var settings = editor.settings;
  26294. var blobCache = editor.editorUpload.blobCache;
  26295. return removeUndefined({
  26296. allow_conditional_comments: settings.allow_conditional_comments,
  26297. allow_html_data_urls: settings.allow_html_data_urls,
  26298. allow_svg_data_urls: settings.allow_svg_data_urls,
  26299. allow_html_in_named_anchor: settings.allow_html_in_named_anchor,
  26300. allow_script_urls: settings.allow_script_urls,
  26301. allow_unsafe_link_target: settings.allow_unsafe_link_target,
  26302. convert_fonts_to_spans: settings.convert_fonts_to_spans,
  26303. fix_list_elements: settings.fix_list_elements,
  26304. font_size_legacy_values: settings.font_size_legacy_values,
  26305. forced_root_block: settings.forced_root_block,
  26306. forced_root_block_attrs: settings.forced_root_block_attrs,
  26307. padd_empty_with_br: settings.padd_empty_with_br,
  26308. preserve_cdata: settings.preserve_cdata,
  26309. remove_trailing_brs: settings.remove_trailing_brs,
  26310. inline_styles: settings.inline_styles,
  26311. root_name: getRootName(editor),
  26312. validate: true,
  26313. blob_cache: blobCache,
  26314. document: editor.getDoc(),
  26315. images_dataimg_filter: settings.images_dataimg_filter
  26316. });
  26317. };
  26318. var mkSerializerSettings = function (editor) {
  26319. var settings = editor.settings;
  26320. return __assign(__assign({}, mkParserSettings(editor)), removeUndefined({
  26321. url_converter: settings.url_converter,
  26322. url_converter_scope: settings.url_converter_scope,
  26323. element_format: settings.element_format,
  26324. entities: settings.entities,
  26325. entity_encoding: settings.entity_encoding,
  26326. indent: settings.indent,
  26327. indent_after: settings.indent_after,
  26328. indent_before: settings.indent_before,
  26329. block_elements: settings.block_elements,
  26330. boolean_attributes: settings.boolean_attributes,
  26331. custom_elements: settings.custom_elements,
  26332. extended_valid_elements: settings.extended_valid_elements,
  26333. invalid_elements: settings.invalid_elements,
  26334. invalid_styles: settings.invalid_styles,
  26335. move_caret_before_on_enter_elements: settings.move_caret_before_on_enter_elements,
  26336. non_empty_elements: settings.non_empty_elements,
  26337. schema: settings.schema,
  26338. self_closing_elements: settings.self_closing_elements,
  26339. short_ended_elements: settings.short_ended_elements,
  26340. special: settings.special,
  26341. text_block_elements: settings.text_block_elements,
  26342. text_inline_elements: settings.text_inline_elements,
  26343. valid_children: settings.valid_children,
  26344. valid_classes: settings.valid_classes,
  26345. valid_elements: settings.valid_elements,
  26346. valid_styles: settings.valid_styles,
  26347. verify_html: settings.verify_html,
  26348. whitespace_elements: settings.whitespace_elements
  26349. }));
  26350. };
  26351. var createParser = function (editor) {
  26352. var parser = DomParser(mkParserSettings(editor), editor.schema);
  26353. parser.addAttributeFilter('src,href,style,tabindex', function (nodes, name) {
  26354. var i = nodes.length, node, value;
  26355. var dom = editor.dom;
  26356. var internalName = 'data-mce-' + name;
  26357. while (i--) {
  26358. node = nodes[i];
  26359. value = node.attr(name);
  26360. if (value && !node.attr(internalName)) {
  26361. if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) {
  26362. continue;
  26363. }
  26364. if (name === 'style') {
  26365. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  26366. if (!value.length) {
  26367. value = null;
  26368. }
  26369. node.attr(internalName, value);
  26370. node.attr(name, value);
  26371. } else if (name === 'tabindex') {
  26372. node.attr(internalName, value);
  26373. node.attr(name, null);
  26374. } else {
  26375. node.attr(internalName, editor.convertURL(value, name, node.name));
  26376. }
  26377. }
  26378. }
  26379. });
  26380. parser.addNodeFilter('script', function (nodes) {
  26381. var i = nodes.length;
  26382. while (i--) {
  26383. var node = nodes[i];
  26384. var type = node.attr('type') || 'no/type';
  26385. if (type.indexOf('mce-') !== 0) {
  26386. node.attr('type', 'mce-' + type);
  26387. }
  26388. }
  26389. });
  26390. if (editor.settings.preserve_cdata) {
  26391. parser.addNodeFilter('#cdata', function (nodes) {
  26392. var i = nodes.length;
  26393. while (i--) {
  26394. var node = nodes[i];
  26395. node.type = 8;
  26396. node.name = '#comment';
  26397. node.value = '[CDATA[' + editor.dom.encode(node.value) + ']]';
  26398. }
  26399. });
  26400. }
  26401. parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function (nodes) {
  26402. var i = nodes.length;
  26403. var nonEmptyElements = editor.schema.getNonEmptyElements();
  26404. while (i--) {
  26405. var node = nodes[i];
  26406. if (node.isEmpty(nonEmptyElements) && node.getAll('br').length === 0) {
  26407. node.append(new AstNode('br', 1)).shortEnded = true;
  26408. }
  26409. }
  26410. });
  26411. return parser;
  26412. };
  26413. var autoFocus = function (editor) {
  26414. if (editor.settings.auto_focus) {
  26415. Delay.setEditorTimeout(editor, function () {
  26416. var focusEditor;
  26417. if (editor.settings.auto_focus === true) {
  26418. focusEditor = editor;
  26419. } else {
  26420. focusEditor = editor.editorManager.get(editor.settings.auto_focus);
  26421. }
  26422. if (!focusEditor.destroyed) {
  26423. focusEditor.focus();
  26424. }
  26425. }, 100);
  26426. }
  26427. };
  26428. var moveSelectionToFirstCaretPosition = function (editor) {
  26429. var root = editor.dom.getRoot();
  26430. if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) {
  26431. firstPositionIn(root).each(function (pos) {
  26432. var node = pos.getNode();
  26433. var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  26434. if (Env.browser.isIE()) {
  26435. storeNative(editor, caretPos.toRange());
  26436. } else {
  26437. editor.selection.setRng(caretPos.toRange());
  26438. }
  26439. });
  26440. }
  26441. };
  26442. var initEditor = function (editor) {
  26443. editor.bindPendingEventDelegates();
  26444. editor.initialized = true;
  26445. fireInit(editor);
  26446. editor.focus(true);
  26447. moveSelectionToFirstCaretPosition(editor);
  26448. editor.nodeChanged({ initial: true });
  26449. editor.execCallback('init_instance_callback', editor);
  26450. autoFocus(editor);
  26451. };
  26452. var getStyleSheetLoader$1 = function (editor) {
  26453. return editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader;
  26454. };
  26455. var makeStylesheetLoadingPromises = function (editor, css, framedFonts) {
  26456. var promises = [new promiseObj(function (resolve, reject) {
  26457. return getStyleSheetLoader$1(editor).loadAll(css, resolve, reject);
  26458. })];
  26459. if (editor.inline) {
  26460. return promises;
  26461. } else {
  26462. return promises.concat([new promiseObj(function (resolve, reject) {
  26463. return editor.ui.styleSheetLoader.loadAll(framedFonts, resolve, reject);
  26464. })]);
  26465. }
  26466. };
  26467. var loadContentCss = function (editor) {
  26468. var styleSheetLoader = getStyleSheetLoader$1(editor);
  26469. var fontCss = getFontCss(editor);
  26470. var css = editor.contentCSS;
  26471. var removeCss = function () {
  26472. styleSheetLoader.unloadAll(css);
  26473. if (!editor.inline) {
  26474. editor.ui.styleSheetLoader.unloadAll(fontCss);
  26475. }
  26476. };
  26477. var loaded = function () {
  26478. if (editor.removed) {
  26479. removeCss();
  26480. } else {
  26481. editor.on('remove', removeCss);
  26482. }
  26483. };
  26484. if (editor.contentStyles.length > 0) {
  26485. var contentCssText_1 = '';
  26486. Tools.each(editor.contentStyles, function (style) {
  26487. contentCssText_1 += style + '\r\n';
  26488. });
  26489. editor.dom.addStyle(contentCssText_1);
  26490. }
  26491. var allStylesheets = promiseObj.all(makeStylesheetLoadingPromises(editor, css, fontCss)).then(loaded).catch(loaded);
  26492. if (editor.settings.content_style) {
  26493. appendStyle(editor, editor.settings.content_style);
  26494. }
  26495. return allStylesheets;
  26496. };
  26497. var preInit = function (editor) {
  26498. var settings = editor.settings, doc = editor.getDoc(), body = editor.getBody();
  26499. firePreInit(editor);
  26500. if (!settings.browser_spellcheck && !settings.gecko_spellcheck) {
  26501. doc.body.spellcheck = false;
  26502. DOM$6.setAttrib(body, 'spellcheck', 'false');
  26503. }
  26504. editor.quirks = Quirks(editor);
  26505. firePostRender(editor);
  26506. var directionality = getDirectionality(editor);
  26507. if (directionality !== undefined) {
  26508. body.dir = directionality;
  26509. }
  26510. if (settings.protect) {
  26511. editor.on('BeforeSetContent', function (e) {
  26512. Tools.each(settings.protect, function (pattern) {
  26513. e.content = e.content.replace(pattern, function (str) {
  26514. return '<!--mce:protected ' + escape(str) + '-->';
  26515. });
  26516. });
  26517. });
  26518. }
  26519. editor.on('SetContent', function () {
  26520. editor.addVisual(editor.getBody());
  26521. });
  26522. editor.on('compositionstart compositionend', function (e) {
  26523. editor.composing = e.type === 'compositionstart';
  26524. });
  26525. };
  26526. var loadInitialContent = function (editor) {
  26527. if (!isRtc(editor)) {
  26528. editor.load({
  26529. initial: true,
  26530. format: 'html'
  26531. });
  26532. }
  26533. editor.startContent = editor.getContent({ format: 'raw' });
  26534. };
  26535. var initEditorWithInitialContent = function (editor) {
  26536. if (editor.removed !== true) {
  26537. loadInitialContent(editor);
  26538. initEditor(editor);
  26539. }
  26540. };
  26541. var initContentBody = function (editor, skipWrite) {
  26542. var settings = editor.settings;
  26543. var targetElm = editor.getElement();
  26544. var doc = editor.getDoc();
  26545. if (!settings.inline) {
  26546. editor.getElement().style.visibility = editor.orgVisibility;
  26547. }
  26548. if (!skipWrite && !editor.inline) {
  26549. doc.open();
  26550. doc.write(editor.iframeHTML);
  26551. doc.close();
  26552. }
  26553. if (editor.inline) {
  26554. DOM$6.addClass(targetElm, 'mce-content-body');
  26555. editor.contentDocument = doc = document;
  26556. editor.contentWindow = window;
  26557. editor.bodyElement = targetElm;
  26558. editor.contentAreaContainer = targetElm;
  26559. }
  26560. var body = editor.getBody();
  26561. body.disabled = true;
  26562. editor.readonly = !!settings.readonly;
  26563. if (!editor.readonly) {
  26564. if (editor.inline && DOM$6.getStyle(body, 'position', true) === 'static') {
  26565. body.style.position = 'relative';
  26566. }
  26567. body.contentEditable = editor.getParam('content_editable_state', true);
  26568. }
  26569. body.disabled = false;
  26570. editor.editorUpload = EditorUpload(editor);
  26571. editor.schema = Schema(settings);
  26572. editor.dom = DOMUtils(doc, {
  26573. keep_values: true,
  26574. url_converter: editor.convertURL,
  26575. url_converter_scope: editor,
  26576. hex_colors: settings.force_hex_style_colors,
  26577. update_styles: true,
  26578. root_element: editor.inline ? editor.getBody() : null,
  26579. collect: function () {
  26580. return editor.inline;
  26581. },
  26582. schema: editor.schema,
  26583. contentCssCors: shouldUseContentCssCors(editor),
  26584. referrerPolicy: getReferrerPolicy(editor),
  26585. onSetAttrib: function (e) {
  26586. editor.fire('SetAttrib', e);
  26587. }
  26588. });
  26589. editor.parser = createParser(editor);
  26590. editor.serializer = DomSerializer(mkSerializerSettings(editor), editor);
  26591. editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor);
  26592. editor.annotator = Annotator(editor);
  26593. editor.formatter = Formatter(editor);
  26594. editor.undoManager = UndoManager(editor);
  26595. editor._nodeChangeDispatcher = new NodeChange(editor);
  26596. editor._selectionOverrides = SelectionOverrides(editor);
  26597. setup$e(editor);
  26598. setup$3(editor);
  26599. if (!isRtc(editor)) {
  26600. setup$2(editor);
  26601. }
  26602. var caret = setup$4(editor);
  26603. setup$f(editor, caret);
  26604. setup$d(editor);
  26605. setup$g(editor);
  26606. var setupRtcThunk = setup$i(editor);
  26607. preInit(editor);
  26608. setupRtcThunk.fold(function () {
  26609. loadContentCss(editor).then(function () {
  26610. return initEditorWithInitialContent(editor);
  26611. });
  26612. }, function (setupRtc) {
  26613. editor.setProgressState(true);
  26614. loadContentCss(editor).then(function () {
  26615. setupRtc().then(function (_rtcMode) {
  26616. editor.setProgressState(false);
  26617. initEditorWithInitialContent(editor);
  26618. }, function (err) {
  26619. editor.notificationManager.open({
  26620. type: 'error',
  26621. text: String(err)
  26622. });
  26623. initEditorWithInitialContent(editor);
  26624. });
  26625. });
  26626. });
  26627. };
  26628. var DOM$5 = DOMUtils.DOM;
  26629. var relaxDomain = function (editor, ifr) {
  26630. if (document.domain !== window.location.hostname && Env.browser.isIE()) {
  26631. var bodyUuid = uuid('mce');
  26632. editor[bodyUuid] = function () {
  26633. initContentBody(editor);
  26634. };
  26635. 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);})()';
  26636. DOM$5.setAttrib(ifr, 'src', domainRelaxUrl);
  26637. return true;
  26638. }
  26639. return false;
  26640. };
  26641. var createIframeElement = function (id, title, height, customAttrs) {
  26642. var iframe = SugarElement.fromTag('iframe');
  26643. setAll$1(iframe, customAttrs);
  26644. setAll$1(iframe, {
  26645. id: id + '_ifr',
  26646. frameBorder: '0',
  26647. allowTransparency: 'true',
  26648. title: title
  26649. });
  26650. add$1(iframe, 'tox-edit-area__iframe');
  26651. return iframe;
  26652. };
  26653. var getIframeHtml = function (editor) {
  26654. var iframeHTML = getDocType(editor) + '<html><head>';
  26655. if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
  26656. iframeHTML += '<base href="' + editor.documentBaseURI.getURI() + '" />';
  26657. }
  26658. iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
  26659. var bodyId = getBodyId(editor);
  26660. var bodyClass = getBodyClass(editor);
  26661. if (getContentSecurityPolicy(editor)) {
  26662. iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + getContentSecurityPolicy(editor) + '" />';
  26663. }
  26664. iframeHTML += '</head><body id="' + bodyId + '" class="mce-content-body ' + bodyClass + '" data-id="' + editor.id + '"><br></body></html>';
  26665. return iframeHTML;
  26666. };
  26667. var createIframe = function (editor, o) {
  26668. var iframeTranslatedTitle = editor.translate(getIframeTitle(editor));
  26669. var ifr = createIframeElement(editor.id, iframeTranslatedTitle, o.height, getIframeAttrs(editor)).dom;
  26670. ifr.onload = function () {
  26671. ifr.onload = null;
  26672. editor.fire('load');
  26673. };
  26674. var isDomainRelaxed = relaxDomain(editor, ifr);
  26675. editor.contentAreaContainer = o.iframeContainer;
  26676. editor.iframeElement = ifr;
  26677. editor.iframeHTML = getIframeHtml(editor);
  26678. DOM$5.add(o.iframeContainer, ifr);
  26679. return isDomainRelaxed;
  26680. };
  26681. var init$1 = function (editor, boxInfo) {
  26682. var isDomainRelaxed = createIframe(editor, boxInfo);
  26683. if (boxInfo.editorContainer) {
  26684. DOM$5.get(boxInfo.editorContainer).style.display = editor.orgDisplay;
  26685. editor.hidden = DOM$5.isHidden(boxInfo.editorContainer);
  26686. }
  26687. editor.getElement().style.display = 'none';
  26688. DOM$5.setAttrib(editor.id, 'aria-hidden', 'true');
  26689. if (!isDomainRelaxed) {
  26690. initContentBody(editor);
  26691. }
  26692. };
  26693. var DOM$4 = DOMUtils.DOM;
  26694. var initPlugin = function (editor, initializedPlugins, plugin) {
  26695. var Plugin = PluginManager.get(plugin);
  26696. var pluginUrl = PluginManager.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, '');
  26697. plugin = Tools.trim(plugin);
  26698. if (Plugin && Tools.inArray(initializedPlugins, plugin) === -1) {
  26699. Tools.each(PluginManager.dependencies(plugin), function (dep) {
  26700. initPlugin(editor, initializedPlugins, dep);
  26701. });
  26702. if (editor.plugins[plugin]) {
  26703. return;
  26704. }
  26705. try {
  26706. var pluginInstance = new Plugin(editor, pluginUrl, editor.$);
  26707. editor.plugins[plugin] = pluginInstance;
  26708. if (pluginInstance.init) {
  26709. pluginInstance.init(editor, pluginUrl);
  26710. initializedPlugins.push(plugin);
  26711. }
  26712. } catch (e) {
  26713. pluginInitError(editor, plugin, e);
  26714. }
  26715. }
  26716. };
  26717. var trimLegacyPrefix = function (name) {
  26718. return name.replace(/^\-/, '');
  26719. };
  26720. var initPlugins = function (editor) {
  26721. var initializedPlugins = [];
  26722. Tools.each(getPlugins(editor).split(/[ ,]/), function (name) {
  26723. initPlugin(editor, initializedPlugins, trimLegacyPrefix(name));
  26724. });
  26725. };
  26726. var initIcons = function (editor) {
  26727. var iconPackName = Tools.trim(getIconPackName(editor));
  26728. var currentIcons = editor.ui.registry.getAll().icons;
  26729. var loadIcons = __assign(__assign({}, IconManager.get('default').icons), IconManager.get(iconPackName).icons);
  26730. each$j(loadIcons, function (svgData, icon) {
  26731. if (!has$2(currentIcons, icon)) {
  26732. editor.ui.registry.addIcon(icon, svgData);
  26733. }
  26734. });
  26735. };
  26736. var initTheme = function (editor) {
  26737. var theme = getTheme(editor);
  26738. if (isString$1(theme)) {
  26739. editor.settings.theme = trimLegacyPrefix(theme);
  26740. var Theme = ThemeManager.get(theme);
  26741. editor.theme = new Theme(editor, ThemeManager.urls[theme]);
  26742. if (editor.theme.init) {
  26743. editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ''), editor.$);
  26744. }
  26745. } else {
  26746. editor.theme = {};
  26747. }
  26748. };
  26749. var renderFromLoadedTheme = function (editor) {
  26750. return editor.theme.renderUI();
  26751. };
  26752. var renderFromThemeFunc = function (editor) {
  26753. var elm = editor.getElement();
  26754. var theme = getTheme(editor);
  26755. var info = theme(editor, elm);
  26756. if (info.editorContainer.nodeType) {
  26757. info.editorContainer.id = info.editorContainer.id || editor.id + '_parent';
  26758. }
  26759. if (info.iframeContainer && info.iframeContainer.nodeType) {
  26760. info.iframeContainer.id = info.iframeContainer.id || editor.id + '_iframecontainer';
  26761. }
  26762. info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
  26763. return info;
  26764. };
  26765. var createThemeFalseResult = function (element) {
  26766. return {
  26767. editorContainer: element,
  26768. iframeContainer: element,
  26769. api: {}
  26770. };
  26771. };
  26772. var renderThemeFalseIframe = function (targetElement) {
  26773. var iframeContainer = DOM$4.create('div');
  26774. DOM$4.insertAfter(iframeContainer, targetElement);
  26775. return createThemeFalseResult(iframeContainer);
  26776. };
  26777. var renderThemeFalse = function (editor) {
  26778. var targetElement = editor.getElement();
  26779. return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
  26780. };
  26781. var renderThemeUi = function (editor) {
  26782. var elm = editor.getElement();
  26783. editor.orgDisplay = elm.style.display;
  26784. if (isString$1(getTheme(editor))) {
  26785. return renderFromLoadedTheme(editor);
  26786. } else if (isFunction(getTheme(editor))) {
  26787. return renderFromThemeFunc(editor);
  26788. } else {
  26789. return renderThemeFalse(editor);
  26790. }
  26791. };
  26792. var augmentEditorUiApi = function (editor, api) {
  26793. var uiApiFacade = {
  26794. show: Optional.from(api.show).getOr(noop),
  26795. hide: Optional.from(api.hide).getOr(noop),
  26796. disable: Optional.from(api.disable).getOr(noop),
  26797. isDisabled: Optional.from(api.isDisabled).getOr(never),
  26798. enable: function () {
  26799. if (!editor.mode.isReadOnly()) {
  26800. Optional.from(api.enable).map(call);
  26801. }
  26802. }
  26803. };
  26804. editor.ui = __assign(__assign({}, editor.ui), uiApiFacade);
  26805. };
  26806. var init = function (editor) {
  26807. editor.fire('ScriptsLoaded');
  26808. initIcons(editor);
  26809. initTheme(editor);
  26810. initPlugins(editor);
  26811. var renderInfo = renderThemeUi(editor);
  26812. augmentEditorUiApi(editor, Optional.from(renderInfo.api).getOr({}));
  26813. var boxInfo = {
  26814. editorContainer: renderInfo.editorContainer,
  26815. iframeContainer: renderInfo.iframeContainer
  26816. };
  26817. editor.editorContainer = boxInfo.editorContainer ? boxInfo.editorContainer : null;
  26818. appendContentCssFromSettings(editor);
  26819. if (editor.inline) {
  26820. return initContentBody(editor);
  26821. } else {
  26822. return init$1(editor, boxInfo);
  26823. }
  26824. };
  26825. var DOM$3 = DOMUtils.DOM;
  26826. var hasSkipLoadPrefix = function (name) {
  26827. return name.charAt(0) === '-';
  26828. };
  26829. var loadLanguage = function (scriptLoader, editor) {
  26830. var languageCode = getLanguageCode(editor);
  26831. var languageUrl = getLanguageUrl(editor);
  26832. if (I18n.hasCode(languageCode) === false && languageCode !== 'en') {
  26833. var url_1 = languageUrl !== '' ? languageUrl : editor.editorManager.baseURL + '/langs/' + languageCode + '.js';
  26834. scriptLoader.add(url_1, noop, undefined, function () {
  26835. languageLoadError(editor, url_1, languageCode);
  26836. });
  26837. }
  26838. };
  26839. var loadTheme = function (scriptLoader, editor, suffix, callback) {
  26840. var theme = getTheme(editor);
  26841. if (isString$1(theme)) {
  26842. if (!hasSkipLoadPrefix(theme) && !has$2(ThemeManager.urls, theme)) {
  26843. var themeUrl = getThemeUrl(editor);
  26844. if (themeUrl) {
  26845. ThemeManager.load(theme, editor.documentBaseURI.toAbsolute(themeUrl));
  26846. } else {
  26847. ThemeManager.load(theme, 'themes/' + theme + '/theme' + suffix + '.js');
  26848. }
  26849. }
  26850. scriptLoader.loadQueue(function () {
  26851. ThemeManager.waitFor(theme, callback);
  26852. });
  26853. } else {
  26854. callback();
  26855. }
  26856. };
  26857. var getIconsUrlMetaFromUrl = function (editor) {
  26858. return Optional.from(getIconsUrl(editor)).filter(function (url) {
  26859. return url.length > 0;
  26860. }).map(function (url) {
  26861. return {
  26862. url: url,
  26863. name: Optional.none()
  26864. };
  26865. });
  26866. };
  26867. var getIconsUrlMetaFromName = function (editor, name, suffix) {
  26868. return Optional.from(name).filter(function (name) {
  26869. return name.length > 0 && !IconManager.has(name);
  26870. }).map(function (name) {
  26871. return {
  26872. url: editor.editorManager.baseURL + '/icons/' + name + '/icons' + suffix + '.js',
  26873. name: Optional.some(name)
  26874. };
  26875. });
  26876. };
  26877. var loadIcons = function (scriptLoader, editor, suffix) {
  26878. var defaultIconsUrl = getIconsUrlMetaFromName(editor, 'default', suffix);
  26879. var customIconsUrl = getIconsUrlMetaFromUrl(editor).orThunk(function () {
  26880. return getIconsUrlMetaFromName(editor, getIconPackName(editor), '');
  26881. });
  26882. each$k(cat([
  26883. defaultIconsUrl,
  26884. customIconsUrl
  26885. ]), function (urlMeta) {
  26886. scriptLoader.add(urlMeta.url, noop, undefined, function () {
  26887. iconsLoadError(editor, urlMeta.url, urlMeta.name.getOrUndefined());
  26888. });
  26889. });
  26890. };
  26891. var loadPlugins = function (editor, suffix) {
  26892. Tools.each(getExternalPlugins$1(editor), function (url, name) {
  26893. PluginManager.load(name, url, noop, undefined, function () {
  26894. pluginLoadError(editor, url, name);
  26895. });
  26896. editor.settings.plugins += ' ' + name;
  26897. });
  26898. Tools.each(getPlugins(editor).split(/[ ,]/), function (plugin) {
  26899. plugin = Tools.trim(plugin);
  26900. if (plugin && !PluginManager.urls[plugin]) {
  26901. if (hasSkipLoadPrefix(plugin)) {
  26902. plugin = plugin.substr(1, plugin.length);
  26903. var dependencies = PluginManager.dependencies(plugin);
  26904. Tools.each(dependencies, function (depPlugin) {
  26905. var defaultSettings = {
  26906. prefix: 'plugins/',
  26907. resource: depPlugin,
  26908. suffix: '/plugin' + suffix + '.js'
  26909. };
  26910. var dep = PluginManager.createUrl(defaultSettings, depPlugin);
  26911. PluginManager.load(dep.resource, dep, noop, undefined, function () {
  26912. pluginLoadError(editor, dep.prefix + dep.resource + dep.suffix, dep.resource);
  26913. });
  26914. });
  26915. } else {
  26916. var url_2 = {
  26917. prefix: 'plugins/',
  26918. resource: plugin,
  26919. suffix: '/plugin' + suffix + '.js'
  26920. };
  26921. PluginManager.load(plugin, url_2, noop, undefined, function () {
  26922. pluginLoadError(editor, url_2.prefix + url_2.resource + url_2.suffix, plugin);
  26923. });
  26924. }
  26925. }
  26926. });
  26927. };
  26928. var loadScripts = function (editor, suffix) {
  26929. var scriptLoader = ScriptLoader.ScriptLoader;
  26930. loadTheme(scriptLoader, editor, suffix, function () {
  26931. loadLanguage(scriptLoader, editor);
  26932. loadIcons(scriptLoader, editor, suffix);
  26933. loadPlugins(editor, suffix);
  26934. scriptLoader.loadQueue(function () {
  26935. if (!editor.removed) {
  26936. init(editor);
  26937. }
  26938. }, editor, function () {
  26939. if (!editor.removed) {
  26940. init(editor);
  26941. }
  26942. });
  26943. });
  26944. };
  26945. var getStyleSheetLoader = function (element, editor) {
  26946. return instance.forElement(element, {
  26947. contentCssCors: hasContentCssCors(editor),
  26948. referrerPolicy: getReferrerPolicy(editor)
  26949. });
  26950. };
  26951. var render = function (editor) {
  26952. var id = editor.id;
  26953. I18n.setCode(getLanguageCode(editor));
  26954. var readyHandler = function () {
  26955. DOM$3.unbind(window, 'ready', readyHandler);
  26956. editor.render();
  26957. };
  26958. if (!EventUtils.Event.domLoaded) {
  26959. DOM$3.bind(window, 'ready', readyHandler);
  26960. return;
  26961. }
  26962. if (!editor.getElement()) {
  26963. return;
  26964. }
  26965. if (!Env.contentEditable) {
  26966. return;
  26967. }
  26968. var element = SugarElement.fromDom(editor.getElement());
  26969. var snapshot = clone$3(element);
  26970. editor.on('remove', function () {
  26971. eachr(element.dom.attributes, function (attr) {
  26972. return remove$6(element, attr.name);
  26973. });
  26974. setAll$1(element, snapshot);
  26975. });
  26976. editor.ui.styleSheetLoader = getStyleSheetLoader(element, editor);
  26977. if (!isInline(editor)) {
  26978. editor.orgVisibility = editor.getElement().style.visibility;
  26979. editor.getElement().style.visibility = 'hidden';
  26980. } else {
  26981. editor.inline = true;
  26982. }
  26983. var form = editor.getElement().form || DOM$3.getParent(id, 'form');
  26984. if (form) {
  26985. editor.formElement = form;
  26986. if (hasHiddenInput(editor) && !isTextareaOrInput(editor.getElement())) {
  26987. DOM$3.insertAfter(DOM$3.create('input', {
  26988. type: 'hidden',
  26989. name: id
  26990. }), id);
  26991. editor.hasHiddenInput = true;
  26992. }
  26993. editor.formEventDelegate = function (e) {
  26994. editor.fire(e.type, e);
  26995. };
  26996. DOM$3.bind(form, 'submit reset', editor.formEventDelegate);
  26997. editor.on('reset', function () {
  26998. editor.resetContent();
  26999. });
  27000. if (shouldPatchSubmit(editor) && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
  27001. form._mceOldSubmit = form.submit;
  27002. form.submit = function () {
  27003. editor.editorManager.triggerSave();
  27004. editor.setDirty(false);
  27005. return form._mceOldSubmit(form);
  27006. };
  27007. }
  27008. }
  27009. editor.windowManager = WindowManager(editor);
  27010. editor.notificationManager = NotificationManager(editor);
  27011. if (isEncodingXml(editor)) {
  27012. editor.on('GetContent', function (e) {
  27013. if (e.save) {
  27014. e.content = DOM$3.encode(e.content);
  27015. }
  27016. });
  27017. }
  27018. if (shouldAddFormSubmitTrigger(editor)) {
  27019. editor.on('submit', function () {
  27020. if (editor.initialized) {
  27021. editor.save();
  27022. }
  27023. });
  27024. }
  27025. if (shouldAddUnloadTrigger(editor)) {
  27026. editor._beforeUnload = function () {
  27027. if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
  27028. editor.save({
  27029. format: 'raw',
  27030. no_events: true,
  27031. set_dirty: false
  27032. });
  27033. }
  27034. };
  27035. editor.editorManager.on('BeforeUnload', editor._beforeUnload);
  27036. }
  27037. editor.editorManager.add(editor);
  27038. loadScripts(editor, editor.suffix);
  27039. };
  27040. var addVisual = function (editor, elm) {
  27041. return addVisual$1(editor, elm);
  27042. };
  27043. var legacyPropNames = {
  27044. 'font-size': 'size',
  27045. 'font-family': 'face'
  27046. };
  27047. var getSpecifiedFontProp = function (propName, rootElm, elm) {
  27048. var getProperty = function (elm) {
  27049. return getRaw(elm, propName).orThunk(function () {
  27050. if (name(elm) === 'font') {
  27051. return get$9(legacyPropNames, propName).bind(function (legacyPropName) {
  27052. return getOpt(elm, legacyPropName);
  27053. });
  27054. } else {
  27055. return Optional.none();
  27056. }
  27057. });
  27058. };
  27059. var isRoot = function (elm) {
  27060. return eq(SugarElement.fromDom(rootElm), elm);
  27061. };
  27062. return closest$1(SugarElement.fromDom(elm), function (elm) {
  27063. return getProperty(elm);
  27064. }, isRoot);
  27065. };
  27066. var normalizeFontFamily = function (fontFamily) {
  27067. return fontFamily.replace(/[\'\"\\]/g, '').replace(/,\s+/g, ',');
  27068. };
  27069. var getComputedFontProp = function (propName, elm) {
  27070. return Optional.from(DOMUtils.DOM.getStyle(elm, propName, true));
  27071. };
  27072. var getFontProp = function (propName) {
  27073. return function (rootElm, elm) {
  27074. return Optional.from(elm).map(SugarElement.fromDom).filter(isElement$6).bind(function (element) {
  27075. return getSpecifiedFontProp(propName, rootElm, element.dom).or(getComputedFontProp(propName, element.dom));
  27076. }).getOr('');
  27077. };
  27078. };
  27079. var getFontSize = getFontProp('font-size');
  27080. var getFontFamily = compose(normalizeFontFamily, getFontProp('font-family'));
  27081. var findFirstCaretElement = function (editor) {
  27082. return firstPositionIn(editor.getBody()).map(function (caret) {
  27083. var container = caret.container();
  27084. return isText$7(container) ? container.parentNode : container;
  27085. });
  27086. };
  27087. var getCaretElement = function (editor) {
  27088. return Optional.from(editor.selection.getRng()).bind(function (rng) {
  27089. var root = editor.getBody();
  27090. var atStartOfNode = rng.startContainer === root && rng.startOffset === 0;
  27091. return atStartOfNode ? Optional.none() : Optional.from(editor.selection.getStart(true));
  27092. });
  27093. };
  27094. var bindRange = function (editor, binder) {
  27095. return getCaretElement(editor).orThunk(curry(findFirstCaretElement, editor)).map(SugarElement.fromDom).filter(isElement$6).bind(binder);
  27096. };
  27097. var mapRange = function (editor, mapper) {
  27098. return bindRange(editor, compose1(Optional.some, mapper));
  27099. };
  27100. var fromFontSizeNumber = function (editor, value) {
  27101. if (/^[0-9.]+$/.test(value)) {
  27102. var fontSizeNumber = parseInt(value, 10);
  27103. if (fontSizeNumber >= 1 && fontSizeNumber <= 7) {
  27104. var fontSizes = getFontStyleValues(editor);
  27105. var fontClasses = getFontSizeClasses(editor);
  27106. if (fontClasses) {
  27107. return fontClasses[fontSizeNumber - 1] || value;
  27108. } else {
  27109. return fontSizes[fontSizeNumber - 1] || value;
  27110. }
  27111. } else {
  27112. return value;
  27113. }
  27114. } else {
  27115. return value;
  27116. }
  27117. };
  27118. var normalizeFontNames = function (font) {
  27119. var fonts = font.split(/\s*,\s*/);
  27120. return map$3(fonts, function (font) {
  27121. if (font.indexOf(' ') !== -1 && !(startsWith(font, '"') || startsWith(font, '\''))) {
  27122. return '\'' + font + '\'';
  27123. } else {
  27124. return font;
  27125. }
  27126. }).join(',');
  27127. };
  27128. var fontNameAction = function (editor, value) {
  27129. var font = fromFontSizeNumber(editor, value);
  27130. editor.formatter.toggle('fontname', { value: normalizeFontNames(font) });
  27131. editor.nodeChanged();
  27132. };
  27133. var fontNameQuery = function (editor) {
  27134. return mapRange(editor, function (elm) {
  27135. return getFontFamily(editor.getBody(), elm.dom);
  27136. }).getOr('');
  27137. };
  27138. var fontSizeAction = function (editor, value) {
  27139. editor.formatter.toggle('fontsize', { value: fromFontSizeNumber(editor, value) });
  27140. editor.nodeChanged();
  27141. };
  27142. var fontSizeQuery = function (editor) {
  27143. return mapRange(editor, function (elm) {
  27144. return getFontSize(editor.getBody(), elm.dom);
  27145. }).getOr('');
  27146. };
  27147. var lineHeightQuery = function (editor) {
  27148. return mapRange(editor, function (elm) {
  27149. var root = SugarElement.fromDom(editor.getBody());
  27150. var specifiedStyle = closest$1(elm, function (elm) {
  27151. return getRaw(elm, 'line-height');
  27152. }, curry(eq, root));
  27153. var computedStyle = function () {
  27154. var lineHeight = parseFloat(get$5(elm, 'line-height'));
  27155. var fontSize = parseFloat(get$5(elm, 'font-size'));
  27156. return String(lineHeight / fontSize);
  27157. };
  27158. return specifiedStyle.getOrThunk(computedStyle);
  27159. }).getOr('');
  27160. };
  27161. var lineHeightAction = function (editor, lineHeight) {
  27162. editor.formatter.toggle('lineheight', { value: String(lineHeight) });
  27163. editor.nodeChanged();
  27164. };
  27165. var processValue = function (value) {
  27166. if (typeof value !== 'string') {
  27167. var details = Tools.extend({
  27168. paste: value.paste,
  27169. data: { paste: value.paste }
  27170. }, value);
  27171. return {
  27172. content: value.content,
  27173. details: details
  27174. };
  27175. }
  27176. return {
  27177. content: value,
  27178. details: {}
  27179. };
  27180. };
  27181. var insertAtCaret = function (editor, value) {
  27182. var result = processValue(value);
  27183. insertContent(editor, result.content, result.details);
  27184. };
  27185. var each$5 = Tools.each;
  27186. var map = Tools.map, inArray = Tools.inArray;
  27187. var EditorCommands = function () {
  27188. function EditorCommands(editor) {
  27189. this.commands = {
  27190. state: {},
  27191. exec: {},
  27192. value: {}
  27193. };
  27194. this.editor = editor;
  27195. this.setupCommands(editor);
  27196. }
  27197. EditorCommands.prototype.execCommand = function (command, ui, value, args) {
  27198. var func, state = false;
  27199. var self = this;
  27200. if (self.editor.removed) {
  27201. return;
  27202. }
  27203. if (command.toLowerCase() !== 'mcefocus') {
  27204. if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) {
  27205. self.editor.focus();
  27206. } else {
  27207. restore(self.editor);
  27208. }
  27209. }
  27210. args = self.editor.fire('BeforeExecCommand', {
  27211. command: command,
  27212. ui: ui,
  27213. value: value
  27214. });
  27215. if (args.isDefaultPrevented()) {
  27216. return false;
  27217. }
  27218. var customCommand = command.toLowerCase();
  27219. if (func = self.commands.exec[customCommand]) {
  27220. func(customCommand, ui, value);
  27221. self.editor.fire('ExecCommand', {
  27222. command: command,
  27223. ui: ui,
  27224. value: value
  27225. });
  27226. return true;
  27227. }
  27228. each$5(this.editor.plugins, function (p) {
  27229. if (p.execCommand && p.execCommand(command, ui, value)) {
  27230. self.editor.fire('ExecCommand', {
  27231. command: command,
  27232. ui: ui,
  27233. value: value
  27234. });
  27235. state = true;
  27236. return false;
  27237. }
  27238. });
  27239. if (state) {
  27240. return state;
  27241. }
  27242. if (self.editor.theme && self.editor.theme.execCommand && self.editor.theme.execCommand(command, ui, value)) {
  27243. self.editor.fire('ExecCommand', {
  27244. command: command,
  27245. ui: ui,
  27246. value: value
  27247. });
  27248. return true;
  27249. }
  27250. try {
  27251. state = self.editor.getDoc().execCommand(command, ui, value);
  27252. } catch (ex) {
  27253. }
  27254. if (state) {
  27255. self.editor.fire('ExecCommand', {
  27256. command: command,
  27257. ui: ui,
  27258. value: value
  27259. });
  27260. return true;
  27261. }
  27262. return false;
  27263. };
  27264. EditorCommands.prototype.queryCommandState = function (command) {
  27265. var func;
  27266. if (this.editor.quirks.isHidden() || this.editor.removed) {
  27267. return;
  27268. }
  27269. command = command.toLowerCase();
  27270. if (func = this.commands.state[command]) {
  27271. return func(command);
  27272. }
  27273. try {
  27274. return this.editor.getDoc().queryCommandState(command);
  27275. } catch (ex) {
  27276. }
  27277. return false;
  27278. };
  27279. EditorCommands.prototype.queryCommandValue = function (command) {
  27280. var func;
  27281. if (this.editor.quirks.isHidden() || this.editor.removed) {
  27282. return;
  27283. }
  27284. command = command.toLowerCase();
  27285. if (func = this.commands.value[command]) {
  27286. return func(command);
  27287. }
  27288. try {
  27289. return this.editor.getDoc().queryCommandValue(command);
  27290. } catch (ex) {
  27291. }
  27292. };
  27293. EditorCommands.prototype.addCommands = function (commandList, type) {
  27294. if (type === void 0) {
  27295. type = 'exec';
  27296. }
  27297. var self = this;
  27298. each$5(commandList, function (callback, command) {
  27299. each$5(command.toLowerCase().split(','), function (command) {
  27300. self.commands[type][command] = callback;
  27301. });
  27302. });
  27303. };
  27304. EditorCommands.prototype.addCommand = function (command, callback, scope) {
  27305. var _this = this;
  27306. command = command.toLowerCase();
  27307. this.commands.exec[command] = function (command, ui, value, args) {
  27308. return callback.call(scope || _this.editor, ui, value, args);
  27309. };
  27310. };
  27311. EditorCommands.prototype.queryCommandSupported = function (command) {
  27312. command = command.toLowerCase();
  27313. if (this.commands.exec[command]) {
  27314. return true;
  27315. }
  27316. try {
  27317. return this.editor.getDoc().queryCommandSupported(command);
  27318. } catch (ex) {
  27319. }
  27320. return false;
  27321. };
  27322. EditorCommands.prototype.addQueryStateHandler = function (command, callback, scope) {
  27323. var _this = this;
  27324. command = command.toLowerCase();
  27325. this.commands.state[command] = function () {
  27326. return callback.call(scope || _this.editor);
  27327. };
  27328. };
  27329. EditorCommands.prototype.addQueryValueHandler = function (command, callback, scope) {
  27330. var _this = this;
  27331. command = command.toLowerCase();
  27332. this.commands.value[command] = function () {
  27333. return callback.call(scope || _this.editor);
  27334. };
  27335. };
  27336. EditorCommands.prototype.hasCustomCommand = function (command) {
  27337. command = command.toLowerCase();
  27338. return !!this.commands.exec[command];
  27339. };
  27340. EditorCommands.prototype.execNativeCommand = function (command, ui, value) {
  27341. if (ui === undefined) {
  27342. ui = false;
  27343. }
  27344. if (value === undefined) {
  27345. value = null;
  27346. }
  27347. return this.editor.getDoc().execCommand(command, ui, value);
  27348. };
  27349. EditorCommands.prototype.isFormatMatch = function (name) {
  27350. return this.editor.formatter.match(name);
  27351. };
  27352. EditorCommands.prototype.toggleFormat = function (name, value) {
  27353. this.editor.formatter.toggle(name, value);
  27354. this.editor.nodeChanged();
  27355. };
  27356. EditorCommands.prototype.storeSelection = function (type) {
  27357. this.selectionBookmark = this.editor.selection.getBookmark(type);
  27358. };
  27359. EditorCommands.prototype.restoreSelection = function () {
  27360. this.editor.selection.moveToBookmark(this.selectionBookmark);
  27361. };
  27362. EditorCommands.prototype.setupCommands = function (editor) {
  27363. var self = this;
  27364. this.addCommands({
  27365. 'mceResetDesignMode,mceBeginUndoLevel': noop,
  27366. 'mceEndUndoLevel,mceAddUndoLevel': function () {
  27367. editor.undoManager.add();
  27368. },
  27369. 'mceFocus': function (_command, _ui, value) {
  27370. focus(editor, value);
  27371. },
  27372. 'Cut,Copy,Paste': function (command) {
  27373. var doc = editor.getDoc();
  27374. var failed;
  27375. try {
  27376. self.execNativeCommand(command);
  27377. } catch (ex) {
  27378. failed = true;
  27379. }
  27380. if (command === 'paste' && !doc.queryCommandEnabled(command)) {
  27381. failed = true;
  27382. }
  27383. if (failed || !doc.queryCommandSupported(command)) {
  27384. var msg = editor.translate('Your browser doesn\'t support direct access to the clipboard. ' + 'Please use the Ctrl+X/C/V keyboard shortcuts instead.');
  27385. if (Env.mac) {
  27386. msg = msg.replace(/Ctrl\+/g, '\u2318+');
  27387. }
  27388. editor.notificationManager.open({
  27389. text: msg,
  27390. type: 'error'
  27391. });
  27392. }
  27393. },
  27394. 'unlink': function () {
  27395. if (editor.selection.isCollapsed()) {
  27396. var elm = editor.dom.getParent(editor.selection.getStart(), 'a');
  27397. if (elm) {
  27398. editor.dom.remove(elm, true);
  27399. }
  27400. return;
  27401. }
  27402. editor.formatter.remove('link');
  27403. },
  27404. 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone': function (command) {
  27405. var align = command.substring(7);
  27406. if (align === 'full') {
  27407. align = 'justify';
  27408. }
  27409. each$5('left,center,right,justify'.split(','), function (name) {
  27410. if (align !== name) {
  27411. editor.formatter.remove('align' + name);
  27412. }
  27413. });
  27414. if (align !== 'none') {
  27415. self.toggleFormat('align' + align);
  27416. }
  27417. },
  27418. 'InsertUnorderedList,InsertOrderedList': function (command) {
  27419. var listParent;
  27420. self.execNativeCommand(command);
  27421. var listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
  27422. if (listElm) {
  27423. listParent = listElm.parentNode;
  27424. if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
  27425. self.storeSelection();
  27426. editor.dom.split(listParent, listElm);
  27427. self.restoreSelection();
  27428. }
  27429. }
  27430. },
  27431. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  27432. self.toggleFormat(command);
  27433. },
  27434. 'ForeColor,HiliteColor': function (command, ui, value) {
  27435. self.toggleFormat(command, { value: value });
  27436. },
  27437. 'FontName': function (command, ui, value) {
  27438. fontNameAction(editor, value);
  27439. },
  27440. 'FontSize': function (command, ui, value) {
  27441. fontSizeAction(editor, value);
  27442. },
  27443. 'LineHeight': function (command, ui, value) {
  27444. lineHeightAction(editor, value);
  27445. },
  27446. 'Lang': function (command, ui, lang) {
  27447. self.toggleFormat(command, {
  27448. value: lang.code,
  27449. customValue: lang.customCode
  27450. });
  27451. },
  27452. 'RemoveFormat': function (command) {
  27453. editor.formatter.remove(command);
  27454. },
  27455. 'mceBlockQuote': function () {
  27456. self.toggleFormat('blockquote');
  27457. },
  27458. 'FormatBlock': function (command, ui, value) {
  27459. return self.toggleFormat(value || 'p');
  27460. },
  27461. 'mceCleanup': function () {
  27462. var bookmark = editor.selection.getBookmark();
  27463. editor.setContent(editor.getContent());
  27464. editor.selection.moveToBookmark(bookmark);
  27465. },
  27466. 'mceRemoveNode': function (command, ui, value) {
  27467. var node = value || editor.selection.getNode();
  27468. if (node !== editor.getBody()) {
  27469. self.storeSelection();
  27470. editor.dom.remove(node, true);
  27471. self.restoreSelection();
  27472. }
  27473. },
  27474. 'mceSelectNodeDepth': function (command, ui, value) {
  27475. var counter = 0;
  27476. editor.dom.getParent(editor.selection.getNode(), function (node) {
  27477. if (node.nodeType === 1 && counter++ === value) {
  27478. editor.selection.select(node);
  27479. return false;
  27480. }
  27481. }, editor.getBody());
  27482. },
  27483. 'mceSelectNode': function (command, ui, value) {
  27484. editor.selection.select(value);
  27485. },
  27486. 'mceInsertContent': function (command, ui, value) {
  27487. insertAtCaret(editor, value);
  27488. },
  27489. 'mceInsertRawHTML': function (command, ui, value) {
  27490. editor.selection.setContent('tiny_mce_marker');
  27491. var content = editor.getContent();
  27492. editor.setContent(content.replace(/tiny_mce_marker/g, function () {
  27493. return value;
  27494. }));
  27495. },
  27496. 'mceInsertNewLine': function (command, ui, value) {
  27497. insert(editor, value);
  27498. },
  27499. 'mceToggleFormat': function (command, ui, value) {
  27500. self.toggleFormat(value);
  27501. },
  27502. 'mceSetContent': function (command, ui, value) {
  27503. editor.setContent(value);
  27504. },
  27505. 'Indent,Outdent': function (command) {
  27506. handle(editor, command);
  27507. },
  27508. 'mceRepaint': noop,
  27509. 'InsertHorizontalRule': function () {
  27510. editor.execCommand('mceInsertContent', false, '<hr />');
  27511. },
  27512. 'mceToggleVisualAid': function () {
  27513. editor.hasVisual = !editor.hasVisual;
  27514. editor.addVisual();
  27515. },
  27516. 'mceReplaceContent': function (command, ui, value) {
  27517. editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, editor.selection.getContent({ format: 'text' })));
  27518. },
  27519. 'mceInsertLink': function (command, ui, value) {
  27520. if (typeof value === 'string') {
  27521. value = { href: value };
  27522. }
  27523. var anchor = editor.dom.getParent(editor.selection.getNode(), 'a');
  27524. value.href = value.href.replace(/ /g, '%20');
  27525. if (!anchor || !value.href) {
  27526. editor.formatter.remove('link');
  27527. }
  27528. if (value.href) {
  27529. editor.formatter.apply('link', value, anchor);
  27530. }
  27531. },
  27532. 'selectAll': function () {
  27533. var editingHost = editor.dom.getParent(editor.selection.getStart(), isContentEditableTrue$4);
  27534. if (editingHost) {
  27535. var rng = editor.dom.createRng();
  27536. rng.selectNodeContents(editingHost);
  27537. editor.selection.setRng(rng);
  27538. }
  27539. },
  27540. 'mceNewDocument': function () {
  27541. editor.setContent('');
  27542. },
  27543. 'InsertLineBreak': function (command, ui, value) {
  27544. insert$1(editor, value);
  27545. return true;
  27546. }
  27547. });
  27548. var alignStates = function (name) {
  27549. return function () {
  27550. var selection = editor.selection;
  27551. var nodes = selection.isCollapsed() ? [editor.dom.getParent(selection.getNode(), editor.dom.isBlock)] : selection.getSelectedBlocks();
  27552. var matches = map(nodes, function (node) {
  27553. return !!editor.formatter.matchNode(node, name);
  27554. });
  27555. return inArray(matches, true) !== -1;
  27556. };
  27557. };
  27558. self.addCommands({
  27559. 'JustifyLeft': alignStates('alignleft'),
  27560. 'JustifyCenter': alignStates('aligncenter'),
  27561. 'JustifyRight': alignStates('alignright'),
  27562. 'JustifyFull': alignStates('alignjustify'),
  27563. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  27564. return self.isFormatMatch(command);
  27565. },
  27566. 'mceBlockQuote': function () {
  27567. return self.isFormatMatch('blockquote');
  27568. },
  27569. 'Outdent': function () {
  27570. return canOutdent(editor);
  27571. },
  27572. 'InsertUnorderedList,InsertOrderedList': function (command) {
  27573. var list = editor.dom.getParent(editor.selection.getNode(), 'ul,ol');
  27574. return list && (command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL');
  27575. }
  27576. }, 'state');
  27577. self.addCommands({
  27578. Undo: function () {
  27579. editor.undoManager.undo();
  27580. },
  27581. Redo: function () {
  27582. editor.undoManager.redo();
  27583. }
  27584. });
  27585. self.addQueryValueHandler('FontName', function () {
  27586. return fontNameQuery(editor);
  27587. }, this);
  27588. self.addQueryValueHandler('FontSize', function () {
  27589. return fontSizeQuery(editor);
  27590. }, this);
  27591. self.addQueryValueHandler('LineHeight', function () {
  27592. return lineHeightQuery(editor);
  27593. }, this);
  27594. };
  27595. return EditorCommands;
  27596. }();
  27597. var internalContentEditableAttr = 'data-mce-contenteditable';
  27598. var toggleClass = function (elm, cls, state) {
  27599. if (has(elm, cls) && state === false) {
  27600. remove$3(elm, cls);
  27601. } else if (state) {
  27602. add$1(elm, cls);
  27603. }
  27604. };
  27605. var setEditorCommandState = function (editor, cmd, state) {
  27606. try {
  27607. editor.getDoc().execCommand(cmd, false, String(state));
  27608. } catch (ex) {
  27609. }
  27610. };
  27611. var setContentEditable = function (elm, state) {
  27612. elm.dom.contentEditable = state ? 'true' : 'false';
  27613. };
  27614. var switchOffContentEditableTrue = function (elm) {
  27615. each$k(descendants(elm, '*[contenteditable="true"]'), function (elm) {
  27616. set$1(elm, internalContentEditableAttr, 'true');
  27617. setContentEditable(elm, false);
  27618. });
  27619. };
  27620. var switchOnContentEditableTrue = function (elm) {
  27621. each$k(descendants(elm, '*[' + internalContentEditableAttr + '="true"]'), function (elm) {
  27622. remove$6(elm, internalContentEditableAttr);
  27623. setContentEditable(elm, true);
  27624. });
  27625. };
  27626. var removeFakeSelection = function (editor) {
  27627. Optional.from(editor.selection.getNode()).each(function (elm) {
  27628. elm.removeAttribute('data-mce-selected');
  27629. });
  27630. };
  27631. var restoreFakeSelection = function (editor) {
  27632. editor.selection.setRng(editor.selection.getRng());
  27633. };
  27634. var toggleReadOnly = function (editor, state) {
  27635. var body = SugarElement.fromDom(editor.getBody());
  27636. toggleClass(body, 'mce-content-readonly', state);
  27637. if (state) {
  27638. editor.selection.controlSelection.hideResizeRect();
  27639. editor._selectionOverrides.hideFakeCaret();
  27640. removeFakeSelection(editor);
  27641. editor.readonly = true;
  27642. setContentEditable(body, false);
  27643. switchOffContentEditableTrue(body);
  27644. } else {
  27645. editor.readonly = false;
  27646. setContentEditable(body, true);
  27647. switchOnContentEditableTrue(body);
  27648. setEditorCommandState(editor, 'StyleWithCSS', false);
  27649. setEditorCommandState(editor, 'enableInlineTableEditing', false);
  27650. setEditorCommandState(editor, 'enableObjectResizing', false);
  27651. if (hasEditorOrUiFocus(editor)) {
  27652. editor.focus();
  27653. }
  27654. restoreFakeSelection(editor);
  27655. editor.nodeChanged();
  27656. }
  27657. };
  27658. var isReadOnly = function (editor) {
  27659. return editor.readonly;
  27660. };
  27661. var registerFilters = function (editor) {
  27662. editor.parser.addAttributeFilter('contenteditable', function (nodes) {
  27663. if (isReadOnly(editor)) {
  27664. each$k(nodes, function (node) {
  27665. node.attr(internalContentEditableAttr, node.attr('contenteditable'));
  27666. node.attr('contenteditable', 'false');
  27667. });
  27668. }
  27669. });
  27670. editor.serializer.addAttributeFilter(internalContentEditableAttr, function (nodes) {
  27671. if (isReadOnly(editor)) {
  27672. each$k(nodes, function (node) {
  27673. node.attr('contenteditable', node.attr(internalContentEditableAttr));
  27674. });
  27675. }
  27676. });
  27677. editor.serializer.addTempAttr(internalContentEditableAttr);
  27678. };
  27679. var registerReadOnlyContentFilters = function (editor) {
  27680. if (editor.serializer) {
  27681. registerFilters(editor);
  27682. } else {
  27683. editor.on('PreInit', function () {
  27684. registerFilters(editor);
  27685. });
  27686. }
  27687. };
  27688. var isClickEvent = function (e) {
  27689. return e.type === 'click';
  27690. };
  27691. var getAnchorHrefOpt = function (editor, elm) {
  27692. var isRoot = function (elm) {
  27693. return eq(elm, SugarElement.fromDom(editor.getBody()));
  27694. };
  27695. return closest$2(elm, 'a', isRoot).bind(function (a) {
  27696. return getOpt(a, 'href');
  27697. });
  27698. };
  27699. var processReadonlyEvents = function (editor, e) {
  27700. if (isClickEvent(e) && !VK.metaKeyPressed(e)) {
  27701. var elm = SugarElement.fromDom(e.target);
  27702. getAnchorHrefOpt(editor, elm).each(function (href) {
  27703. e.preventDefault();
  27704. if (/^#/.test(href)) {
  27705. var targetEl = editor.dom.select(href + ',[name="' + removeLeading(href, '#') + '"]');
  27706. if (targetEl.length) {
  27707. editor.selection.scrollIntoView(targetEl[0], true);
  27708. }
  27709. } else {
  27710. window.open(href, '_blank', 'rel=noopener noreferrer,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes,scrollbars=yes');
  27711. }
  27712. });
  27713. }
  27714. };
  27715. var registerReadOnlySelectionBlockers = function (editor) {
  27716. editor.on('ShowCaret', function (e) {
  27717. if (isReadOnly(editor)) {
  27718. e.preventDefault();
  27719. }
  27720. });
  27721. editor.on('ObjectSelected', function (e) {
  27722. if (isReadOnly(editor)) {
  27723. e.preventDefault();
  27724. }
  27725. });
  27726. };
  27727. 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', ' ');
  27728. var EventDispatcher = function () {
  27729. function EventDispatcher(settings) {
  27730. this.bindings = {};
  27731. this.settings = settings || {};
  27732. this.scope = this.settings.scope || this;
  27733. this.toggleEvent = this.settings.toggleEvent || never;
  27734. }
  27735. EventDispatcher.isNative = function (name) {
  27736. return !!nativeEvents[name.toLowerCase()];
  27737. };
  27738. EventDispatcher.prototype.fire = function (name, args) {
  27739. var lcName = name.toLowerCase();
  27740. var event = normalize$3(lcName, args || {}, this.scope);
  27741. if (this.settings.beforeFire) {
  27742. this.settings.beforeFire(event);
  27743. }
  27744. var handlers = this.bindings[lcName];
  27745. if (handlers) {
  27746. for (var i = 0, l = handlers.length; i < l; i++) {
  27747. var callback = handlers[i];
  27748. if (callback.removed) {
  27749. continue;
  27750. }
  27751. if (callback.once) {
  27752. this.off(lcName, callback.func);
  27753. }
  27754. if (event.isImmediatePropagationStopped()) {
  27755. return event;
  27756. }
  27757. if (callback.func.call(this.scope, event) === false) {
  27758. event.preventDefault();
  27759. return event;
  27760. }
  27761. }
  27762. }
  27763. return event;
  27764. };
  27765. EventDispatcher.prototype.on = function (name, callback, prepend, extra) {
  27766. if (callback === false) {
  27767. callback = never;
  27768. }
  27769. if (callback) {
  27770. var wrappedCallback = {
  27771. func: callback,
  27772. removed: false
  27773. };
  27774. if (extra) {
  27775. Tools.extend(wrappedCallback, extra);
  27776. }
  27777. var names = name.toLowerCase().split(' ');
  27778. var i = names.length;
  27779. while (i--) {
  27780. var currentName = names[i];
  27781. var handlers = this.bindings[currentName];
  27782. if (!handlers) {
  27783. handlers = [];
  27784. this.toggleEvent(currentName, true);
  27785. }
  27786. if (prepend) {
  27787. handlers = __spreadArray([wrappedCallback], handlers);
  27788. } else {
  27789. handlers = __spreadArray(__spreadArray([], handlers), [wrappedCallback]);
  27790. }
  27791. this.bindings[currentName] = handlers;
  27792. }
  27793. }
  27794. return this;
  27795. };
  27796. EventDispatcher.prototype.off = function (name, callback) {
  27797. var _this = this;
  27798. if (name) {
  27799. var names = name.toLowerCase().split(' ');
  27800. var i = names.length;
  27801. while (i--) {
  27802. var currentName = names[i];
  27803. var handlers = this.bindings[currentName];
  27804. if (!currentName) {
  27805. each$j(this.bindings, function (_value, bindingName) {
  27806. _this.toggleEvent(bindingName, false);
  27807. delete _this.bindings[bindingName];
  27808. });
  27809. return this;
  27810. }
  27811. if (handlers) {
  27812. if (!callback) {
  27813. handlers.length = 0;
  27814. } else {
  27815. var filteredHandlers = partition(handlers, function (handler) {
  27816. return handler.func === callback;
  27817. });
  27818. handlers = filteredHandlers.fail;
  27819. this.bindings[currentName] = handlers;
  27820. each$k(filteredHandlers.pass, function (handler) {
  27821. handler.removed = true;
  27822. });
  27823. }
  27824. if (!handlers.length) {
  27825. this.toggleEvent(name, false);
  27826. delete this.bindings[currentName];
  27827. }
  27828. }
  27829. }
  27830. } else {
  27831. each$j(this.bindings, function (_value, name) {
  27832. _this.toggleEvent(name, false);
  27833. });
  27834. this.bindings = {};
  27835. }
  27836. return this;
  27837. };
  27838. EventDispatcher.prototype.once = function (name, callback, prepend) {
  27839. return this.on(name, callback, prepend, { once: true });
  27840. };
  27841. EventDispatcher.prototype.has = function (name) {
  27842. name = name.toLowerCase();
  27843. return !(!this.bindings[name] || this.bindings[name].length === 0);
  27844. };
  27845. return EventDispatcher;
  27846. }();
  27847. var getEventDispatcher = function (obj) {
  27848. if (!obj._eventDispatcher) {
  27849. obj._eventDispatcher = new EventDispatcher({
  27850. scope: obj,
  27851. toggleEvent: function (name, state) {
  27852. if (EventDispatcher.isNative(name) && obj.toggleNativeEvent) {
  27853. obj.toggleNativeEvent(name, state);
  27854. }
  27855. }
  27856. });
  27857. }
  27858. return obj._eventDispatcher;
  27859. };
  27860. var Observable = {
  27861. fire: function (name, args, bubble) {
  27862. var self = this;
  27863. if (self.removed && name !== 'remove' && name !== 'detach') {
  27864. return args;
  27865. }
  27866. var dispatcherArgs = getEventDispatcher(self).fire(name, args);
  27867. if (bubble !== false && self.parent) {
  27868. var parent_1 = self.parent();
  27869. while (parent_1 && !dispatcherArgs.isPropagationStopped()) {
  27870. parent_1.fire(name, dispatcherArgs, false);
  27871. parent_1 = parent_1.parent();
  27872. }
  27873. }
  27874. return dispatcherArgs;
  27875. },
  27876. on: function (name, callback, prepend) {
  27877. return getEventDispatcher(this).on(name, callback, prepend);
  27878. },
  27879. off: function (name, callback) {
  27880. return getEventDispatcher(this).off(name, callback);
  27881. },
  27882. once: function (name, callback) {
  27883. return getEventDispatcher(this).once(name, callback);
  27884. },
  27885. hasEventListeners: function (name) {
  27886. return getEventDispatcher(this).has(name);
  27887. }
  27888. };
  27889. var DOM$2 = DOMUtils.DOM;
  27890. var customEventRootDelegates;
  27891. var getEventTarget = function (editor, eventName) {
  27892. if (eventName === 'selectionchange') {
  27893. return editor.getDoc();
  27894. }
  27895. if (!editor.inline && /^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(eventName)) {
  27896. return editor.getDoc().documentElement;
  27897. }
  27898. var eventRoot = getEventRoot(editor);
  27899. if (eventRoot) {
  27900. if (!editor.eventRoot) {
  27901. editor.eventRoot = DOM$2.select(eventRoot)[0];
  27902. }
  27903. return editor.eventRoot;
  27904. }
  27905. return editor.getBody();
  27906. };
  27907. var isListening = function (editor) {
  27908. return !editor.hidden && !isReadOnly(editor);
  27909. };
  27910. var fireEvent = function (editor, eventName, e) {
  27911. if (isListening(editor)) {
  27912. editor.fire(eventName, e);
  27913. } else if (isReadOnly(editor)) {
  27914. processReadonlyEvents(editor, e);
  27915. }
  27916. };
  27917. var bindEventDelegate = function (editor, eventName) {
  27918. var delegate;
  27919. if (!editor.delegates) {
  27920. editor.delegates = {};
  27921. }
  27922. if (editor.delegates[eventName] || editor.removed) {
  27923. return;
  27924. }
  27925. var eventRootElm = getEventTarget(editor, eventName);
  27926. if (getEventRoot(editor)) {
  27927. if (!customEventRootDelegates) {
  27928. customEventRootDelegates = {};
  27929. editor.editorManager.on('removeEditor', function () {
  27930. if (!editor.editorManager.activeEditor) {
  27931. if (customEventRootDelegates) {
  27932. each$j(customEventRootDelegates, function (_value, name) {
  27933. editor.dom.unbind(getEventTarget(editor, name));
  27934. });
  27935. customEventRootDelegates = null;
  27936. }
  27937. }
  27938. });
  27939. }
  27940. if (customEventRootDelegates[eventName]) {
  27941. return;
  27942. }
  27943. delegate = function (e) {
  27944. var target = e.target;
  27945. var editors = editor.editorManager.get();
  27946. var i = editors.length;
  27947. while (i--) {
  27948. var body = editors[i].getBody();
  27949. if (body === target || DOM$2.isChildOf(target, body)) {
  27950. fireEvent(editors[i], eventName, e);
  27951. }
  27952. }
  27953. };
  27954. customEventRootDelegates[eventName] = delegate;
  27955. DOM$2.bind(eventRootElm, eventName, delegate);
  27956. } else {
  27957. delegate = function (e) {
  27958. fireEvent(editor, eventName, e);
  27959. };
  27960. DOM$2.bind(eventRootElm, eventName, delegate);
  27961. editor.delegates[eventName] = delegate;
  27962. }
  27963. };
  27964. var EditorObservable = __assign(__assign({}, Observable), {
  27965. bindPendingEventDelegates: function () {
  27966. var self = this;
  27967. Tools.each(self._pendingNativeEvents, function (name) {
  27968. bindEventDelegate(self, name);
  27969. });
  27970. },
  27971. toggleNativeEvent: function (name, state) {
  27972. var self = this;
  27973. if (name === 'focus' || name === 'blur') {
  27974. return;
  27975. }
  27976. if (self.removed) {
  27977. return;
  27978. }
  27979. if (state) {
  27980. if (self.initialized) {
  27981. bindEventDelegate(self, name);
  27982. } else {
  27983. if (!self._pendingNativeEvents) {
  27984. self._pendingNativeEvents = [name];
  27985. } else {
  27986. self._pendingNativeEvents.push(name);
  27987. }
  27988. }
  27989. } else if (self.initialized) {
  27990. self.dom.unbind(getEventTarget(self, name), name, self.delegates[name]);
  27991. delete self.delegates[name];
  27992. }
  27993. },
  27994. unbindAllNativeEvents: function () {
  27995. var self = this;
  27996. var body = self.getBody();
  27997. var dom = self.dom;
  27998. if (self.delegates) {
  27999. each$j(self.delegates, function (value, name) {
  28000. self.dom.unbind(getEventTarget(self, name), name, value);
  28001. });
  28002. delete self.delegates;
  28003. }
  28004. if (!self.inline && body && dom) {
  28005. body.onload = null;
  28006. dom.unbind(self.getWin());
  28007. dom.unbind(self.getDoc());
  28008. }
  28009. if (dom) {
  28010. dom.unbind(body);
  28011. dom.unbind(self.getContainer());
  28012. }
  28013. }
  28014. });
  28015. var defaultModes = [
  28016. 'design',
  28017. 'readonly'
  28018. ];
  28019. var switchToMode = function (editor, activeMode, availableModes, mode) {
  28020. var oldMode = availableModes[activeMode.get()];
  28021. var newMode = availableModes[mode];
  28022. try {
  28023. newMode.activate();
  28024. } catch (e) {
  28025. console.error('problem while activating editor mode ' + mode + ':', e);
  28026. return;
  28027. }
  28028. oldMode.deactivate();
  28029. if (oldMode.editorReadOnly !== newMode.editorReadOnly) {
  28030. toggleReadOnly(editor, newMode.editorReadOnly);
  28031. }
  28032. activeMode.set(mode);
  28033. fireSwitchMode(editor, mode);
  28034. };
  28035. var setMode = function (editor, availableModes, activeMode, mode) {
  28036. if (mode === activeMode.get()) {
  28037. return;
  28038. } else if (!has$2(availableModes, mode)) {
  28039. throw new Error('Editor mode \'' + mode + '\' is invalid');
  28040. }
  28041. if (editor.initialized) {
  28042. switchToMode(editor, activeMode, availableModes, mode);
  28043. } else {
  28044. editor.on('init', function () {
  28045. return switchToMode(editor, activeMode, availableModes, mode);
  28046. });
  28047. }
  28048. };
  28049. var registerMode = function (availableModes, mode, api) {
  28050. var _a;
  28051. if (contains$3(defaultModes, mode)) {
  28052. throw new Error('Cannot override default mode ' + mode);
  28053. }
  28054. return __assign(__assign({}, availableModes), (_a = {}, _a[mode] = __assign(__assign({}, api), {
  28055. deactivate: function () {
  28056. try {
  28057. api.deactivate();
  28058. } catch (e) {
  28059. console.error('problem while deactivating editor mode ' + mode + ':', e);
  28060. }
  28061. }
  28062. }), _a));
  28063. };
  28064. var create$4 = function (editor) {
  28065. var activeMode = Cell('design');
  28066. var availableModes = Cell({
  28067. design: {
  28068. activate: noop,
  28069. deactivate: noop,
  28070. editorReadOnly: false
  28071. },
  28072. readonly: {
  28073. activate: noop,
  28074. deactivate: noop,
  28075. editorReadOnly: true
  28076. }
  28077. });
  28078. registerReadOnlyContentFilters(editor);
  28079. registerReadOnlySelectionBlockers(editor);
  28080. return {
  28081. isReadOnly: function () {
  28082. return isReadOnly(editor);
  28083. },
  28084. set: function (mode) {
  28085. return setMode(editor, availableModes.get(), activeMode, mode);
  28086. },
  28087. get: function () {
  28088. return activeMode.get();
  28089. },
  28090. register: function (mode, api) {
  28091. availableModes.set(registerMode(availableModes.get(), mode, api));
  28092. }
  28093. };
  28094. };
  28095. var each$4 = Tools.each, explode$1 = Tools.explode;
  28096. var keyCodeLookup = {
  28097. f1: 112,
  28098. f2: 113,
  28099. f3: 114,
  28100. f4: 115,
  28101. f5: 116,
  28102. f6: 117,
  28103. f7: 118,
  28104. f8: 119,
  28105. f9: 120,
  28106. f10: 121,
  28107. f11: 122,
  28108. f12: 123
  28109. };
  28110. var modifierNames = Tools.makeMap('alt,ctrl,shift,meta,access');
  28111. var parseShortcut = function (pattern) {
  28112. var key;
  28113. var shortcut = {};
  28114. each$4(explode$1(pattern.toLowerCase(), '+'), function (value) {
  28115. if (value in modifierNames) {
  28116. shortcut[value] = true;
  28117. } else {
  28118. if (/^[0-9]{2,}$/.test(value)) {
  28119. shortcut.keyCode = parseInt(value, 10);
  28120. } else {
  28121. shortcut.charCode = value.charCodeAt(0);
  28122. shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);
  28123. }
  28124. }
  28125. });
  28126. var id = [shortcut.keyCode];
  28127. for (key in modifierNames) {
  28128. if (shortcut[key]) {
  28129. id.push(key);
  28130. } else {
  28131. shortcut[key] = false;
  28132. }
  28133. }
  28134. shortcut.id = id.join(',');
  28135. if (shortcut.access) {
  28136. shortcut.alt = true;
  28137. if (Env.mac) {
  28138. shortcut.ctrl = true;
  28139. } else {
  28140. shortcut.shift = true;
  28141. }
  28142. }
  28143. if (shortcut.meta) {
  28144. if (Env.mac) {
  28145. shortcut.meta = true;
  28146. } else {
  28147. shortcut.ctrl = true;
  28148. shortcut.meta = false;
  28149. }
  28150. }
  28151. return shortcut;
  28152. };
  28153. var Shortcuts = function () {
  28154. function Shortcuts(editor) {
  28155. this.shortcuts = {};
  28156. this.pendingPatterns = [];
  28157. this.editor = editor;
  28158. var self = this;
  28159. editor.on('keyup keypress keydown', function (e) {
  28160. if ((self.hasModifier(e) || self.isFunctionKey(e)) && !e.isDefaultPrevented()) {
  28161. each$4(self.shortcuts, function (shortcut) {
  28162. if (self.matchShortcut(e, shortcut)) {
  28163. self.pendingPatterns = shortcut.subpatterns.slice(0);
  28164. if (e.type === 'keydown') {
  28165. self.executeShortcutAction(shortcut);
  28166. }
  28167. return true;
  28168. }
  28169. });
  28170. if (self.matchShortcut(e, self.pendingPatterns[0])) {
  28171. if (self.pendingPatterns.length === 1) {
  28172. if (e.type === 'keydown') {
  28173. self.executeShortcutAction(self.pendingPatterns[0]);
  28174. }
  28175. }
  28176. self.pendingPatterns.shift();
  28177. }
  28178. }
  28179. });
  28180. }
  28181. Shortcuts.prototype.add = function (pattern, desc, cmdFunc, scope) {
  28182. var self = this;
  28183. var func = self.normalizeCommandFunc(cmdFunc);
  28184. each$4(explode$1(Tools.trim(pattern)), function (pattern) {
  28185. var shortcut = self.createShortcut(pattern, desc, func, scope);
  28186. self.shortcuts[shortcut.id] = shortcut;
  28187. });
  28188. return true;
  28189. };
  28190. Shortcuts.prototype.remove = function (pattern) {
  28191. var shortcut = this.createShortcut(pattern);
  28192. if (this.shortcuts[shortcut.id]) {
  28193. delete this.shortcuts[shortcut.id];
  28194. return true;
  28195. }
  28196. return false;
  28197. };
  28198. Shortcuts.prototype.normalizeCommandFunc = function (cmdFunc) {
  28199. var self = this;
  28200. var cmd = cmdFunc;
  28201. if (typeof cmd === 'string') {
  28202. return function () {
  28203. self.editor.execCommand(cmd, false, null);
  28204. };
  28205. } else if (Tools.isArray(cmd)) {
  28206. return function () {
  28207. self.editor.execCommand(cmd[0], cmd[1], cmd[2]);
  28208. };
  28209. } else {
  28210. return cmd;
  28211. }
  28212. };
  28213. Shortcuts.prototype.createShortcut = function (pattern, desc, cmdFunc, scope) {
  28214. var shortcuts = Tools.map(explode$1(pattern, '>'), parseShortcut);
  28215. shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {
  28216. func: cmdFunc,
  28217. scope: scope || this.editor
  28218. });
  28219. return Tools.extend(shortcuts[0], {
  28220. desc: this.editor.translate(desc),
  28221. subpatterns: shortcuts.slice(1)
  28222. });
  28223. };
  28224. Shortcuts.prototype.hasModifier = function (e) {
  28225. return e.altKey || e.ctrlKey || e.metaKey;
  28226. };
  28227. Shortcuts.prototype.isFunctionKey = function (e) {
  28228. return e.type === 'keydown' && e.keyCode >= 112 && e.keyCode <= 123;
  28229. };
  28230. Shortcuts.prototype.matchShortcut = function (e, shortcut) {
  28231. if (!shortcut) {
  28232. return false;
  28233. }
  28234. if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
  28235. return false;
  28236. }
  28237. if (shortcut.alt !== e.altKey || shortcut.shift !== e.shiftKey) {
  28238. return false;
  28239. }
  28240. if (e.keyCode === shortcut.keyCode || e.charCode && e.charCode === shortcut.charCode) {
  28241. e.preventDefault();
  28242. return true;
  28243. }
  28244. return false;
  28245. };
  28246. Shortcuts.prototype.executeShortcutAction = function (shortcut) {
  28247. return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
  28248. };
  28249. return Shortcuts;
  28250. }();
  28251. var create$3 = function () {
  28252. var buttons = {};
  28253. var menuItems = {};
  28254. var popups = {};
  28255. var icons = {};
  28256. var contextMenus = {};
  28257. var contextToolbars = {};
  28258. var sidebars = {};
  28259. var add = function (collection, type) {
  28260. return function (name, spec) {
  28261. return collection[name.toLowerCase()] = __assign(__assign({}, spec), { type: type });
  28262. };
  28263. };
  28264. var addIcon = function (name, svgData) {
  28265. return icons[name.toLowerCase()] = svgData;
  28266. };
  28267. return {
  28268. addButton: add(buttons, 'button'),
  28269. addGroupToolbarButton: add(buttons, 'grouptoolbarbutton'),
  28270. addToggleButton: add(buttons, 'togglebutton'),
  28271. addMenuButton: add(buttons, 'menubutton'),
  28272. addSplitButton: add(buttons, 'splitbutton'),
  28273. addMenuItem: add(menuItems, 'menuitem'),
  28274. addNestedMenuItem: add(menuItems, 'nestedmenuitem'),
  28275. addToggleMenuItem: add(menuItems, 'togglemenuitem'),
  28276. addAutocompleter: add(popups, 'autocompleter'),
  28277. addContextMenu: add(contextMenus, 'contextmenu'),
  28278. addContextToolbar: add(contextToolbars, 'contexttoolbar'),
  28279. addContextForm: add(contextToolbars, 'contextform'),
  28280. addSidebar: add(sidebars, 'sidebar'),
  28281. addIcon: addIcon,
  28282. getAll: function () {
  28283. return {
  28284. buttons: buttons,
  28285. menuItems: menuItems,
  28286. icons: icons,
  28287. popups: popups,
  28288. contextMenus: contextMenus,
  28289. contextToolbars: contextToolbars,
  28290. sidebars: sidebars
  28291. };
  28292. }
  28293. };
  28294. };
  28295. var registry = function () {
  28296. var bridge = create$3();
  28297. return {
  28298. addAutocompleter: bridge.addAutocompleter,
  28299. addButton: bridge.addButton,
  28300. addContextForm: bridge.addContextForm,
  28301. addContextMenu: bridge.addContextMenu,
  28302. addContextToolbar: bridge.addContextToolbar,
  28303. addIcon: bridge.addIcon,
  28304. addMenuButton: bridge.addMenuButton,
  28305. addMenuItem: bridge.addMenuItem,
  28306. addNestedMenuItem: bridge.addNestedMenuItem,
  28307. addSidebar: bridge.addSidebar,
  28308. addSplitButton: bridge.addSplitButton,
  28309. addToggleButton: bridge.addToggleButton,
  28310. addGroupToolbarButton: bridge.addGroupToolbarButton,
  28311. addToggleMenuItem: bridge.addToggleMenuItem,
  28312. getAll: bridge.getAll
  28313. };
  28314. };
  28315. var each$3 = Tools.each, trim = Tools.trim;
  28316. var queryParts = 'source protocol authority userInfo user password host port relative path directory file query anchor'.split(' ');
  28317. var DEFAULT_PORTS = {
  28318. ftp: 21,
  28319. http: 80,
  28320. https: 443,
  28321. mailto: 25
  28322. };
  28323. var URI = function () {
  28324. function URI(url, settings) {
  28325. url = trim(url);
  28326. this.settings = settings || {};
  28327. var baseUri = this.settings.base_uri;
  28328. var self = this;
  28329. if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
  28330. self.source = url;
  28331. return;
  28332. }
  28333. var isProtocolRelative = url.indexOf('//') === 0;
  28334. if (url.indexOf('/') === 0 && !isProtocolRelative) {
  28335. url = (baseUri ? baseUri.protocol || 'http' : 'http') + '://mce_host' + url;
  28336. }
  28337. if (!/^[\w\-]*:?\/\//.test(url)) {
  28338. var baseUrl = this.settings.base_uri ? this.settings.base_uri.path : new URI(document.location.href).directory;
  28339. if (this.settings.base_uri && this.settings.base_uri.protocol == '') {
  28340. url = '//mce_host' + self.toAbsPath(baseUrl, url);
  28341. } else {
  28342. var match = /([^#?]*)([#?]?.*)/.exec(url);
  28343. url = (baseUri && baseUri.protocol || 'http') + '://mce_host' + self.toAbsPath(baseUrl, match[1]) + match[2];
  28344. }
  28345. }
  28346. url = url.replace(/@@/g, '(mce_at)');
  28347. var urlMatch = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?(\[[a-zA-Z0-9:.%]+\]|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
  28348. each$3(queryParts, function (v, i) {
  28349. var part = urlMatch[i];
  28350. if (part) {
  28351. part = part.replace(/\(mce_at\)/g, '@@');
  28352. }
  28353. self[v] = part;
  28354. });
  28355. if (baseUri) {
  28356. if (!self.protocol) {
  28357. self.protocol = baseUri.protocol;
  28358. }
  28359. if (!self.userInfo) {
  28360. self.userInfo = baseUri.userInfo;
  28361. }
  28362. if (!self.port && self.host === 'mce_host') {
  28363. self.port = baseUri.port;
  28364. }
  28365. if (!self.host || self.host === 'mce_host') {
  28366. self.host = baseUri.host;
  28367. }
  28368. self.source = '';
  28369. }
  28370. if (isProtocolRelative) {
  28371. self.protocol = '';
  28372. }
  28373. }
  28374. URI.parseDataUri = function (uri) {
  28375. var type;
  28376. var uriComponents = decodeURIComponent(uri).split(',');
  28377. var matches = /data:([^;]+)/.exec(uriComponents[0]);
  28378. if (matches) {
  28379. type = matches[1];
  28380. }
  28381. return {
  28382. type: type,
  28383. data: uriComponents[1]
  28384. };
  28385. };
  28386. URI.getDocumentBaseUrl = function (loc) {
  28387. var baseUrl;
  28388. if (loc.protocol.indexOf('http') !== 0 && loc.protocol !== 'file:') {
  28389. baseUrl = loc.href;
  28390. } else {
  28391. baseUrl = loc.protocol + '//' + loc.host + loc.pathname;
  28392. }
  28393. if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
  28394. baseUrl = baseUrl.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  28395. if (!/[\/\\]$/.test(baseUrl)) {
  28396. baseUrl += '/';
  28397. }
  28398. }
  28399. return baseUrl;
  28400. };
  28401. URI.prototype.setPath = function (path) {
  28402. var pathMatch = /^(.*?)\/?(\w+)?$/.exec(path);
  28403. this.path = pathMatch[0];
  28404. this.directory = pathMatch[1];
  28405. this.file = pathMatch[2];
  28406. this.source = '';
  28407. this.getURI();
  28408. };
  28409. URI.prototype.toRelative = function (uri) {
  28410. var output;
  28411. if (uri === './') {
  28412. return uri;
  28413. }
  28414. var relativeUri = new URI(uri, { base_uri: this });
  28415. if (relativeUri.host !== 'mce_host' && this.host !== relativeUri.host && relativeUri.host || this.port !== relativeUri.port || this.protocol !== relativeUri.protocol && relativeUri.protocol !== '') {
  28416. return relativeUri.getURI();
  28417. }
  28418. var tu = this.getURI(), uu = relativeUri.getURI();
  28419. if (tu === uu || tu.charAt(tu.length - 1) === '/' && tu.substr(0, tu.length - 1) === uu) {
  28420. return tu;
  28421. }
  28422. output = this.toRelPath(this.path, relativeUri.path);
  28423. if (relativeUri.query) {
  28424. output += '?' + relativeUri.query;
  28425. }
  28426. if (relativeUri.anchor) {
  28427. output += '#' + relativeUri.anchor;
  28428. }
  28429. return output;
  28430. };
  28431. URI.prototype.toAbsolute = function (uri, noHost) {
  28432. var absoluteUri = new URI(uri, { base_uri: this });
  28433. return absoluteUri.getURI(noHost && this.isSameOrigin(absoluteUri));
  28434. };
  28435. URI.prototype.isSameOrigin = function (uri) {
  28436. if (this.host == uri.host && this.protocol == uri.protocol) {
  28437. if (this.port == uri.port) {
  28438. return true;
  28439. }
  28440. var defaultPort = DEFAULT_PORTS[this.protocol];
  28441. if (defaultPort && (this.port || defaultPort) == (uri.port || defaultPort)) {
  28442. return true;
  28443. }
  28444. }
  28445. return false;
  28446. };
  28447. URI.prototype.toRelPath = function (base, path) {
  28448. var breakPoint = 0, out = '', i, l;
  28449. var normalizedBase = base.substring(0, base.lastIndexOf('/')).split('/');
  28450. var items = path.split('/');
  28451. if (normalizedBase.length >= items.length) {
  28452. for (i = 0, l = normalizedBase.length; i < l; i++) {
  28453. if (i >= items.length || normalizedBase[i] !== items[i]) {
  28454. breakPoint = i + 1;
  28455. break;
  28456. }
  28457. }
  28458. }
  28459. if (normalizedBase.length < items.length) {
  28460. for (i = 0, l = items.length; i < l; i++) {
  28461. if (i >= normalizedBase.length || normalizedBase[i] !== items[i]) {
  28462. breakPoint = i + 1;
  28463. break;
  28464. }
  28465. }
  28466. }
  28467. if (breakPoint === 1) {
  28468. return path;
  28469. }
  28470. for (i = 0, l = normalizedBase.length - (breakPoint - 1); i < l; i++) {
  28471. out += '../';
  28472. }
  28473. for (i = breakPoint - 1, l = items.length; i < l; i++) {
  28474. if (i !== breakPoint - 1) {
  28475. out += '/' + items[i];
  28476. } else {
  28477. out += items[i];
  28478. }
  28479. }
  28480. return out;
  28481. };
  28482. URI.prototype.toAbsPath = function (base, path) {
  28483. var i, nb = 0, o = [], outPath;
  28484. var tr = /\/$/.test(path) ? '/' : '';
  28485. var normalizedBase = base.split('/');
  28486. var normalizedPath = path.split('/');
  28487. each$3(normalizedBase, function (k) {
  28488. if (k) {
  28489. o.push(k);
  28490. }
  28491. });
  28492. normalizedBase = o;
  28493. for (i = normalizedPath.length - 1, o = []; i >= 0; i--) {
  28494. if (normalizedPath[i].length === 0 || normalizedPath[i] === '.') {
  28495. continue;
  28496. }
  28497. if (normalizedPath[i] === '..') {
  28498. nb++;
  28499. continue;
  28500. }
  28501. if (nb > 0) {
  28502. nb--;
  28503. continue;
  28504. }
  28505. o.push(normalizedPath[i]);
  28506. }
  28507. i = normalizedBase.length - nb;
  28508. if (i <= 0) {
  28509. outPath = reverse(o).join('/');
  28510. } else {
  28511. outPath = normalizedBase.slice(0, i).join('/') + '/' + reverse(o).join('/');
  28512. }
  28513. if (outPath.indexOf('/') !== 0) {
  28514. outPath = '/' + outPath;
  28515. }
  28516. if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) {
  28517. outPath += tr;
  28518. }
  28519. return outPath;
  28520. };
  28521. URI.prototype.getURI = function (noProtoHost) {
  28522. if (noProtoHost === void 0) {
  28523. noProtoHost = false;
  28524. }
  28525. var s;
  28526. if (!this.source || noProtoHost) {
  28527. s = '';
  28528. if (!noProtoHost) {
  28529. if (this.protocol) {
  28530. s += this.protocol + '://';
  28531. } else {
  28532. s += '//';
  28533. }
  28534. if (this.userInfo) {
  28535. s += this.userInfo + '@';
  28536. }
  28537. if (this.host) {
  28538. s += this.host;
  28539. }
  28540. if (this.port) {
  28541. s += ':' + this.port;
  28542. }
  28543. }
  28544. if (this.path) {
  28545. s += this.path;
  28546. }
  28547. if (this.query) {
  28548. s += '?' + this.query;
  28549. }
  28550. if (this.anchor) {
  28551. s += '#' + this.anchor;
  28552. }
  28553. this.source = s;
  28554. }
  28555. return this.source;
  28556. };
  28557. return URI;
  28558. }();
  28559. var DOM$1 = DOMUtils.DOM;
  28560. var extend$3 = Tools.extend, each$2 = Tools.each;
  28561. var resolve = Tools.resolve;
  28562. var ie = Env.ie;
  28563. var Editor = function () {
  28564. function Editor(id, settings, editorManager) {
  28565. var _this = this;
  28566. this.plugins = {};
  28567. this.contentCSS = [];
  28568. this.contentStyles = [];
  28569. this.loadedCSS = {};
  28570. this.isNotDirty = false;
  28571. this.editorManager = editorManager;
  28572. this.documentBaseUrl = editorManager.documentBaseURL;
  28573. extend$3(this, EditorObservable);
  28574. this.settings = getEditorSettings(this, id, this.documentBaseUrl, editorManager.defaultSettings, settings);
  28575. if (this.settings.suffix) {
  28576. editorManager.suffix = this.settings.suffix;
  28577. }
  28578. this.suffix = editorManager.suffix;
  28579. if (this.settings.base_url) {
  28580. editorManager._setBaseUrl(this.settings.base_url);
  28581. }
  28582. this.baseUri = editorManager.baseURI;
  28583. if (this.settings.referrer_policy) {
  28584. ScriptLoader.ScriptLoader._setReferrerPolicy(this.settings.referrer_policy);
  28585. DOMUtils.DOM.styleSheetLoader._setReferrerPolicy(this.settings.referrer_policy);
  28586. }
  28587. AddOnManager.languageLoad = this.settings.language_load;
  28588. AddOnManager.baseURL = editorManager.baseURL;
  28589. this.id = id;
  28590. this.setDirty(false);
  28591. this.documentBaseURI = new URI(this.settings.document_base_url, { base_uri: this.baseUri });
  28592. this.baseURI = this.baseUri;
  28593. this.inline = !!this.settings.inline;
  28594. this.shortcuts = new Shortcuts(this);
  28595. this.editorCommands = new EditorCommands(this);
  28596. if (this.settings.cache_suffix) {
  28597. Env.cacheSuffix = this.settings.cache_suffix.replace(/^[\?\&]+/, '');
  28598. }
  28599. this.ui = {
  28600. registry: registry(),
  28601. styleSheetLoader: undefined,
  28602. show: noop,
  28603. hide: noop,
  28604. enable: noop,
  28605. disable: noop,
  28606. isDisabled: never
  28607. };
  28608. var self = this;
  28609. var modeInstance = create$4(self);
  28610. this.mode = modeInstance;
  28611. this.setMode = modeInstance.set;
  28612. editorManager.fire('SetupEditor', { editor: this });
  28613. this.execCallback('setup', this);
  28614. this.$ = DomQuery.overrideDefaults(function () {
  28615. return {
  28616. context: _this.inline ? _this.getBody() : _this.getDoc(),
  28617. element: _this.getBody()
  28618. };
  28619. });
  28620. }
  28621. Editor.prototype.render = function () {
  28622. render(this);
  28623. };
  28624. Editor.prototype.focus = function (skipFocus) {
  28625. this.execCommand('mceFocus', false, skipFocus);
  28626. };
  28627. Editor.prototype.hasFocus = function () {
  28628. return hasFocus(this);
  28629. };
  28630. Editor.prototype.execCallback = function (name) {
  28631. var x = [];
  28632. for (var _i = 1; _i < arguments.length; _i++) {
  28633. x[_i - 1] = arguments[_i];
  28634. }
  28635. var self = this;
  28636. var callback = self.settings[name], scope;
  28637. if (!callback) {
  28638. return;
  28639. }
  28640. if (self.callbackLookup && (scope = self.callbackLookup[name])) {
  28641. callback = scope.func;
  28642. scope = scope.scope;
  28643. }
  28644. if (typeof callback === 'string') {
  28645. scope = callback.replace(/\.\w+$/, '');
  28646. scope = scope ? resolve(scope) : 0;
  28647. callback = resolve(callback);
  28648. self.callbackLookup = self.callbackLookup || {};
  28649. self.callbackLookup[name] = {
  28650. func: callback,
  28651. scope: scope
  28652. };
  28653. }
  28654. return callback.apply(scope || self, x);
  28655. };
  28656. Editor.prototype.translate = function (text) {
  28657. return I18n.translate(text);
  28658. };
  28659. Editor.prototype.getParam = function (name, defaultVal, type) {
  28660. return getParam(this, name, defaultVal, type);
  28661. };
  28662. Editor.prototype.hasPlugin = function (name, loaded) {
  28663. var hasPlugin = contains$3(getPlugins(this).split(/[ ,]/), name);
  28664. if (hasPlugin) {
  28665. return loaded ? PluginManager.get(name) !== undefined : true;
  28666. } else {
  28667. return false;
  28668. }
  28669. };
  28670. Editor.prototype.nodeChanged = function (args) {
  28671. this._nodeChangeDispatcher.nodeChanged(args);
  28672. };
  28673. Editor.prototype.addCommand = function (name, callback, scope) {
  28674. this.editorCommands.addCommand(name, callback, scope);
  28675. };
  28676. Editor.prototype.addQueryStateHandler = function (name, callback, scope) {
  28677. this.editorCommands.addQueryStateHandler(name, callback, scope);
  28678. };
  28679. Editor.prototype.addQueryValueHandler = function (name, callback, scope) {
  28680. this.editorCommands.addQueryValueHandler(name, callback, scope);
  28681. };
  28682. Editor.prototype.addShortcut = function (pattern, desc, cmdFunc, scope) {
  28683. this.shortcuts.add(pattern, desc, cmdFunc, scope);
  28684. };
  28685. Editor.prototype.execCommand = function (cmd, ui, value, args) {
  28686. return this.editorCommands.execCommand(cmd, ui, value, args);
  28687. };
  28688. Editor.prototype.queryCommandState = function (cmd) {
  28689. return this.editorCommands.queryCommandState(cmd);
  28690. };
  28691. Editor.prototype.queryCommandValue = function (cmd) {
  28692. return this.editorCommands.queryCommandValue(cmd);
  28693. };
  28694. Editor.prototype.queryCommandSupported = function (cmd) {
  28695. return this.editorCommands.queryCommandSupported(cmd);
  28696. };
  28697. Editor.prototype.show = function () {
  28698. var self = this;
  28699. if (self.hidden) {
  28700. self.hidden = false;
  28701. if (self.inline) {
  28702. self.getBody().contentEditable = 'true';
  28703. } else {
  28704. DOM$1.show(self.getContainer());
  28705. DOM$1.hide(self.id);
  28706. }
  28707. self.load();
  28708. self.fire('show');
  28709. }
  28710. };
  28711. Editor.prototype.hide = function () {
  28712. var self = this, doc = self.getDoc();
  28713. if (!self.hidden) {
  28714. if (ie && doc && !self.inline) {
  28715. doc.execCommand('SelectAll');
  28716. }
  28717. self.save();
  28718. if (self.inline) {
  28719. self.getBody().contentEditable = 'false';
  28720. if (self === self.editorManager.focusedEditor) {
  28721. self.editorManager.focusedEditor = null;
  28722. }
  28723. } else {
  28724. DOM$1.hide(self.getContainer());
  28725. DOM$1.setStyle(self.id, 'display', self.orgDisplay);
  28726. }
  28727. self.hidden = true;
  28728. self.fire('hide');
  28729. }
  28730. };
  28731. Editor.prototype.isHidden = function () {
  28732. return !!this.hidden;
  28733. };
  28734. Editor.prototype.setProgressState = function (state, time) {
  28735. this.fire('ProgressState', {
  28736. state: state,
  28737. time: time
  28738. });
  28739. };
  28740. Editor.prototype.load = function (args) {
  28741. var self = this;
  28742. var elm = self.getElement(), html;
  28743. if (self.removed) {
  28744. return '';
  28745. }
  28746. if (elm) {
  28747. args = args || {};
  28748. args.load = true;
  28749. var value = isTextareaOrInput(elm) ? elm.value : elm.innerHTML;
  28750. html = self.setContent(value, args);
  28751. args.element = elm;
  28752. if (!args.no_events) {
  28753. self.fire('LoadContent', args);
  28754. }
  28755. args.element = elm = null;
  28756. return html;
  28757. }
  28758. };
  28759. Editor.prototype.save = function (args) {
  28760. var self = this;
  28761. var elm = self.getElement(), html, form;
  28762. if (!elm || !self.initialized || self.removed) {
  28763. return;
  28764. }
  28765. args = args || {};
  28766. args.save = true;
  28767. args.element = elm;
  28768. html = args.content = self.getContent(args);
  28769. if (!args.no_events) {
  28770. self.fire('SaveContent', args);
  28771. }
  28772. if (args.format === 'raw') {
  28773. self.fire('RawSaveContent', args);
  28774. }
  28775. html = args.content;
  28776. if (!isTextareaOrInput(elm)) {
  28777. if (args.is_removing || !self.inline) {
  28778. elm.innerHTML = html;
  28779. }
  28780. if (form = DOM$1.getParent(self.id, 'form')) {
  28781. each$2(form.elements, function (elm) {
  28782. if (elm.name === self.id) {
  28783. elm.value = html;
  28784. return false;
  28785. }
  28786. });
  28787. }
  28788. } else {
  28789. elm.value = html;
  28790. }
  28791. args.element = elm = null;
  28792. if (args.set_dirty !== false) {
  28793. self.setDirty(false);
  28794. }
  28795. return html;
  28796. };
  28797. Editor.prototype.setContent = function (content, args) {
  28798. return setContent(this, content, args);
  28799. };
  28800. Editor.prototype.getContent = function (args) {
  28801. return getContent(this, args);
  28802. };
  28803. Editor.prototype.insertContent = function (content, args) {
  28804. if (args) {
  28805. content = extend$3({ content: content }, args);
  28806. }
  28807. this.execCommand('mceInsertContent', false, content);
  28808. };
  28809. Editor.prototype.resetContent = function (initialContent) {
  28810. if (initialContent === undefined) {
  28811. setContent(this, this.startContent, { format: 'raw' });
  28812. } else {
  28813. setContent(this, initialContent);
  28814. }
  28815. this.undoManager.reset();
  28816. this.setDirty(false);
  28817. this.nodeChanged();
  28818. };
  28819. Editor.prototype.isDirty = function () {
  28820. return !this.isNotDirty;
  28821. };
  28822. Editor.prototype.setDirty = function (state) {
  28823. var oldState = !this.isNotDirty;
  28824. this.isNotDirty = !state;
  28825. if (state && state !== oldState) {
  28826. this.fire('dirty');
  28827. }
  28828. };
  28829. Editor.prototype.getContainer = function () {
  28830. var self = this;
  28831. if (!self.container) {
  28832. self.container = DOM$1.get(self.editorContainer || self.id + '_parent');
  28833. }
  28834. return self.container;
  28835. };
  28836. Editor.prototype.getContentAreaContainer = function () {
  28837. return this.contentAreaContainer;
  28838. };
  28839. Editor.prototype.getElement = function () {
  28840. if (!this.targetElm) {
  28841. this.targetElm = DOM$1.get(this.id);
  28842. }
  28843. return this.targetElm;
  28844. };
  28845. Editor.prototype.getWin = function () {
  28846. var self = this;
  28847. var elm;
  28848. if (!self.contentWindow) {
  28849. elm = self.iframeElement;
  28850. if (elm) {
  28851. self.contentWindow = elm.contentWindow;
  28852. }
  28853. }
  28854. return self.contentWindow;
  28855. };
  28856. Editor.prototype.getDoc = function () {
  28857. var self = this;
  28858. var win;
  28859. if (!self.contentDocument) {
  28860. win = self.getWin();
  28861. if (win) {
  28862. self.contentDocument = win.document;
  28863. }
  28864. }
  28865. return self.contentDocument;
  28866. };
  28867. Editor.prototype.getBody = function () {
  28868. var doc = this.getDoc();
  28869. return this.bodyElement || (doc ? doc.body : null);
  28870. };
  28871. Editor.prototype.convertURL = function (url, name, elm) {
  28872. var self = this, settings = self.settings;
  28873. if (settings.urlconverter_callback) {
  28874. return self.execCallback('urlconverter_callback', url, elm, true, name);
  28875. }
  28876. if (!settings.convert_urls || elm && elm.nodeName === 'LINK' || url.indexOf('file:') === 0 || url.length === 0) {
  28877. return url;
  28878. }
  28879. if (settings.relative_urls) {
  28880. return self.documentBaseURI.toRelative(url);
  28881. }
  28882. url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host);
  28883. return url;
  28884. };
  28885. Editor.prototype.addVisual = function (elm) {
  28886. addVisual(this, elm);
  28887. };
  28888. Editor.prototype.remove = function () {
  28889. remove(this);
  28890. };
  28891. Editor.prototype.destroy = function (automatic) {
  28892. destroy(this, automatic);
  28893. };
  28894. Editor.prototype.uploadImages = function (callback) {
  28895. return this.editorUpload.uploadImages(callback);
  28896. };
  28897. Editor.prototype._scanForImages = function () {
  28898. return this.editorUpload.scanForImages();
  28899. };
  28900. Editor.prototype.addButton = function () {
  28901. 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');
  28902. };
  28903. Editor.prototype.addSidebar = function () {
  28904. throw new Error('editor.addSidebar has been removed in tinymce 5x, use editor.ui.registry.addSidebar instead');
  28905. };
  28906. Editor.prototype.addMenuItem = function () {
  28907. throw new Error('editor.addMenuItem has been removed in tinymce 5x, use editor.ui.registry.addMenuItem instead');
  28908. };
  28909. Editor.prototype.addContextToolbar = function () {
  28910. throw new Error('editor.addContextToolbar has been removed in tinymce 5x, use editor.ui.registry.addContextToolbar instead');
  28911. };
  28912. return Editor;
  28913. }();
  28914. var DOM = DOMUtils.DOM;
  28915. var explode = Tools.explode, each$1 = Tools.each, extend$2 = Tools.extend;
  28916. var instanceCounter = 0, boundGlobalEvents = false;
  28917. var beforeUnloadDelegate;
  28918. var legacyEditors = [];
  28919. var editors = [];
  28920. var isValidLegacyKey = function (id) {
  28921. return id !== 'length';
  28922. };
  28923. var globalEventDelegate = function (e) {
  28924. var type = e.type;
  28925. each$1(EditorManager.get(), function (editor) {
  28926. switch (type) {
  28927. case 'scroll':
  28928. editor.fire('ScrollWindow', e);
  28929. break;
  28930. case 'resize':
  28931. editor.fire('ResizeWindow', e);
  28932. break;
  28933. }
  28934. });
  28935. };
  28936. var toggleGlobalEvents = function (state) {
  28937. if (state !== boundGlobalEvents) {
  28938. if (state) {
  28939. DomQuery(window).on('resize scroll', globalEventDelegate);
  28940. } else {
  28941. DomQuery(window).off('resize scroll', globalEventDelegate);
  28942. }
  28943. boundGlobalEvents = state;
  28944. }
  28945. };
  28946. var removeEditorFromList = function (targetEditor) {
  28947. var oldEditors = editors;
  28948. delete legacyEditors[targetEditor.id];
  28949. for (var i = 0; i < legacyEditors.length; i++) {
  28950. if (legacyEditors[i] === targetEditor) {
  28951. legacyEditors.splice(i, 1);
  28952. break;
  28953. }
  28954. }
  28955. editors = filter$4(editors, function (editor) {
  28956. return targetEditor !== editor;
  28957. });
  28958. if (EditorManager.activeEditor === targetEditor) {
  28959. EditorManager.activeEditor = editors.length > 0 ? editors[0] : null;
  28960. }
  28961. if (EditorManager.focusedEditor === targetEditor) {
  28962. EditorManager.focusedEditor = null;
  28963. }
  28964. return oldEditors.length !== editors.length;
  28965. };
  28966. var purgeDestroyedEditor = function (editor) {
  28967. if (editor && editor.initialized && !(editor.getContainer() || editor.getBody()).parentNode) {
  28968. removeEditorFromList(editor);
  28969. editor.unbindAllNativeEvents();
  28970. editor.destroy(true);
  28971. editor.removed = true;
  28972. editor = null;
  28973. }
  28974. return editor;
  28975. };
  28976. var isQuirksMode = document.compatMode !== 'CSS1Compat';
  28977. var EditorManager = __assign(__assign({}, Observable), {
  28978. baseURI: null,
  28979. baseURL: null,
  28980. defaultSettings: {},
  28981. documentBaseURL: null,
  28982. suffix: null,
  28983. $: DomQuery,
  28984. majorVersion: '5',
  28985. minorVersion: '9.1',
  28986. releaseDate: '2021-08-27',
  28987. editors: legacyEditors,
  28988. i18n: I18n,
  28989. activeEditor: null,
  28990. focusedEditor: null,
  28991. settings: {},
  28992. setup: function () {
  28993. var self = this;
  28994. var baseURL, documentBaseURL, suffix = '';
  28995. documentBaseURL = URI.getDocumentBaseUrl(document.location);
  28996. if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
  28997. documentBaseURL = documentBaseURL.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  28998. if (!/[\/\\]$/.test(documentBaseURL)) {
  28999. documentBaseURL += '/';
  29000. }
  29001. }
  29002. var preInit = window.tinymce || window.tinyMCEPreInit;
  29003. if (preInit) {
  29004. baseURL = preInit.base || preInit.baseURL;
  29005. suffix = preInit.suffix;
  29006. } else {
  29007. var scripts = document.getElementsByTagName('script');
  29008. for (var i = 0; i < scripts.length; i++) {
  29009. var src = scripts[i].src || '';
  29010. if (src === '') {
  29011. continue;
  29012. }
  29013. var srcScript = src.substring(src.lastIndexOf('/'));
  29014. if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
  29015. if (srcScript.indexOf('.min') !== -1) {
  29016. suffix = '.min';
  29017. }
  29018. baseURL = src.substring(0, src.lastIndexOf('/'));
  29019. break;
  29020. }
  29021. }
  29022. if (!baseURL && document.currentScript) {
  29023. var src = document.currentScript.src;
  29024. if (src.indexOf('.min') !== -1) {
  29025. suffix = '.min';
  29026. }
  29027. baseURL = src.substring(0, src.lastIndexOf('/'));
  29028. }
  29029. }
  29030. self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
  29031. self.documentBaseURL = documentBaseURL;
  29032. self.baseURI = new URI(self.baseURL);
  29033. self.suffix = suffix;
  29034. setup$l(self);
  29035. },
  29036. overrideDefaults: function (defaultSettings) {
  29037. var baseUrl = defaultSettings.base_url;
  29038. if (baseUrl) {
  29039. this._setBaseUrl(baseUrl);
  29040. }
  29041. var suffix = defaultSettings.suffix;
  29042. if (defaultSettings.suffix) {
  29043. this.suffix = suffix;
  29044. }
  29045. this.defaultSettings = defaultSettings;
  29046. var pluginBaseUrls = defaultSettings.plugin_base_urls;
  29047. if (pluginBaseUrls !== undefined) {
  29048. each$j(pluginBaseUrls, function (pluginBaseUrl, pluginName) {
  29049. AddOnManager.PluginManager.urls[pluginName] = pluginBaseUrl;
  29050. });
  29051. }
  29052. },
  29053. init: function (settings) {
  29054. var self = this;
  29055. var result;
  29056. 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', ' ');
  29057. var isInvalidInlineTarget = function (settings, elm) {
  29058. return settings.inline && elm.tagName.toLowerCase() in invalidInlineTargets;
  29059. };
  29060. var createId = function (elm) {
  29061. var id = elm.id;
  29062. if (!id) {
  29063. id = get$9(elm, 'name').filter(function (name) {
  29064. return !DOM.get(name);
  29065. }).getOrThunk(DOM.uniqueId);
  29066. elm.setAttribute('id', id);
  29067. }
  29068. return id;
  29069. };
  29070. var execCallback = function (name) {
  29071. var callback = settings[name];
  29072. if (!callback) {
  29073. return;
  29074. }
  29075. return callback.apply(self, []);
  29076. };
  29077. var hasClass = function (elm, className) {
  29078. return className.constructor === RegExp ? className.test(elm.className) : DOM.hasClass(elm, className);
  29079. };
  29080. var findTargets = function (settings) {
  29081. var targets = [];
  29082. if (Env.browser.isIE() && Env.browser.version.major < 11) {
  29083. 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/');
  29084. return [];
  29085. } else if (isQuirksMode) {
  29086. initError('Failed to initialize the editor as the document is not in standards mode. ' + 'TinyMCE requires standards mode.');
  29087. return [];
  29088. }
  29089. if (settings.types) {
  29090. each$1(settings.types, function (type) {
  29091. targets = targets.concat(DOM.select(type.selector));
  29092. });
  29093. return targets;
  29094. } else if (settings.selector) {
  29095. return DOM.select(settings.selector);
  29096. } else if (settings.target) {
  29097. return [settings.target];
  29098. }
  29099. switch (settings.mode) {
  29100. case 'exact':
  29101. var l = settings.elements || '';
  29102. if (l.length > 0) {
  29103. each$1(explode(l), function (id) {
  29104. var elm = DOM.get(id);
  29105. if (elm) {
  29106. targets.push(elm);
  29107. } else {
  29108. each$1(document.forms, function (f) {
  29109. each$1(f.elements, function (e) {
  29110. if (e.name === id) {
  29111. id = 'mce_editor_' + instanceCounter++;
  29112. DOM.setAttrib(e, 'id', id);
  29113. targets.push(e);
  29114. }
  29115. });
  29116. });
  29117. }
  29118. });
  29119. }
  29120. break;
  29121. case 'textareas':
  29122. case 'specific_textareas':
  29123. each$1(DOM.select('textarea'), function (elm) {
  29124. if (settings.editor_deselector && hasClass(elm, settings.editor_deselector)) {
  29125. return;
  29126. }
  29127. if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) {
  29128. targets.push(elm);
  29129. }
  29130. });
  29131. break;
  29132. }
  29133. return targets;
  29134. };
  29135. var provideResults = function (editors) {
  29136. result = editors;
  29137. };
  29138. var initEditors = function () {
  29139. var initCount = 0;
  29140. var editors = [];
  29141. var targets;
  29142. var createEditor = function (id, settings, targetElm) {
  29143. var editor = new Editor(id, settings, self);
  29144. editors.push(editor);
  29145. editor.on('init', function () {
  29146. if (++initCount === targets.length) {
  29147. provideResults(editors);
  29148. }
  29149. });
  29150. editor.targetElm = editor.targetElm || targetElm;
  29151. editor.render();
  29152. };
  29153. DOM.unbind(window, 'ready', initEditors);
  29154. execCallback('onpageload');
  29155. targets = DomQuery.unique(findTargets(settings));
  29156. if (settings.types) {
  29157. each$1(settings.types, function (type) {
  29158. Tools.each(targets, function (elm) {
  29159. if (DOM.is(elm, type.selector)) {
  29160. createEditor(createId(elm), extend$2({}, settings, type), elm);
  29161. return false;
  29162. }
  29163. return true;
  29164. });
  29165. });
  29166. return;
  29167. }
  29168. Tools.each(targets, function (elm) {
  29169. purgeDestroyedEditor(self.get(elm.id));
  29170. });
  29171. targets = Tools.grep(targets, function (elm) {
  29172. return !self.get(elm.id);
  29173. });
  29174. if (targets.length === 0) {
  29175. provideResults([]);
  29176. } else {
  29177. each$1(targets, function (elm) {
  29178. if (isInvalidInlineTarget(settings, elm)) {
  29179. initError('Could not initialize inline editor on invalid inline target element', elm);
  29180. } else {
  29181. createEditor(createId(elm), settings, elm);
  29182. }
  29183. });
  29184. }
  29185. };
  29186. self.settings = settings;
  29187. DOM.bind(window, 'ready', initEditors);
  29188. return new promiseObj(function (resolve) {
  29189. if (result) {
  29190. resolve(result);
  29191. } else {
  29192. provideResults = function (editors) {
  29193. resolve(editors);
  29194. };
  29195. }
  29196. });
  29197. },
  29198. get: function (id) {
  29199. if (arguments.length === 0) {
  29200. return editors.slice(0);
  29201. } else if (isString$1(id)) {
  29202. return find$3(editors, function (editor) {
  29203. return editor.id === id;
  29204. }).getOr(null);
  29205. } else if (isNumber(id)) {
  29206. return editors[id] ? editors[id] : null;
  29207. } else {
  29208. return null;
  29209. }
  29210. },
  29211. add: function (editor) {
  29212. var self = this;
  29213. var existingEditor = legacyEditors[editor.id];
  29214. if (existingEditor === editor) {
  29215. return editor;
  29216. }
  29217. if (self.get(editor.id) === null) {
  29218. if (isValidLegacyKey(editor.id)) {
  29219. legacyEditors[editor.id] = editor;
  29220. }
  29221. legacyEditors.push(editor);
  29222. editors.push(editor);
  29223. }
  29224. toggleGlobalEvents(true);
  29225. self.activeEditor = editor;
  29226. self.fire('AddEditor', { editor: editor });
  29227. if (!beforeUnloadDelegate) {
  29228. beforeUnloadDelegate = function (e) {
  29229. var event = self.fire('BeforeUnload');
  29230. if (event.returnValue) {
  29231. e.preventDefault();
  29232. e.returnValue = event.returnValue;
  29233. return event.returnValue;
  29234. }
  29235. };
  29236. window.addEventListener('beforeunload', beforeUnloadDelegate);
  29237. }
  29238. return editor;
  29239. },
  29240. createEditor: function (id, settings) {
  29241. return this.add(new Editor(id, settings, this));
  29242. },
  29243. remove: function (selector) {
  29244. var self = this;
  29245. var i, editor;
  29246. if (!selector) {
  29247. for (i = editors.length - 1; i >= 0; i--) {
  29248. self.remove(editors[i]);
  29249. }
  29250. return;
  29251. }
  29252. if (isString$1(selector)) {
  29253. each$1(DOM.select(selector), function (elm) {
  29254. editor = self.get(elm.id);
  29255. if (editor) {
  29256. self.remove(editor);
  29257. }
  29258. });
  29259. return;
  29260. }
  29261. editor = selector;
  29262. if (isNull(self.get(editor.id))) {
  29263. return null;
  29264. }
  29265. if (removeEditorFromList(editor)) {
  29266. self.fire('RemoveEditor', { editor: editor });
  29267. }
  29268. if (editors.length === 0) {
  29269. window.removeEventListener('beforeunload', beforeUnloadDelegate);
  29270. }
  29271. editor.remove();
  29272. toggleGlobalEvents(editors.length > 0);
  29273. return editor;
  29274. },
  29275. execCommand: function (cmd, ui, value) {
  29276. var self = this, editor = self.get(value);
  29277. switch (cmd) {
  29278. case 'mceAddEditor':
  29279. if (!self.get(value)) {
  29280. new Editor(value, self.settings, self).render();
  29281. }
  29282. return true;
  29283. case 'mceRemoveEditor':
  29284. if (editor) {
  29285. editor.remove();
  29286. }
  29287. return true;
  29288. case 'mceToggleEditor':
  29289. if (!editor) {
  29290. self.execCommand('mceAddEditor', false, value);
  29291. return true;
  29292. }
  29293. if (editor.isHidden()) {
  29294. editor.show();
  29295. } else {
  29296. editor.hide();
  29297. }
  29298. return true;
  29299. }
  29300. if (self.activeEditor) {
  29301. return self.activeEditor.execCommand(cmd, ui, value);
  29302. }
  29303. return false;
  29304. },
  29305. triggerSave: function () {
  29306. each$1(editors, function (editor) {
  29307. editor.save();
  29308. });
  29309. },
  29310. addI18n: function (code, items) {
  29311. I18n.add(code, items);
  29312. },
  29313. translate: function (text) {
  29314. return I18n.translate(text);
  29315. },
  29316. setActive: function (editor) {
  29317. var activeEditor = this.activeEditor;
  29318. if (this.activeEditor !== editor) {
  29319. if (activeEditor) {
  29320. activeEditor.fire('deactivate', { relatedTarget: editor });
  29321. }
  29322. editor.fire('activate', { relatedTarget: activeEditor });
  29323. }
  29324. this.activeEditor = editor;
  29325. },
  29326. _setBaseUrl: function (baseUrl) {
  29327. this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ''));
  29328. this.baseURI = new URI(this.baseURL);
  29329. }
  29330. });
  29331. EditorManager.setup();
  29332. var min$1 = Math.min, max$1 = Math.max, round$1 = Math.round;
  29333. var relativePosition = function (rect, targetRect, rel) {
  29334. var x = targetRect.x;
  29335. var y = targetRect.y;
  29336. var w = rect.w;
  29337. var h = rect.h;
  29338. var targetW = targetRect.w;
  29339. var targetH = targetRect.h;
  29340. var relChars = (rel || '').split('');
  29341. if (relChars[0] === 'b') {
  29342. y += targetH;
  29343. }
  29344. if (relChars[1] === 'r') {
  29345. x += targetW;
  29346. }
  29347. if (relChars[0] === 'c') {
  29348. y += round$1(targetH / 2);
  29349. }
  29350. if (relChars[1] === 'c') {
  29351. x += round$1(targetW / 2);
  29352. }
  29353. if (relChars[3] === 'b') {
  29354. y -= h;
  29355. }
  29356. if (relChars[4] === 'r') {
  29357. x -= w;
  29358. }
  29359. if (relChars[3] === 'c') {
  29360. y -= round$1(h / 2);
  29361. }
  29362. if (relChars[4] === 'c') {
  29363. x -= round$1(w / 2);
  29364. }
  29365. return create$2(x, y, w, h);
  29366. };
  29367. var findBestRelativePosition = function (rect, targetRect, constrainRect, rels) {
  29368. var pos, i;
  29369. for (i = 0; i < rels.length; i++) {
  29370. pos = relativePosition(rect, targetRect, rels[i]);
  29371. 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) {
  29372. return rels[i];
  29373. }
  29374. }
  29375. return null;
  29376. };
  29377. var inflate = function (rect, w, h) {
  29378. return create$2(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2);
  29379. };
  29380. var intersect = function (rect, cropRect) {
  29381. var x1 = max$1(rect.x, cropRect.x);
  29382. var y1 = max$1(rect.y, cropRect.y);
  29383. var x2 = min$1(rect.x + rect.w, cropRect.x + cropRect.w);
  29384. var y2 = min$1(rect.y + rect.h, cropRect.y + cropRect.h);
  29385. if (x2 - x1 < 0 || y2 - y1 < 0) {
  29386. return null;
  29387. }
  29388. return create$2(x1, y1, x2 - x1, y2 - y1);
  29389. };
  29390. var clamp = function (rect, clampRect, fixedSize) {
  29391. var x1 = rect.x;
  29392. var y1 = rect.y;
  29393. var x2 = rect.x + rect.w;
  29394. var y2 = rect.y + rect.h;
  29395. var cx2 = clampRect.x + clampRect.w;
  29396. var cy2 = clampRect.y + clampRect.h;
  29397. var underflowX1 = max$1(0, clampRect.x - x1);
  29398. var underflowY1 = max$1(0, clampRect.y - y1);
  29399. var overflowX2 = max$1(0, x2 - cx2);
  29400. var overflowY2 = max$1(0, y2 - cy2);
  29401. x1 += underflowX1;
  29402. y1 += underflowY1;
  29403. if (fixedSize) {
  29404. x2 += underflowX1;
  29405. y2 += underflowY1;
  29406. x1 -= overflowX2;
  29407. y1 -= overflowY2;
  29408. }
  29409. x2 -= overflowX2;
  29410. y2 -= overflowY2;
  29411. return create$2(x1, y1, x2 - x1, y2 - y1);
  29412. };
  29413. var create$2 = function (x, y, w, h) {
  29414. return {
  29415. x: x,
  29416. y: y,
  29417. w: w,
  29418. h: h
  29419. };
  29420. };
  29421. var fromClientRect = function (clientRect) {
  29422. return create$2(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
  29423. };
  29424. var Rect = {
  29425. inflate: inflate,
  29426. relativePosition: relativePosition,
  29427. findBestRelativePosition: findBestRelativePosition,
  29428. intersect: intersect,
  29429. clamp: clamp,
  29430. create: create$2,
  29431. fromClientRect: fromClientRect
  29432. };
  29433. var awaiter = function (resolveCb, rejectCb, timeout) {
  29434. if (timeout === void 0) {
  29435. timeout = 1000;
  29436. }
  29437. var done = false;
  29438. var timer = null;
  29439. var complete = function (completer) {
  29440. return function () {
  29441. var args = [];
  29442. for (var _i = 0; _i < arguments.length; _i++) {
  29443. args[_i] = arguments[_i];
  29444. }
  29445. if (!done) {
  29446. done = true;
  29447. if (timer !== null) {
  29448. clearTimeout(timer);
  29449. timer = null;
  29450. }
  29451. completer.apply(null, args);
  29452. }
  29453. };
  29454. };
  29455. var resolve = complete(resolveCb);
  29456. var reject = complete(rejectCb);
  29457. var start = function () {
  29458. var args = [];
  29459. for (var _i = 0; _i < arguments.length; _i++) {
  29460. args[_i] = arguments[_i];
  29461. }
  29462. if (!done && timer === null) {
  29463. timer = setTimeout(function () {
  29464. return reject.apply(null, args);
  29465. }, timeout);
  29466. }
  29467. };
  29468. return {
  29469. start: start,
  29470. resolve: resolve,
  29471. reject: reject
  29472. };
  29473. };
  29474. var create$1 = function () {
  29475. var tasks = {};
  29476. var resultFns = {};
  29477. var load = function (id, url) {
  29478. var loadErrMsg = 'Script at URL "' + url + '" failed to load';
  29479. var runErrMsg = 'Script at URL "' + url + '" did not call `tinymce.Resource.add(\'' + id + '\', data)` within 1 second';
  29480. if (tasks[id] !== undefined) {
  29481. return tasks[id];
  29482. } else {
  29483. var task = new promiseObj(function (resolve, reject) {
  29484. var waiter = awaiter(resolve, reject);
  29485. resultFns[id] = waiter.resolve;
  29486. ScriptLoader.ScriptLoader.loadScript(url, function () {
  29487. return waiter.start(runErrMsg);
  29488. }, function () {
  29489. return waiter.reject(loadErrMsg);
  29490. });
  29491. });
  29492. tasks[id] = task;
  29493. return task;
  29494. }
  29495. };
  29496. var add = function (id, data) {
  29497. if (resultFns[id] !== undefined) {
  29498. resultFns[id](data);
  29499. delete resultFns[id];
  29500. }
  29501. tasks[id] = promiseObj.resolve(data);
  29502. };
  29503. return {
  29504. load: load,
  29505. add: add
  29506. };
  29507. };
  29508. var Resource = create$1();
  29509. var each = Tools.each, extend$1 = Tools.extend;
  29510. var extendClass, initializing;
  29511. var Class = function () {
  29512. };
  29513. Class.extend = extendClass = function (props) {
  29514. var self = this;
  29515. var _super = self.prototype;
  29516. var Class = function () {
  29517. var i, mixins, mixin;
  29518. var self = this;
  29519. if (!initializing) {
  29520. if (self.init) {
  29521. self.init.apply(self, arguments);
  29522. }
  29523. mixins = self.Mixins;
  29524. if (mixins) {
  29525. i = mixins.length;
  29526. while (i--) {
  29527. mixin = mixins[i];
  29528. if (mixin.init) {
  29529. mixin.init.apply(self, arguments);
  29530. }
  29531. }
  29532. }
  29533. }
  29534. };
  29535. var dummy = function () {
  29536. return this;
  29537. };
  29538. var createMethod = function (name, fn) {
  29539. return function () {
  29540. var self = this;
  29541. var tmp = self._super;
  29542. self._super = _super[name];
  29543. var ret = fn.apply(self, arguments);
  29544. self._super = tmp;
  29545. return ret;
  29546. };
  29547. };
  29548. initializing = true;
  29549. var prototype = new self();
  29550. initializing = false;
  29551. if (props.Mixins) {
  29552. each(props.Mixins, function (mixin) {
  29553. for (var name_1 in mixin) {
  29554. if (name_1 !== 'init') {
  29555. props[name_1] = mixin[name_1];
  29556. }
  29557. }
  29558. });
  29559. if (_super.Mixins) {
  29560. props.Mixins = _super.Mixins.concat(props.Mixins);
  29561. }
  29562. }
  29563. if (props.Methods) {
  29564. each(props.Methods.split(','), function (name) {
  29565. props[name] = dummy;
  29566. });
  29567. }
  29568. if (props.Properties) {
  29569. each(props.Properties.split(','), function (name) {
  29570. var fieldName = '_' + name;
  29571. props[name] = function (value) {
  29572. var self = this;
  29573. if (value !== undefined) {
  29574. self[fieldName] = value;
  29575. return self;
  29576. }
  29577. return self[fieldName];
  29578. };
  29579. });
  29580. }
  29581. if (props.Statics) {
  29582. each(props.Statics, function (func, name) {
  29583. Class[name] = func;
  29584. });
  29585. }
  29586. if (props.Defaults && _super.Defaults) {
  29587. props.Defaults = extend$1({}, _super.Defaults, props.Defaults);
  29588. }
  29589. each$j(props, function (member, name) {
  29590. if (typeof member === 'function' && _super[name]) {
  29591. prototype[name] = createMethod(name, member);
  29592. } else {
  29593. prototype[name] = member;
  29594. }
  29595. });
  29596. Class.prototype = prototype;
  29597. Class.constructor = Class;
  29598. Class.extend = extendClass;
  29599. return Class;
  29600. };
  29601. var min = Math.min, max = Math.max, round = Math.round;
  29602. var Color = function (value) {
  29603. var self = {};
  29604. var r = 0, g = 0, b = 0;
  29605. var rgb2hsv = function (r, g, b) {
  29606. var h, s, v;
  29607. h = 0;
  29608. s = 0;
  29609. v = 0;
  29610. r = r / 255;
  29611. g = g / 255;
  29612. b = b / 255;
  29613. var minRGB = min(r, min(g, b));
  29614. var maxRGB = max(r, max(g, b));
  29615. if (minRGB === maxRGB) {
  29616. v = minRGB;
  29617. return {
  29618. h: 0,
  29619. s: 0,
  29620. v: v * 100
  29621. };
  29622. }
  29623. var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  29624. h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  29625. h = 60 * (h - d / (maxRGB - minRGB));
  29626. s = (maxRGB - minRGB) / maxRGB;
  29627. v = maxRGB;
  29628. return {
  29629. h: round(h),
  29630. s: round(s * 100),
  29631. v: round(v * 100)
  29632. };
  29633. };
  29634. var hsvToRgb = function (hue, saturation, brightness) {
  29635. hue = (parseInt(hue, 10) || 0) % 360;
  29636. saturation = parseInt(saturation, 10) / 100;
  29637. brightness = parseInt(brightness, 10) / 100;
  29638. saturation = max(0, min(saturation, 1));
  29639. brightness = max(0, min(brightness, 1));
  29640. if (saturation === 0) {
  29641. r = g = b = round(255 * brightness);
  29642. return;
  29643. }
  29644. var side = hue / 60;
  29645. var chroma = brightness * saturation;
  29646. var x = chroma * (1 - Math.abs(side % 2 - 1));
  29647. var match = brightness - chroma;
  29648. switch (Math.floor(side)) {
  29649. case 0:
  29650. r = chroma;
  29651. g = x;
  29652. b = 0;
  29653. break;
  29654. case 1:
  29655. r = x;
  29656. g = chroma;
  29657. b = 0;
  29658. break;
  29659. case 2:
  29660. r = 0;
  29661. g = chroma;
  29662. b = x;
  29663. break;
  29664. case 3:
  29665. r = 0;
  29666. g = x;
  29667. b = chroma;
  29668. break;
  29669. case 4:
  29670. r = x;
  29671. g = 0;
  29672. b = chroma;
  29673. break;
  29674. case 5:
  29675. r = chroma;
  29676. g = 0;
  29677. b = x;
  29678. break;
  29679. default:
  29680. r = g = b = 0;
  29681. }
  29682. r = round(255 * (r + match));
  29683. g = round(255 * (g + match));
  29684. b = round(255 * (b + match));
  29685. };
  29686. var toHex = function () {
  29687. var hex = function (val) {
  29688. val = parseInt(val, 10).toString(16);
  29689. return val.length > 1 ? val : '0' + val;
  29690. };
  29691. return '#' + hex(r) + hex(g) + hex(b);
  29692. };
  29693. var toRgb = function () {
  29694. return {
  29695. r: r,
  29696. g: g,
  29697. b: b
  29698. };
  29699. };
  29700. var toHsv = function () {
  29701. return rgb2hsv(r, g, b);
  29702. };
  29703. var parse = function (value) {
  29704. var matches;
  29705. if (typeof value === 'object') {
  29706. if ('r' in value) {
  29707. r = value.r;
  29708. g = value.g;
  29709. b = value.b;
  29710. } else if ('v' in value) {
  29711. hsvToRgb(value.h, value.s, value.v);
  29712. }
  29713. } else {
  29714. if (matches = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)[^\)]*\)/gi.exec(value)) {
  29715. r = parseInt(matches[1], 10);
  29716. g = parseInt(matches[2], 10);
  29717. b = parseInt(matches[3], 10);
  29718. } else if (matches = /#([0-F]{2})([0-F]{2})([0-F]{2})/gi.exec(value)) {
  29719. r = parseInt(matches[1], 16);
  29720. g = parseInt(matches[2], 16);
  29721. b = parseInt(matches[3], 16);
  29722. } else if (matches = /#([0-F])([0-F])([0-F])/gi.exec(value)) {
  29723. r = parseInt(matches[1] + matches[1], 16);
  29724. g = parseInt(matches[2] + matches[2], 16);
  29725. b = parseInt(matches[3] + matches[3], 16);
  29726. }
  29727. }
  29728. r = r < 0 ? 0 : r > 255 ? 255 : r;
  29729. g = g < 0 ? 0 : g > 255 ? 255 : g;
  29730. b = b < 0 ? 0 : b > 255 ? 255 : b;
  29731. return self;
  29732. };
  29733. if (value) {
  29734. parse(value);
  29735. }
  29736. self.toRgb = toRgb;
  29737. self.toHsv = toHsv;
  29738. self.toHex = toHex;
  29739. self.parse = parse;
  29740. return self;
  29741. };
  29742. var serialize = function (obj) {
  29743. var data = JSON.stringify(obj);
  29744. if (!isString$1(data)) {
  29745. return data;
  29746. }
  29747. return data.replace(/[\u0080-\uFFFF]/g, function (match) {
  29748. var hexCode = match.charCodeAt(0).toString(16);
  29749. return '\\u' + '0000'.substring(hexCode.length) + hexCode;
  29750. });
  29751. };
  29752. var JSONUtils = {
  29753. serialize: serialize,
  29754. parse: function (text) {
  29755. try {
  29756. return JSON.parse(text);
  29757. } catch (ex) {
  29758. }
  29759. }
  29760. };
  29761. var JSONP = {
  29762. callbacks: {},
  29763. count: 0,
  29764. send: function (settings) {
  29765. var self = this, dom = DOMUtils.DOM, count = settings.count !== undefined ? settings.count : self.count;
  29766. var id = 'tinymce_jsonp_' + count;
  29767. self.callbacks[count] = function (json) {
  29768. dom.remove(id);
  29769. delete self.callbacks[count];
  29770. settings.callback(json);
  29771. };
  29772. dom.add(dom.doc.body, 'script', {
  29773. id: id,
  29774. src: settings.url,
  29775. type: 'text/javascript'
  29776. });
  29777. self.count++;
  29778. }
  29779. };
  29780. var XHR = __assign(__assign({}, Observable), {
  29781. send: function (settings) {
  29782. var xhr, count = 0;
  29783. var ready = function () {
  29784. if (!settings.async || xhr.readyState === 4 || count++ > 10000) {
  29785. if (settings.success && count < 10000 && xhr.status === 200) {
  29786. settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings);
  29787. } else if (settings.error) {
  29788. settings.error.call(settings.error_scope, count > 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings);
  29789. }
  29790. xhr = null;
  29791. } else {
  29792. Delay.setTimeout(ready, 10);
  29793. }
  29794. };
  29795. settings.scope = settings.scope || this;
  29796. settings.success_scope = settings.success_scope || settings.scope;
  29797. settings.error_scope = settings.error_scope || settings.scope;
  29798. settings.async = settings.async !== false;
  29799. settings.data = settings.data || '';
  29800. XHR.fire('beforeInitialize', { settings: settings });
  29801. xhr = new XMLHttpRequest();
  29802. if (xhr.overrideMimeType) {
  29803. xhr.overrideMimeType(settings.content_type);
  29804. }
  29805. xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async);
  29806. if (settings.crossDomain) {
  29807. xhr.withCredentials = true;
  29808. }
  29809. if (settings.content_type) {
  29810. xhr.setRequestHeader('Content-Type', settings.content_type);
  29811. }
  29812. if (settings.requestheaders) {
  29813. Tools.each(settings.requestheaders, function (header) {
  29814. xhr.setRequestHeader(header.key, header.value);
  29815. });
  29816. }
  29817. xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  29818. xhr = XHR.fire('beforeSend', {
  29819. xhr: xhr,
  29820. settings: settings
  29821. }).xhr;
  29822. xhr.send(settings.data);
  29823. if (!settings.async) {
  29824. return ready();
  29825. }
  29826. Delay.setTimeout(ready, 10);
  29827. }
  29828. });
  29829. var extend = Tools.extend;
  29830. var JSONRequest = function () {
  29831. function JSONRequest(settings) {
  29832. this.settings = extend({}, settings);
  29833. this.count = 0;
  29834. }
  29835. JSONRequest.sendRPC = function (o) {
  29836. return new JSONRequest().send(o);
  29837. };
  29838. JSONRequest.prototype.send = function (args) {
  29839. var ecb = args.error, scb = args.success;
  29840. var xhrArgs = extend(this.settings, args);
  29841. xhrArgs.success = function (c, x) {
  29842. c = JSONUtils.parse(c);
  29843. if (typeof c === 'undefined') {
  29844. c = { error: 'JSON Parse error.' };
  29845. }
  29846. if (c.error) {
  29847. ecb.call(xhrArgs.error_scope || xhrArgs.scope, c.error, x);
  29848. } else {
  29849. scb.call(xhrArgs.success_scope || xhrArgs.scope, c.result);
  29850. }
  29851. };
  29852. xhrArgs.error = function (ty, x) {
  29853. if (ecb) {
  29854. ecb.call(xhrArgs.error_scope || xhrArgs.scope, ty, x);
  29855. }
  29856. };
  29857. xhrArgs.data = JSONUtils.serialize({
  29858. id: args.id || 'c' + this.count++,
  29859. method: args.method,
  29860. params: args.params
  29861. });
  29862. xhrArgs.content_type = 'application/json';
  29863. XHR.send(xhrArgs);
  29864. };
  29865. return JSONRequest;
  29866. }();
  29867. var create = function () {
  29868. return function () {
  29869. var data = {};
  29870. var keys = [];
  29871. var storage = {
  29872. getItem: function (key) {
  29873. var item = data[key];
  29874. return item ? item : null;
  29875. },
  29876. setItem: function (key, value) {
  29877. keys.push(key);
  29878. data[key] = String(value);
  29879. },
  29880. key: function (index) {
  29881. return keys[index];
  29882. },
  29883. removeItem: function (key) {
  29884. keys = keys.filter(function (k) {
  29885. return k === key;
  29886. });
  29887. delete data[key];
  29888. },
  29889. clear: function () {
  29890. keys = [];
  29891. data = {};
  29892. },
  29893. length: 0
  29894. };
  29895. Object.defineProperty(storage, 'length', {
  29896. get: function () {
  29897. return keys.length;
  29898. },
  29899. configurable: false,
  29900. enumerable: false
  29901. });
  29902. return storage;
  29903. }();
  29904. };
  29905. var localStorage;
  29906. try {
  29907. var test = '__storage_test__';
  29908. localStorage = window.localStorage;
  29909. localStorage.setItem(test, test);
  29910. localStorage.removeItem(test);
  29911. } catch (e) {
  29912. localStorage = create();
  29913. }
  29914. var LocalStorage = localStorage;
  29915. var publicApi = {
  29916. geom: { Rect: Rect },
  29917. util: {
  29918. Promise: promiseObj,
  29919. Delay: Delay,
  29920. Tools: Tools,
  29921. VK: VK,
  29922. URI: URI,
  29923. Class: Class,
  29924. EventDispatcher: EventDispatcher,
  29925. Observable: Observable,
  29926. I18n: I18n,
  29927. XHR: XHR,
  29928. JSON: JSONUtils,
  29929. JSONRequest: JSONRequest,
  29930. JSONP: JSONP,
  29931. LocalStorage: LocalStorage,
  29932. Color: Color,
  29933. ImageUploader: ImageUploader
  29934. },
  29935. dom: {
  29936. EventUtils: EventUtils,
  29937. Sizzle: Sizzle,
  29938. DomQuery: DomQuery,
  29939. TreeWalker: DomTreeWalker,
  29940. TextSeeker: TextSeeker,
  29941. DOMUtils: DOMUtils,
  29942. ScriptLoader: ScriptLoader,
  29943. RangeUtils: RangeUtils,
  29944. Serializer: DomSerializer,
  29945. StyleSheetLoader: StyleSheetLoader,
  29946. ControlSelection: ControlSelection,
  29947. BookmarkManager: BookmarkManager,
  29948. Selection: EditorSelection,
  29949. Event: EventUtils.Event
  29950. },
  29951. html: {
  29952. Styles: Styles,
  29953. Entities: Entities,
  29954. Node: AstNode,
  29955. Schema: Schema,
  29956. SaxParser: SaxParser,
  29957. DomParser: DomParser,
  29958. Writer: Writer,
  29959. Serializer: HtmlSerializer
  29960. },
  29961. Env: Env,
  29962. AddOnManager: AddOnManager,
  29963. Annotator: Annotator,
  29964. Formatter: Formatter,
  29965. UndoManager: UndoManager,
  29966. EditorCommands: EditorCommands,
  29967. WindowManager: WindowManager,
  29968. NotificationManager: NotificationManager,
  29969. EditorObservable: EditorObservable,
  29970. Shortcuts: Shortcuts,
  29971. Editor: Editor,
  29972. FocusManager: FocusManager,
  29973. EditorManager: EditorManager,
  29974. DOM: DOMUtils.DOM,
  29975. ScriptLoader: ScriptLoader.ScriptLoader,
  29976. PluginManager: PluginManager,
  29977. ThemeManager: ThemeManager,
  29978. IconManager: IconManager,
  29979. Resource: Resource,
  29980. trim: Tools.trim,
  29981. isArray: Tools.isArray,
  29982. is: Tools.is,
  29983. toArray: Tools.toArray,
  29984. makeMap: Tools.makeMap,
  29985. each: Tools.each,
  29986. map: Tools.map,
  29987. grep: Tools.grep,
  29988. inArray: Tools.inArray,
  29989. extend: Tools.extend,
  29990. create: Tools.create,
  29991. walk: Tools.walk,
  29992. createNS: Tools.createNS,
  29993. resolve: Tools.resolve,
  29994. explode: Tools.explode,
  29995. _addCacheSuffix: Tools._addCacheSuffix,
  29996. isOpera: Env.opera,
  29997. isWebKit: Env.webkit,
  29998. isIE: Env.ie,
  29999. isGecko: Env.gecko,
  30000. isMac: Env.mac
  30001. };
  30002. var tinymce = Tools.extend(EditorManager, publicApi);
  30003. var exportToModuleLoaders = function (tinymce) {
  30004. if (typeof module === 'object') {
  30005. try {
  30006. module.exports = tinymce;
  30007. } catch (_) {
  30008. }
  30009. }
  30010. };
  30011. var exportToWindowGlobal = function (tinymce) {
  30012. window.tinymce = tinymce;
  30013. window.tinyMCE = tinymce;
  30014. };
  30015. exportToWindowGlobal(tinymce);
  30016. exportToModuleLoaders(tinymce);
  30017. }());