tinymce.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055
  1. /**
  2. * TinyMCE version 6.0.3 (2022-05-25)
  3. */
  4. (function () {
  5. 'use strict';
  6. var typeOf$1 = function (x) {
  7. if (x === null) {
  8. return 'null';
  9. }
  10. if (x === undefined) {
  11. return 'undefined';
  12. }
  13. var t = typeof x;
  14. if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  15. return 'array';
  16. }
  17. if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  18. return 'string';
  19. }
  20. return t;
  21. };
  22. var isEquatableType = function (x) {
  23. return [
  24. 'undefined',
  25. 'boolean',
  26. 'number',
  27. 'string',
  28. 'function',
  29. 'xml',
  30. 'null'
  31. ].indexOf(x) !== -1;
  32. };
  33. var sort$1 = function (xs, compareFn) {
  34. var clone = Array.prototype.slice.call(xs);
  35. return clone.sort(compareFn);
  36. };
  37. var contramap = function (eqa, f) {
  38. return eq$2(function (x, y) {
  39. return eqa.eq(f(x), f(y));
  40. });
  41. };
  42. var eq$2 = function (f) {
  43. return { eq: f };
  44. };
  45. var tripleEq = eq$2(function (x, y) {
  46. return x === y;
  47. });
  48. var eqString = tripleEq;
  49. var eqArray = function (eqa) {
  50. return eq$2(function (x, y) {
  51. if (x.length !== y.length) {
  52. return false;
  53. }
  54. var len = x.length;
  55. for (var i = 0; i < len; i++) {
  56. if (!eqa.eq(x[i], y[i])) {
  57. return false;
  58. }
  59. }
  60. return true;
  61. });
  62. };
  63. var eqSortedArray = function (eqa, compareFn) {
  64. return contramap(eqArray(eqa), function (xs) {
  65. return sort$1(xs, compareFn);
  66. });
  67. };
  68. var eqRecord = function (eqa) {
  69. return eq$2(function (x, y) {
  70. var kx = Object.keys(x);
  71. var ky = Object.keys(y);
  72. if (!eqSortedArray(eqString).eq(kx, ky)) {
  73. return false;
  74. }
  75. var len = kx.length;
  76. for (var i = 0; i < len; i++) {
  77. var q = kx[i];
  78. if (!eqa.eq(x[q], y[q])) {
  79. return false;
  80. }
  81. }
  82. return true;
  83. });
  84. };
  85. var eqAny = eq$2(function (x, y) {
  86. if (x === y) {
  87. return true;
  88. }
  89. var tx = typeOf$1(x);
  90. var ty = typeOf$1(y);
  91. if (tx !== ty) {
  92. return false;
  93. }
  94. if (isEquatableType(tx)) {
  95. return x === y;
  96. } else if (tx === 'array') {
  97. return eqArray(eqAny).eq(x, y);
  98. } else if (tx === 'object') {
  99. return eqRecord(eqAny).eq(x, y);
  100. }
  101. return false;
  102. });
  103. const getPrototypeOf$1 = Object.getPrototypeOf;
  104. const hasProto = (v, constructor, predicate) => {
  105. var _a;
  106. if (predicate(v, constructor.prototype)) {
  107. return true;
  108. } else {
  109. return ((_a = v.constructor) === null || _a === void 0 ? void 0 : _a.name) === constructor.name;
  110. }
  111. };
  112. const typeOf = x => {
  113. const t = typeof x;
  114. if (x === null) {
  115. return 'null';
  116. } else if (t === 'object' && Array.isArray(x)) {
  117. return 'array';
  118. } else if (t === 'object' && hasProto(x, String, (o, proto) => proto.isPrototypeOf(o))) {
  119. return 'string';
  120. } else {
  121. return t;
  122. }
  123. };
  124. const isType$1 = type => value => typeOf(value) === type;
  125. const isSimpleType = type => value => typeof value === type;
  126. const eq$1 = t => a => t === a;
  127. const is$4 = (value, constructor) => isObject(value) && hasProto(value, constructor, (o, proto) => getPrototypeOf$1(o) === proto);
  128. const isString = isType$1('string');
  129. const isObject = isType$1('object');
  130. const isPlainObject = value => is$4(value, Object);
  131. const isArray$1 = isType$1('array');
  132. const isNull = eq$1(null);
  133. const isBoolean = isSimpleType('boolean');
  134. const isUndefined = eq$1(undefined);
  135. const isNullable = a => a === null || a === undefined;
  136. const isNonNullable = a => !isNullable(a);
  137. const isFunction = isSimpleType('function');
  138. const isNumber = isSimpleType('number');
  139. const isArrayOf = (value, pred) => {
  140. if (isArray$1(value)) {
  141. for (let i = 0, len = value.length; i < len; ++i) {
  142. if (!pred(value[i])) {
  143. return false;
  144. }
  145. }
  146. return true;
  147. }
  148. return false;
  149. };
  150. const noop = () => {
  151. };
  152. const compose = (fa, fb) => {
  153. return (...args) => {
  154. return fa(fb.apply(null, args));
  155. };
  156. };
  157. const compose1 = (fbc, fab) => a => fbc(fab(a));
  158. const constant = value => {
  159. return () => {
  160. return value;
  161. };
  162. };
  163. const identity = x => {
  164. return x;
  165. };
  166. const tripleEquals = (a, b) => {
  167. return a === b;
  168. };
  169. function curry(fn, ...initialArgs) {
  170. return (...restArgs) => {
  171. const all = initialArgs.concat(restArgs);
  172. return fn.apply(null, all);
  173. };
  174. }
  175. const not = f => t => !f(t);
  176. const die = msg => {
  177. return () => {
  178. throw new Error(msg);
  179. };
  180. };
  181. const apply$1 = f => {
  182. return f();
  183. };
  184. const call = f => {
  185. f();
  186. };
  187. const never = constant(false);
  188. const always = constant(true);
  189. class Optional {
  190. constructor(tag, value) {
  191. this.tag = tag;
  192. this.value = value;
  193. }
  194. static some(value) {
  195. return new Optional(true, value);
  196. }
  197. static none() {
  198. return Optional.singletonNone;
  199. }
  200. fold(onNone, onSome) {
  201. if (this.tag) {
  202. return onSome(this.value);
  203. } else {
  204. return onNone();
  205. }
  206. }
  207. isSome() {
  208. return this.tag;
  209. }
  210. isNone() {
  211. return !this.tag;
  212. }
  213. map(mapper) {
  214. if (this.tag) {
  215. return Optional.some(mapper(this.value));
  216. } else {
  217. return Optional.none();
  218. }
  219. }
  220. bind(binder) {
  221. if (this.tag) {
  222. return binder(this.value);
  223. } else {
  224. return Optional.none();
  225. }
  226. }
  227. exists(predicate) {
  228. return this.tag && predicate(this.value);
  229. }
  230. forall(predicate) {
  231. return !this.tag || predicate(this.value);
  232. }
  233. filter(predicate) {
  234. if (!this.tag || predicate(this.value)) {
  235. return this;
  236. } else {
  237. return Optional.none();
  238. }
  239. }
  240. getOr(replacement) {
  241. return this.tag ? this.value : replacement;
  242. }
  243. or(replacement) {
  244. return this.tag ? this : replacement;
  245. }
  246. getOrThunk(thunk) {
  247. return this.tag ? this.value : thunk();
  248. }
  249. orThunk(thunk) {
  250. return this.tag ? this : thunk();
  251. }
  252. getOrDie(message) {
  253. if (!this.tag) {
  254. throw new Error(message !== null && message !== void 0 ? message : 'Called getOrDie on None');
  255. } else {
  256. return this.value;
  257. }
  258. }
  259. static from(value) {
  260. return isNonNullable(value) ? Optional.some(value) : Optional.none();
  261. }
  262. getOrNull() {
  263. return this.tag ? this.value : null;
  264. }
  265. getOrUndefined() {
  266. return this.value;
  267. }
  268. each(worker) {
  269. if (this.tag) {
  270. worker(this.value);
  271. }
  272. }
  273. toArray() {
  274. return this.tag ? [this.value] : [];
  275. }
  276. toString() {
  277. return this.tag ? `some(${ this.value })` : 'none()';
  278. }
  279. }
  280. Optional.singletonNone = new Optional(false);
  281. const nativeSlice = Array.prototype.slice;
  282. const nativeIndexOf = Array.prototype.indexOf;
  283. const nativePush = Array.prototype.push;
  284. const rawIndexOf = (ts, t) => nativeIndexOf.call(ts, t);
  285. const indexOf$1 = (xs, x) => {
  286. const r = rawIndexOf(xs, x);
  287. return r === -1 ? Optional.none() : Optional.some(r);
  288. };
  289. const contains$2 = (xs, x) => rawIndexOf(xs, x) > -1;
  290. const exists = (xs, pred) => {
  291. for (let i = 0, len = xs.length; i < len; i++) {
  292. const x = xs[i];
  293. if (pred(x, i)) {
  294. return true;
  295. }
  296. }
  297. return false;
  298. };
  299. const map$3 = (xs, f) => {
  300. const len = xs.length;
  301. const r = new Array(len);
  302. for (let i = 0; i < len; i++) {
  303. const x = xs[i];
  304. r[i] = f(x, i);
  305. }
  306. return r;
  307. };
  308. const each$g = (xs, f) => {
  309. for (let i = 0, len = xs.length; i < len; i++) {
  310. const x = xs[i];
  311. f(x, i);
  312. }
  313. };
  314. const eachr = (xs, f) => {
  315. for (let i = xs.length - 1; i >= 0; i--) {
  316. const x = xs[i];
  317. f(x, i);
  318. }
  319. };
  320. const partition$2 = (xs, pred) => {
  321. const pass = [];
  322. const fail = [];
  323. for (let i = 0, len = xs.length; i < len; i++) {
  324. const x = xs[i];
  325. const arr = pred(x, i) ? pass : fail;
  326. arr.push(x);
  327. }
  328. return {
  329. pass,
  330. fail
  331. };
  332. };
  333. const filter$6 = (xs, pred) => {
  334. const r = [];
  335. for (let i = 0, len = xs.length; i < len; i++) {
  336. const x = xs[i];
  337. if (pred(x, i)) {
  338. r.push(x);
  339. }
  340. }
  341. return r;
  342. };
  343. const foldr = (xs, f, acc) => {
  344. eachr(xs, (x, i) => {
  345. acc = f(acc, x, i);
  346. });
  347. return acc;
  348. };
  349. const foldl = (xs, f, acc) => {
  350. each$g(xs, (x, i) => {
  351. acc = f(acc, x, i);
  352. });
  353. return acc;
  354. };
  355. const findUntil$1 = (xs, pred, until) => {
  356. for (let i = 0, len = xs.length; i < len; i++) {
  357. const x = xs[i];
  358. if (pred(x, i)) {
  359. return Optional.some(x);
  360. } else if (until(x, i)) {
  361. break;
  362. }
  363. }
  364. return Optional.none();
  365. };
  366. const find$2 = (xs, pred) => {
  367. return findUntil$1(xs, pred, never);
  368. };
  369. const findIndex$2 = (xs, pred) => {
  370. for (let i = 0, len = xs.length; i < len; i++) {
  371. const x = xs[i];
  372. if (pred(x, i)) {
  373. return Optional.some(i);
  374. }
  375. }
  376. return Optional.none();
  377. };
  378. const flatten = xs => {
  379. const r = [];
  380. for (let i = 0, len = xs.length; i < len; ++i) {
  381. if (!isArray$1(xs[i])) {
  382. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  383. }
  384. nativePush.apply(r, xs[i]);
  385. }
  386. return r;
  387. };
  388. const bind$3 = (xs, f) => flatten(map$3(xs, f));
  389. const forall = (xs, pred) => {
  390. for (let i = 0, len = xs.length; i < len; ++i) {
  391. const x = xs[i];
  392. if (pred(x, i) !== true) {
  393. return false;
  394. }
  395. }
  396. return true;
  397. };
  398. const reverse = xs => {
  399. const r = nativeSlice.call(xs, 0);
  400. r.reverse();
  401. return r;
  402. };
  403. const difference = (a1, a2) => filter$6(a1, x => !contains$2(a2, x));
  404. const mapToObject = (xs, f) => {
  405. const r = {};
  406. for (let i = 0, len = xs.length; i < len; i++) {
  407. const x = xs[i];
  408. r[String(x)] = f(x, i);
  409. }
  410. return r;
  411. };
  412. const sort = (xs, comparator) => {
  413. const copy = nativeSlice.call(xs, 0);
  414. copy.sort(comparator);
  415. return copy;
  416. };
  417. const get$b = (xs, i) => i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
  418. const head = xs => get$b(xs, 0);
  419. const last$3 = xs => get$b(xs, xs.length - 1);
  420. const from = isFunction(Array.from) ? Array.from : x => nativeSlice.call(x);
  421. const findMap = (arr, f) => {
  422. for (let i = 0; i < arr.length; i++) {
  423. const r = f(arr[i], i);
  424. if (r.isSome()) {
  425. return r;
  426. }
  427. }
  428. return Optional.none();
  429. };
  430. const unique$1 = (xs, comparator) => {
  431. const r = [];
  432. const isDuplicated = isFunction(comparator) ? x => exists(r, i => comparator(i, x)) : x => contains$2(r, x);
  433. for (let i = 0, len = xs.length; i < len; i++) {
  434. const x = xs[i];
  435. if (!isDuplicated(x)) {
  436. r.push(x);
  437. }
  438. }
  439. return r;
  440. };
  441. const keys = Object.keys;
  442. const hasOwnProperty$2 = Object.hasOwnProperty;
  443. const each$f = (obj, f) => {
  444. const props = keys(obj);
  445. for (let k = 0, len = props.length; k < len; k++) {
  446. const i = props[k];
  447. const x = obj[i];
  448. f(x, i);
  449. }
  450. };
  451. const map$2 = (obj, f) => {
  452. return tupleMap(obj, (x, i) => ({
  453. k: i,
  454. v: f(x, i)
  455. }));
  456. };
  457. const tupleMap = (obj, f) => {
  458. const r = {};
  459. each$f(obj, (x, i) => {
  460. const tuple = f(x, i);
  461. r[tuple.k] = tuple.v;
  462. });
  463. return r;
  464. };
  465. const objAcc = r => (x, i) => {
  466. r[i] = x;
  467. };
  468. const internalFilter = (obj, pred, onTrue, onFalse) => {
  469. const r = {};
  470. each$f(obj, (x, i) => {
  471. (pred(x, i) ? onTrue : onFalse)(x, i);
  472. });
  473. return r;
  474. };
  475. const bifilter = (obj, pred) => {
  476. const t = {};
  477. const f = {};
  478. internalFilter(obj, pred, objAcc(t), objAcc(f));
  479. return {
  480. t,
  481. f
  482. };
  483. };
  484. const filter$5 = (obj, pred) => {
  485. const t = {};
  486. internalFilter(obj, pred, objAcc(t), noop);
  487. return t;
  488. };
  489. const mapToArray = (obj, f) => {
  490. const r = [];
  491. each$f(obj, (value, name) => {
  492. r.push(f(value, name));
  493. });
  494. return r;
  495. };
  496. const values = obj => {
  497. return mapToArray(obj, identity);
  498. };
  499. const get$a = (obj, key) => {
  500. return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
  501. };
  502. const has$2 = (obj, key) => hasOwnProperty$2.call(obj, key);
  503. const hasNonNullableKey = (obj, key) => has$2(obj, key) && obj[key] !== undefined && obj[key] !== null;
  504. const equal$1 = (a1, a2, eq = eqAny) => eqRecord(eq).eq(a1, a2);
  505. const stringArray = a => {
  506. const all = {};
  507. each$g(a, key => {
  508. all[key] = {};
  509. });
  510. return keys(all);
  511. };
  512. const isArray = Array.isArray;
  513. const toArray$1 = obj => {
  514. if (!isArray(obj)) {
  515. const array = [];
  516. for (let i = 0, l = obj.length; i < l; i++) {
  517. array[i] = obj[i];
  518. }
  519. return array;
  520. } else {
  521. return obj;
  522. }
  523. };
  524. const each$e = (o, cb, s) => {
  525. let n, l;
  526. if (!o) {
  527. return false;
  528. }
  529. s = s || o;
  530. if (o.length !== undefined) {
  531. for (n = 0, l = o.length; n < l; n++) {
  532. if (cb.call(s, o[n], n, o) === false) {
  533. return false;
  534. }
  535. }
  536. } else {
  537. for (n in o) {
  538. if (has$2(o, n)) {
  539. if (cb.call(s, o[n], n, o) === false) {
  540. return false;
  541. }
  542. }
  543. }
  544. }
  545. return true;
  546. };
  547. const map$1 = (array, callback) => {
  548. const out = [];
  549. each$e(array, (item, index) => {
  550. out.push(callback(item, index, array));
  551. });
  552. return out;
  553. };
  554. const filter$4 = (a, f) => {
  555. const o = [];
  556. each$e(a, (v, index) => {
  557. if (!f || f(v, index, a)) {
  558. o.push(v);
  559. }
  560. });
  561. return o;
  562. };
  563. const indexOf = (a, v) => {
  564. if (a) {
  565. for (let i = 0, l = a.length; i < l; i++) {
  566. if (a[i] === v) {
  567. return i;
  568. }
  569. }
  570. }
  571. return -1;
  572. };
  573. const reduce = (collection, iteratee, accumulator, thisArg) => {
  574. let acc = isUndefined(accumulator) ? collection[0] : accumulator;
  575. for (let i = 0; i < collection.length; i++) {
  576. acc = iteratee.call(thisArg, acc, collection[i], i);
  577. }
  578. return acc;
  579. };
  580. const findIndex$1 = (array, predicate, thisArg) => {
  581. let i, l;
  582. for (i = 0, l = array.length; i < l; i++) {
  583. if (predicate.call(thisArg, array[i], i, array)) {
  584. return i;
  585. }
  586. }
  587. return -1;
  588. };
  589. const last$2 = collection => collection[collection.length - 1];
  590. const cached = f => {
  591. let called = false;
  592. let r;
  593. return (...args) => {
  594. if (!called) {
  595. called = true;
  596. r = f.apply(null, args);
  597. }
  598. return r;
  599. };
  600. };
  601. const DeviceType = (os, browser, userAgent, mediaMatch) => {
  602. const isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  603. const isiPhone = os.isiOS() && !isiPad;
  604. const isMobile = os.isiOS() || os.isAndroid();
  605. const isTouch = isMobile || mediaMatch('(pointer:coarse)');
  606. const isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  607. const isPhone = isiPhone || isMobile && !isTablet;
  608. const iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  609. const isDesktop = !isPhone && !isTablet && !iOSwebview;
  610. return {
  611. isiPad: constant(isiPad),
  612. isiPhone: constant(isiPhone),
  613. isTablet: constant(isTablet),
  614. isPhone: constant(isPhone),
  615. isTouch: constant(isTouch),
  616. isAndroid: os.isAndroid,
  617. isiOS: os.isiOS,
  618. isWebView: constant(iOSwebview),
  619. isDesktop: constant(isDesktop)
  620. };
  621. };
  622. const firstMatch = (regexes, s) => {
  623. for (let i = 0; i < regexes.length; i++) {
  624. const x = regexes[i];
  625. if (x.test(s)) {
  626. return x;
  627. }
  628. }
  629. return undefined;
  630. };
  631. const find$1 = (regexes, agent) => {
  632. const r = firstMatch(regexes, agent);
  633. if (!r) {
  634. return {
  635. major: 0,
  636. minor: 0
  637. };
  638. }
  639. const group = i => {
  640. return Number(agent.replace(r, '$' + i));
  641. };
  642. return nu$3(group(1), group(2));
  643. };
  644. const detect$5 = (versionRegexes, agent) => {
  645. const cleanedAgent = String(agent).toLowerCase();
  646. if (versionRegexes.length === 0) {
  647. return unknown$2();
  648. }
  649. return find$1(versionRegexes, cleanedAgent);
  650. };
  651. const unknown$2 = () => {
  652. return nu$3(0, 0);
  653. };
  654. const nu$3 = (major, minor) => {
  655. return {
  656. major,
  657. minor
  658. };
  659. };
  660. const Version = {
  661. nu: nu$3,
  662. detect: detect$5,
  663. unknown: unknown$2
  664. };
  665. const detectBrowser$1 = (browsers, userAgentData) => {
  666. return findMap(userAgentData.brands, uaBrand => {
  667. const lcBrand = uaBrand.brand.toLowerCase();
  668. return find$2(browsers, browser => {
  669. var _a;
  670. return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
  671. }).map(info => ({
  672. current: info.name,
  673. version: Version.nu(parseInt(uaBrand.version, 10), 0)
  674. }));
  675. });
  676. };
  677. const detect$4 = (candidates, userAgent) => {
  678. const agent = String(userAgent).toLowerCase();
  679. return find$2(candidates, candidate => {
  680. return candidate.search(agent);
  681. });
  682. };
  683. const detectBrowser = (browsers, userAgent) => {
  684. return detect$4(browsers, userAgent).map(browser => {
  685. const version = Version.detect(browser.versionRegexes, userAgent);
  686. return {
  687. current: browser.name,
  688. version
  689. };
  690. });
  691. };
  692. const detectOs = (oses, userAgent) => {
  693. return detect$4(oses, userAgent).map(os => {
  694. const version = Version.detect(os.versionRegexes, userAgent);
  695. return {
  696. current: os.name,
  697. version
  698. };
  699. });
  700. };
  701. const removeFromStart = (str, numChars) => {
  702. return str.substring(numChars);
  703. };
  704. const checkRange = (str, substr, start) => substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  705. const removeLeading = (str, prefix) => {
  706. return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
  707. };
  708. const contains$1 = (str, substr) => {
  709. return str.indexOf(substr) !== -1;
  710. };
  711. const startsWith = (str, prefix) => {
  712. return checkRange(str, prefix, 0);
  713. };
  714. const endsWith = (str, suffix) => {
  715. return checkRange(str, suffix, str.length - suffix.length);
  716. };
  717. const blank = r => s => s.replace(r, '');
  718. const trim$3 = blank(/^\s+|\s+$/g);
  719. const lTrim = blank(/^\s+/g);
  720. const rTrim = blank(/\s+$/g);
  721. const isNotEmpty = s => s.length > 0;
  722. const isEmpty$3 = s => !isNotEmpty(s);
  723. const repeat = (s, count) => count <= 0 ? '' : new Array(count + 1).join(s);
  724. const toInt = (value, radix = 10) => {
  725. const num = parseInt(value, radix);
  726. return isNaN(num) ? Optional.none() : Optional.some(num);
  727. };
  728. const normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  729. const checkContains = target => {
  730. return uastring => {
  731. return contains$1(uastring, target);
  732. };
  733. };
  734. const browsers = [
  735. {
  736. name: 'Edge',
  737. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  738. search: uastring => {
  739. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  740. }
  741. },
  742. {
  743. name: 'Chromium',
  744. brand: 'Chromium',
  745. versionRegexes: [
  746. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  747. normalVersionRegex
  748. ],
  749. search: uastring => {
  750. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  751. }
  752. },
  753. {
  754. name: 'IE',
  755. versionRegexes: [
  756. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  757. /.*?rv:([0-9]+)\.([0-9]+).*/
  758. ],
  759. search: uastring => {
  760. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  761. }
  762. },
  763. {
  764. name: 'Opera',
  765. versionRegexes: [
  766. normalVersionRegex,
  767. /.*?opera\/([0-9]+)\.([0-9]+).*/
  768. ],
  769. search: checkContains('opera')
  770. },
  771. {
  772. name: 'Firefox',
  773. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  774. search: checkContains('firefox')
  775. },
  776. {
  777. name: 'Safari',
  778. versionRegexes: [
  779. normalVersionRegex,
  780. /.*?cpu os ([0-9]+)_([0-9]+).*/
  781. ],
  782. search: uastring => {
  783. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  784. }
  785. }
  786. ];
  787. const oses = [
  788. {
  789. name: 'Windows',
  790. search: checkContains('win'),
  791. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  792. },
  793. {
  794. name: 'iOS',
  795. search: uastring => {
  796. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  797. },
  798. versionRegexes: [
  799. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  800. /.*cpu os ([0-9]+)_([0-9]+).*/,
  801. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  802. ]
  803. },
  804. {
  805. name: 'Android',
  806. search: checkContains('android'),
  807. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  808. },
  809. {
  810. name: 'macOS',
  811. search: checkContains('mac os x'),
  812. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  813. },
  814. {
  815. name: 'Linux',
  816. search: checkContains('linux'),
  817. versionRegexes: []
  818. },
  819. {
  820. name: 'Solaris',
  821. search: checkContains('sunos'),
  822. versionRegexes: []
  823. },
  824. {
  825. name: 'FreeBSD',
  826. search: checkContains('freebsd'),
  827. versionRegexes: []
  828. },
  829. {
  830. name: 'ChromeOS',
  831. search: checkContains('cros'),
  832. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  833. }
  834. ];
  835. const PlatformInfo = {
  836. browsers: constant(browsers),
  837. oses: constant(oses)
  838. };
  839. const edge = 'Edge';
  840. const chromium = 'Chromium';
  841. const ie = 'IE';
  842. const opera = 'Opera';
  843. const firefox = 'Firefox';
  844. const safari = 'Safari';
  845. const unknown$1 = () => {
  846. return nu$2({
  847. current: undefined,
  848. version: Version.unknown()
  849. });
  850. };
  851. const nu$2 = info => {
  852. const current = info.current;
  853. const version = info.version;
  854. const isBrowser = name => () => current === name;
  855. return {
  856. current,
  857. version,
  858. isEdge: isBrowser(edge),
  859. isChromium: isBrowser(chromium),
  860. isIE: isBrowser(ie),
  861. isOpera: isBrowser(opera),
  862. isFirefox: isBrowser(firefox),
  863. isSafari: isBrowser(safari)
  864. };
  865. };
  866. const Browser = {
  867. unknown: unknown$1,
  868. nu: nu$2,
  869. edge: constant(edge),
  870. chromium: constant(chromium),
  871. ie: constant(ie),
  872. opera: constant(opera),
  873. firefox: constant(firefox),
  874. safari: constant(safari)
  875. };
  876. const windows = 'Windows';
  877. const ios = 'iOS';
  878. const android = 'Android';
  879. const linux = 'Linux';
  880. const macos = 'macOS';
  881. const solaris = 'Solaris';
  882. const freebsd = 'FreeBSD';
  883. const chromeos = 'ChromeOS';
  884. const unknown = () => {
  885. return nu$1({
  886. current: undefined,
  887. version: Version.unknown()
  888. });
  889. };
  890. const nu$1 = info => {
  891. const current = info.current;
  892. const version = info.version;
  893. const isOS = name => () => current === name;
  894. return {
  895. current,
  896. version,
  897. isWindows: isOS(windows),
  898. isiOS: isOS(ios),
  899. isAndroid: isOS(android),
  900. isMacOS: isOS(macos),
  901. isLinux: isOS(linux),
  902. isSolaris: isOS(solaris),
  903. isFreeBSD: isOS(freebsd),
  904. isChromeOS: isOS(chromeos)
  905. };
  906. };
  907. const OperatingSystem = {
  908. unknown,
  909. nu: nu$1,
  910. windows: constant(windows),
  911. ios: constant(ios),
  912. android: constant(android),
  913. linux: constant(linux),
  914. macos: constant(macos),
  915. solaris: constant(solaris),
  916. freebsd: constant(freebsd),
  917. chromeos: constant(chromeos)
  918. };
  919. const detect$3 = (userAgent, userAgentDataOpt, mediaMatch) => {
  920. const browsers = PlatformInfo.browsers();
  921. const oses = PlatformInfo.oses();
  922. const browser = userAgentDataOpt.bind(userAgentData => detectBrowser$1(browsers, userAgentData)).orThunk(() => detectBrowser(browsers, userAgent)).fold(Browser.unknown, Browser.nu);
  923. const os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  924. const deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  925. return {
  926. browser,
  927. os,
  928. deviceType
  929. };
  930. };
  931. const PlatformDetection = { detect: detect$3 };
  932. const mediaMatch = query => window.matchMedia(query).matches;
  933. let platform$2 = cached(() => PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch));
  934. const detect$2 = () => platform$2();
  935. const userAgent = navigator.userAgent;
  936. const platform$1 = detect$2();
  937. const browser$1 = platform$1.browser;
  938. const os = platform$1.os;
  939. const deviceType = platform$1.deviceType;
  940. const windowsPhone = userAgent.indexOf('Windows Phone') !== -1;
  941. const Env = {
  942. transparentSrc: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
  943. documentMode: browser$1.isIE() ? document.documentMode || 7 : 10,
  944. cacheSuffix: null,
  945. container: null,
  946. canHaveCSP: !browser$1.isIE(),
  947. windowsPhone,
  948. browser: {
  949. current: browser$1.current,
  950. version: browser$1.version,
  951. isChromium: browser$1.isChromium,
  952. isEdge: browser$1.isEdge,
  953. isFirefox: browser$1.isFirefox,
  954. isIE: browser$1.isIE,
  955. isOpera: browser$1.isOpera,
  956. isSafari: browser$1.isSafari
  957. },
  958. os: {
  959. current: os.current,
  960. version: os.version,
  961. isAndroid: os.isAndroid,
  962. isChromeOS: os.isChromeOS,
  963. isFreeBSD: os.isFreeBSD,
  964. isiOS: os.isiOS,
  965. isLinux: os.isLinux,
  966. isMacOS: os.isMacOS,
  967. isSolaris: os.isSolaris,
  968. isWindows: os.isWindows
  969. },
  970. deviceType: {
  971. isDesktop: deviceType.isDesktop,
  972. isiPad: deviceType.isiPad,
  973. isiPhone: deviceType.isiPhone,
  974. isPhone: deviceType.isPhone,
  975. isTablet: deviceType.isTablet,
  976. isTouch: deviceType.isTouch,
  977. isWebView: deviceType.isWebView
  978. }
  979. };
  980. const whiteSpaceRegExp$1 = /^\s*|\s*$/g;
  981. const trim$2 = str => {
  982. return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp$1, '');
  983. };
  984. const is$3 = (obj, type) => {
  985. if (!type) {
  986. return obj !== undefined;
  987. }
  988. if (type === 'array' && isArray(obj)) {
  989. return true;
  990. }
  991. return typeof obj === type;
  992. };
  993. const makeMap$4 = (items, delim, map) => {
  994. let i;
  995. items = items || [];
  996. delim = delim || ',';
  997. if (typeof items === 'string') {
  998. items = items.split(delim);
  999. }
  1000. map = map || {};
  1001. i = items.length;
  1002. while (i--) {
  1003. map[items[i]] = {};
  1004. }
  1005. return map;
  1006. };
  1007. const hasOwnProperty$1 = has$2;
  1008. const extend$3 = (obj, ...exts) => {
  1009. for (let i = 0; i < exts.length; i++) {
  1010. const ext = exts[i];
  1011. for (const name in ext) {
  1012. if (has$2(ext, name)) {
  1013. const value = ext[name];
  1014. if (value !== undefined) {
  1015. obj[name] = value;
  1016. }
  1017. }
  1018. }
  1019. }
  1020. return obj;
  1021. };
  1022. const walk$4 = function (o, f, n, s) {
  1023. s = s || this;
  1024. if (o) {
  1025. if (n) {
  1026. o = o[n];
  1027. }
  1028. each$e(o, (o, i) => {
  1029. if (f.call(s, o, i, n) === false) {
  1030. return false;
  1031. }
  1032. walk$4(o, f, n, s);
  1033. });
  1034. }
  1035. };
  1036. const resolve$2 = (n, o) => {
  1037. let i, l;
  1038. o = o || window;
  1039. n = n.split('.');
  1040. for (i = 0, l = n.length; i < l; i++) {
  1041. o = o[n[i]];
  1042. if (!o) {
  1043. break;
  1044. }
  1045. }
  1046. return o;
  1047. };
  1048. const explode$3 = (s, d) => {
  1049. if (!s || is$3(s, 'array')) {
  1050. return s;
  1051. }
  1052. return map$1(s.split(d || ','), trim$2);
  1053. };
  1054. const _addCacheSuffix = url => {
  1055. const cacheSuffix = Env.cacheSuffix;
  1056. if (cacheSuffix) {
  1057. url += (url.indexOf('?') === -1 ? '?' : '&') + cacheSuffix;
  1058. }
  1059. return url;
  1060. };
  1061. const Tools = {
  1062. trim: trim$2,
  1063. isArray: isArray,
  1064. is: is$3,
  1065. toArray: toArray$1,
  1066. makeMap: makeMap$4,
  1067. each: each$e,
  1068. map: map$1,
  1069. grep: filter$4,
  1070. inArray: indexOf,
  1071. hasOwn: hasOwnProperty$1,
  1072. extend: extend$3,
  1073. walk: walk$4,
  1074. resolve: resolve$2,
  1075. explode: explode$3,
  1076. _addCacheSuffix
  1077. };
  1078. const is$2 = (lhs, rhs, comparator = tripleEquals) => lhs.exists(left => comparator(left, rhs));
  1079. const cat = arr => {
  1080. const r = [];
  1081. const push = x => {
  1082. r.push(x);
  1083. };
  1084. for (let i = 0; i < arr.length; i++) {
  1085. arr[i].each(push);
  1086. }
  1087. return r;
  1088. };
  1089. const lift2 = (oa, ob, f) => oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  1090. const lift3 = (oa, ob, oc, f) => oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
  1091. const someIf = (b, a) => b ? Optional.some(a) : Optional.none();
  1092. typeof window !== 'undefined' ? window : Function('return this;')();
  1093. const COMMENT = 8;
  1094. const DOCUMENT = 9;
  1095. const DOCUMENT_FRAGMENT = 11;
  1096. const ELEMENT = 1;
  1097. const TEXT = 3;
  1098. const name = element => {
  1099. const r = element.dom.nodeName;
  1100. return r.toLowerCase();
  1101. };
  1102. const type$1 = element => element.dom.nodeType;
  1103. const isType = t => element => type$1(element) === t;
  1104. const isComment$1 = element => type$1(element) === COMMENT || name(element) === '#comment';
  1105. const isElement$7 = isType(ELEMENT);
  1106. const isText$9 = isType(TEXT);
  1107. const isDocument$2 = isType(DOCUMENT);
  1108. const isDocumentFragment$1 = isType(DOCUMENT_FRAGMENT);
  1109. const isTag = tag => e => isElement$7(e) && name(e) === tag;
  1110. const rawSet = (dom, key, value) => {
  1111. if (isString(value) || isBoolean(value) || isNumber(value)) {
  1112. dom.setAttribute(key, value + '');
  1113. } else {
  1114. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1115. throw new Error('Attribute value was not simple');
  1116. }
  1117. };
  1118. const set$2 = (element, key, value) => {
  1119. rawSet(element.dom, key, value);
  1120. };
  1121. const setAll$1 = (element, attrs) => {
  1122. const dom = element.dom;
  1123. each$f(attrs, (v, k) => {
  1124. rawSet(dom, k, v);
  1125. });
  1126. };
  1127. const get$9 = (element, key) => {
  1128. const v = element.dom.getAttribute(key);
  1129. return v === null ? undefined : v;
  1130. };
  1131. const getOpt = (element, key) => Optional.from(get$9(element, key));
  1132. const has$1 = (element, key) => {
  1133. const dom = element.dom;
  1134. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  1135. };
  1136. const remove$a = (element, key) => {
  1137. element.dom.removeAttribute(key);
  1138. };
  1139. const hasNone = element => {
  1140. const attrs = element.dom.attributes;
  1141. return attrs === undefined || attrs === null || attrs.length === 0;
  1142. };
  1143. const clone$4 = element => foldl(element.dom.attributes, (acc, attr) => {
  1144. acc[attr.name] = attr.value;
  1145. return acc;
  1146. }, {});
  1147. const read$4 = (element, attr) => {
  1148. const value = get$9(element, attr);
  1149. return value === undefined || value === '' ? [] : value.split(' ');
  1150. };
  1151. const add$4 = (element, attr, id) => {
  1152. const old = read$4(element, attr);
  1153. const nu = old.concat([id]);
  1154. set$2(element, attr, nu.join(' '));
  1155. return true;
  1156. };
  1157. const remove$9 = (element, attr, id) => {
  1158. const nu = filter$6(read$4(element, attr), v => v !== id);
  1159. if (nu.length > 0) {
  1160. set$2(element, attr, nu.join(' '));
  1161. } else {
  1162. remove$a(element, attr);
  1163. }
  1164. return false;
  1165. };
  1166. const supports = element => element.dom.classList !== undefined;
  1167. const get$8 = element => read$4(element, 'class');
  1168. const add$3 = (element, clazz) => add$4(element, 'class', clazz);
  1169. const remove$8 = (element, clazz) => remove$9(element, 'class', clazz);
  1170. const toggle$2 = (element, clazz) => {
  1171. if (contains$2(get$8(element), clazz)) {
  1172. return remove$8(element, clazz);
  1173. } else {
  1174. return add$3(element, clazz);
  1175. }
  1176. };
  1177. const add$2 = (element, clazz) => {
  1178. if (supports(element)) {
  1179. element.dom.classList.add(clazz);
  1180. } else {
  1181. add$3(element, clazz);
  1182. }
  1183. };
  1184. const cleanClass = element => {
  1185. const classList = supports(element) ? element.dom.classList : get$8(element);
  1186. if (classList.length === 0) {
  1187. remove$a(element, 'class');
  1188. }
  1189. };
  1190. const remove$7 = (element, clazz) => {
  1191. if (supports(element)) {
  1192. const classList = element.dom.classList;
  1193. classList.remove(clazz);
  1194. } else {
  1195. remove$8(element, clazz);
  1196. }
  1197. cleanClass(element);
  1198. };
  1199. const toggle$1 = (element, clazz) => {
  1200. const result = supports(element) ? element.dom.classList.toggle(clazz) : toggle$2(element, clazz);
  1201. cleanClass(element);
  1202. return result;
  1203. };
  1204. const has = (element, clazz) => supports(element) && element.dom.classList.contains(clazz);
  1205. const isSupported$1 = dom => dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  1206. const fromHtml$1 = (html, scope) => {
  1207. const doc = scope || document;
  1208. const div = doc.createElement('div');
  1209. div.innerHTML = html;
  1210. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  1211. const message = 'HTML does not have a single root node';
  1212. console.error(message, html);
  1213. throw new Error(message);
  1214. }
  1215. return fromDom$2(div.childNodes[0]);
  1216. };
  1217. const fromTag = (tag, scope) => {
  1218. const doc = scope || document;
  1219. const node = doc.createElement(tag);
  1220. return fromDom$2(node);
  1221. };
  1222. const fromText = (text, scope) => {
  1223. const doc = scope || document;
  1224. const node = doc.createTextNode(text);
  1225. return fromDom$2(node);
  1226. };
  1227. const fromDom$2 = node => {
  1228. if (node === null || node === undefined) {
  1229. throw new Error('Node cannot be null or undefined');
  1230. }
  1231. return { dom: node };
  1232. };
  1233. const fromPoint$2 = (docElm, x, y) => Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom$2);
  1234. const SugarElement = {
  1235. fromHtml: fromHtml$1,
  1236. fromTag,
  1237. fromText,
  1238. fromDom: fromDom$2,
  1239. fromPoint: fromPoint$2
  1240. };
  1241. const toArray = (target, f) => {
  1242. const r = [];
  1243. const recurse = e => {
  1244. r.push(e);
  1245. return f(e);
  1246. };
  1247. let cur = f(target);
  1248. do {
  1249. cur = cur.bind(recurse);
  1250. } while (cur.isSome());
  1251. return r;
  1252. };
  1253. const is$1 = (element, selector) => {
  1254. const dom = element.dom;
  1255. if (dom.nodeType !== ELEMENT) {
  1256. return false;
  1257. } else {
  1258. const elem = dom;
  1259. if (elem.matches !== undefined) {
  1260. return elem.matches(selector);
  1261. } else if (elem.msMatchesSelector !== undefined) {
  1262. return elem.msMatchesSelector(selector);
  1263. } else if (elem.webkitMatchesSelector !== undefined) {
  1264. return elem.webkitMatchesSelector(selector);
  1265. } else if (elem.mozMatchesSelector !== undefined) {
  1266. return elem.mozMatchesSelector(selector);
  1267. } else {
  1268. throw new Error('Browser lacks native selectors');
  1269. }
  1270. }
  1271. };
  1272. const bypassSelector = dom => dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  1273. const all = (selector, scope) => {
  1274. const base = scope === undefined ? document : scope.dom;
  1275. return bypassSelector(base) ? [] : map$3(base.querySelectorAll(selector), SugarElement.fromDom);
  1276. };
  1277. const one = (selector, scope) => {
  1278. const base = scope === undefined ? document : scope.dom;
  1279. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  1280. };
  1281. const eq = (e1, e2) => e1.dom === e2.dom;
  1282. const contains = (e1, e2) => {
  1283. const d1 = e1.dom;
  1284. const d2 = e2.dom;
  1285. return d1 === d2 ? false : d1.contains(d2);
  1286. };
  1287. const owner$1 = element => SugarElement.fromDom(element.dom.ownerDocument);
  1288. const documentOrOwner = dos => isDocument$2(dos) ? dos : owner$1(dos);
  1289. const documentElement = element => SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
  1290. const defaultView = element => SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  1291. const parent = element => Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  1292. const parentElement = element => Optional.from(element.dom.parentElement).map(SugarElement.fromDom);
  1293. const parents$1 = (element, isRoot) => {
  1294. const stop = isFunction(isRoot) ? isRoot : never;
  1295. let dom = element.dom;
  1296. const ret = [];
  1297. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  1298. const rawParent = dom.parentNode;
  1299. const p = SugarElement.fromDom(rawParent);
  1300. ret.push(p);
  1301. if (stop(p) === true) {
  1302. break;
  1303. } else {
  1304. dom = rawParent;
  1305. }
  1306. }
  1307. return ret;
  1308. };
  1309. const siblings = element => {
  1310. const filterSelf = elements => filter$6(elements, x => !eq(element, x));
  1311. return parent(element).map(children).map(filterSelf).getOr([]);
  1312. };
  1313. const prevSibling = element => Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
  1314. const nextSibling = element => Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  1315. const prevSiblings = element => reverse(toArray(element, prevSibling));
  1316. const nextSiblings = element => toArray(element, nextSibling);
  1317. const children = element => map$3(element.dom.childNodes, SugarElement.fromDom);
  1318. const child$1 = (element, index) => {
  1319. const cs = element.dom.childNodes;
  1320. return Optional.from(cs[index]).map(SugarElement.fromDom);
  1321. };
  1322. const firstChild = element => child$1(element, 0);
  1323. const lastChild = element => child$1(element, element.dom.childNodes.length - 1);
  1324. const childNodesCount = element => element.dom.childNodes.length;
  1325. const getHead = doc => {
  1326. const b = doc.dom.head;
  1327. if (b === null || b === undefined) {
  1328. throw new Error('Head is not available yet');
  1329. }
  1330. return SugarElement.fromDom(b);
  1331. };
  1332. const isShadowRoot = dos => isDocumentFragment$1(dos) && isNonNullable(dos.dom.host);
  1333. const supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  1334. const isSupported = constant(supported);
  1335. const getRootNode = supported ? e => SugarElement.fromDom(e.dom.getRootNode()) : documentOrOwner;
  1336. const getStyleContainer = dos => isShadowRoot(dos) ? dos : getHead(documentOrOwner(dos));
  1337. const getShadowRoot = e => {
  1338. const r = getRootNode(e);
  1339. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  1340. };
  1341. const getShadowHost = e => SugarElement.fromDom(e.dom.host);
  1342. const getOriginalEventTarget = event => {
  1343. if (isSupported() && isNonNullable(event.target)) {
  1344. const el = SugarElement.fromDom(event.target);
  1345. if (isElement$7(el) && isOpenShadowHost(el)) {
  1346. if (event.composed && event.composedPath) {
  1347. const composedPath = event.composedPath();
  1348. if (composedPath) {
  1349. return head(composedPath);
  1350. }
  1351. }
  1352. }
  1353. }
  1354. return Optional.from(event.target);
  1355. };
  1356. const isOpenShadowHost = element => isNonNullable(element.dom.shadowRoot);
  1357. const inBody = element => {
  1358. const dom = isText$9(element) ? element.dom.parentNode : element.dom;
  1359. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1360. return false;
  1361. }
  1362. const doc = dom.ownerDocument;
  1363. return getShadowRoot(SugarElement.fromDom(dom)).fold(() => doc.body.contains(dom), compose1(inBody, getShadowHost));
  1364. };
  1365. const internalSet = (dom, property, value) => {
  1366. if (!isString(value)) {
  1367. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  1368. throw new Error('CSS value must be a string: ' + value);
  1369. }
  1370. if (isSupported$1(dom)) {
  1371. dom.style.setProperty(property, value);
  1372. }
  1373. };
  1374. const internalRemove = (dom, property) => {
  1375. if (isSupported$1(dom)) {
  1376. dom.style.removeProperty(property);
  1377. }
  1378. };
  1379. const set$1 = (element, property, value) => {
  1380. const dom = element.dom;
  1381. internalSet(dom, property, value);
  1382. };
  1383. const setAll = (element, css) => {
  1384. const dom = element.dom;
  1385. each$f(css, (v, k) => {
  1386. internalSet(dom, k, v);
  1387. });
  1388. };
  1389. const get$7 = (element, property) => {
  1390. const dom = element.dom;
  1391. const styles = window.getComputedStyle(dom);
  1392. const r = styles.getPropertyValue(property);
  1393. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  1394. };
  1395. const getUnsafeProperty = (dom, property) => isSupported$1(dom) ? dom.style.getPropertyValue(property) : '';
  1396. const getRaw$1 = (element, property) => {
  1397. const dom = element.dom;
  1398. const raw = getUnsafeProperty(dom, property);
  1399. return Optional.from(raw).filter(r => r.length > 0);
  1400. };
  1401. const getAllRaw = element => {
  1402. const css = {};
  1403. const dom = element.dom;
  1404. if (isSupported$1(dom)) {
  1405. for (let i = 0; i < dom.style.length; i++) {
  1406. const ruleName = dom.style.item(i);
  1407. css[ruleName] = dom.style[ruleName];
  1408. }
  1409. }
  1410. return css;
  1411. };
  1412. const remove$6 = (element, property) => {
  1413. const dom = element.dom;
  1414. internalRemove(dom, property);
  1415. if (is$2(getOpt(element, 'style').map(trim$3), '')) {
  1416. remove$a(element, 'style');
  1417. }
  1418. };
  1419. const reflow = e => e.dom.offsetWidth;
  1420. const before$3 = (marker, element) => {
  1421. const parent$1 = parent(marker);
  1422. parent$1.each(v => {
  1423. v.dom.insertBefore(element.dom, marker.dom);
  1424. });
  1425. };
  1426. const after$4 = (marker, element) => {
  1427. const sibling = nextSibling(marker);
  1428. sibling.fold(() => {
  1429. const parent$1 = parent(marker);
  1430. parent$1.each(v => {
  1431. append$1(v, element);
  1432. });
  1433. }, v => {
  1434. before$3(v, element);
  1435. });
  1436. };
  1437. const prepend = (parent, element) => {
  1438. const firstChild$1 = firstChild(parent);
  1439. firstChild$1.fold(() => {
  1440. append$1(parent, element);
  1441. }, v => {
  1442. parent.dom.insertBefore(element.dom, v.dom);
  1443. });
  1444. };
  1445. const append$1 = (parent, element) => {
  1446. parent.dom.appendChild(element.dom);
  1447. };
  1448. const wrap$2 = (element, wrapper) => {
  1449. before$3(element, wrapper);
  1450. append$1(wrapper, element);
  1451. };
  1452. const after$3 = (marker, elements) => {
  1453. each$g(elements, (x, i) => {
  1454. const e = i === 0 ? marker : elements[i - 1];
  1455. after$4(e, x);
  1456. });
  1457. };
  1458. const append = (parent, elements) => {
  1459. each$g(elements, x => {
  1460. append$1(parent, x);
  1461. });
  1462. };
  1463. const empty = element => {
  1464. element.dom.textContent = '';
  1465. each$g(children(element), rogue => {
  1466. remove$5(rogue);
  1467. });
  1468. };
  1469. const remove$5 = element => {
  1470. const dom = element.dom;
  1471. if (dom.parentNode !== null) {
  1472. dom.parentNode.removeChild(dom);
  1473. }
  1474. };
  1475. const unwrap = wrapper => {
  1476. const children$1 = children(wrapper);
  1477. if (children$1.length > 0) {
  1478. after$3(wrapper, children$1);
  1479. }
  1480. remove$5(wrapper);
  1481. };
  1482. const fromHtml = (html, scope) => {
  1483. const doc = scope || document;
  1484. const div = doc.createElement('div');
  1485. div.innerHTML = html;
  1486. return children(SugarElement.fromDom(div));
  1487. };
  1488. const fromDom$1 = nodes => map$3(nodes, SugarElement.fromDom);
  1489. const get$6 = element => element.dom.innerHTML;
  1490. const set = (element, content) => {
  1491. const owner = owner$1(element);
  1492. const docDom = owner.dom;
  1493. const fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  1494. const contentElements = fromHtml(content, docDom);
  1495. append(fragment, contentElements);
  1496. empty(element);
  1497. append$1(element, fragment);
  1498. };
  1499. const getOuter = element => {
  1500. const container = SugarElement.fromTag('div');
  1501. const clone = SugarElement.fromDom(element.dom.cloneNode(true));
  1502. append$1(container, clone);
  1503. return get$6(container);
  1504. };
  1505. const mkEvent = (target, x, y, stop, prevent, kill, raw) => ({
  1506. target,
  1507. x,
  1508. y,
  1509. stop,
  1510. prevent,
  1511. kill,
  1512. raw
  1513. });
  1514. const fromRawEvent = rawEvent => {
  1515. const target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
  1516. const stop = () => rawEvent.stopPropagation();
  1517. const prevent = () => rawEvent.preventDefault();
  1518. const kill = compose(prevent, stop);
  1519. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  1520. };
  1521. const handle$1 = (filter, handler) => rawEvent => {
  1522. if (filter(rawEvent)) {
  1523. handler(fromRawEvent(rawEvent));
  1524. }
  1525. };
  1526. const binder = (element, event, filter, handler, useCapture) => {
  1527. const wrapped = handle$1(filter, handler);
  1528. element.dom.addEventListener(event, wrapped, useCapture);
  1529. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  1530. };
  1531. const bind$2 = (element, event, filter, handler) => binder(element, event, filter, handler, false);
  1532. const unbind = (element, event, handler, useCapture) => {
  1533. element.dom.removeEventListener(event, handler, useCapture);
  1534. };
  1535. const r = (left, top) => {
  1536. const translate = (x, y) => r(left + x, top + y);
  1537. return {
  1538. left,
  1539. top,
  1540. translate
  1541. };
  1542. };
  1543. const SugarPosition = r;
  1544. const boxPosition = dom => {
  1545. const box = dom.getBoundingClientRect();
  1546. return SugarPosition(box.left, box.top);
  1547. };
  1548. const firstDefinedOrZero = (a, b) => {
  1549. if (a !== undefined) {
  1550. return a;
  1551. } else {
  1552. return b !== undefined ? b : 0;
  1553. }
  1554. };
  1555. const absolute = element => {
  1556. const doc = element.dom.ownerDocument;
  1557. const body = doc.body;
  1558. const win = doc.defaultView;
  1559. const html = doc.documentElement;
  1560. if (body === element.dom) {
  1561. return SugarPosition(body.offsetLeft, body.offsetTop);
  1562. }
  1563. const scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
  1564. const scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
  1565. const clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  1566. const clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  1567. return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  1568. };
  1569. const viewport = element => {
  1570. const dom = element.dom;
  1571. const doc = dom.ownerDocument;
  1572. const body = doc.body;
  1573. if (body === dom) {
  1574. return SugarPosition(body.offsetLeft, body.offsetTop);
  1575. }
  1576. if (!inBody(element)) {
  1577. return SugarPosition(0, 0);
  1578. }
  1579. return boxPosition(dom);
  1580. };
  1581. const get$5 = _DOC => {
  1582. const doc = _DOC !== undefined ? _DOC.dom : document;
  1583. const x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  1584. const y = doc.body.scrollTop || doc.documentElement.scrollTop;
  1585. return SugarPosition(x, y);
  1586. };
  1587. const to = (x, y, _DOC) => {
  1588. const doc = _DOC !== undefined ? _DOC.dom : document;
  1589. const win = doc.defaultView;
  1590. if (win) {
  1591. win.scrollTo(x, y);
  1592. }
  1593. };
  1594. const intoView = (element, alignToTop) => {
  1595. const isSafari = detect$2().browser.isSafari();
  1596. if (isSafari && isFunction(element.dom.scrollIntoViewIfNeeded)) {
  1597. element.dom.scrollIntoViewIfNeeded(false);
  1598. } else {
  1599. element.dom.scrollIntoView(alignToTop);
  1600. }
  1601. };
  1602. const get$4 = _win => {
  1603. const win = _win === undefined ? window : _win;
  1604. if (detect$2().browser.isFirefox()) {
  1605. return Optional.none();
  1606. } else {
  1607. return Optional.from(win.visualViewport);
  1608. }
  1609. };
  1610. const bounds = (x, y, width, height) => ({
  1611. x,
  1612. y,
  1613. width,
  1614. height,
  1615. right: x + width,
  1616. bottom: y + height
  1617. });
  1618. const getBounds = _win => {
  1619. const win = _win === undefined ? window : _win;
  1620. const doc = win.document;
  1621. const scroll = get$5(SugarElement.fromDom(doc));
  1622. return get$4(win).fold(() => {
  1623. const html = win.document.documentElement;
  1624. const width = html.clientWidth;
  1625. const height = html.clientHeight;
  1626. return bounds(scroll.left, scroll.top, width, height);
  1627. }, visualViewport => bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height));
  1628. };
  1629. const isNodeType = type => {
  1630. return node => {
  1631. return !!node && node.nodeType === type;
  1632. };
  1633. };
  1634. const isRestrictedNode = node => !!node && !Object.getPrototypeOf(node);
  1635. const isElement$6 = isNodeType(1);
  1636. const matchNodeNames = names => {
  1637. const lowercasedNames = names.map(s => s.toLowerCase());
  1638. return node => {
  1639. if (node && node.nodeName) {
  1640. const nodeName = node.nodeName.toLowerCase();
  1641. return contains$2(lowercasedNames, nodeName);
  1642. }
  1643. return false;
  1644. };
  1645. };
  1646. const matchStyleValues = (name, values) => {
  1647. const items = values.toLowerCase().split(' ');
  1648. return node => {
  1649. if (isElement$6(node)) {
  1650. for (let i = 0; i < items.length; i++) {
  1651. const computed = node.ownerDocument.defaultView.getComputedStyle(node, null);
  1652. const cssValue = computed ? computed.getPropertyValue(name) : null;
  1653. if (cssValue === items[i]) {
  1654. return true;
  1655. }
  1656. }
  1657. }
  1658. return false;
  1659. };
  1660. };
  1661. const hasAttribute = attrName => {
  1662. return node => {
  1663. return isElement$6(node) && node.hasAttribute(attrName);
  1664. };
  1665. };
  1666. const hasAttributeValue = (attrName, attrValue) => {
  1667. return node => {
  1668. return isElement$6(node) && node.getAttribute(attrName) === attrValue;
  1669. };
  1670. };
  1671. const isBogus$2 = node => isElement$6(node) && node.hasAttribute('data-mce-bogus');
  1672. const isBogusAll$1 = node => isElement$6(node) && node.getAttribute('data-mce-bogus') === 'all';
  1673. const isTable$3 = node => isElement$6(node) && node.tagName === 'TABLE';
  1674. const hasContentEditableState = value => {
  1675. return node => {
  1676. if (isElement$6(node)) {
  1677. if (node.contentEditable === value) {
  1678. return true;
  1679. }
  1680. if (node.getAttribute('data-mce-contenteditable') === value) {
  1681. return true;
  1682. }
  1683. }
  1684. return false;
  1685. };
  1686. };
  1687. const isTextareaOrInput = matchNodeNames([
  1688. 'textarea',
  1689. 'input'
  1690. ]);
  1691. const isText$8 = isNodeType(3);
  1692. const isCData = isNodeType(4);
  1693. const isPi = isNodeType(7);
  1694. const isComment = isNodeType(8);
  1695. const isDocument$1 = isNodeType(9);
  1696. const isDocumentFragment = isNodeType(11);
  1697. const isBr$5 = matchNodeNames(['br']);
  1698. const isImg = matchNodeNames(['img']);
  1699. const isContentEditableTrue$4 = hasContentEditableState('true');
  1700. const isContentEditableFalse$a = hasContentEditableState('false');
  1701. const isTableCell$5 = matchNodeNames([
  1702. 'td',
  1703. 'th'
  1704. ]);
  1705. const isMedia$2 = matchNodeNames([
  1706. 'video',
  1707. 'audio',
  1708. 'object',
  1709. 'embed'
  1710. ]);
  1711. const browser = detect$2().browser;
  1712. const firstElement = nodes => find$2(nodes, isElement$7);
  1713. const getTableCaptionDeltaY = elm => {
  1714. if (browser.isFirefox() && name(elm) === 'table') {
  1715. return firstElement(children(elm)).filter(elm => {
  1716. return name(elm) === 'caption';
  1717. }).bind(caption => {
  1718. return firstElement(nextSiblings(caption)).map(body => {
  1719. const bodyTop = body.dom.offsetTop;
  1720. const captionTop = caption.dom.offsetTop;
  1721. const captionHeight = caption.dom.offsetHeight;
  1722. return bodyTop <= captionTop ? -captionHeight : 0;
  1723. });
  1724. }).getOr(0);
  1725. } else {
  1726. return 0;
  1727. }
  1728. };
  1729. const hasChild = (elm, child) => elm.children && contains$2(elm.children, child);
  1730. const getPos = (body, elm, rootElm) => {
  1731. let x = 0, y = 0;
  1732. const doc = body.ownerDocument;
  1733. rootElm = rootElm ? rootElm : body;
  1734. if (elm) {
  1735. if (rootElm === body && elm.getBoundingClientRect && get$7(SugarElement.fromDom(body), 'position') === 'static') {
  1736. const pos = elm.getBoundingClientRect();
  1737. x = pos.left + (doc.documentElement.scrollLeft || body.scrollLeft) - doc.documentElement.clientLeft;
  1738. y = pos.top + (doc.documentElement.scrollTop || body.scrollTop) - doc.documentElement.clientTop;
  1739. return {
  1740. x,
  1741. y
  1742. };
  1743. }
  1744. let offsetParent = elm;
  1745. while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  1746. const castOffsetParent = offsetParent;
  1747. x += castOffsetParent.offsetLeft || 0;
  1748. y += castOffsetParent.offsetTop || 0;
  1749. offsetParent = castOffsetParent.offsetParent;
  1750. }
  1751. offsetParent = elm.parentNode;
  1752. while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  1753. x -= offsetParent.scrollLeft || 0;
  1754. y -= offsetParent.scrollTop || 0;
  1755. offsetParent = offsetParent.parentNode;
  1756. }
  1757. y += getTableCaptionDeltaY(SugarElement.fromDom(elm));
  1758. }
  1759. return {
  1760. x,
  1761. y
  1762. };
  1763. };
  1764. var ClosestOrAncestor = (is, ancestor, scope, a, isRoot) => {
  1765. if (is(scope, a)) {
  1766. return Optional.some(scope);
  1767. } else if (isFunction(isRoot) && isRoot(scope)) {
  1768. return Optional.none();
  1769. } else {
  1770. return ancestor(scope, a, isRoot);
  1771. }
  1772. };
  1773. const ancestor$3 = (scope, predicate, isRoot) => {
  1774. let element = scope.dom;
  1775. const stop = isFunction(isRoot) ? isRoot : never;
  1776. while (element.parentNode) {
  1777. element = element.parentNode;
  1778. const el = SugarElement.fromDom(element);
  1779. if (predicate(el)) {
  1780. return Optional.some(el);
  1781. } else if (stop(el)) {
  1782. break;
  1783. }
  1784. }
  1785. return Optional.none();
  1786. };
  1787. const closest$4 = (scope, predicate, isRoot) => {
  1788. const is = (s, test) => test(s);
  1789. return ClosestOrAncestor(is, ancestor$3, scope, predicate, isRoot);
  1790. };
  1791. const sibling$1 = (scope, predicate) => {
  1792. const element = scope.dom;
  1793. if (!element.parentNode) {
  1794. return Optional.none();
  1795. }
  1796. return child(SugarElement.fromDom(element.parentNode), x => !eq(scope, x) && predicate(x));
  1797. };
  1798. const child = (scope, predicate) => {
  1799. const pred = node => predicate(SugarElement.fromDom(node));
  1800. const result = find$2(scope.dom.childNodes, pred);
  1801. return result.map(SugarElement.fromDom);
  1802. };
  1803. const descendant$1 = (scope, predicate) => {
  1804. const descend = node => {
  1805. for (let i = 0; i < node.childNodes.length; i++) {
  1806. const child = SugarElement.fromDom(node.childNodes[i]);
  1807. if (predicate(child)) {
  1808. return Optional.some(child);
  1809. }
  1810. const res = descend(node.childNodes[i]);
  1811. if (res.isSome()) {
  1812. return res;
  1813. }
  1814. }
  1815. return Optional.none();
  1816. };
  1817. return descend(scope.dom);
  1818. };
  1819. const ancestor$2 = (scope, selector, isRoot) => ancestor$3(scope, e => is$1(e, selector), isRoot);
  1820. const descendant = (scope, selector) => one(selector, scope);
  1821. const closest$3 = (scope, selector, isRoot) => {
  1822. const is = (element, selector) => is$1(element, selector);
  1823. return ClosestOrAncestor(is, ancestor$2, scope, selector, isRoot);
  1824. };
  1825. const StyleSheetLoader = (documentOrShadowRoot, settings = {}) => {
  1826. let idCount = 0;
  1827. const loadedStates = {};
  1828. const edos = SugarElement.fromDom(documentOrShadowRoot);
  1829. const doc = documentOrOwner(edos);
  1830. const maxLoadTime = settings.maxLoadTime || 5000;
  1831. const _setReferrerPolicy = referrerPolicy => {
  1832. settings.referrerPolicy = referrerPolicy;
  1833. };
  1834. const addStyle = element => {
  1835. append$1(getStyleContainer(edos), element);
  1836. };
  1837. const removeStyle = id => {
  1838. const styleContainer = getStyleContainer(edos);
  1839. descendant(styleContainer, '#' + id).each(remove$5);
  1840. };
  1841. const getOrCreateState = url => get$a(loadedStates, url).getOrThunk(() => ({
  1842. id: 'mce-u' + idCount++,
  1843. passed: [],
  1844. failed: [],
  1845. count: 0
  1846. }));
  1847. const load = url => new Promise((success, failure) => {
  1848. let link;
  1849. const urlWithSuffix = Tools._addCacheSuffix(url);
  1850. const state = getOrCreateState(urlWithSuffix);
  1851. loadedStates[urlWithSuffix] = state;
  1852. state.count++;
  1853. const resolve = (callbacks, status) => {
  1854. each$g(callbacks, call);
  1855. state.status = status;
  1856. state.passed = [];
  1857. state.failed = [];
  1858. if (link) {
  1859. link.onload = null;
  1860. link.onerror = null;
  1861. link = null;
  1862. }
  1863. };
  1864. const passed = () => resolve(state.passed, 2);
  1865. const failed = () => resolve(state.failed, 3);
  1866. const wait = (testCallback, waitCallback) => {
  1867. if (!testCallback()) {
  1868. if (Date.now() - startTime < maxLoadTime) {
  1869. setTimeout(waitCallback);
  1870. } else {
  1871. failed();
  1872. }
  1873. }
  1874. };
  1875. const waitForWebKitLinkLoaded = () => {
  1876. wait(() => {
  1877. const styleSheets = documentOrShadowRoot.styleSheets;
  1878. let i = styleSheets.length;
  1879. while (i--) {
  1880. const styleSheet = styleSheets[i];
  1881. const owner = styleSheet.ownerNode;
  1882. if (owner && owner.id === link.id) {
  1883. passed();
  1884. return true;
  1885. }
  1886. }
  1887. return false;
  1888. }, waitForWebKitLinkLoaded);
  1889. };
  1890. if (success) {
  1891. state.passed.push(success);
  1892. }
  1893. if (failure) {
  1894. state.failed.push(failure);
  1895. }
  1896. if (state.status === 1) {
  1897. return;
  1898. }
  1899. if (state.status === 2) {
  1900. passed();
  1901. return;
  1902. }
  1903. if (state.status === 3) {
  1904. failed();
  1905. return;
  1906. }
  1907. state.status = 1;
  1908. const linkElem = SugarElement.fromTag('link', doc.dom);
  1909. setAll$1(linkElem, {
  1910. rel: 'stylesheet',
  1911. type: 'text/css',
  1912. id: state.id
  1913. });
  1914. const startTime = Date.now();
  1915. if (settings.contentCssCors) {
  1916. set$2(linkElem, 'crossOrigin', 'anonymous');
  1917. }
  1918. if (settings.referrerPolicy) {
  1919. set$2(linkElem, 'referrerpolicy', settings.referrerPolicy);
  1920. }
  1921. link = linkElem.dom;
  1922. link.onload = waitForWebKitLinkLoaded;
  1923. link.onerror = failed;
  1924. addStyle(linkElem);
  1925. set$2(linkElem, 'href', urlWithSuffix);
  1926. });
  1927. const loadAll = urls => {
  1928. const loadedUrls = Promise.allSettled(map$3(urls, url => load(url).then(constant(url))));
  1929. return loadedUrls.then(results => {
  1930. const parts = partition$2(results, r => r.status === 'fulfilled');
  1931. if (parts.fail.length > 0) {
  1932. return Promise.reject(map$3(parts.fail, result => result.reason));
  1933. } else {
  1934. return map$3(parts.pass, result => result.value);
  1935. }
  1936. });
  1937. };
  1938. const unload = url => {
  1939. const urlWithSuffix = Tools._addCacheSuffix(url);
  1940. get$a(loadedStates, urlWithSuffix).each(state => {
  1941. const count = --state.count;
  1942. if (count === 0) {
  1943. delete loadedStates[urlWithSuffix];
  1944. removeStyle(state.id);
  1945. }
  1946. });
  1947. };
  1948. const unloadAll = urls => {
  1949. each$g(urls, url => {
  1950. unload(url);
  1951. });
  1952. };
  1953. return {
  1954. load,
  1955. loadAll,
  1956. unload,
  1957. unloadAll,
  1958. _setReferrerPolicy
  1959. };
  1960. };
  1961. const create$c = () => {
  1962. const map = new WeakMap();
  1963. const forElement = (referenceElement, settings) => {
  1964. const root = getRootNode(referenceElement);
  1965. const rootDom = root.dom;
  1966. return Optional.from(map.get(rootDom)).getOrThunk(() => {
  1967. const sl = StyleSheetLoader(rootDom, settings);
  1968. map.set(rootDom, sl);
  1969. return sl;
  1970. });
  1971. };
  1972. return { forElement };
  1973. };
  1974. const instance = create$c();
  1975. class DomTreeWalker {
  1976. constructor(startNode, rootNode) {
  1977. this.node = startNode;
  1978. this.rootNode = rootNode;
  1979. this.current = this.current.bind(this);
  1980. this.next = this.next.bind(this);
  1981. this.prev = this.prev.bind(this);
  1982. this.prev2 = this.prev2.bind(this);
  1983. }
  1984. current() {
  1985. return this.node;
  1986. }
  1987. next(shallow) {
  1988. this.node = this.findSibling(this.node, 'firstChild', 'nextSibling', shallow);
  1989. return this.node;
  1990. }
  1991. prev(shallow) {
  1992. this.node = this.findSibling(this.node, 'lastChild', 'previousSibling', shallow);
  1993. return this.node;
  1994. }
  1995. prev2(shallow) {
  1996. this.node = this.findPreviousNode(this.node, 'lastChild', 'previousSibling', shallow);
  1997. return this.node;
  1998. }
  1999. findSibling(node, startName, siblingName, shallow) {
  2000. let sibling, parent;
  2001. if (node) {
  2002. if (!shallow && node[startName]) {
  2003. return node[startName];
  2004. }
  2005. if (node !== this.rootNode) {
  2006. sibling = node[siblingName];
  2007. if (sibling) {
  2008. return sibling;
  2009. }
  2010. for (parent = node.parentNode; parent && parent !== this.rootNode; parent = parent.parentNode) {
  2011. sibling = parent[siblingName];
  2012. if (sibling) {
  2013. return sibling;
  2014. }
  2015. }
  2016. }
  2017. }
  2018. }
  2019. findPreviousNode(node, startName, siblingName, shallow) {
  2020. let sibling, parent, child;
  2021. if (node) {
  2022. sibling = node[siblingName];
  2023. if (this.rootNode && sibling === this.rootNode) {
  2024. return;
  2025. }
  2026. if (sibling) {
  2027. if (!shallow) {
  2028. for (child = sibling[startName]; child; child = child[startName]) {
  2029. if (!child[startName]) {
  2030. return child;
  2031. }
  2032. }
  2033. }
  2034. return sibling;
  2035. }
  2036. parent = node.parentNode;
  2037. if (parent && parent !== this.rootNode) {
  2038. return parent;
  2039. }
  2040. }
  2041. }
  2042. }
  2043. const blocks = [
  2044. 'article',
  2045. 'aside',
  2046. 'details',
  2047. 'div',
  2048. 'dt',
  2049. 'figcaption',
  2050. 'footer',
  2051. 'form',
  2052. 'fieldset',
  2053. 'header',
  2054. 'hgroup',
  2055. 'html',
  2056. 'main',
  2057. 'nav',
  2058. 'section',
  2059. 'summary',
  2060. 'body',
  2061. 'p',
  2062. 'dl',
  2063. 'multicol',
  2064. 'dd',
  2065. 'figure',
  2066. 'address',
  2067. 'center',
  2068. 'blockquote',
  2069. 'h1',
  2070. 'h2',
  2071. 'h3',
  2072. 'h4',
  2073. 'h5',
  2074. 'h6',
  2075. 'listing',
  2076. 'xmp',
  2077. 'pre',
  2078. 'plaintext',
  2079. 'menu',
  2080. 'dir',
  2081. 'ul',
  2082. 'ol',
  2083. 'li',
  2084. 'hr',
  2085. 'table',
  2086. 'tbody',
  2087. 'thead',
  2088. 'tfoot',
  2089. 'th',
  2090. 'tr',
  2091. 'td',
  2092. 'caption'
  2093. ];
  2094. const tableCells = [
  2095. 'td',
  2096. 'th'
  2097. ];
  2098. const tableSections = [
  2099. 'thead',
  2100. 'tbody',
  2101. 'tfoot'
  2102. ];
  2103. const textBlocks = [
  2104. 'h1',
  2105. 'h2',
  2106. 'h3',
  2107. 'h4',
  2108. 'h5',
  2109. 'h6',
  2110. 'p',
  2111. 'div',
  2112. 'address',
  2113. 'pre',
  2114. 'form',
  2115. 'blockquote',
  2116. 'center',
  2117. 'dir',
  2118. 'fieldset',
  2119. 'header',
  2120. 'footer',
  2121. 'article',
  2122. 'section',
  2123. 'hgroup',
  2124. 'aside',
  2125. 'nav',
  2126. 'figure'
  2127. ];
  2128. const headings = [
  2129. 'h1',
  2130. 'h2',
  2131. 'h3',
  2132. 'h4',
  2133. 'h5',
  2134. 'h6'
  2135. ];
  2136. const listItems$1 = [
  2137. 'li',
  2138. 'dd',
  2139. 'dt'
  2140. ];
  2141. const lists = [
  2142. 'ul',
  2143. 'ol',
  2144. 'dl'
  2145. ];
  2146. const wsElements = [
  2147. 'pre',
  2148. 'script',
  2149. 'textarea',
  2150. 'style'
  2151. ];
  2152. const lazyLookup = items => {
  2153. let lookup;
  2154. return node => {
  2155. lookup = lookup ? lookup : mapToObject(items, always);
  2156. return has$2(lookup, name(node));
  2157. };
  2158. };
  2159. const isHeading = lazyLookup(headings);
  2160. const isBlock$2 = lazyLookup(blocks);
  2161. const isTable$2 = node => name(node) === 'table';
  2162. const isInline$1 = node => isElement$7(node) && !isBlock$2(node);
  2163. const isBr$4 = node => isElement$7(node) && name(node) === 'br';
  2164. const isTextBlock$2 = lazyLookup(textBlocks);
  2165. const isList = lazyLookup(lists);
  2166. const isListItem = lazyLookup(listItems$1);
  2167. const isTableSection = lazyLookup(tableSections);
  2168. const isTableCell$4 = lazyLookup(tableCells);
  2169. const isWsPreserveElement = lazyLookup(wsElements);
  2170. const ancestor$1 = (scope, selector, isRoot) => ancestor$2(scope, selector, isRoot).isSome();
  2171. const zeroWidth = '\uFEFF';
  2172. const nbsp = '\xA0';
  2173. const isZwsp$1 = char => char === zeroWidth;
  2174. const removeZwsp = s => s.replace(/\uFEFF/g, '');
  2175. const ZWSP$1 = zeroWidth;
  2176. const isZwsp = isZwsp$1;
  2177. const trim$1 = removeZwsp;
  2178. const isElement$5 = isElement$6;
  2179. const isText$7 = isText$8;
  2180. const isCaretContainerBlock$1 = node => {
  2181. if (isText$7(node)) {
  2182. node = node.parentNode;
  2183. }
  2184. return isElement$5(node) && node.hasAttribute('data-mce-caret');
  2185. };
  2186. const isCaretContainerInline = node => isText$7(node) && isZwsp(node.data);
  2187. const isCaretContainer$2 = node => isCaretContainerBlock$1(node) || isCaretContainerInline(node);
  2188. const hasContent = node => node.firstChild !== node.lastChild || !isBr$5(node.firstChild);
  2189. const insertInline$1 = (node, before) => {
  2190. const doc = node.ownerDocument;
  2191. const textNode = doc.createTextNode(ZWSP$1);
  2192. const parentNode = node.parentNode;
  2193. if (!before) {
  2194. const sibling = node.nextSibling;
  2195. if (isText$7(sibling)) {
  2196. if (isCaretContainer$2(sibling)) {
  2197. return sibling;
  2198. }
  2199. if (startsWithCaretContainer$1(sibling)) {
  2200. sibling.splitText(1);
  2201. return sibling;
  2202. }
  2203. }
  2204. if (node.nextSibling) {
  2205. parentNode.insertBefore(textNode, node.nextSibling);
  2206. } else {
  2207. parentNode.appendChild(textNode);
  2208. }
  2209. } else {
  2210. const sibling = node.previousSibling;
  2211. if (isText$7(sibling)) {
  2212. if (isCaretContainer$2(sibling)) {
  2213. return sibling;
  2214. }
  2215. if (endsWithCaretContainer$1(sibling)) {
  2216. return sibling.splitText(sibling.data.length - 1);
  2217. }
  2218. }
  2219. parentNode.insertBefore(textNode, node);
  2220. }
  2221. return textNode;
  2222. };
  2223. const isBeforeInline = pos => {
  2224. const container = pos.container();
  2225. if (!isText$8(container)) {
  2226. return false;
  2227. }
  2228. return container.data.charAt(pos.offset()) === ZWSP$1 || pos.isAtStart() && isCaretContainerInline(container.previousSibling);
  2229. };
  2230. const isAfterInline = pos => {
  2231. const container = pos.container();
  2232. if (!isText$8(container)) {
  2233. return false;
  2234. }
  2235. return container.data.charAt(pos.offset() - 1) === ZWSP$1 || pos.isAtEnd() && isCaretContainerInline(container.nextSibling);
  2236. };
  2237. const createBogusBr = () => {
  2238. const br = document.createElement('br');
  2239. br.setAttribute('data-mce-bogus', '1');
  2240. return br;
  2241. };
  2242. const insertBlock = (blockName, node, before) => {
  2243. const doc = node.ownerDocument;
  2244. const blockNode = doc.createElement(blockName);
  2245. blockNode.setAttribute('data-mce-caret', before ? 'before' : 'after');
  2246. blockNode.setAttribute('data-mce-bogus', 'all');
  2247. blockNode.appendChild(createBogusBr());
  2248. const parentNode = node.parentNode;
  2249. if (!before) {
  2250. if (node.nextSibling) {
  2251. parentNode.insertBefore(blockNode, node.nextSibling);
  2252. } else {
  2253. parentNode.appendChild(blockNode);
  2254. }
  2255. } else {
  2256. parentNode.insertBefore(blockNode, node);
  2257. }
  2258. return blockNode;
  2259. };
  2260. const startsWithCaretContainer$1 = node => isText$7(node) && node.data[0] === ZWSP$1;
  2261. const endsWithCaretContainer$1 = node => isText$7(node) && node.data[node.data.length - 1] === ZWSP$1;
  2262. const trimBogusBr = elm => {
  2263. const brs = elm.getElementsByTagName('br');
  2264. const lastBr = brs[brs.length - 1];
  2265. if (isBogus$2(lastBr)) {
  2266. lastBr.parentNode.removeChild(lastBr);
  2267. }
  2268. };
  2269. const showCaretContainerBlock = caretContainer => {
  2270. if (caretContainer && caretContainer.hasAttribute('data-mce-caret')) {
  2271. trimBogusBr(caretContainer);
  2272. caretContainer.removeAttribute('data-mce-caret');
  2273. caretContainer.removeAttribute('data-mce-bogus');
  2274. caretContainer.removeAttribute('style');
  2275. caretContainer.removeAttribute('data-mce-style');
  2276. caretContainer.removeAttribute('_moz_abspos');
  2277. return caretContainer;
  2278. }
  2279. return null;
  2280. };
  2281. const isRangeInCaretContainerBlock = range => isCaretContainerBlock$1(range.startContainer);
  2282. const isContentEditableTrue$3 = isContentEditableTrue$4;
  2283. const isContentEditableFalse$9 = isContentEditableFalse$a;
  2284. const isBr$3 = isBr$5;
  2285. const isText$6 = isText$8;
  2286. const isInvalidTextElement = matchNodeNames([
  2287. 'script',
  2288. 'style',
  2289. 'textarea'
  2290. ]);
  2291. const isAtomicInline = matchNodeNames([
  2292. 'img',
  2293. 'input',
  2294. 'textarea',
  2295. 'hr',
  2296. 'iframe',
  2297. 'video',
  2298. 'audio',
  2299. 'object',
  2300. 'embed'
  2301. ]);
  2302. const isTable$1 = matchNodeNames(['table']);
  2303. const isCaretContainer$1 = isCaretContainer$2;
  2304. const isCaretCandidate$3 = node => {
  2305. if (isCaretContainer$1(node)) {
  2306. return false;
  2307. }
  2308. if (isText$6(node)) {
  2309. return !isInvalidTextElement(node.parentNode);
  2310. }
  2311. return isAtomicInline(node) || isBr$3(node) || isTable$1(node) || isNonUiContentEditableFalse(node);
  2312. };
  2313. const isUnselectable = node => isElement$6(node) && node.getAttribute('unselectable') === 'true';
  2314. const isNonUiContentEditableFalse = node => isUnselectable(node) === false && isContentEditableFalse$9(node);
  2315. const isInEditable = (node, root) => {
  2316. for (node = node.parentNode; node && node !== root; node = node.parentNode) {
  2317. if (isNonUiContentEditableFalse(node)) {
  2318. return false;
  2319. }
  2320. if (isContentEditableTrue$3(node)) {
  2321. return true;
  2322. }
  2323. }
  2324. return true;
  2325. };
  2326. const isAtomicContentEditableFalse = node => {
  2327. if (!isNonUiContentEditableFalse(node)) {
  2328. return false;
  2329. }
  2330. return foldl(from(node.getElementsByTagName('*')), (result, elm) => {
  2331. return result || isContentEditableTrue$3(elm);
  2332. }, false) !== true;
  2333. };
  2334. const isAtomic$1 = node => isAtomicInline(node) || isAtomicContentEditableFalse(node);
  2335. const isEditableCaretCandidate$1 = (node, root) => isCaretCandidate$3(node) && isInEditable(node, root);
  2336. const whiteSpaceRegExp = /^[ \t\r\n]*$/;
  2337. const isWhitespaceText = text => whiteSpaceRegExp.test(text);
  2338. const isCollapsibleWhitespace$1 = c => ' \f\t\x0B'.indexOf(c) !== -1;
  2339. const isNewLineChar = c => c === '\n' || c === '\r';
  2340. const isNewline = (text, idx) => idx < text.length && idx >= 0 ? isNewLineChar(text[idx]) : false;
  2341. const normalize$4 = (text, tabSpaces = 4, isStartOfContent = true, isEndOfContent = true) => {
  2342. const tabSpace = repeat(' ', tabSpaces);
  2343. const normalizedText = text.replace(/\t/g, tabSpace);
  2344. const result = foldl(normalizedText, (acc, c) => {
  2345. if (isCollapsibleWhitespace$1(c) || c === nbsp) {
  2346. if (acc.pcIsSpace || acc.str === '' && isStartOfContent || acc.str.length === normalizedText.length - 1 && isEndOfContent || isNewline(normalizedText, acc.str.length + 1)) {
  2347. return {
  2348. pcIsSpace: false,
  2349. str: acc.str + nbsp
  2350. };
  2351. } else {
  2352. return {
  2353. pcIsSpace: true,
  2354. str: acc.str + ' '
  2355. };
  2356. }
  2357. } else {
  2358. return {
  2359. pcIsSpace: isNewLineChar(c),
  2360. str: acc.str + c
  2361. };
  2362. }
  2363. }, {
  2364. pcIsSpace: false,
  2365. str: ''
  2366. });
  2367. return result.str;
  2368. };
  2369. const hasWhitespacePreserveParent = (node, rootNode) => {
  2370. const rootElement = SugarElement.fromDom(rootNode);
  2371. const startNode = SugarElement.fromDom(node);
  2372. return ancestor$1(startNode, 'pre,code', curry(eq, rootElement));
  2373. };
  2374. const isWhitespace$1 = (node, rootNode) => {
  2375. return isText$8(node) && isWhitespaceText(node.data) && hasWhitespacePreserveParent(node, rootNode) === false;
  2376. };
  2377. const isNamedAnchor = node => {
  2378. return isElement$6(node) && node.nodeName === 'A' && !node.hasAttribute('href') && (node.hasAttribute('name') || node.hasAttribute('id'));
  2379. };
  2380. const isContent$1 = (node, rootNode) => {
  2381. return isCaretCandidate$3(node) && isWhitespace$1(node, rootNode) === false || isNamedAnchor(node) || isBookmark(node);
  2382. };
  2383. const isBookmark = hasAttribute('data-mce-bookmark');
  2384. const isBogus$1 = hasAttribute('data-mce-bogus');
  2385. const isBogusAll = hasAttributeValue('data-mce-bogus', 'all');
  2386. const isEmptyNode = (targetNode, skipBogus) => {
  2387. let brCount = 0;
  2388. if (isContent$1(targetNode, targetNode)) {
  2389. return false;
  2390. } else {
  2391. let node = targetNode.firstChild;
  2392. if (!node) {
  2393. return true;
  2394. }
  2395. const walker = new DomTreeWalker(node, targetNode);
  2396. do {
  2397. if (skipBogus) {
  2398. if (isBogusAll(node)) {
  2399. node = walker.next(true);
  2400. continue;
  2401. }
  2402. if (isBogus$1(node)) {
  2403. node = walker.next();
  2404. continue;
  2405. }
  2406. }
  2407. if (isBr$5(node)) {
  2408. brCount++;
  2409. node = walker.next();
  2410. continue;
  2411. }
  2412. if (isContent$1(node, targetNode)) {
  2413. return false;
  2414. }
  2415. node = walker.next();
  2416. } while (node);
  2417. return brCount <= 1;
  2418. }
  2419. };
  2420. const isEmpty$2 = (elm, skipBogus = true) => isEmptyNode(elm.dom, skipBogus);
  2421. const isSpan = node => node.nodeName.toLowerCase() === 'span';
  2422. const isInlineContent = (node, root) => isNonNullable(node) && (isContent$1(node, root) || isInline$1(SugarElement.fromDom(node)));
  2423. const surroundedByInlineContent = (node, root) => {
  2424. const prev = new DomTreeWalker(node, root).prev(false);
  2425. const next = new DomTreeWalker(node, root).next(false);
  2426. const prevIsInline = isUndefined(prev) || isInlineContent(prev, root);
  2427. const nextIsInline = isUndefined(next) || isInlineContent(next, root);
  2428. return prevIsInline && nextIsInline;
  2429. };
  2430. const isBookmarkNode$2 = node => isSpan(node) && node.getAttribute('data-mce-type') === 'bookmark';
  2431. const isKeepTextNode = (node, root) => isText$8(node) && node.data.length > 0 && surroundedByInlineContent(node, root);
  2432. const isKeepElement = node => isElement$6(node) ? node.childNodes.length > 0 : false;
  2433. const isDocument = node => isDocumentFragment(node) || isDocument$1(node);
  2434. const trimNode = (dom, node, root) => {
  2435. const rootNode = root || node;
  2436. if (isElement$6(node) && isBookmarkNode$2(node)) {
  2437. return node;
  2438. }
  2439. const children = node.childNodes;
  2440. for (let i = children.length - 1; i >= 0; i--) {
  2441. trimNode(dom, children[i], rootNode);
  2442. }
  2443. if (isElement$6(node)) {
  2444. const currentChildren = node.childNodes;
  2445. if (currentChildren.length === 1 && isBookmarkNode$2(currentChildren[0])) {
  2446. node.parentNode.insertBefore(currentChildren[0], node);
  2447. }
  2448. }
  2449. if (!isDocument(node) && !isContent$1(node, rootNode) && !isKeepElement(node) && !isKeepTextNode(node, rootNode)) {
  2450. dom.remove(node);
  2451. }
  2452. return node;
  2453. };
  2454. const makeMap$3 = Tools.makeMap;
  2455. const attrsCharsRegExp = /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  2456. const textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  2457. const rawCharsRegExp = /[<>&\"\']/g;
  2458. const entityRegExp = /&#([a-z0-9]+);?|&([a-z0-9]+);/gi;
  2459. const asciiMap = {
  2460. 128: '\u20AC',
  2461. 130: '\u201A',
  2462. 131: '\u0192',
  2463. 132: '\u201E',
  2464. 133: '\u2026',
  2465. 134: '\u2020',
  2466. 135: '\u2021',
  2467. 136: '\u02c6',
  2468. 137: '\u2030',
  2469. 138: '\u0160',
  2470. 139: '\u2039',
  2471. 140: '\u0152',
  2472. 142: '\u017d',
  2473. 145: '\u2018',
  2474. 146: '\u2019',
  2475. 147: '\u201C',
  2476. 148: '\u201D',
  2477. 149: '\u2022',
  2478. 150: '\u2013',
  2479. 151: '\u2014',
  2480. 152: '\u02DC',
  2481. 153: '\u2122',
  2482. 154: '\u0161',
  2483. 155: '\u203A',
  2484. 156: '\u0153',
  2485. 158: '\u017e',
  2486. 159: '\u0178'
  2487. };
  2488. const baseEntities = {
  2489. '"': '&quot;',
  2490. '\'': '&#39;',
  2491. '<': '&lt;',
  2492. '>': '&gt;',
  2493. '&': '&amp;',
  2494. '`': '&#96;'
  2495. };
  2496. const reverseEntities = {
  2497. '&lt;': '<',
  2498. '&gt;': '>',
  2499. '&amp;': '&',
  2500. '&quot;': '"',
  2501. '&apos;': `'`
  2502. };
  2503. const nativeDecode = text => {
  2504. const elm = SugarElement.fromTag('div').dom;
  2505. elm.innerHTML = text;
  2506. return elm.textContent || elm.innerText || text;
  2507. };
  2508. const buildEntitiesLookup = (items, radix) => {
  2509. let i, chr, entity;
  2510. const lookup = {};
  2511. if (items) {
  2512. items = items.split(',');
  2513. radix = radix || 10;
  2514. for (i = 0; i < items.length; i += 2) {
  2515. chr = String.fromCharCode(parseInt(items[i], radix));
  2516. if (!baseEntities[chr]) {
  2517. entity = '&' + items[i + 1] + ';';
  2518. lookup[chr] = entity;
  2519. lookup[entity] = chr;
  2520. }
  2521. }
  2522. return lookup;
  2523. }
  2524. };
  2525. const 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);
  2526. const encodeRaw = (text, attr) => text.replace(attr ? attrsCharsRegExp : textCharsRegExp, chr => {
  2527. return baseEntities[chr] || chr;
  2528. });
  2529. const encodeAllRaw = text => ('' + text).replace(rawCharsRegExp, chr => {
  2530. return baseEntities[chr] || chr;
  2531. });
  2532. const encodeNumeric = (text, attr) => text.replace(attr ? attrsCharsRegExp : textCharsRegExp, chr => {
  2533. if (chr.length > 1) {
  2534. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  2535. }
  2536. return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
  2537. });
  2538. const encodeNamed = (text, attr, entities) => {
  2539. entities = entities || namedEntities;
  2540. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, chr => {
  2541. return baseEntities[chr] || entities[chr] || chr;
  2542. });
  2543. };
  2544. const getEncodeFunc = (name, entities) => {
  2545. const entitiesMap = buildEntitiesLookup(entities) || namedEntities;
  2546. const encodeNamedAndNumeric = (text, attr) => text.replace(attr ? attrsCharsRegExp : textCharsRegExp, chr => {
  2547. if (baseEntities[chr] !== undefined) {
  2548. return baseEntities[chr];
  2549. }
  2550. if (entitiesMap[chr] !== undefined) {
  2551. return entitiesMap[chr];
  2552. }
  2553. if (chr.length > 1) {
  2554. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  2555. }
  2556. return '&#' + chr.charCodeAt(0) + ';';
  2557. });
  2558. const encodeCustomNamed = (text, attr) => {
  2559. return encodeNamed(text, attr, entitiesMap);
  2560. };
  2561. const nameMap = makeMap$3(name.replace(/\+/g, ','));
  2562. if (nameMap.named && nameMap.numeric) {
  2563. return encodeNamedAndNumeric;
  2564. }
  2565. if (nameMap.named) {
  2566. if (entities) {
  2567. return encodeCustomNamed;
  2568. }
  2569. return encodeNamed;
  2570. }
  2571. if (nameMap.numeric) {
  2572. return encodeNumeric;
  2573. }
  2574. return encodeRaw;
  2575. };
  2576. const decode = text => text.replace(entityRegExp, (all, numeric) => {
  2577. if (numeric) {
  2578. if (numeric.charAt(0).toLowerCase() === 'x') {
  2579. numeric = parseInt(numeric.substr(1), 16);
  2580. } else {
  2581. numeric = parseInt(numeric, 10);
  2582. }
  2583. if (numeric > 65535) {
  2584. numeric -= 65536;
  2585. return String.fromCharCode(55296 + (numeric >> 10), 56320 + (numeric & 1023));
  2586. }
  2587. return asciiMap[numeric] || String.fromCharCode(numeric);
  2588. }
  2589. return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
  2590. });
  2591. const Entities = {
  2592. encodeRaw,
  2593. encodeAllRaw,
  2594. encodeNumeric,
  2595. encodeNamed,
  2596. getEncodeFunc,
  2597. decode
  2598. };
  2599. const mapCache = {}, dummyObj = {};
  2600. const makeMap$2 = Tools.makeMap, each$d = Tools.each, extend$2 = Tools.extend, explode$2 = Tools.explode, inArray = Tools.inArray;
  2601. const split$1 = (items, delim) => {
  2602. items = Tools.trim(items);
  2603. return items ? items.split(delim || ' ') : [];
  2604. };
  2605. const createMap = (defaultValue, extendWith) => {
  2606. const value = makeMap$2(defaultValue, ' ', makeMap$2(defaultValue.toUpperCase(), ' '));
  2607. return extend$2(value, extendWith);
  2608. };
  2609. const getTextRootBlockElements = schema => createMap('td th li dt dd figcaption caption details summary', schema.getTextBlockElements());
  2610. const compileSchema = type => {
  2611. const schema = {};
  2612. let globalAttributes, blockContent;
  2613. let phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
  2614. const add = (name, attributes = '', children = '') => {
  2615. const childNames = split$1(children);
  2616. const names = split$1(name);
  2617. let ni = names.length;
  2618. while (ni--) {
  2619. const attributesOrder = split$1([
  2620. globalAttributes,
  2621. attributes
  2622. ].join(' '));
  2623. schema[names[ni]] = {
  2624. attributes: mapToObject(attributesOrder, () => ({})),
  2625. attributesOrder,
  2626. children: mapToObject(childNames, constant(dummyObj))
  2627. };
  2628. }
  2629. };
  2630. const addAttrs = (name, attributes) => {
  2631. const names = split$1(name);
  2632. const attrs = split$1(attributes);
  2633. let ni = names.length;
  2634. while (ni--) {
  2635. const schemaItem = schema[names[ni]];
  2636. for (let i = 0, l = attrs.length; i < l; i++) {
  2637. schemaItem.attributes[attrs[i]] = {};
  2638. schemaItem.attributesOrder.push(attrs[i]);
  2639. }
  2640. }
  2641. };
  2642. if (mapCache[type]) {
  2643. return mapCache[type];
  2644. }
  2645. globalAttributes = 'id accesskey class dir lang style tabindex title role';
  2646. blockContent = 'address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul';
  2647. 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';
  2648. if (type !== 'html4') {
  2649. globalAttributes += ' contenteditable contextmenu draggable dropzone ' + 'hidden spellcheck translate';
  2650. blockContent += ' article aside details dialog figure main header footer hgroup section nav';
  2651. phrasingContent += ' audio canvas command datalist mark meter output picture ' + 'progress time wbr video ruby bdi keygen';
  2652. }
  2653. if (type !== 'html5-strict') {
  2654. globalAttributes += ' xml:lang';
  2655. html4PhrasingContent = 'acronym applet basefont big font strike tt';
  2656. phrasingContent = [
  2657. phrasingContent,
  2658. html4PhrasingContent
  2659. ].join(' ');
  2660. each$d(split$1(html4PhrasingContent), name => {
  2661. add(name, '', phrasingContent);
  2662. });
  2663. html4BlockContent = 'center dir isindex noframes';
  2664. blockContent = [
  2665. blockContent,
  2666. html4BlockContent
  2667. ].join(' ');
  2668. flowContent = [
  2669. blockContent,
  2670. phrasingContent
  2671. ].join(' ');
  2672. each$d(split$1(html4BlockContent), name => {
  2673. add(name, '', flowContent);
  2674. });
  2675. }
  2676. flowContent = flowContent || [
  2677. blockContent,
  2678. phrasingContent
  2679. ].join(' ');
  2680. add('html', 'manifest', 'head body');
  2681. add('head', '', 'base command link meta noscript script style title');
  2682. add('title hr noscript br');
  2683. add('base', 'href target');
  2684. add('link', 'href rel media hreflang type sizes hreflang');
  2685. add('meta', 'name http-equiv content charset');
  2686. add('style', 'media type scoped');
  2687. add('script', 'src async defer type charset');
  2688. add('body', 'onafterprint onbeforeprint onbeforeunload onblur onerror onfocus ' + 'onhashchange onload onmessage onoffline ononline onpagehide onpageshow ' + 'onpopstate onresize onscroll onstorage onunload', flowContent);
  2689. add('address dt dd div caption', '', flowContent);
  2690. 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);
  2691. add('blockquote', 'cite', flowContent);
  2692. add('ol', 'reversed start type', 'li');
  2693. add('ul', '', 'li');
  2694. add('li', 'value', flowContent);
  2695. add('dl', '', 'dt dd');
  2696. add('a', 'href target rel media hreflang type', phrasingContent);
  2697. add('q', 'cite', phrasingContent);
  2698. add('ins del', 'cite datetime', flowContent);
  2699. add('img', 'src sizes srcset alt usemap ismap width height');
  2700. add('iframe', 'src name width height', flowContent);
  2701. add('embed', 'src type width height');
  2702. add('object', 'data type typemustmatch name usemap form width height', [
  2703. flowContent,
  2704. 'param'
  2705. ].join(' '));
  2706. add('param', 'name value');
  2707. add('map', 'name', [
  2708. flowContent,
  2709. 'area'
  2710. ].join(' '));
  2711. add('area', 'alt coords shape href target rel media hreflang type');
  2712. add('table', 'border', 'caption colgroup thead tfoot tbody tr' + (type === 'html4' ? ' col' : ''));
  2713. add('colgroup', 'span', 'col');
  2714. add('col', 'span');
  2715. add('tbody thead tfoot', '', 'tr');
  2716. add('tr', '', 'td th');
  2717. add('td', 'colspan rowspan headers', flowContent);
  2718. add('th', 'colspan rowspan headers scope abbr', flowContent);
  2719. add('form', 'accept-charset action autocomplete enctype method name novalidate target', flowContent);
  2720. add('fieldset', 'disabled form name', [
  2721. flowContent,
  2722. 'legend'
  2723. ].join(' '));
  2724. add('label', 'form for', phrasingContent);
  2725. 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');
  2726. add('button', 'disabled form formaction formenctype formmethod formnovalidate formtarget name type value', type === 'html4' ? flowContent : phrasingContent);
  2727. add('select', 'disabled form multiple name required size', 'option optgroup');
  2728. add('optgroup', 'disabled label', 'option');
  2729. add('option', 'disabled label selected value');
  2730. add('textarea', 'cols dirname disabled form maxlength name readonly required rows wrap');
  2731. add('menu', 'type label', [
  2732. flowContent,
  2733. 'li'
  2734. ].join(' '));
  2735. add('noscript', '', flowContent);
  2736. if (type !== 'html4') {
  2737. add('wbr');
  2738. add('ruby', '', [
  2739. phrasingContent,
  2740. 'rt rp'
  2741. ].join(' '));
  2742. add('figcaption', '', flowContent);
  2743. add('mark rt rp summary bdi', '', phrasingContent);
  2744. add('canvas', 'width height', flowContent);
  2745. add('video', 'src crossorigin poster preload autoplay mediagroup loop ' + 'muted controls width height buffered', [
  2746. flowContent,
  2747. 'track source'
  2748. ].join(' '));
  2749. add('audio', 'src crossorigin preload autoplay mediagroup loop muted controls ' + 'buffered volume', [
  2750. flowContent,
  2751. 'track source'
  2752. ].join(' '));
  2753. add('picture', '', 'img source');
  2754. add('source', 'src srcset type media sizes');
  2755. add('track', 'kind src srclang label default');
  2756. add('datalist', '', [
  2757. phrasingContent,
  2758. 'option'
  2759. ].join(' '));
  2760. add('article section nav aside main header footer', '', flowContent);
  2761. add('hgroup', '', 'h1 h2 h3 h4 h5 h6');
  2762. add('figure', '', [
  2763. flowContent,
  2764. 'figcaption'
  2765. ].join(' '));
  2766. add('time', 'datetime', phrasingContent);
  2767. add('dialog', 'open', flowContent);
  2768. add('command', 'type label icon disabled checked radiogroup command');
  2769. add('output', 'for form name', phrasingContent);
  2770. add('progress', 'value max', phrasingContent);
  2771. add('meter', 'value min max low high optimum', phrasingContent);
  2772. add('details', 'open', [
  2773. flowContent,
  2774. 'summary'
  2775. ].join(' '));
  2776. add('keygen', 'autofocus challenge disabled form keytype name');
  2777. }
  2778. if (type !== 'html5-strict') {
  2779. addAttrs('script', 'language xml:space');
  2780. addAttrs('style', 'xml:space');
  2781. addAttrs('object', 'declare classid code codebase codetype archive standby align border hspace vspace');
  2782. addAttrs('embed', 'align name hspace vspace');
  2783. addAttrs('param', 'valuetype type');
  2784. addAttrs('a', 'charset name rev shape coords');
  2785. addAttrs('br', 'clear');
  2786. addAttrs('applet', 'codebase archive code object alt name width height align hspace vspace');
  2787. addAttrs('img', 'name longdesc align border hspace vspace');
  2788. addAttrs('iframe', 'longdesc frameborder marginwidth marginheight scrolling align');
  2789. addAttrs('font basefont', 'size color face');
  2790. addAttrs('input', 'usemap align');
  2791. addAttrs('select');
  2792. addAttrs('textarea');
  2793. addAttrs('h1 h2 h3 h4 h5 h6 div p legend caption', 'align');
  2794. addAttrs('ul', 'type compact');
  2795. addAttrs('li', 'type');
  2796. addAttrs('ol dl menu dir', 'compact');
  2797. addAttrs('pre', 'width xml:space');
  2798. addAttrs('hr', 'align noshade size width');
  2799. addAttrs('isindex', 'prompt');
  2800. addAttrs('table', 'summary width frame rules cellspacing cellpadding align bgcolor');
  2801. addAttrs('col', 'width align char charoff valign');
  2802. addAttrs('colgroup', 'width align char charoff valign');
  2803. addAttrs('thead', 'align char charoff valign');
  2804. addAttrs('tr', 'align char charoff valign bgcolor');
  2805. addAttrs('th', 'axis align char charoff valign nowrap bgcolor width height');
  2806. addAttrs('form', 'accept');
  2807. addAttrs('td', 'abbr axis scope align char charoff valign nowrap bgcolor width height');
  2808. addAttrs('tfoot', 'align char charoff valign');
  2809. addAttrs('tbody', 'align char charoff valign');
  2810. addAttrs('area', 'nohref');
  2811. addAttrs('body', 'background bgcolor text link vlink alink');
  2812. }
  2813. if (type !== 'html4') {
  2814. addAttrs('input button select textarea', 'autofocus');
  2815. addAttrs('input textarea', 'placeholder');
  2816. addAttrs('a', 'download');
  2817. addAttrs('link script img', 'crossorigin');
  2818. addAttrs('img', 'loading');
  2819. addAttrs('iframe', 'sandbox seamless allowfullscreen loading');
  2820. }
  2821. if (type !== 'html4') {
  2822. each$g([
  2823. schema.video,
  2824. schema.audio
  2825. ], item => {
  2826. delete item.children.audio;
  2827. delete item.children.video;
  2828. });
  2829. }
  2830. each$d(split$1('a form meter progress dfn'), name => {
  2831. if (schema[name]) {
  2832. delete schema[name].children[name];
  2833. }
  2834. });
  2835. delete schema.caption.children.table;
  2836. delete schema.script;
  2837. mapCache[type] = schema;
  2838. return schema;
  2839. };
  2840. const compileElementMap = (value, mode) => {
  2841. let styles;
  2842. if (value) {
  2843. styles = {};
  2844. if (typeof value === 'string') {
  2845. value = { '*': value };
  2846. }
  2847. each$d(value, (value, key) => {
  2848. styles[key] = styles[key.toUpperCase()] = mode === 'map' ? makeMap$2(value, /[, ]/) : explode$2(value, /[, ]/);
  2849. });
  2850. }
  2851. return styles;
  2852. };
  2853. const Schema = settings => {
  2854. var _a;
  2855. const elements = {};
  2856. const children = {};
  2857. let patternElements = [];
  2858. const customElementsMap = {}, specialElements = {};
  2859. const createLookupTable = (option, defaultValue, extendWith) => {
  2860. let value = settings[option];
  2861. if (!value) {
  2862. value = mapCache[option];
  2863. if (!value) {
  2864. value = createMap(defaultValue, extendWith);
  2865. mapCache[option] = value;
  2866. }
  2867. } else {
  2868. value = makeMap$2(value, /[, ]/, makeMap$2(value.toUpperCase(), /[, ]/));
  2869. }
  2870. return value;
  2871. };
  2872. settings = settings || {};
  2873. const schemaType = (_a = settings.schema) !== null && _a !== void 0 ? _a : 'html5';
  2874. const schemaItems = compileSchema(schemaType);
  2875. if (settings.verify_html === false) {
  2876. settings.valid_elements = '*[*]';
  2877. }
  2878. const validStyles = compileElementMap(settings.valid_styles);
  2879. const invalidStyles = compileElementMap(settings.invalid_styles, 'map');
  2880. const validClasses = compileElementMap(settings.valid_classes, 'map');
  2881. const whitespaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object code');
  2882. const selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
  2883. const voidElementsMap = createLookupTable('void_elements', 'area base basefont br col frame hr img input isindex link ' + 'meta param embed source wbr track');
  2884. const boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + 'noshade nowrap readonly selected autoplay loop controls allowfullscreen');
  2885. const nonEmptyOrMoveCaretBeforeOnEnter = 'td th iframe video audio object script code';
  2886. const nonEmptyElementsMap = createLookupTable('non_empty_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' pre', voidElementsMap);
  2887. const moveCaretBeforeOnEnterElementsMap = createLookupTable('move_caret_before_on_enter_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' table', voidElementsMap);
  2888. const 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');
  2889. const 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);
  2890. const textInlineElementsMap = createLookupTable('text_inline_elements', 'span strong b em i font s strike u var cite ' + 'dfn code mark q sup sub samp');
  2891. each$d('script noscript iframe noframes noembed title style textarea xmp plaintext'.split(' '), name => {
  2892. specialElements[name] = new RegExp('</' + name + '[^>]*>', 'gi');
  2893. });
  2894. const patternToRegExp = str => new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
  2895. const addValidElements = validElements => {
  2896. let ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, value;
  2897. const elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/, attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=~<]+)?(?:([=~<])(.*))?$/, hasPatternsRegExp = /[*?+]/;
  2898. if (validElements) {
  2899. const validElementsArr = split$1(validElements, ',');
  2900. if (elements['@']) {
  2901. globalAttributes = elements['@'].attributes;
  2902. globalAttributesOrder = elements['@'].attributesOrder;
  2903. }
  2904. for (ei = 0, el = validElementsArr.length; ei < el; ei++) {
  2905. matches = elementRuleRegExp.exec(validElementsArr[ei]);
  2906. if (matches) {
  2907. prefix = matches[1];
  2908. elementName = matches[2];
  2909. outputName = matches[3];
  2910. attrData = matches[5];
  2911. attributes = {};
  2912. attributesOrder = [];
  2913. element = {
  2914. attributes,
  2915. attributesOrder
  2916. };
  2917. if (prefix === '#') {
  2918. element.paddEmpty = true;
  2919. }
  2920. if (prefix === '-') {
  2921. element.removeEmpty = true;
  2922. }
  2923. if (matches[4] === '!') {
  2924. element.removeEmptyAttrs = true;
  2925. }
  2926. if (globalAttributes) {
  2927. each$f(globalAttributes, (value, key) => {
  2928. attributes[key] = value;
  2929. });
  2930. attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
  2931. }
  2932. if (attrData) {
  2933. attrData = split$1(attrData, '|');
  2934. for (ai = 0, al = attrData.length; ai < al; ai++) {
  2935. matches = attrRuleRegExp.exec(attrData[ai]);
  2936. if (matches) {
  2937. attr = {};
  2938. attrType = matches[1];
  2939. attrName = matches[2].replace(/[\\:]:/g, ':');
  2940. prefix = matches[3];
  2941. value = matches[4];
  2942. if (attrType === '!') {
  2943. element.attributesRequired = element.attributesRequired || [];
  2944. element.attributesRequired.push(attrName);
  2945. attr.required = true;
  2946. }
  2947. if (attrType === '-') {
  2948. delete attributes[attrName];
  2949. attributesOrder.splice(inArray(attributesOrder, attrName), 1);
  2950. continue;
  2951. }
  2952. if (prefix) {
  2953. if (prefix === '=') {
  2954. element.attributesDefault = element.attributesDefault || [];
  2955. element.attributesDefault.push({
  2956. name: attrName,
  2957. value
  2958. });
  2959. attr.defaultValue = value;
  2960. }
  2961. if (prefix === '~') {
  2962. element.attributesForced = element.attributesForced || [];
  2963. element.attributesForced.push({
  2964. name: attrName,
  2965. value
  2966. });
  2967. attr.forcedValue = value;
  2968. }
  2969. if (prefix === '<') {
  2970. attr.validValues = makeMap$2(value, '?');
  2971. }
  2972. }
  2973. if (hasPatternsRegExp.test(attrName)) {
  2974. element.attributePatterns = element.attributePatterns || [];
  2975. attr.pattern = patternToRegExp(attrName);
  2976. element.attributePatterns.push(attr);
  2977. } else {
  2978. if (!attributes[attrName]) {
  2979. attributesOrder.push(attrName);
  2980. }
  2981. attributes[attrName] = attr;
  2982. }
  2983. }
  2984. }
  2985. }
  2986. if (!globalAttributes && elementName === '@') {
  2987. globalAttributes = attributes;
  2988. globalAttributesOrder = attributesOrder;
  2989. }
  2990. if (outputName) {
  2991. element.outputName = elementName;
  2992. elements[outputName] = element;
  2993. }
  2994. if (hasPatternsRegExp.test(elementName)) {
  2995. element.pattern = patternToRegExp(elementName);
  2996. patternElements.push(element);
  2997. } else {
  2998. elements[elementName] = element;
  2999. }
  3000. }
  3001. }
  3002. }
  3003. };
  3004. const setValidElements = validElements => {
  3005. patternElements = [];
  3006. each$g(keys(elements), name => {
  3007. delete elements[name];
  3008. });
  3009. addValidElements(validElements);
  3010. each$d(schemaItems, (element, name) => {
  3011. children[name] = element.children;
  3012. });
  3013. };
  3014. const addCustomElements = customElements => {
  3015. const customElementRegExp = /^(~)?(.+)$/;
  3016. if (customElements) {
  3017. mapCache.text_block_elements = mapCache.block_elements = null;
  3018. each$d(split$1(customElements, ','), rule => {
  3019. const matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2];
  3020. children[name] = children[cloneName];
  3021. customElementsMap[name] = cloneName;
  3022. if (!inline) {
  3023. blockElementsMap[name.toUpperCase()] = {};
  3024. blockElementsMap[name] = {};
  3025. }
  3026. if (!elements[name]) {
  3027. let customRule = elements[cloneName];
  3028. customRule = extend$2({}, customRule);
  3029. delete customRule.removeEmptyAttrs;
  3030. delete customRule.removeEmpty;
  3031. elements[name] = customRule;
  3032. }
  3033. each$d(children, (element, elmName) => {
  3034. if (element[cloneName]) {
  3035. children[elmName] = element = extend$2({}, children[elmName]);
  3036. element[name] = element[cloneName];
  3037. }
  3038. });
  3039. });
  3040. }
  3041. };
  3042. const addValidChildren = validChildren => {
  3043. const 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]+)\[([^\]]+)]$/;
  3044. mapCache[schemaType] = null;
  3045. if (validChildren) {
  3046. each$d(split$1(validChildren, ','), rule => {
  3047. const matches = childRuleRegExp.exec(rule);
  3048. let parent, prefix;
  3049. if (matches) {
  3050. prefix = matches[1];
  3051. if (prefix) {
  3052. parent = children[matches[2]];
  3053. } else {
  3054. parent = children[matches[2]] = { '#comment': {} };
  3055. }
  3056. parent = children[matches[2]];
  3057. each$d(split$1(matches[3], '|'), child => {
  3058. if (prefix === '-') {
  3059. delete parent[child];
  3060. } else {
  3061. parent[child] = {};
  3062. }
  3063. });
  3064. }
  3065. });
  3066. }
  3067. };
  3068. const getElementRule = name => {
  3069. let element = elements[name], i;
  3070. if (element) {
  3071. return element;
  3072. }
  3073. i = patternElements.length;
  3074. while (i--) {
  3075. element = patternElements[i];
  3076. if (element.pattern.test(name)) {
  3077. return element;
  3078. }
  3079. }
  3080. };
  3081. if (!settings.valid_elements) {
  3082. each$d(schemaItems, (element, name) => {
  3083. elements[name] = {
  3084. attributes: element.attributes,
  3085. attributesOrder: element.attributesOrder
  3086. };
  3087. children[name] = element.children;
  3088. });
  3089. each$d(split$1('strong/b em/i'), item => {
  3090. const items = split$1(item, '/');
  3091. elements[items[1]].outputName = items[0];
  3092. });
  3093. each$d(textInlineElementsMap, (_val, name) => {
  3094. if (elements[name]) {
  3095. if (settings.padd_empty_block_inline_children) {
  3096. elements[name].paddInEmptyBlock = true;
  3097. }
  3098. elements[name].removeEmpty = true;
  3099. }
  3100. });
  3101. each$d(split$1('ol ul blockquote a table tbody'), name => {
  3102. if (elements[name]) {
  3103. elements[name].removeEmpty = true;
  3104. }
  3105. });
  3106. each$d(split$1('p h1 h2 h3 h4 h5 h6 th td pre div address caption li'), name => {
  3107. elements[name].paddEmpty = true;
  3108. });
  3109. each$d(split$1('span'), name => {
  3110. elements[name].removeEmptyAttrs = true;
  3111. });
  3112. } else {
  3113. setValidElements(settings.valid_elements);
  3114. }
  3115. addCustomElements(settings.custom_elements);
  3116. addValidChildren(settings.valid_children);
  3117. addValidElements(settings.extended_valid_elements);
  3118. addValidChildren('+ol[ul|ol],+ul[ul|ol]');
  3119. each$d({
  3120. dd: 'dl',
  3121. dt: 'dl',
  3122. li: 'ul ol',
  3123. td: 'tr',
  3124. th: 'tr',
  3125. tr: 'tbody thead tfoot',
  3126. tbody: 'table',
  3127. thead: 'table',
  3128. tfoot: 'table',
  3129. legend: 'fieldset',
  3130. area: 'map',
  3131. param: 'video audio object'
  3132. }, (parents, item) => {
  3133. if (elements[item]) {
  3134. elements[item].parentsRequired = split$1(parents);
  3135. }
  3136. });
  3137. if (settings.invalid_elements) {
  3138. each$d(explode$2(settings.invalid_elements), item => {
  3139. if (elements[item]) {
  3140. delete elements[item];
  3141. }
  3142. });
  3143. }
  3144. if (!getElementRule('span')) {
  3145. addValidElements('span[!data-mce-type|*]');
  3146. }
  3147. const getValidStyles = constant(validStyles);
  3148. const getInvalidStyles = constant(invalidStyles);
  3149. const getValidClasses = constant(validClasses);
  3150. const getBoolAttrs = constant(boolAttrMap);
  3151. const getBlockElements = constant(blockElementsMap);
  3152. const getTextBlockElements = constant(textBlockElementsMap);
  3153. const getTextInlineElements = constant(textInlineElementsMap);
  3154. const getVoidElements = constant(Object.seal(voidElementsMap));
  3155. const getSelfClosingElements = constant(selfClosingElementsMap);
  3156. const getNonEmptyElements = constant(nonEmptyElementsMap);
  3157. const getMoveCaretBeforeOnEnterElements = constant(moveCaretBeforeOnEnterElementsMap);
  3158. const getWhitespaceElements = constant(whitespaceElementsMap);
  3159. const getSpecialElements = constant(Object.seal(specialElements));
  3160. const isValidChild = (name, child) => {
  3161. const parent = children[name.toLowerCase()];
  3162. return !!(parent && parent[child.toLowerCase()]);
  3163. };
  3164. const isValid = (name, attr) => {
  3165. let attrPatterns, i;
  3166. const rule = getElementRule(name);
  3167. if (rule) {
  3168. if (attr) {
  3169. if (rule.attributes[attr]) {
  3170. return true;
  3171. }
  3172. attrPatterns = rule.attributePatterns;
  3173. if (attrPatterns) {
  3174. i = attrPatterns.length;
  3175. while (i--) {
  3176. if (attrPatterns[i].pattern.test(attr)) {
  3177. return true;
  3178. }
  3179. }
  3180. }
  3181. } else {
  3182. return true;
  3183. }
  3184. }
  3185. return false;
  3186. };
  3187. const getCustomElements = constant(customElementsMap);
  3188. return {
  3189. type: schemaType,
  3190. children,
  3191. elements,
  3192. getValidStyles,
  3193. getValidClasses,
  3194. getBlockElements,
  3195. getInvalidStyles,
  3196. getVoidElements,
  3197. getTextBlockElements,
  3198. getTextInlineElements,
  3199. getBoolAttrs,
  3200. getElementRule,
  3201. getSelfClosingElements,
  3202. getNonEmptyElements,
  3203. getMoveCaretBeforeOnEnterElements,
  3204. getWhitespaceElements,
  3205. getSpecialElements,
  3206. isValidChild,
  3207. isValid,
  3208. getCustomElements,
  3209. addValidElements,
  3210. setValidElements,
  3211. addCustomElements,
  3212. addValidChildren
  3213. };
  3214. };
  3215. const Styles = (settings, schema) => {
  3216. const urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
  3217. const styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
  3218. const trimRightRegExp = /\s+$/;
  3219. let i;
  3220. const encodingLookup = {};
  3221. let validStyles;
  3222. let invalidStyles;
  3223. const invisibleChar = zeroWidth;
  3224. settings = settings || {};
  3225. if (schema) {
  3226. validStyles = schema.getValidStyles();
  3227. invalidStyles = schema.getInvalidStyles();
  3228. }
  3229. const encodingItems = (`\\" \\' \\; \\: ; : ` + invisibleChar).split(' ');
  3230. for (i = 0; i < encodingItems.length; i++) {
  3231. encodingLookup[encodingItems[i]] = invisibleChar + i;
  3232. encodingLookup[invisibleChar + i] = encodingItems[i];
  3233. }
  3234. const self = {
  3235. parse: css => {
  3236. const styles = {};
  3237. let matches, name, value, isEncoded;
  3238. const urlConverter = settings.url_converter;
  3239. const urlConverterScope = settings.url_converter_scope || self;
  3240. const compress = (prefix, suffix, noJoin) => {
  3241. const top = styles[prefix + '-top' + suffix];
  3242. if (!top) {
  3243. return;
  3244. }
  3245. const right = styles[prefix + '-right' + suffix];
  3246. if (!right) {
  3247. return;
  3248. }
  3249. const bottom = styles[prefix + '-bottom' + suffix];
  3250. if (!bottom) {
  3251. return;
  3252. }
  3253. const left = styles[prefix + '-left' + suffix];
  3254. if (!left) {
  3255. return;
  3256. }
  3257. const box = [
  3258. top,
  3259. right,
  3260. bottom,
  3261. left
  3262. ];
  3263. i = box.length - 1;
  3264. while (i--) {
  3265. if (box[i] !== box[i + 1]) {
  3266. break;
  3267. }
  3268. }
  3269. if (i > -1 && noJoin) {
  3270. return;
  3271. }
  3272. styles[prefix + suffix] = i === -1 ? box[0] : box.join(' ');
  3273. delete styles[prefix + '-top' + suffix];
  3274. delete styles[prefix + '-right' + suffix];
  3275. delete styles[prefix + '-bottom' + suffix];
  3276. delete styles[prefix + '-left' + suffix];
  3277. };
  3278. const canCompress = key => {
  3279. let value = styles[key], i;
  3280. if (!value) {
  3281. return;
  3282. }
  3283. value = value.split(' ');
  3284. i = value.length;
  3285. while (i--) {
  3286. if (value[i] !== value[0]) {
  3287. return false;
  3288. }
  3289. }
  3290. styles[key] = value[0];
  3291. return true;
  3292. };
  3293. const compress2 = (target, a, b, c) => {
  3294. if (!canCompress(a)) {
  3295. return;
  3296. }
  3297. if (!canCompress(b)) {
  3298. return;
  3299. }
  3300. if (!canCompress(c)) {
  3301. return;
  3302. }
  3303. styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
  3304. delete styles[a];
  3305. delete styles[b];
  3306. delete styles[c];
  3307. };
  3308. const encode = str => {
  3309. isEncoded = true;
  3310. return encodingLookup[str];
  3311. };
  3312. const decode = (str, keepSlashes) => {
  3313. if (isEncoded) {
  3314. str = str.replace(/\uFEFF[0-9]/g, str => {
  3315. return encodingLookup[str];
  3316. });
  3317. }
  3318. if (!keepSlashes) {
  3319. str = str.replace(/\\([\'\";:])/g, '$1');
  3320. }
  3321. return str;
  3322. };
  3323. const decodeSingleHexSequence = escSeq => {
  3324. return String.fromCharCode(parseInt(escSeq.slice(1), 16));
  3325. };
  3326. const decodeHexSequences = value => {
  3327. return value.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
  3328. };
  3329. const processUrl = (match, url, url2, url3, str, str2) => {
  3330. str = str || str2;
  3331. if (str) {
  3332. str = decode(str);
  3333. return `'` + str.replace(/\'/g, `\\'`) + `'`;
  3334. }
  3335. url = decode(url || url2 || url3);
  3336. if (!settings.allow_script_urls) {
  3337. const scriptUrl = url.replace(/[\s\r\n]+/g, '');
  3338. if (/(java|vb)script:/i.test(scriptUrl)) {
  3339. return '';
  3340. }
  3341. if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
  3342. return '';
  3343. }
  3344. }
  3345. if (urlConverter) {
  3346. url = urlConverter.call(urlConverterScope, url, 'style');
  3347. }
  3348. return `url('` + url.replace(/\'/g, `\\'`) + `')`;
  3349. };
  3350. if (css) {
  3351. css = css.replace(/[\u0000-\u001F]/g, '');
  3352. css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, str => {
  3353. return str.replace(/[;:]/g, encode);
  3354. });
  3355. while (matches = styleRegExp.exec(css)) {
  3356. styleRegExp.lastIndex = matches.index + matches[0].length;
  3357. name = matches[1].replace(trimRightRegExp, '').toLowerCase();
  3358. value = matches[2].replace(trimRightRegExp, '');
  3359. if (name && value) {
  3360. name = decodeHexSequences(name);
  3361. value = decodeHexSequences(value);
  3362. if (name.indexOf(invisibleChar) !== -1 || name.indexOf('"') !== -1) {
  3363. continue;
  3364. }
  3365. if (!settings.allow_script_urls && (name === 'behavior' || /expression\s*\(|\/\*|\*\//.test(value))) {
  3366. continue;
  3367. }
  3368. if (name === 'font-weight' && value === '700') {
  3369. value = 'bold';
  3370. } else if (name === 'color' || name === 'background-color') {
  3371. value = value.toLowerCase();
  3372. }
  3373. value = value.replace(urlOrStrRegExp, processUrl);
  3374. styles[name] = isEncoded ? decode(value, true) : value;
  3375. }
  3376. }
  3377. compress('border', '', true);
  3378. compress('border', '-width');
  3379. compress('border', '-color');
  3380. compress('border', '-style');
  3381. compress('padding', '');
  3382. compress('margin', '');
  3383. compress2('border', 'border-width', 'border-style', 'border-color');
  3384. if (styles.border === 'medium none') {
  3385. delete styles.border;
  3386. }
  3387. if (styles['border-image'] === 'none') {
  3388. delete styles['border-image'];
  3389. }
  3390. }
  3391. return styles;
  3392. },
  3393. serialize: (styles, elementName) => {
  3394. let css = '';
  3395. const serializeStyles = name => {
  3396. let value;
  3397. const styleList = validStyles[name];
  3398. if (styleList) {
  3399. for (let i = 0, l = styleList.length; i < l; i++) {
  3400. name = styleList[i];
  3401. value = styles[name];
  3402. if (value) {
  3403. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  3404. }
  3405. }
  3406. }
  3407. };
  3408. const isValid = (name, elementName) => {
  3409. let styleMap = invalidStyles['*'];
  3410. if (styleMap && styleMap[name]) {
  3411. return false;
  3412. }
  3413. styleMap = invalidStyles[elementName];
  3414. return !(styleMap && styleMap[name]);
  3415. };
  3416. if (elementName && validStyles) {
  3417. serializeStyles('*');
  3418. serializeStyles(elementName);
  3419. } else {
  3420. each$f(styles, (value, name) => {
  3421. if (value && (!invalidStyles || isValid(name, elementName))) {
  3422. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  3423. }
  3424. });
  3425. }
  3426. return css;
  3427. }
  3428. };
  3429. return self;
  3430. };
  3431. const deprecated = {
  3432. keyLocation: true,
  3433. layerX: true,
  3434. layerY: true,
  3435. returnValue: true,
  3436. webkitMovementX: true,
  3437. webkitMovementY: true,
  3438. keyIdentifier: true,
  3439. mozPressure: true
  3440. };
  3441. const isNativeEvent = event => event instanceof Event || isFunction(event.initEvent);
  3442. const hasIsDefaultPrevented = event => event.isDefaultPrevented === always || event.isDefaultPrevented === never;
  3443. const needsNormalizing = event => isNullable(event.preventDefault) || isNativeEvent(event);
  3444. const clone$3 = (originalEvent, data) => {
  3445. const event = data !== null && data !== void 0 ? data : {};
  3446. for (const name in originalEvent) {
  3447. if (!has$2(deprecated, name)) {
  3448. event[name] = originalEvent[name];
  3449. }
  3450. }
  3451. if (isNonNullable(event.composedPath)) {
  3452. event.composedPath = () => originalEvent.composedPath();
  3453. }
  3454. return event;
  3455. };
  3456. const normalize$3 = (type, originalEvent, fallbackTarget, data) => {
  3457. var _a;
  3458. const event = clone$3(originalEvent, data);
  3459. event.type = type;
  3460. if (isNullable(event.target)) {
  3461. event.target = (_a = event.srcElement) !== null && _a !== void 0 ? _a : fallbackTarget;
  3462. }
  3463. if (needsNormalizing(originalEvent)) {
  3464. event.preventDefault = () => {
  3465. event.defaultPrevented = true;
  3466. event.isDefaultPrevented = always;
  3467. if (isFunction(originalEvent.preventDefault)) {
  3468. originalEvent.preventDefault();
  3469. }
  3470. };
  3471. event.stopPropagation = () => {
  3472. event.cancelBubble = true;
  3473. event.isPropagationStopped = always;
  3474. if (isFunction(originalEvent.stopPropagation)) {
  3475. originalEvent.stopPropagation();
  3476. }
  3477. };
  3478. event.stopImmediatePropagation = () => {
  3479. event.isImmediatePropagationStopped = always;
  3480. event.stopPropagation();
  3481. };
  3482. if (!hasIsDefaultPrevented(event)) {
  3483. event.isDefaultPrevented = event.defaultPrevented === true ? always : never;
  3484. event.isPropagationStopped = event.cancelBubble === true ? always : never;
  3485. event.isImmediatePropagationStopped = never;
  3486. }
  3487. }
  3488. return event;
  3489. };
  3490. const eventExpandoPrefix = 'mce-data-';
  3491. const mouseEventRe = /^(?:mouse|contextmenu)|click/;
  3492. const addEvent = (target, name, callback, capture) => {
  3493. if (target.addEventListener) {
  3494. target.addEventListener(name, callback, capture || false);
  3495. } else if (target.attachEvent) {
  3496. target.attachEvent('on' + name, callback);
  3497. }
  3498. };
  3499. const removeEvent = (target, name, callback, capture) => {
  3500. if (target.removeEventListener) {
  3501. target.removeEventListener(name, callback, capture || false);
  3502. } else if (target.detachEvent) {
  3503. target.detachEvent('on' + name, callback);
  3504. }
  3505. };
  3506. const isMouseEvent = event => isNonNullable(event) && mouseEventRe.test(event.type);
  3507. const fix = (originalEvent, data) => {
  3508. const event = normalize$3(originalEvent.type, originalEvent, document, data);
  3509. if (isMouseEvent(originalEvent) && isUndefined(originalEvent.pageX) && !isUndefined(originalEvent.clientX)) {
  3510. const eventDoc = event.target.ownerDocument || document;
  3511. const doc = eventDoc.documentElement;
  3512. const body = eventDoc.body;
  3513. const mouseEvent = event;
  3514. mouseEvent.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  3515. mouseEvent.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  3516. }
  3517. return event;
  3518. };
  3519. const bindOnReady = (win, callback, eventUtils) => {
  3520. const doc = win.document, event = { type: 'ready' };
  3521. if (eventUtils.domLoaded) {
  3522. callback(event);
  3523. return;
  3524. }
  3525. const isDocReady = () => {
  3526. return doc.readyState === 'complete' || doc.readyState === 'interactive' && doc.body;
  3527. };
  3528. const readyHandler = () => {
  3529. removeEvent(win, 'DOMContentLoaded', readyHandler);
  3530. removeEvent(win, 'load', readyHandler);
  3531. if (!eventUtils.domLoaded) {
  3532. eventUtils.domLoaded = true;
  3533. callback(event);
  3534. }
  3535. win = null;
  3536. };
  3537. if (isDocReady()) {
  3538. readyHandler();
  3539. } else {
  3540. addEvent(win, 'DOMContentLoaded', readyHandler);
  3541. }
  3542. if (!eventUtils.domLoaded) {
  3543. addEvent(win, 'load', readyHandler);
  3544. }
  3545. };
  3546. class EventUtils {
  3547. constructor() {
  3548. this.domLoaded = false;
  3549. this.events = {};
  3550. this.count = 1;
  3551. this.expando = eventExpandoPrefix + (+new Date()).toString(32);
  3552. this.hasMouseEnterLeave = 'onmouseenter' in document.documentElement;
  3553. this.hasFocusIn = 'onfocusin' in document.documentElement;
  3554. this.count = 1;
  3555. }
  3556. bind(target, names, callback, scope) {
  3557. const self = this;
  3558. let id, callbackList, i, name, fakeName, nativeHandler, capture;
  3559. const win = window;
  3560. const defaultNativeHandler = evt => {
  3561. self.executeHandlers(fix(evt || win.event), id);
  3562. };
  3563. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  3564. return;
  3565. }
  3566. if (!target[self.expando]) {
  3567. id = self.count++;
  3568. target[self.expando] = id;
  3569. self.events[id] = {};
  3570. } else {
  3571. id = target[self.expando];
  3572. }
  3573. scope = scope || target;
  3574. const namesList = names.split(' ');
  3575. i = namesList.length;
  3576. while (i--) {
  3577. name = namesList[i];
  3578. nativeHandler = defaultNativeHandler;
  3579. fakeName = capture = false;
  3580. if (name === 'DOMContentLoaded') {
  3581. name = 'ready';
  3582. }
  3583. if (self.domLoaded && name === 'ready' && target.readyState === 'complete') {
  3584. callback.call(scope, fix({ type: name }));
  3585. continue;
  3586. }
  3587. if (!self.hasMouseEnterLeave) {
  3588. fakeName = self.mouseEnterLeave[name];
  3589. if (fakeName) {
  3590. nativeHandler = evt => {
  3591. const current = evt.currentTarget;
  3592. let related = evt.relatedTarget;
  3593. if (related && current.contains) {
  3594. related = current.contains(related);
  3595. } else {
  3596. while (related && related !== current) {
  3597. related = related.parentNode;
  3598. }
  3599. }
  3600. if (!related) {
  3601. evt = fix(evt || win.event);
  3602. evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
  3603. evt.target = current;
  3604. self.executeHandlers(evt, id);
  3605. }
  3606. };
  3607. }
  3608. }
  3609. if (!self.hasFocusIn && (name === 'focusin' || name === 'focusout')) {
  3610. capture = true;
  3611. fakeName = name === 'focusin' ? 'focus' : 'blur';
  3612. nativeHandler = evt => {
  3613. evt = fix(evt || win.event);
  3614. evt.type = evt.type === 'focus' ? 'focusin' : 'focusout';
  3615. self.executeHandlers(evt, id);
  3616. };
  3617. }
  3618. callbackList = self.events[id][name];
  3619. if (!callbackList) {
  3620. self.events[id][name] = callbackList = [{
  3621. func: callback,
  3622. scope
  3623. }];
  3624. callbackList.fakeName = fakeName;
  3625. callbackList.capture = capture;
  3626. callbackList.nativeHandler = nativeHandler;
  3627. if (name === 'ready') {
  3628. bindOnReady(target, nativeHandler, self);
  3629. } else {
  3630. addEvent(target, fakeName || name, nativeHandler, capture);
  3631. }
  3632. } else {
  3633. if (name === 'ready' && self.domLoaded) {
  3634. callback(fix({ type: name }));
  3635. } else {
  3636. callbackList.push({
  3637. func: callback,
  3638. scope
  3639. });
  3640. }
  3641. }
  3642. }
  3643. target = callbackList = null;
  3644. return callback;
  3645. }
  3646. unbind(target, names, callback) {
  3647. let callbackList, i, ci, name, eventMap;
  3648. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  3649. return this;
  3650. }
  3651. const id = target[this.expando];
  3652. if (id) {
  3653. eventMap = this.events[id];
  3654. if (names) {
  3655. const namesList = names.split(' ');
  3656. i = namesList.length;
  3657. while (i--) {
  3658. name = namesList[i];
  3659. callbackList = eventMap[name];
  3660. if (callbackList) {
  3661. if (callback) {
  3662. ci = callbackList.length;
  3663. while (ci--) {
  3664. if (callbackList[ci].func === callback) {
  3665. const nativeHandler = callbackList.nativeHandler;
  3666. const fakeName = callbackList.fakeName, capture = callbackList.capture;
  3667. callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
  3668. callbackList.nativeHandler = nativeHandler;
  3669. callbackList.fakeName = fakeName;
  3670. callbackList.capture = capture;
  3671. eventMap[name] = callbackList;
  3672. }
  3673. }
  3674. }
  3675. if (!callback || callbackList.length === 0) {
  3676. delete eventMap[name];
  3677. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  3678. }
  3679. }
  3680. }
  3681. } else {
  3682. each$f(eventMap, (callbackList, name) => {
  3683. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  3684. });
  3685. eventMap = {};
  3686. }
  3687. for (name in eventMap) {
  3688. if (has$2(eventMap, name)) {
  3689. return this;
  3690. }
  3691. }
  3692. delete this.events[id];
  3693. try {
  3694. delete target[this.expando];
  3695. } catch (ex) {
  3696. target[this.expando] = null;
  3697. }
  3698. }
  3699. return this;
  3700. }
  3701. fire(target, name, args) {
  3702. return this.dispatch(target, name, args);
  3703. }
  3704. dispatch(target, name, args) {
  3705. let id;
  3706. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  3707. return this;
  3708. }
  3709. const event = fix({
  3710. type: name,
  3711. target
  3712. }, args);
  3713. do {
  3714. id = target[this.expando];
  3715. if (id) {
  3716. this.executeHandlers(event, id);
  3717. }
  3718. target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
  3719. } while (target && !event.isPropagationStopped());
  3720. return this;
  3721. }
  3722. clean(target) {
  3723. let i, children;
  3724. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  3725. return this;
  3726. }
  3727. if (target[this.expando]) {
  3728. this.unbind(target);
  3729. }
  3730. if (!target.getElementsByTagName) {
  3731. target = target.document;
  3732. }
  3733. if (target && target.getElementsByTagName) {
  3734. this.unbind(target);
  3735. children = target.getElementsByTagName('*');
  3736. i = children.length;
  3737. while (i--) {
  3738. target = children[i];
  3739. if (target[this.expando]) {
  3740. this.unbind(target);
  3741. }
  3742. }
  3743. }
  3744. return this;
  3745. }
  3746. destroy() {
  3747. this.events = {};
  3748. }
  3749. cancel(e) {
  3750. if (e) {
  3751. e.preventDefault();
  3752. e.stopImmediatePropagation();
  3753. }
  3754. return false;
  3755. }
  3756. executeHandlers(evt, id) {
  3757. const container = this.events[id];
  3758. const callbackList = container && container[evt.type];
  3759. if (callbackList) {
  3760. for (let i = 0, l = callbackList.length; i < l; i++) {
  3761. const callback = callbackList[i];
  3762. if (callback && callback.func.call(callback.scope, evt) === false) {
  3763. evt.preventDefault();
  3764. }
  3765. if (evt.isImmediatePropagationStopped()) {
  3766. return;
  3767. }
  3768. }
  3769. }
  3770. }
  3771. }
  3772. EventUtils.Event = new EventUtils();
  3773. const each$c = Tools.each;
  3774. const grep = Tools.grep;
  3775. const internalStyleName = 'data-mce-style';
  3776. const legacySetAttribute = (elm, name, value) => {
  3777. if (isNullable(value) || value === '') {
  3778. remove$a(elm, name);
  3779. } else {
  3780. set$2(elm, name, value);
  3781. }
  3782. };
  3783. const setupAttrHooks = (styles, settings, getContext) => {
  3784. const keepValues = settings.keep_values;
  3785. const keepUrlHook = {
  3786. set: (elm, value, name) => {
  3787. const sugarElm = SugarElement.fromDom(elm);
  3788. if (isFunction(settings.url_converter) && isNonNullable(value)) {
  3789. value = settings.url_converter.call(settings.url_converter_scope || getContext(), value, name, elm[0]);
  3790. }
  3791. const internalName = 'data-mce-' + name;
  3792. legacySetAttribute(sugarElm, internalName, value);
  3793. legacySetAttribute(sugarElm, name, value);
  3794. },
  3795. get: (elm, name) => {
  3796. const sugarElm = SugarElement.fromDom(elm);
  3797. return get$9(sugarElm, 'data-mce-' + name) || get$9(sugarElm, name);
  3798. }
  3799. };
  3800. const attrHooks = {
  3801. style: {
  3802. set: (elm, value) => {
  3803. const sugarElm = SugarElement.fromDom(elm);
  3804. if (isObject(value)) {
  3805. setAll(sugarElm, value);
  3806. return;
  3807. }
  3808. if (keepValues) {
  3809. legacySetAttribute(sugarElm, internalStyleName, value);
  3810. }
  3811. remove$a(sugarElm, 'style');
  3812. if (isString(value)) {
  3813. setAll(sugarElm, styles.parse(value));
  3814. }
  3815. },
  3816. get: elm => {
  3817. const sugarElm = SugarElement.fromDom(elm);
  3818. const value = get$9(sugarElm, internalStyleName) || get$9(sugarElm, 'style');
  3819. return styles.serialize(styles.parse(value), name(sugarElm));
  3820. }
  3821. }
  3822. };
  3823. if (keepValues) {
  3824. attrHooks.href = attrHooks.src = keepUrlHook;
  3825. }
  3826. return attrHooks;
  3827. };
  3828. const updateInternalStyleAttr = (styles, elm) => {
  3829. const rawValue = get$9(elm, 'style');
  3830. const value = styles.serialize(styles.parse(rawValue), name(elm));
  3831. legacySetAttribute(elm, internalStyleName, value);
  3832. };
  3833. const findNodeIndex = (node, normalized) => {
  3834. let idx = 0, lastNodeType, nodeType;
  3835. if (node) {
  3836. for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
  3837. nodeType = node.nodeType;
  3838. if (normalized && nodeType === 3) {
  3839. if (nodeType === lastNodeType || !node.nodeValue.length) {
  3840. continue;
  3841. }
  3842. }
  3843. idx++;
  3844. lastNodeType = nodeType;
  3845. }
  3846. }
  3847. return idx;
  3848. };
  3849. const numericalCssMap = Tools.makeMap('fill-opacity font-weight line-height opacity orphans widows z-index zoom', ' ');
  3850. const camelCaseToHyphens = name => name.replace(/[A-Z]/g, v => '-' + v.toLowerCase());
  3851. const DOMUtils = (doc, settings = {}) => {
  3852. const addedStyles = {};
  3853. const win = window;
  3854. const files = {};
  3855. let counter = 0;
  3856. const stdMode = true;
  3857. const boxModel = true;
  3858. const styleSheetLoader = instance.forElement(SugarElement.fromDom(doc), {
  3859. contentCssCors: settings.contentCssCors,
  3860. referrerPolicy: settings.referrerPolicy
  3861. });
  3862. const boundEvents = [];
  3863. const schema = settings.schema ? settings.schema : Schema({});
  3864. const styles = Styles({
  3865. url_converter: settings.url_converter,
  3866. url_converter_scope: settings.url_converter_scope
  3867. }, settings.schema);
  3868. const events = settings.ownEvents ? new EventUtils() : EventUtils.Event;
  3869. const blockElementsMap = schema.getBlockElements();
  3870. const isBlock = node => {
  3871. if (isString(node)) {
  3872. return has$2(blockElementsMap, node);
  3873. } else {
  3874. return isElement$6(node) && has$2(blockElementsMap, node.nodeName);
  3875. }
  3876. };
  3877. const get = elm => elm && doc && isString(elm) ? doc.getElementById(elm) : elm;
  3878. const _get = elm => {
  3879. const value = get(elm);
  3880. return isNonNullable(value) ? SugarElement.fromDom(value) : null;
  3881. };
  3882. const getAttrib = (elm, name, defaultVal) => {
  3883. let value;
  3884. const $elm = _get(elm);
  3885. if (isNonNullable($elm) && isElement$7($elm)) {
  3886. const hook = attrHooks[name];
  3887. if (hook && hook.get) {
  3888. value = hook.get($elm.dom, name);
  3889. } else {
  3890. value = get$9($elm, name);
  3891. }
  3892. }
  3893. return isNonNullable(value) ? value : defaultVal !== null && defaultVal !== void 0 ? defaultVal : '';
  3894. };
  3895. const getAttribs = elm => {
  3896. const node = get(elm);
  3897. return isNullable(node) ? [] : node.attributes;
  3898. };
  3899. const setAttrib = (elm, name, value) => {
  3900. run(elm, e => {
  3901. if (isElement$6(e)) {
  3902. const $elm = SugarElement.fromDom(e);
  3903. if (value === '') {
  3904. value = null;
  3905. }
  3906. const originalValue = get$9($elm, name);
  3907. const hook = attrHooks[name];
  3908. if (hook && hook.set) {
  3909. hook.set($elm.dom, value, name);
  3910. } else {
  3911. legacySetAttribute($elm, name, value);
  3912. }
  3913. if (originalValue !== value && settings.onSetAttrib) {
  3914. settings.onSetAttrib({
  3915. attrElm: $elm,
  3916. attrName: name,
  3917. attrValue: value
  3918. });
  3919. }
  3920. }
  3921. });
  3922. };
  3923. const clone = (node, deep) => {
  3924. return node.cloneNode(deep);
  3925. };
  3926. const getRoot = () => settings.root_element || doc.body;
  3927. const getViewPort = argWin => {
  3928. const vp = getBounds(argWin);
  3929. return {
  3930. x: vp.x,
  3931. y: vp.y,
  3932. w: vp.width,
  3933. h: vp.height
  3934. };
  3935. };
  3936. const getPos$1 = (elm, rootElm) => getPos(doc.body, get(elm), rootElm);
  3937. const setStyle = (elm, name, value) => {
  3938. const convertStyleToString = (cssValue, cssName) => {
  3939. if (isString(cssValue)) {
  3940. return cssValue;
  3941. } else if (isNumber(cssValue)) {
  3942. return has$2(numericalCssMap, cssName) ? cssValue + '' : cssValue + 'px';
  3943. } else {
  3944. return map$2(cssValue, convertStyleToString);
  3945. }
  3946. };
  3947. const applyStyle = ($elm, cssName, cssValue) => {
  3948. const normalizedName = camelCaseToHyphens(cssName);
  3949. if (isNullable(cssValue) || cssValue === '') {
  3950. remove$6($elm, normalizedName);
  3951. } else {
  3952. set$1($elm, normalizedName, convertStyleToString(cssValue, normalizedName));
  3953. }
  3954. };
  3955. run(elm, e => {
  3956. const $elm = SugarElement.fromDom(e);
  3957. if (isString(name)) {
  3958. applyStyle($elm, name, value);
  3959. } else {
  3960. each$f(name, (v, n) => {
  3961. applyStyle($elm, n, v);
  3962. });
  3963. }
  3964. if (settings.update_styles) {
  3965. updateInternalStyleAttr(styles, $elm);
  3966. }
  3967. });
  3968. };
  3969. const setStyles = (elm, stylesArg) => {
  3970. setStyle(elm, stylesArg);
  3971. };
  3972. const getStyle = (elm, name, computed) => {
  3973. const $elm = get(elm);
  3974. if (isNullable($elm) || !isElement$6($elm)) {
  3975. return undefined;
  3976. }
  3977. if (computed) {
  3978. return get$7(SugarElement.fromDom($elm), camelCaseToHyphens(name));
  3979. } else {
  3980. name = name.replace(/-(\D)/g, (a, b) => b.toUpperCase());
  3981. if (name === 'float') {
  3982. name = 'cssFloat';
  3983. }
  3984. return $elm.style ? $elm.style[name] : undefined;
  3985. }
  3986. };
  3987. const getSize = elm => {
  3988. let w, h;
  3989. const $elm = get(elm);
  3990. w = getStyle($elm, 'width');
  3991. h = getStyle($elm, 'height');
  3992. if (w.indexOf('px') === -1) {
  3993. w = 0;
  3994. }
  3995. if (h.indexOf('px') === -1) {
  3996. h = 0;
  3997. }
  3998. return {
  3999. w: parseInt(w, 10) || $elm.offsetWidth || $elm.clientWidth,
  4000. h: parseInt(h, 10) || $elm.offsetHeight || $elm.clientHeight
  4001. };
  4002. };
  4003. const getRect = elm => {
  4004. const $elm = get(elm);
  4005. const pos = getPos$1($elm);
  4006. const size = getSize($elm);
  4007. return {
  4008. x: pos.x,
  4009. y: pos.y,
  4010. w: size.w,
  4011. h: size.h
  4012. };
  4013. };
  4014. const is = (elm, selector) => {
  4015. if (!elm) {
  4016. return false;
  4017. }
  4018. const elms = isArray$1(elm) ? elm : [elm];
  4019. return exists(elms, e => {
  4020. return is$1(SugarElement.fromDom(e), selector);
  4021. });
  4022. };
  4023. const getParents = (elm, selector, root, collect) => {
  4024. const result = [];
  4025. let selectorVal;
  4026. let node = get(elm);
  4027. collect = collect === undefined;
  4028. root = root || (getRoot().nodeName !== 'BODY' ? getRoot().parentNode : null);
  4029. if (isString(selector)) {
  4030. selectorVal = selector;
  4031. if (selector === '*') {
  4032. selector = isElement$6;
  4033. } else {
  4034. selector = node => is(node, selectorVal);
  4035. }
  4036. }
  4037. while (node) {
  4038. if (node === root || isNullable(node.nodeType) || isDocument$1(node) || isDocumentFragment(node)) {
  4039. break;
  4040. }
  4041. if (!selector || selector(node)) {
  4042. if (collect) {
  4043. result.push(node);
  4044. } else {
  4045. return [node];
  4046. }
  4047. }
  4048. node = node.parentNode;
  4049. }
  4050. return collect ? result : null;
  4051. };
  4052. const getParent = (node, selector, root) => {
  4053. const parents = getParents(node, selector, root, false);
  4054. return parents && parents.length > 0 ? parents[0] : null;
  4055. };
  4056. const _findSib = (node, selector, name) => {
  4057. let func = selector;
  4058. if (node) {
  4059. if (isString(selector)) {
  4060. func = node => {
  4061. return is(node, selector);
  4062. };
  4063. }
  4064. for (node = node[name]; node; node = node[name]) {
  4065. if (isFunction(func) && func(node)) {
  4066. return node;
  4067. }
  4068. }
  4069. }
  4070. return null;
  4071. };
  4072. const getNext = (node, selector) => _findSib(node, selector, 'nextSibling');
  4073. const getPrev = (node, selector) => _findSib(node, selector, 'previousSibling');
  4074. const select = (selector, scope) => {
  4075. var _a, _b;
  4076. const elm = (_b = (_a = get(scope)) !== null && _a !== void 0 ? _a : settings.root_element) !== null && _b !== void 0 ? _b : doc;
  4077. return from(elm.querySelectorAll(selector));
  4078. };
  4079. const run = function (elm, func, scope) {
  4080. const context = scope !== null && scope !== void 0 ? scope : this;
  4081. const node = isString(elm) ? get(elm) : elm;
  4082. if (!node) {
  4083. return false;
  4084. }
  4085. if (isArray$1(node) && (node.length || node.length === 0)) {
  4086. const result = [];
  4087. each$c(node, (elm, i) => {
  4088. if (elm) {
  4089. result.push(func.call(context, isString(elm) ? get(elm) : elm, i));
  4090. }
  4091. });
  4092. return result;
  4093. } else {
  4094. return func.call(context, node);
  4095. }
  4096. };
  4097. const setAttribs = (elm, attrs) => {
  4098. run(elm, $elm => {
  4099. each$f(attrs, (value, name) => {
  4100. setAttrib($elm, name, value);
  4101. });
  4102. });
  4103. };
  4104. const setHTML = (elm, html) => {
  4105. run(elm, e => {
  4106. const $elm = SugarElement.fromDom(e);
  4107. set($elm, html);
  4108. });
  4109. };
  4110. const add = (parentElm, name, attrs, html, create) => run(parentElm, parentElm => {
  4111. const newElm = isString(name) ? doc.createElement(name) : name;
  4112. if (isNonNullable(attrs)) {
  4113. setAttribs(newElm, attrs);
  4114. }
  4115. if (html) {
  4116. if (!isString(html) && html.nodeType) {
  4117. newElm.appendChild(html);
  4118. } else if (isString(html)) {
  4119. setHTML(newElm, html);
  4120. }
  4121. }
  4122. return !create ? parentElm.appendChild(newElm) : newElm;
  4123. });
  4124. const create = (name, attrs, html) => add(doc.createElement(name), name, attrs, html, true);
  4125. const decode = Entities.decode;
  4126. const encode = Entities.encodeAllRaw;
  4127. const createHTML = (name, attrs, html = '') => {
  4128. let outHtml = '', key;
  4129. outHtml += '<' + name;
  4130. for (key in attrs) {
  4131. if (hasNonNullableKey(attrs, key)) {
  4132. outHtml += ' ' + key + '="' + encode(attrs[key]) + '"';
  4133. }
  4134. }
  4135. if (isEmpty$3(html) && has$2(schema.getVoidElements(), name)) {
  4136. return outHtml + ' />';
  4137. } else {
  4138. return outHtml + '>' + html + '</' + name + '>';
  4139. }
  4140. };
  4141. const createFragment = html => {
  4142. let node;
  4143. const container = doc.createElement('div');
  4144. const frag = doc.createDocumentFragment();
  4145. frag.appendChild(container);
  4146. if (html) {
  4147. container.innerHTML = html;
  4148. }
  4149. while (node = container.firstChild) {
  4150. frag.appendChild(node);
  4151. }
  4152. frag.removeChild(container);
  4153. return frag;
  4154. };
  4155. const remove = (node, keepChildren) => {
  4156. return run(node, n => {
  4157. const $node = SugarElement.fromDom(n);
  4158. if (keepChildren) {
  4159. each$g(children($node), child => {
  4160. if (isText$9(child) && child.dom.length === 0) {
  4161. remove$5(child);
  4162. } else {
  4163. before$3($node, child);
  4164. }
  4165. });
  4166. }
  4167. remove$5($node);
  4168. return $node.dom;
  4169. });
  4170. };
  4171. const removeAllAttribs = e => run(e, e => {
  4172. const attrs = e.attributes;
  4173. for (let i = attrs.length - 1; i >= 0; i--) {
  4174. e.removeAttributeNode(attrs.item(i));
  4175. }
  4176. });
  4177. const parseStyle = cssText => styles.parse(cssText);
  4178. const serializeStyle = (stylesArg, name) => styles.serialize(stylesArg, name);
  4179. const addStyle = cssText => {
  4180. let head, styleElm;
  4181. if (self !== DOMUtils.DOM && doc === document) {
  4182. if (addedStyles[cssText]) {
  4183. return;
  4184. }
  4185. addedStyles[cssText] = true;
  4186. }
  4187. styleElm = doc.getElementById('mceDefaultStyles');
  4188. if (!styleElm) {
  4189. styleElm = doc.createElement('style');
  4190. styleElm.id = 'mceDefaultStyles';
  4191. styleElm.type = 'text/css';
  4192. head = doc.getElementsByTagName('head')[0];
  4193. if (head.firstChild) {
  4194. head.insertBefore(styleElm, head.firstChild);
  4195. } else {
  4196. head.appendChild(styleElm);
  4197. }
  4198. }
  4199. if (styleElm.styleSheet) {
  4200. styleElm.styleSheet.cssText += cssText;
  4201. } else {
  4202. styleElm.appendChild(doc.createTextNode(cssText));
  4203. }
  4204. };
  4205. const loadCSS = urls => {
  4206. if (!urls) {
  4207. urls = '';
  4208. }
  4209. each$g(urls.split(','), url => {
  4210. files[url] = true;
  4211. styleSheetLoader.load(url).catch(noop);
  4212. });
  4213. };
  4214. const toggleClass = (elm, cls, state) => {
  4215. run(elm, e => {
  4216. if (isElement$6(e)) {
  4217. const $elm = SugarElement.fromDom(e);
  4218. const classes = cls.split(' ');
  4219. each$g(classes, c => {
  4220. if (isNonNullable(state)) {
  4221. const fn = state ? add$2 : remove$7;
  4222. fn($elm, c);
  4223. } else {
  4224. toggle$1($elm, c);
  4225. }
  4226. });
  4227. }
  4228. });
  4229. };
  4230. const addClass = (elm, cls) => {
  4231. toggleClass(elm, cls, true);
  4232. };
  4233. const removeClass = (elm, cls) => {
  4234. toggleClass(elm, cls, false);
  4235. };
  4236. const hasClass = (elm, cls) => {
  4237. const $elm = _get(elm);
  4238. const classes = cls.split(' ');
  4239. return forall(classes, c => has($elm, c));
  4240. };
  4241. const show = elm => {
  4242. run(elm, e => remove$6(SugarElement.fromDom(e), 'display'));
  4243. };
  4244. const hide = elm => {
  4245. run(elm, e => set$1(SugarElement.fromDom(e), 'display', 'none'));
  4246. };
  4247. const isHidden = elm => {
  4248. const $elm = _get(elm);
  4249. return is$2(getRaw$1($elm, 'display'), 'none');
  4250. };
  4251. const uniqueId = prefix => (!prefix ? 'mce_' : prefix) + counter++;
  4252. const getOuterHTML = elm => {
  4253. const $elm = _get(elm);
  4254. return isElement$6($elm.dom) ? $elm.dom.outerHTML : getOuter($elm);
  4255. };
  4256. const setOuterHTML = (elm, html) => {
  4257. run(elm, $elm => {
  4258. if (isElement$6($elm)) {
  4259. $elm.outerHTML = html;
  4260. }
  4261. });
  4262. };
  4263. const insertAfter = (node, reference) => {
  4264. const referenceNode = get(reference);
  4265. return run(node, node => {
  4266. const parent = referenceNode.parentNode;
  4267. const nextSibling = referenceNode.nextSibling;
  4268. if (nextSibling) {
  4269. parent.insertBefore(node, nextSibling);
  4270. } else {
  4271. parent.appendChild(node);
  4272. }
  4273. return node;
  4274. });
  4275. };
  4276. const replace = (newElm, oldElm, keepChildren) => run(oldElm, oldElm => {
  4277. if (isArray$1(oldElm)) {
  4278. newElm = newElm.cloneNode(true);
  4279. }
  4280. if (keepChildren) {
  4281. each$c(grep(oldElm.childNodes), node => {
  4282. newElm.appendChild(node);
  4283. });
  4284. }
  4285. return oldElm.parentNode.replaceChild(newElm, oldElm);
  4286. });
  4287. const rename = (elm, name) => {
  4288. let newElm;
  4289. if (elm.nodeName !== name.toUpperCase()) {
  4290. newElm = create(name);
  4291. each$c(getAttribs(elm), attrNode => {
  4292. setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
  4293. });
  4294. replace(newElm, elm, true);
  4295. }
  4296. return newElm || elm;
  4297. };
  4298. const findCommonAncestor = (a, b) => {
  4299. let ps = a, pe;
  4300. while (ps) {
  4301. pe = b;
  4302. while (pe && ps !== pe) {
  4303. pe = pe.parentNode;
  4304. }
  4305. if (ps === pe) {
  4306. break;
  4307. }
  4308. ps = ps.parentNode;
  4309. }
  4310. if (!ps && a.ownerDocument) {
  4311. return a.ownerDocument.documentElement;
  4312. }
  4313. return ps;
  4314. };
  4315. const isNonEmptyElement = node => {
  4316. if (isElement$6(node)) {
  4317. const isNamedAnchor = node.nodeName.toLowerCase() === 'a' && !getAttrib(node, 'href') && getAttrib(node, 'id');
  4318. if (getAttrib(node, 'name') || getAttrib(node, 'data-mce-bookmark') || isNamedAnchor) {
  4319. return true;
  4320. }
  4321. }
  4322. return false;
  4323. };
  4324. const isEmpty = (node, elements) => {
  4325. let type, name, brCount = 0;
  4326. if (isNonEmptyElement(node)) {
  4327. return false;
  4328. }
  4329. node = node.firstChild;
  4330. if (node) {
  4331. const walker = new DomTreeWalker(node, node.parentNode);
  4332. const whitespace = schema ? schema.getWhitespaceElements() : {};
  4333. elements = elements || (schema ? schema.getNonEmptyElements() : null);
  4334. do {
  4335. type = node.nodeType;
  4336. if (isElement$6(node)) {
  4337. const bogusVal = node.getAttribute('data-mce-bogus');
  4338. if (bogusVal) {
  4339. node = walker.next(bogusVal === 'all');
  4340. continue;
  4341. }
  4342. name = node.nodeName.toLowerCase();
  4343. if (elements && elements[name]) {
  4344. if (name === 'br') {
  4345. brCount++;
  4346. node = walker.next();
  4347. continue;
  4348. }
  4349. return false;
  4350. }
  4351. if (isNonEmptyElement(node)) {
  4352. return false;
  4353. }
  4354. }
  4355. if (type === 8) {
  4356. return false;
  4357. }
  4358. if (type === 3 && !isWhitespaceText(node.nodeValue)) {
  4359. return false;
  4360. }
  4361. if (type === 3 && node.parentNode && whitespace[node.parentNode.nodeName] && isWhitespaceText(node.nodeValue)) {
  4362. return false;
  4363. }
  4364. node = walker.next();
  4365. } while (node);
  4366. }
  4367. return brCount <= 1;
  4368. };
  4369. const createRng = () => doc.createRange();
  4370. const split = (parentElm, splitElm, replacementElm) => {
  4371. let range = createRng();
  4372. let beforeFragment;
  4373. let afterFragment;
  4374. let parentNode;
  4375. if (parentElm && splitElm) {
  4376. range.setStart(parentElm.parentNode, findNodeIndex(parentElm));
  4377. range.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
  4378. beforeFragment = range.extractContents();
  4379. range = createRng();
  4380. range.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
  4381. range.setEnd(parentElm.parentNode, findNodeIndex(parentElm) + 1);
  4382. afterFragment = range.extractContents();
  4383. parentNode = parentElm.parentNode;
  4384. parentNode.insertBefore(trimNode(self, beforeFragment), parentElm);
  4385. if (replacementElm) {
  4386. parentNode.insertBefore(replacementElm, parentElm);
  4387. } else {
  4388. parentNode.insertBefore(splitElm, parentElm);
  4389. }
  4390. parentNode.insertBefore(trimNode(self, afterFragment), parentElm);
  4391. remove(parentElm);
  4392. return replacementElm || splitElm;
  4393. }
  4394. };
  4395. const bind = (target, name, func, scope) => {
  4396. if (isArray$1(target)) {
  4397. let i = target.length;
  4398. const rv = [];
  4399. while (i--) {
  4400. rv[i] = bind(target[i], name, func, scope);
  4401. }
  4402. return rv;
  4403. } else {
  4404. if (settings.collect && (target === doc || target === win)) {
  4405. boundEvents.push([
  4406. target,
  4407. name,
  4408. func,
  4409. scope
  4410. ]);
  4411. }
  4412. return events.bind(target, name, func, scope || self);
  4413. }
  4414. };
  4415. const unbind = (target, name, func) => {
  4416. if (isArray$1(target)) {
  4417. let i = target.length;
  4418. const rv = [];
  4419. while (i--) {
  4420. rv[i] = unbind(target[i], name, func);
  4421. }
  4422. return rv;
  4423. } else {
  4424. if (boundEvents.length > 0 && (target === doc || target === win)) {
  4425. let i = boundEvents.length;
  4426. while (i--) {
  4427. const item = boundEvents[i];
  4428. if (target === item[0] && (!name || name === item[1]) && (!func || func === item[2])) {
  4429. events.unbind(item[0], item[1], item[2]);
  4430. }
  4431. }
  4432. }
  4433. return events.unbind(target, name, func);
  4434. }
  4435. };
  4436. const dispatch = (target, name, evt) => events.dispatch(target, name, evt);
  4437. const fire = (target, name, evt) => events.dispatch(target, name, evt);
  4438. const getContentEditable = node => {
  4439. if (node && isElement$6(node)) {
  4440. const contentEditable = node.getAttribute('data-mce-contenteditable');
  4441. if (contentEditable && contentEditable !== 'inherit') {
  4442. return contentEditable;
  4443. }
  4444. return node.contentEditable !== 'inherit' ? node.contentEditable : null;
  4445. } else {
  4446. return null;
  4447. }
  4448. };
  4449. const getContentEditableParent = node => {
  4450. const root = getRoot();
  4451. let state = null;
  4452. for (; node && node !== root; node = node.parentNode) {
  4453. state = getContentEditable(node);
  4454. if (state !== null) {
  4455. break;
  4456. }
  4457. }
  4458. return state;
  4459. };
  4460. const destroy = () => {
  4461. if (boundEvents.length > 0) {
  4462. let i = boundEvents.length;
  4463. while (i--) {
  4464. const item = boundEvents[i];
  4465. events.unbind(item[0], item[1], item[2]);
  4466. }
  4467. }
  4468. each$f(files, (_, url) => {
  4469. styleSheetLoader.unload(url);
  4470. delete files[url];
  4471. });
  4472. };
  4473. const isChildOf = (node, parent) => {
  4474. return node === parent || parent.contains(node);
  4475. };
  4476. const dumpRng = r => 'startContainer: ' + r.startContainer.nodeName + ', startOffset: ' + r.startOffset + ', endContainer: ' + r.endContainer.nodeName + ', endOffset: ' + r.endOffset;
  4477. const self = {
  4478. doc,
  4479. settings,
  4480. win,
  4481. files,
  4482. stdMode,
  4483. boxModel,
  4484. styleSheetLoader,
  4485. boundEvents,
  4486. styles,
  4487. schema,
  4488. events,
  4489. isBlock,
  4490. root: null,
  4491. clone,
  4492. getRoot,
  4493. getViewPort,
  4494. getRect,
  4495. getSize,
  4496. getParent,
  4497. getParents,
  4498. get,
  4499. getNext,
  4500. getPrev,
  4501. select,
  4502. is,
  4503. add,
  4504. create,
  4505. createHTML,
  4506. createFragment,
  4507. remove,
  4508. setStyle,
  4509. getStyle,
  4510. setStyles,
  4511. removeAllAttribs,
  4512. setAttrib,
  4513. setAttribs,
  4514. getAttrib,
  4515. getPos: getPos$1,
  4516. parseStyle,
  4517. serializeStyle,
  4518. addStyle,
  4519. loadCSS,
  4520. addClass,
  4521. removeClass,
  4522. hasClass,
  4523. toggleClass,
  4524. show,
  4525. hide,
  4526. isHidden,
  4527. uniqueId,
  4528. setHTML,
  4529. getOuterHTML,
  4530. setOuterHTML,
  4531. decode,
  4532. encode,
  4533. insertAfter,
  4534. replace,
  4535. rename,
  4536. findCommonAncestor,
  4537. run,
  4538. getAttribs,
  4539. isEmpty,
  4540. createRng,
  4541. nodeIndex: findNodeIndex,
  4542. split,
  4543. bind: bind,
  4544. unbind: unbind,
  4545. fire,
  4546. dispatch,
  4547. getContentEditable,
  4548. getContentEditableParent,
  4549. destroy,
  4550. isChildOf,
  4551. dumpRng
  4552. };
  4553. const attrHooks = setupAttrHooks(styles, settings, constant(self));
  4554. return self;
  4555. };
  4556. DOMUtils.DOM = DOMUtils(document);
  4557. DOMUtils.nodeIndex = findNodeIndex;
  4558. const DOM$b = DOMUtils.DOM;
  4559. const QUEUED = 0;
  4560. const LOADING = 1;
  4561. const LOADED = 2;
  4562. const FAILED = 3;
  4563. class ScriptLoader {
  4564. constructor(settings = {}) {
  4565. this.states = {};
  4566. this.queue = [];
  4567. this.scriptLoadedCallbacks = {};
  4568. this.queueLoadedCallbacks = [];
  4569. this.loading = false;
  4570. this.settings = settings;
  4571. }
  4572. _setReferrerPolicy(referrerPolicy) {
  4573. this.settings.referrerPolicy = referrerPolicy;
  4574. }
  4575. loadScript(url) {
  4576. return new Promise((resolve, reject) => {
  4577. const dom = DOM$b;
  4578. let elm;
  4579. const cleanup = () => {
  4580. dom.remove(id);
  4581. if (elm) {
  4582. elm.onerror = elm.onload = elm = null;
  4583. }
  4584. };
  4585. const done = () => {
  4586. cleanup();
  4587. resolve();
  4588. };
  4589. const error = () => {
  4590. cleanup();
  4591. reject('Failed to load script: ' + url);
  4592. };
  4593. const id = dom.uniqueId();
  4594. elm = document.createElement('script');
  4595. elm.id = id;
  4596. elm.type = 'text/javascript';
  4597. elm.src = Tools._addCacheSuffix(url);
  4598. if (this.settings.referrerPolicy) {
  4599. dom.setAttrib(elm, 'referrerpolicy', this.settings.referrerPolicy);
  4600. }
  4601. elm.onload = done;
  4602. elm.onerror = error;
  4603. (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
  4604. });
  4605. }
  4606. isDone(url) {
  4607. return this.states[url] === LOADED;
  4608. }
  4609. markDone(url) {
  4610. this.states[url] = LOADED;
  4611. }
  4612. add(url) {
  4613. const self = this;
  4614. self.queue.push(url);
  4615. const state = self.states[url];
  4616. if (state === undefined) {
  4617. self.states[url] = QUEUED;
  4618. }
  4619. return new Promise((resolve, reject) => {
  4620. if (!self.scriptLoadedCallbacks[url]) {
  4621. self.scriptLoadedCallbacks[url] = [];
  4622. }
  4623. self.scriptLoadedCallbacks[url].push({
  4624. resolve,
  4625. reject
  4626. });
  4627. });
  4628. }
  4629. load(url) {
  4630. return this.add(url);
  4631. }
  4632. remove(url) {
  4633. delete this.states[url];
  4634. delete this.scriptLoadedCallbacks[url];
  4635. }
  4636. loadQueue() {
  4637. const queue = this.queue;
  4638. this.queue = [];
  4639. return this.loadScripts(queue);
  4640. }
  4641. loadScripts(scripts) {
  4642. const self = this;
  4643. const execCallbacks = (name, url) => {
  4644. get$a(self.scriptLoadedCallbacks, url).each(callbacks => {
  4645. each$g(callbacks, callback => callback[name](url));
  4646. });
  4647. delete self.scriptLoadedCallbacks[url];
  4648. };
  4649. const processResults = results => {
  4650. const failures = filter$6(results, result => result.status === 'rejected');
  4651. if (failures.length > 0) {
  4652. return Promise.reject(bind$3(failures, ({reason}) => isArray$1(reason) ? reason : [reason]));
  4653. } else {
  4654. return Promise.resolve();
  4655. }
  4656. };
  4657. const load = urls => Promise.allSettled(map$3(urls, url => {
  4658. if (self.states[url] === LOADED) {
  4659. execCallbacks('resolve', url);
  4660. return Promise.resolve();
  4661. } else if (self.states[url] === FAILED) {
  4662. execCallbacks('reject', url);
  4663. return Promise.reject(url);
  4664. } else {
  4665. self.states[url] = LOADING;
  4666. return self.loadScript(url).then(() => {
  4667. self.states[url] = LOADED;
  4668. execCallbacks('resolve', url);
  4669. const queue = self.queue;
  4670. if (queue.length > 0) {
  4671. self.queue = [];
  4672. return load(queue).then(processResults);
  4673. }
  4674. }, () => {
  4675. self.states[url] = FAILED;
  4676. execCallbacks('reject', url);
  4677. return Promise.reject(url);
  4678. });
  4679. }
  4680. }));
  4681. const processQueue = urls => {
  4682. self.loading = true;
  4683. return load(urls).then(results => {
  4684. self.loading = false;
  4685. const nextQueuedItem = self.queueLoadedCallbacks.shift();
  4686. Optional.from(nextQueuedItem).each(call);
  4687. return processResults(results);
  4688. });
  4689. };
  4690. const uniqueScripts = stringArray(scripts);
  4691. if (self.loading) {
  4692. return new Promise((resolve, reject) => {
  4693. self.queueLoadedCallbacks.push(() => processQueue(uniqueScripts).then(resolve, reject));
  4694. });
  4695. } else {
  4696. return processQueue(uniqueScripts);
  4697. }
  4698. }
  4699. }
  4700. ScriptLoader.ScriptLoader = new ScriptLoader();
  4701. const Cell = initial => {
  4702. let value = initial;
  4703. const get = () => {
  4704. return value;
  4705. };
  4706. const set = v => {
  4707. value = v;
  4708. };
  4709. return {
  4710. get,
  4711. set
  4712. };
  4713. };
  4714. const isRaw = str => isObject(str) && has$2(str, 'raw');
  4715. const isTokenised = str => isArray$1(str) && str.length > 1;
  4716. const data = {};
  4717. const currentCode = Cell('en');
  4718. const getLanguageData = () => get$a(data, currentCode.get());
  4719. const getData$1 = () => map$2(data, value => ({ ...value }));
  4720. const setCode = newCode => {
  4721. if (newCode) {
  4722. currentCode.set(newCode);
  4723. }
  4724. };
  4725. const getCode = () => currentCode.get();
  4726. const add$1 = (code, items) => {
  4727. let langData = data[code];
  4728. if (!langData) {
  4729. data[code] = langData = {};
  4730. }
  4731. each$f(items, (translation, name) => {
  4732. langData[name.toLowerCase()] = translation;
  4733. });
  4734. };
  4735. const translate = text => {
  4736. const langData = getLanguageData().getOr({});
  4737. const toString = obj => {
  4738. if (isFunction(obj)) {
  4739. return Object.prototype.toString.call(obj);
  4740. }
  4741. return !isEmpty(obj) ? '' + obj : '';
  4742. };
  4743. const isEmpty = text => text === '' || text === null || text === undefined;
  4744. const getLangData = text => {
  4745. const textstr = toString(text);
  4746. return get$a(langData, textstr.toLowerCase()).map(toString).getOr(textstr);
  4747. };
  4748. const removeContext = str => str.replace(/{context:\w+}$/, '');
  4749. if (isEmpty(text)) {
  4750. return '';
  4751. }
  4752. if (isRaw(text)) {
  4753. return toString(text.raw);
  4754. }
  4755. if (isTokenised(text)) {
  4756. const values = text.slice(1);
  4757. const substitued = getLangData(text[0]).replace(/\{([0-9]+)\}/g, ($1, $2) => has$2(values, $2) ? toString(values[$2]) : $1);
  4758. return removeContext(substitued);
  4759. }
  4760. return removeContext(getLangData(text));
  4761. };
  4762. const isRtl$1 = () => getLanguageData().bind(items => get$a(items, '_dir')).exists(dir => dir === 'rtl');
  4763. const hasCode = code => has$2(data, code);
  4764. const I18n = {
  4765. getData: getData$1,
  4766. setCode,
  4767. getCode,
  4768. add: add$1,
  4769. translate,
  4770. isRtl: isRtl$1,
  4771. hasCode
  4772. };
  4773. const AddOnManager = () => {
  4774. const items = [];
  4775. const urls = {};
  4776. const lookup = {};
  4777. const _listeners = [];
  4778. const runListeners = (name, state) => {
  4779. const matchedListeners = filter$6(_listeners, listener => listener.name === name && listener.state === state);
  4780. each$g(matchedListeners, listener => listener.resolve());
  4781. };
  4782. const isLoaded = name => has$2(urls, name);
  4783. const isAdded = name => has$2(lookup, name);
  4784. const get = name => {
  4785. if (lookup[name]) {
  4786. return lookup[name].instance;
  4787. }
  4788. return undefined;
  4789. };
  4790. const loadLanguagePack = (name, languages) => {
  4791. const language = I18n.getCode();
  4792. const wrappedLanguages = ',' + (languages || '') + ',';
  4793. if (!language || languages && wrappedLanguages.indexOf(',' + language + ',') === -1) {
  4794. return;
  4795. }
  4796. ScriptLoader.ScriptLoader.add(urls[name] + '/langs/' + language + '.js');
  4797. };
  4798. const requireLangPack = (name, languages) => {
  4799. if (AddOnManager.languageLoad !== false) {
  4800. if (isLoaded(name)) {
  4801. loadLanguagePack(name, languages);
  4802. } else {
  4803. waitFor(name, 'loaded').then(() => loadLanguagePack(name, languages));
  4804. }
  4805. }
  4806. };
  4807. const add = (id, addOn) => {
  4808. items.push(addOn);
  4809. lookup[id] = { instance: addOn };
  4810. runListeners(id, 'added');
  4811. return addOn;
  4812. };
  4813. const remove = name => {
  4814. delete urls[name];
  4815. delete lookup[name];
  4816. };
  4817. const createUrl = (baseUrl, dep) => {
  4818. if (isString(dep)) {
  4819. return isString(baseUrl) ? {
  4820. prefix: '',
  4821. resource: dep,
  4822. suffix: ''
  4823. } : {
  4824. prefix: baseUrl.prefix,
  4825. resource: dep,
  4826. suffix: baseUrl.suffix
  4827. };
  4828. } else {
  4829. return dep;
  4830. }
  4831. };
  4832. const load = (name, addOnUrl) => {
  4833. if (urls[name]) {
  4834. return Promise.resolve();
  4835. }
  4836. let urlString = isString(addOnUrl) ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
  4837. if (urlString.indexOf('/') !== 0 && urlString.indexOf('://') === -1) {
  4838. urlString = AddOnManager.baseURL + '/' + urlString;
  4839. }
  4840. urls[name] = urlString.substring(0, urlString.lastIndexOf('/'));
  4841. const done = () => {
  4842. runListeners(name, 'loaded');
  4843. return Promise.resolve();
  4844. };
  4845. if (lookup[name]) {
  4846. return done();
  4847. } else {
  4848. return ScriptLoader.ScriptLoader.add(urlString).then(done);
  4849. }
  4850. };
  4851. const waitFor = (name, state = 'added') => {
  4852. if (state === 'added' && isAdded(name)) {
  4853. return Promise.resolve();
  4854. } else if (state === 'loaded' && isLoaded(name)) {
  4855. return Promise.resolve();
  4856. } else {
  4857. return new Promise(resolve => {
  4858. _listeners.push({
  4859. name,
  4860. state,
  4861. resolve
  4862. });
  4863. });
  4864. }
  4865. };
  4866. return {
  4867. items,
  4868. urls,
  4869. lookup,
  4870. get,
  4871. requireLangPack,
  4872. add,
  4873. remove,
  4874. createUrl,
  4875. load,
  4876. waitFor
  4877. };
  4878. };
  4879. AddOnManager.languageLoad = true;
  4880. AddOnManager.baseURL = '';
  4881. AddOnManager.PluginManager = AddOnManager();
  4882. AddOnManager.ThemeManager = AddOnManager();
  4883. AddOnManager.ModelManager = AddOnManager();
  4884. const singleton = doRevoke => {
  4885. const subject = Cell(Optional.none());
  4886. const revoke = () => subject.get().each(doRevoke);
  4887. const clear = () => {
  4888. revoke();
  4889. subject.set(Optional.none());
  4890. };
  4891. const isSet = () => subject.get().isSome();
  4892. const get = () => subject.get();
  4893. const set = s => {
  4894. revoke();
  4895. subject.set(Optional.some(s));
  4896. };
  4897. return {
  4898. clear,
  4899. isSet,
  4900. get,
  4901. set
  4902. };
  4903. };
  4904. const value$2 = () => {
  4905. const subject = singleton(noop);
  4906. const on = f => subject.get().each(f);
  4907. return {
  4908. ...subject,
  4909. on
  4910. };
  4911. };
  4912. const first$1 = (fn, rate) => {
  4913. let timer = null;
  4914. const cancel = () => {
  4915. if (!isNull(timer)) {
  4916. clearTimeout(timer);
  4917. timer = null;
  4918. }
  4919. };
  4920. const throttle = (...args) => {
  4921. if (isNull(timer)) {
  4922. timer = setTimeout(() => {
  4923. timer = null;
  4924. fn.apply(null, args);
  4925. }, rate);
  4926. }
  4927. };
  4928. return {
  4929. cancel,
  4930. throttle
  4931. };
  4932. };
  4933. const last$1 = (fn, rate) => {
  4934. let timer = null;
  4935. const cancel = () => {
  4936. if (!isNull(timer)) {
  4937. clearTimeout(timer);
  4938. timer = null;
  4939. }
  4940. };
  4941. const throttle = (...args) => {
  4942. cancel();
  4943. timer = setTimeout(() => {
  4944. timer = null;
  4945. fn.apply(null, args);
  4946. }, rate);
  4947. };
  4948. return {
  4949. cancel,
  4950. throttle
  4951. };
  4952. };
  4953. const descendants$1 = (scope, predicate) => {
  4954. let result = [];
  4955. each$g(children(scope), x => {
  4956. if (predicate(x)) {
  4957. result = result.concat([x]);
  4958. }
  4959. result = result.concat(descendants$1(x, predicate));
  4960. });
  4961. return result;
  4962. };
  4963. const descendants = (scope, selector) => all(selector, scope);
  4964. const annotation = constant('mce-annotation');
  4965. const dataAnnotation = constant('data-mce-annotation');
  4966. const dataAnnotationId = constant('data-mce-annotation-uid');
  4967. const dataAnnotationActive = constant('data-mce-annotation-active');
  4968. const identify = (editor, annotationName) => {
  4969. const rng = editor.selection.getRng();
  4970. const start = SugarElement.fromDom(rng.startContainer);
  4971. const root = SugarElement.fromDom(editor.getBody());
  4972. const selector = annotationName.fold(() => '.' + annotation(), an => `[${ dataAnnotation() }="${ an }"]`);
  4973. const newStart = child$1(start, rng.startOffset).getOr(start);
  4974. const closest = closest$3(newStart, selector, n => eq(n, root));
  4975. const getAttr = (c, property) => {
  4976. if (has$1(c, property)) {
  4977. return Optional.some(get$9(c, property));
  4978. } else {
  4979. return Optional.none();
  4980. }
  4981. };
  4982. return closest.bind(c => getAttr(c, `${ dataAnnotationId() }`).bind(uid => getAttr(c, `${ dataAnnotation() }`).map(name => {
  4983. const elements = findMarkers(editor, uid);
  4984. return {
  4985. uid,
  4986. name,
  4987. elements
  4988. };
  4989. })));
  4990. };
  4991. const isAnnotation = elem => isElement$7(elem) && has(elem, annotation());
  4992. const findMarkers = (editor, uid) => {
  4993. const body = SugarElement.fromDom(editor.getBody());
  4994. return descendants(body, `[${ dataAnnotationId() }="${ uid }"]`);
  4995. };
  4996. const findAll = (editor, name) => {
  4997. const body = SugarElement.fromDom(editor.getBody());
  4998. const markers = descendants(body, `[${ dataAnnotation() }="${ name }"]`);
  4999. const directory = {};
  5000. each$g(markers, m => {
  5001. const uid = get$9(m, dataAnnotationId());
  5002. const nodesAlready = get$a(directory, uid).getOr([]);
  5003. directory[uid] = nodesAlready.concat([m]);
  5004. });
  5005. return directory;
  5006. };
  5007. const setup$x = (editor, registry) => {
  5008. const changeCallbacks = Cell({});
  5009. const initData = () => ({
  5010. listeners: [],
  5011. previous: value$2()
  5012. });
  5013. const withCallbacks = (name, f) => {
  5014. updateCallbacks(name, data => {
  5015. f(data);
  5016. return data;
  5017. });
  5018. };
  5019. const updateCallbacks = (name, f) => {
  5020. const callbackMap = changeCallbacks.get();
  5021. const data = get$a(callbackMap, name).getOrThunk(initData);
  5022. const outputData = f(data);
  5023. callbackMap[name] = outputData;
  5024. changeCallbacks.set(callbackMap);
  5025. };
  5026. const fireCallbacks = (name, uid, elements) => {
  5027. withCallbacks(name, data => {
  5028. each$g(data.listeners, f => f(true, name, {
  5029. uid,
  5030. nodes: map$3(elements, elem => elem.dom)
  5031. }));
  5032. });
  5033. };
  5034. const fireNoAnnotation = name => {
  5035. withCallbacks(name, data => {
  5036. each$g(data.listeners, f => f(false, name));
  5037. });
  5038. };
  5039. const toggleActiveAttr = (uid, state) => {
  5040. each$g(findMarkers(editor, uid), span => {
  5041. if (state) {
  5042. set$2(span, dataAnnotationActive(), 'true');
  5043. } else {
  5044. remove$a(span, dataAnnotationActive());
  5045. }
  5046. });
  5047. };
  5048. const onNodeChange = last$1(() => {
  5049. const annotations = sort(registry.getNames());
  5050. each$g(annotations, name => {
  5051. updateCallbacks(name, data => {
  5052. const prev = data.previous.get();
  5053. identify(editor, Optional.some(name)).fold(() => {
  5054. prev.each(uid => {
  5055. fireNoAnnotation(name);
  5056. data.previous.clear();
  5057. toggleActiveAttr(uid, false);
  5058. });
  5059. }, ({uid, name, elements}) => {
  5060. if (!is$2(prev, uid)) {
  5061. prev.each(uid => toggleActiveAttr(uid, false));
  5062. fireCallbacks(name, uid, elements);
  5063. data.previous.set(uid);
  5064. toggleActiveAttr(uid, true);
  5065. }
  5066. });
  5067. return {
  5068. previous: data.previous,
  5069. listeners: data.listeners
  5070. };
  5071. });
  5072. });
  5073. }, 30);
  5074. editor.on('remove', () => {
  5075. onNodeChange.cancel();
  5076. });
  5077. editor.on('NodeChange', () => {
  5078. onNodeChange.throttle();
  5079. });
  5080. const addListener = (name, f) => {
  5081. updateCallbacks(name, data => ({
  5082. previous: data.previous,
  5083. listeners: data.listeners.concat([f])
  5084. }));
  5085. };
  5086. return { addListener };
  5087. };
  5088. const setup$w = (editor, registry) => {
  5089. const identifyParserNode = span => Optional.from(span.attr(dataAnnotation())).bind(registry.lookup);
  5090. editor.serializer.addTempAttr(dataAnnotationActive());
  5091. editor.serializer.addNodeFilter('span', spans => {
  5092. each$g(spans, span => {
  5093. identifyParserNode(span).each(settings => {
  5094. if (settings.persistent === false) {
  5095. span.unwrap();
  5096. }
  5097. });
  5098. });
  5099. });
  5100. };
  5101. const create$b = () => {
  5102. const annotations = {};
  5103. const register = (name, settings) => {
  5104. annotations[name] = {
  5105. name,
  5106. settings
  5107. };
  5108. };
  5109. const lookup = name => get$a(annotations, name).map(a => a.settings);
  5110. const getNames = () => keys(annotations);
  5111. return {
  5112. register,
  5113. lookup,
  5114. getNames
  5115. };
  5116. };
  5117. let unique = 0;
  5118. const generate$1 = prefix => {
  5119. const date = new Date();
  5120. const time = date.getTime();
  5121. const random = Math.floor(Math.random() * 1000000000);
  5122. unique++;
  5123. return prefix + '_' + random + unique + String(time);
  5124. };
  5125. const add = (element, classes) => {
  5126. each$g(classes, x => {
  5127. add$2(element, x);
  5128. });
  5129. };
  5130. const clone$2 = (original, isDeep) => SugarElement.fromDom(original.dom.cloneNode(isDeep));
  5131. const shallow$1 = original => clone$2(original, false);
  5132. const deep$1 = original => clone$2(original, true);
  5133. const shallowAs = (original, tag) => {
  5134. const nu = SugarElement.fromTag(tag);
  5135. const attributes = clone$4(original);
  5136. setAll$1(nu, attributes);
  5137. return nu;
  5138. };
  5139. const mutate = (original, tag) => {
  5140. const nu = shallowAs(original, tag);
  5141. after$4(original, nu);
  5142. const children$1 = children(original);
  5143. append(nu, children$1);
  5144. remove$5(original);
  5145. return nu;
  5146. };
  5147. const TextWalker = (startNode, rootNode, isBoundary = never) => {
  5148. const walker = new DomTreeWalker(startNode, rootNode);
  5149. const walk = direction => {
  5150. let next;
  5151. do {
  5152. next = walker[direction]();
  5153. } while (next && !isText$8(next) && !isBoundary(next));
  5154. return Optional.from(next).filter(isText$8);
  5155. };
  5156. return {
  5157. current: () => Optional.from(walker.current()).filter(isText$8),
  5158. next: () => walk('next'),
  5159. prev: () => walk('prev'),
  5160. prev2: () => walk('prev2')
  5161. };
  5162. };
  5163. const TextSeeker = (dom, isBoundary) => {
  5164. const isBlockBoundary = isBoundary ? isBoundary : node => dom.isBlock(node) || isBr$5(node) || isContentEditableFalse$a(node);
  5165. const walk = (node, offset, walker, process) => {
  5166. if (isText$8(node)) {
  5167. const newOffset = process(node, offset, node.data);
  5168. if (newOffset !== -1) {
  5169. return Optional.some({
  5170. container: node,
  5171. offset: newOffset
  5172. });
  5173. }
  5174. }
  5175. return walker().bind(next => walk(next.container, next.offset, walker, process));
  5176. };
  5177. const backwards = (node, offset, process, root) => {
  5178. const walker = TextWalker(node, root, isBlockBoundary);
  5179. return walk(node, offset, () => walker.prev().map(prev => ({
  5180. container: prev,
  5181. offset: prev.length
  5182. })), process).getOrNull();
  5183. };
  5184. const forwards = (node, offset, process, root) => {
  5185. const walker = TextWalker(node, root, isBlockBoundary);
  5186. return walk(node, offset, () => walker.next().map(next => ({
  5187. container: next,
  5188. offset: 0
  5189. })), process).getOrNull();
  5190. };
  5191. return {
  5192. backwards,
  5193. forwards
  5194. };
  5195. };
  5196. const round$1 = Math.round;
  5197. const clone$1 = rect => {
  5198. if (!rect) {
  5199. return {
  5200. left: 0,
  5201. top: 0,
  5202. bottom: 0,
  5203. right: 0,
  5204. width: 0,
  5205. height: 0
  5206. };
  5207. }
  5208. return {
  5209. left: round$1(rect.left),
  5210. top: round$1(rect.top),
  5211. bottom: round$1(rect.bottom),
  5212. right: round$1(rect.right),
  5213. width: round$1(rect.width),
  5214. height: round$1(rect.height)
  5215. };
  5216. };
  5217. const collapse = (rect, toStart) => {
  5218. rect = clone$1(rect);
  5219. if (toStart) {
  5220. rect.right = rect.left;
  5221. } else {
  5222. rect.left = rect.left + rect.width;
  5223. rect.right = rect.left;
  5224. }
  5225. rect.width = 0;
  5226. return rect;
  5227. };
  5228. const isEqual = (rect1, rect2) => rect1.left === rect2.left && rect1.top === rect2.top && rect1.bottom === rect2.bottom && rect1.right === rect2.right;
  5229. const isValidOverflow = (overflowY, rect1, rect2) => overflowY >= 0 && overflowY <= Math.min(rect1.height, rect2.height) / 2;
  5230. const isAbove$1 = (rect1, rect2) => {
  5231. const halfHeight = Math.min(rect2.height / 2, rect1.height / 2);
  5232. if (rect1.bottom - halfHeight < rect2.top) {
  5233. return true;
  5234. }
  5235. if (rect1.top > rect2.bottom) {
  5236. return false;
  5237. }
  5238. return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
  5239. };
  5240. const isBelow$1 = (rect1, rect2) => {
  5241. if (rect1.top > rect2.bottom) {
  5242. return true;
  5243. }
  5244. if (rect1.bottom < rect2.top) {
  5245. return false;
  5246. }
  5247. return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
  5248. };
  5249. const containsXY = (rect, clientX, clientY) => clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
  5250. const boundingClientRectFromRects = rects => {
  5251. return foldl(rects, (acc, rect) => {
  5252. return acc.fold(() => Optional.some(rect), prevRect => {
  5253. const left = Math.min(rect.left, prevRect.left);
  5254. const top = Math.min(rect.top, prevRect.top);
  5255. const right = Math.max(rect.right, prevRect.right);
  5256. const bottom = Math.max(rect.bottom, prevRect.bottom);
  5257. return Optional.some({
  5258. top,
  5259. right,
  5260. bottom,
  5261. left,
  5262. width: right - left,
  5263. height: bottom - top
  5264. });
  5265. });
  5266. }, Optional.none());
  5267. };
  5268. const distanceToRectEdgeFromXY = (rect, x, y) => {
  5269. const cx = Math.max(Math.min(x, rect.left + rect.width), rect.left);
  5270. const cy = Math.max(Math.min(y, rect.top + rect.height), rect.top);
  5271. return Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy));
  5272. };
  5273. const overlapY = (r1, r2) => Math.max(0, Math.min(r1.bottom, r2.bottom) - Math.max(r1.top, r2.top));
  5274. const clamp$2 = (value, min, max) => Math.min(Math.max(value, min), max);
  5275. const getSelectedNode = range => {
  5276. const startContainer = range.startContainer, startOffset = range.startOffset;
  5277. if (startContainer.hasChildNodes() && range.endOffset === startOffset + 1) {
  5278. return startContainer.childNodes[startOffset];
  5279. }
  5280. return null;
  5281. };
  5282. const getNode$1 = (container, offset) => {
  5283. if (isElement$6(container) && container.hasChildNodes()) {
  5284. const childNodes = container.childNodes;
  5285. const safeOffset = clamp$2(offset, 0, childNodes.length - 1);
  5286. return childNodes[safeOffset];
  5287. } else {
  5288. return container;
  5289. }
  5290. };
  5291. const getNodeUnsafe = (container, offset) => {
  5292. if (offset < 0 && isElement$6(container) && container.hasChildNodes()) {
  5293. return undefined;
  5294. } else {
  5295. return getNode$1(container, offset);
  5296. }
  5297. };
  5298. const 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]');
  5299. const isExtendingChar = ch => typeof ch === 'string' && ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
  5300. const or = (...args) => {
  5301. return x => {
  5302. for (let i = 0; i < args.length; i++) {
  5303. if (args[i](x)) {
  5304. return true;
  5305. }
  5306. }
  5307. return false;
  5308. };
  5309. };
  5310. const and = (...args) => {
  5311. return x => {
  5312. for (let i = 0; i < args.length; i++) {
  5313. if (!args[i](x)) {
  5314. return false;
  5315. }
  5316. }
  5317. return true;
  5318. };
  5319. };
  5320. const isElement$4 = isElement$6;
  5321. const isCaretCandidate$2 = isCaretCandidate$3;
  5322. const isBlock$1 = matchStyleValues('display', 'block table');
  5323. const isFloated = matchStyleValues('float', 'left right');
  5324. const isValidElementCaretCandidate = and(isElement$4, isCaretCandidate$2, not(isFloated));
  5325. const isNotPre = not(matchStyleValues('white-space', 'pre pre-line pre-wrap'));
  5326. const isText$5 = isText$8;
  5327. const isBr$2 = isBr$5;
  5328. const nodeIndex$1 = DOMUtils.nodeIndex;
  5329. const resolveIndex$1 = getNodeUnsafe;
  5330. const createRange$1 = doc => 'createRange' in doc ? doc.createRange() : DOMUtils.DOM.createRng();
  5331. const isWhiteSpace$1 = chr => chr && /[\r\n\t ]/.test(chr);
  5332. const isRange = rng => !!rng.setStart && !!rng.setEnd;
  5333. const isHiddenWhiteSpaceRange = range => {
  5334. const container = range.startContainer;
  5335. const offset = range.startOffset;
  5336. if (isWhiteSpace$1(range.toString()) && isNotPre(container.parentNode) && isText$8(container)) {
  5337. const text = container.data;
  5338. if (isWhiteSpace$1(text[offset - 1]) || isWhiteSpace$1(text[offset + 1])) {
  5339. return true;
  5340. }
  5341. }
  5342. return false;
  5343. };
  5344. const getBrClientRect = brNode => {
  5345. const doc = brNode.ownerDocument;
  5346. const rng = createRange$1(doc);
  5347. const nbsp$1 = doc.createTextNode(nbsp);
  5348. const parentNode = brNode.parentNode;
  5349. parentNode.insertBefore(nbsp$1, brNode);
  5350. rng.setStart(nbsp$1, 0);
  5351. rng.setEnd(nbsp$1, 1);
  5352. const clientRect = clone$1(rng.getBoundingClientRect());
  5353. parentNode.removeChild(nbsp$1);
  5354. return clientRect;
  5355. };
  5356. const getBoundingClientRectWebKitText = rng => {
  5357. const sc = rng.startContainer;
  5358. const ec = rng.endContainer;
  5359. const so = rng.startOffset;
  5360. const eo = rng.endOffset;
  5361. if (sc === ec && isText$8(ec) && so === 0 && eo === 1) {
  5362. const newRng = rng.cloneRange();
  5363. newRng.setEndAfter(ec);
  5364. return getBoundingClientRect$1(newRng);
  5365. } else {
  5366. return null;
  5367. }
  5368. };
  5369. const isZeroRect = r => r.left === 0 && r.right === 0 && r.top === 0 && r.bottom === 0;
  5370. const getBoundingClientRect$1 = item => {
  5371. let clientRect;
  5372. const clientRects = item.getClientRects();
  5373. if (clientRects.length > 0) {
  5374. clientRect = clone$1(clientRects[0]);
  5375. } else {
  5376. clientRect = clone$1(item.getBoundingClientRect());
  5377. }
  5378. if (!isRange(item) && isBr$2(item) && isZeroRect(clientRect)) {
  5379. return getBrClientRect(item);
  5380. }
  5381. if (isZeroRect(clientRect) && isRange(item)) {
  5382. return getBoundingClientRectWebKitText(item);
  5383. }
  5384. return clientRect;
  5385. };
  5386. const collapseAndInflateWidth = (clientRect, toStart) => {
  5387. const newClientRect = collapse(clientRect, toStart);
  5388. newClientRect.width = 1;
  5389. newClientRect.right = newClientRect.left + 1;
  5390. return newClientRect;
  5391. };
  5392. const getCaretPositionClientRects = caretPosition => {
  5393. const clientRects = [];
  5394. const addUniqueAndValidRect = clientRect => {
  5395. if (clientRect.height === 0) {
  5396. return;
  5397. }
  5398. if (clientRects.length > 0) {
  5399. if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
  5400. return;
  5401. }
  5402. }
  5403. clientRects.push(clientRect);
  5404. };
  5405. const addCharacterOffset = (container, offset) => {
  5406. const range = createRange$1(container.ownerDocument);
  5407. if (offset < container.data.length) {
  5408. if (isExtendingChar(container.data[offset])) {
  5409. return clientRects;
  5410. }
  5411. if (isExtendingChar(container.data[offset - 1])) {
  5412. range.setStart(container, offset);
  5413. range.setEnd(container, offset + 1);
  5414. if (!isHiddenWhiteSpaceRange(range)) {
  5415. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  5416. return clientRects;
  5417. }
  5418. }
  5419. }
  5420. if (offset > 0) {
  5421. range.setStart(container, offset - 1);
  5422. range.setEnd(container, offset);
  5423. if (!isHiddenWhiteSpaceRange(range)) {
  5424. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  5425. }
  5426. }
  5427. if (offset < container.data.length) {
  5428. range.setStart(container, offset);
  5429. range.setEnd(container, offset + 1);
  5430. if (!isHiddenWhiteSpaceRange(range)) {
  5431. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), true));
  5432. }
  5433. }
  5434. };
  5435. const container = caretPosition.container();
  5436. const offset = caretPosition.offset();
  5437. if (isText$5(container)) {
  5438. addCharacterOffset(container, offset);
  5439. return clientRects;
  5440. }
  5441. if (isElement$4(container)) {
  5442. if (caretPosition.isAtEnd()) {
  5443. const node = resolveIndex$1(container, offset);
  5444. if (isText$5(node)) {
  5445. addCharacterOffset(node, node.data.length);
  5446. }
  5447. if (isValidElementCaretCandidate(node) && !isBr$2(node)) {
  5448. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  5449. }
  5450. } else {
  5451. const node = resolveIndex$1(container, offset);
  5452. if (isText$5(node)) {
  5453. addCharacterOffset(node, 0);
  5454. }
  5455. if (isValidElementCaretCandidate(node) && caretPosition.isAtEnd()) {
  5456. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  5457. return clientRects;
  5458. }
  5459. const beforeNode = resolveIndex$1(caretPosition.container(), caretPosition.offset() - 1);
  5460. if (isValidElementCaretCandidate(beforeNode) && !isBr$2(beforeNode)) {
  5461. if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
  5462. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(beforeNode), false));
  5463. }
  5464. }
  5465. if (isValidElementCaretCandidate(node)) {
  5466. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), true));
  5467. }
  5468. }
  5469. }
  5470. return clientRects;
  5471. };
  5472. const CaretPosition = (container, offset, clientRects) => {
  5473. const isAtStart = () => {
  5474. if (isText$5(container)) {
  5475. return offset === 0;
  5476. }
  5477. return offset === 0;
  5478. };
  5479. const isAtEnd = () => {
  5480. if (isText$5(container)) {
  5481. return offset >= container.data.length;
  5482. }
  5483. return offset >= container.childNodes.length;
  5484. };
  5485. const toRange = () => {
  5486. const range = createRange$1(container.ownerDocument);
  5487. range.setStart(container, offset);
  5488. range.setEnd(container, offset);
  5489. return range;
  5490. };
  5491. const getClientRects = () => {
  5492. if (!clientRects) {
  5493. clientRects = getCaretPositionClientRects(CaretPosition(container, offset));
  5494. }
  5495. return clientRects;
  5496. };
  5497. const isVisible = () => getClientRects().length > 0;
  5498. const isEqual = caretPosition => caretPosition && container === caretPosition.container() && offset === caretPosition.offset();
  5499. const getNode = before => resolveIndex$1(container, before ? offset - 1 : offset);
  5500. return {
  5501. container: constant(container),
  5502. offset: constant(offset),
  5503. toRange,
  5504. getClientRects,
  5505. isVisible,
  5506. isAtStart,
  5507. isAtEnd,
  5508. isEqual,
  5509. getNode
  5510. };
  5511. };
  5512. CaretPosition.fromRangeStart = range => CaretPosition(range.startContainer, range.startOffset);
  5513. CaretPosition.fromRangeEnd = range => CaretPosition(range.endContainer, range.endOffset);
  5514. CaretPosition.after = node => CaretPosition(node.parentNode, nodeIndex$1(node) + 1);
  5515. CaretPosition.before = node => CaretPosition(node.parentNode, nodeIndex$1(node));
  5516. CaretPosition.isAbove = (pos1, pos2) => lift2(head(pos2.getClientRects()), last$3(pos1.getClientRects()), isAbove$1).getOr(false);
  5517. CaretPosition.isBelow = (pos1, pos2) => lift2(last$3(pos2.getClientRects()), head(pos1.getClientRects()), isBelow$1).getOr(false);
  5518. CaretPosition.isAtStart = pos => pos ? pos.isAtStart() : false;
  5519. CaretPosition.isAtEnd = pos => pos ? pos.isAtEnd() : false;
  5520. CaretPosition.isTextPosition = pos => pos ? isText$8(pos.container()) : false;
  5521. CaretPosition.isElementPosition = pos => CaretPosition.isTextPosition(pos) === false;
  5522. const trimEmptyTextNode$1 = (dom, node) => {
  5523. if (isText$8(node) && node.data.length === 0) {
  5524. dom.remove(node);
  5525. }
  5526. };
  5527. const insertNode = (dom, rng, node) => {
  5528. rng.insertNode(node);
  5529. trimEmptyTextNode$1(dom, node.previousSibling);
  5530. trimEmptyTextNode$1(dom, node.nextSibling);
  5531. };
  5532. const insertFragment = (dom, rng, frag) => {
  5533. const firstChild = Optional.from(frag.firstChild);
  5534. const lastChild = Optional.from(frag.lastChild);
  5535. rng.insertNode(frag);
  5536. firstChild.each(child => trimEmptyTextNode$1(dom, child.previousSibling));
  5537. lastChild.each(child => trimEmptyTextNode$1(dom, child.nextSibling));
  5538. };
  5539. const rangeInsertNode = (dom, rng, node) => {
  5540. if (isDocumentFragment(node)) {
  5541. insertFragment(dom, rng, node);
  5542. } else {
  5543. insertNode(dom, rng, node);
  5544. }
  5545. };
  5546. const isText$4 = isText$8;
  5547. const isBogus = isBogus$2;
  5548. const nodeIndex = DOMUtils.nodeIndex;
  5549. const normalizedParent = node => {
  5550. const parentNode = node.parentNode;
  5551. if (isBogus(parentNode)) {
  5552. return normalizedParent(parentNode);
  5553. }
  5554. return parentNode;
  5555. };
  5556. const getChildNodes = node => {
  5557. if (!node) {
  5558. return [];
  5559. }
  5560. return reduce(node.childNodes, (result, node) => {
  5561. if (isBogus(node) && node.nodeName !== 'BR') {
  5562. result = result.concat(getChildNodes(node));
  5563. } else {
  5564. result.push(node);
  5565. }
  5566. return result;
  5567. }, []);
  5568. };
  5569. const normalizedTextOffset = (node, offset) => {
  5570. while (node = node.previousSibling) {
  5571. if (!isText$4(node)) {
  5572. break;
  5573. }
  5574. offset += node.data.length;
  5575. }
  5576. return offset;
  5577. };
  5578. const equal = a => b => a === b;
  5579. const normalizedNodeIndex = node => {
  5580. let nodes, index;
  5581. nodes = getChildNodes(normalizedParent(node));
  5582. index = findIndex$1(nodes, equal(node), node);
  5583. nodes = nodes.slice(0, index + 1);
  5584. const numTextFragments = reduce(nodes, (result, node, i) => {
  5585. if (isText$4(node) && isText$4(nodes[i - 1])) {
  5586. result++;
  5587. }
  5588. return result;
  5589. }, 0);
  5590. nodes = filter$4(nodes, matchNodeNames([node.nodeName]));
  5591. index = findIndex$1(nodes, equal(node), node);
  5592. return index - numTextFragments;
  5593. };
  5594. const createPathItem = node => {
  5595. let name;
  5596. if (isText$4(node)) {
  5597. name = 'text()';
  5598. } else {
  5599. name = node.nodeName.toLowerCase();
  5600. }
  5601. return name + '[' + normalizedNodeIndex(node) + ']';
  5602. };
  5603. const parentsUntil$1 = (root, node, predicate) => {
  5604. const parents = [];
  5605. for (node = node.parentNode; node !== root; node = node.parentNode) {
  5606. if (predicate && predicate(node)) {
  5607. break;
  5608. }
  5609. parents.push(node);
  5610. }
  5611. return parents;
  5612. };
  5613. const create$a = (root, caretPosition) => {
  5614. let container, offset, path = [], outputOffset, childNodes, parents;
  5615. container = caretPosition.container();
  5616. offset = caretPosition.offset();
  5617. if (isText$4(container)) {
  5618. outputOffset = normalizedTextOffset(container, offset);
  5619. } else {
  5620. childNodes = container.childNodes;
  5621. if (offset >= childNodes.length) {
  5622. outputOffset = 'after';
  5623. offset = childNodes.length - 1;
  5624. } else {
  5625. outputOffset = 'before';
  5626. }
  5627. container = childNodes[offset];
  5628. }
  5629. path.push(createPathItem(container));
  5630. parents = parentsUntil$1(root, container);
  5631. parents = filter$4(parents, not(isBogus$2));
  5632. path = path.concat(map$1(parents, node => {
  5633. return createPathItem(node);
  5634. }));
  5635. return path.reverse().join('/') + ',' + outputOffset;
  5636. };
  5637. const resolvePathItem = (node, name, index) => {
  5638. let nodes = getChildNodes(node);
  5639. nodes = filter$4(nodes, (node, index) => {
  5640. return !isText$4(node) || !isText$4(nodes[index - 1]);
  5641. });
  5642. nodes = filter$4(nodes, matchNodeNames([name]));
  5643. return nodes[index];
  5644. };
  5645. const findTextPosition = (container, offset) => {
  5646. let node = container, targetOffset = 0, dataLen;
  5647. while (isText$4(node)) {
  5648. dataLen = node.data.length;
  5649. if (offset >= targetOffset && offset <= targetOffset + dataLen) {
  5650. container = node;
  5651. offset = offset - targetOffset;
  5652. break;
  5653. }
  5654. if (!isText$4(node.nextSibling)) {
  5655. container = node;
  5656. offset = dataLen;
  5657. break;
  5658. }
  5659. targetOffset += dataLen;
  5660. node = node.nextSibling;
  5661. }
  5662. if (isText$4(container) && offset > container.data.length) {
  5663. offset = container.data.length;
  5664. }
  5665. return CaretPosition(container, offset);
  5666. };
  5667. const resolve$1 = (root, path) => {
  5668. let offset;
  5669. if (!path) {
  5670. return null;
  5671. }
  5672. const parts = path.split(',');
  5673. const paths = parts[0].split('/');
  5674. offset = parts.length > 1 ? parts[1] : 'before';
  5675. const container = reduce(paths, (result, value) => {
  5676. const match = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value);
  5677. if (!match) {
  5678. return null;
  5679. }
  5680. if (match[1] === 'text()') {
  5681. match[1] = '#text';
  5682. }
  5683. return resolvePathItem(result, match[1], parseInt(match[2], 10));
  5684. }, root);
  5685. if (!container) {
  5686. return null;
  5687. }
  5688. if (!isText$4(container)) {
  5689. if (offset === 'after') {
  5690. offset = nodeIndex(container) + 1;
  5691. } else {
  5692. offset = nodeIndex(container);
  5693. }
  5694. return CaretPosition(container.parentNode, offset);
  5695. }
  5696. return findTextPosition(container, parseInt(offset, 10));
  5697. };
  5698. const isContentEditableFalse$8 = isContentEditableFalse$a;
  5699. const getNormalizedTextOffset = (trim, container, offset) => {
  5700. let node, trimmedOffset;
  5701. trimmedOffset = trim(container.data.slice(0, offset)).length;
  5702. for (node = container.previousSibling; node && isText$8(node); node = node.previousSibling) {
  5703. trimmedOffset += trim(node.data).length;
  5704. }
  5705. return trimmedOffset;
  5706. };
  5707. const getPoint = (dom, trim, normalized, rng, start) => {
  5708. let container = rng[start ? 'startContainer' : 'endContainer'];
  5709. let offset = rng[start ? 'startOffset' : 'endOffset'];
  5710. const point = [];
  5711. let childNodes, after = 0;
  5712. const root = dom.getRoot();
  5713. if (isText$8(container)) {
  5714. point.push(normalized ? getNormalizedTextOffset(trim, container, offset) : offset);
  5715. } else {
  5716. childNodes = container.childNodes;
  5717. if (offset >= childNodes.length && childNodes.length) {
  5718. after = 1;
  5719. offset = Math.max(0, childNodes.length - 1);
  5720. }
  5721. point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
  5722. }
  5723. for (; container && container !== root; container = container.parentNode) {
  5724. point.push(dom.nodeIndex(container, normalized));
  5725. }
  5726. return point;
  5727. };
  5728. const getLocation = (trim, selection, normalized, rng) => {
  5729. const dom = selection.dom, bookmark = {};
  5730. bookmark.start = getPoint(dom, trim, normalized, rng, true);
  5731. if (!selection.isCollapsed()) {
  5732. bookmark.end = getPoint(dom, trim, normalized, rng, false);
  5733. }
  5734. if (isRangeInCaretContainerBlock(rng)) {
  5735. bookmark.isFakeCaret = true;
  5736. }
  5737. return bookmark;
  5738. };
  5739. const findIndex = (dom, name, element) => {
  5740. let count = 0;
  5741. Tools.each(dom.select(name), node => {
  5742. if (node.getAttribute('data-mce-bogus') === 'all') {
  5743. return;
  5744. }
  5745. if (node === element) {
  5746. return false;
  5747. }
  5748. count++;
  5749. });
  5750. return count;
  5751. };
  5752. const moveEndPoint$1 = (rng, start) => {
  5753. let container, offset, childNodes;
  5754. const prefix = start ? 'start' : 'end';
  5755. container = rng[prefix + 'Container'];
  5756. offset = rng[prefix + 'Offset'];
  5757. if (isElement$6(container) && container.nodeName === 'TR') {
  5758. childNodes = container.childNodes;
  5759. container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
  5760. if (container) {
  5761. offset = start ? 0 : container.childNodes.length;
  5762. rng['set' + (start ? 'Start' : 'End')](container, offset);
  5763. }
  5764. }
  5765. };
  5766. const normalizeTableCellSelection = rng => {
  5767. moveEndPoint$1(rng, true);
  5768. moveEndPoint$1(rng, false);
  5769. return rng;
  5770. };
  5771. const findSibling = (node, offset) => {
  5772. let sibling;
  5773. if (isElement$6(node)) {
  5774. node = getNode$1(node, offset);
  5775. if (isContentEditableFalse$8(node)) {
  5776. return node;
  5777. }
  5778. }
  5779. if (isCaretContainer$2(node)) {
  5780. if (isText$8(node) && isCaretContainerBlock$1(node)) {
  5781. node = node.parentNode;
  5782. }
  5783. sibling = node.previousSibling;
  5784. if (isContentEditableFalse$8(sibling)) {
  5785. return sibling;
  5786. }
  5787. sibling = node.nextSibling;
  5788. if (isContentEditableFalse$8(sibling)) {
  5789. return sibling;
  5790. }
  5791. }
  5792. };
  5793. const findAdjacentContentEditableFalseElm = rng => {
  5794. return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
  5795. };
  5796. const getOffsetBookmark = (trim, normalized, selection) => {
  5797. const element = selection.getNode();
  5798. let name = element ? element.nodeName : null;
  5799. const rng = selection.getRng();
  5800. if (isContentEditableFalse$8(element) || name === 'IMG') {
  5801. return {
  5802. name,
  5803. index: findIndex(selection.dom, name, element)
  5804. };
  5805. }
  5806. const sibling = findAdjacentContentEditableFalseElm(rng);
  5807. if (sibling) {
  5808. name = sibling.tagName;
  5809. return {
  5810. name,
  5811. index: findIndex(selection.dom, name, sibling)
  5812. };
  5813. }
  5814. return getLocation(trim, selection, normalized, rng);
  5815. };
  5816. const getCaretBookmark = selection => {
  5817. const rng = selection.getRng();
  5818. return {
  5819. start: create$a(selection.dom.getRoot(), CaretPosition.fromRangeStart(rng)),
  5820. end: create$a(selection.dom.getRoot(), CaretPosition.fromRangeEnd(rng))
  5821. };
  5822. };
  5823. const getRangeBookmark = selection => {
  5824. return { rng: selection.getRng() };
  5825. };
  5826. const createBookmarkSpan = (dom, id, filled) => {
  5827. const args = {
  5828. 'data-mce-type': 'bookmark',
  5829. id,
  5830. 'style': 'overflow:hidden;line-height:0px'
  5831. };
  5832. return filled ? dom.create('span', args, '&#xFEFF;') : dom.create('span', args);
  5833. };
  5834. const getPersistentBookmark = (selection, filled) => {
  5835. const dom = selection.dom;
  5836. let rng = selection.getRng();
  5837. const id = dom.uniqueId();
  5838. const collapsed = selection.isCollapsed();
  5839. const element = selection.getNode();
  5840. const name = element.nodeName;
  5841. if (name === 'IMG') {
  5842. return {
  5843. name,
  5844. index: findIndex(dom, name, element)
  5845. };
  5846. }
  5847. const rng2 = normalizeTableCellSelection(rng.cloneRange());
  5848. if (!collapsed) {
  5849. rng2.collapse(false);
  5850. const endBookmarkNode = createBookmarkSpan(dom, id + '_end', filled);
  5851. rangeInsertNode(dom, rng2, endBookmarkNode);
  5852. }
  5853. rng = normalizeTableCellSelection(rng);
  5854. rng.collapse(true);
  5855. const startBookmarkNode = createBookmarkSpan(dom, id + '_start', filled);
  5856. rangeInsertNode(dom, rng, startBookmarkNode);
  5857. selection.moveToBookmark({
  5858. id,
  5859. keep: true
  5860. });
  5861. return { id };
  5862. };
  5863. const getBookmark$2 = (selection, type, normalized) => {
  5864. if (type === 2) {
  5865. return getOffsetBookmark(trim$1, normalized, selection);
  5866. } else if (type === 3) {
  5867. return getCaretBookmark(selection);
  5868. } else if (type) {
  5869. return getRangeBookmark(selection);
  5870. } else {
  5871. return getPersistentBookmark(selection, false);
  5872. }
  5873. };
  5874. const getUndoBookmark = curry(getOffsetBookmark, identity, true);
  5875. const value$1 = value => {
  5876. const applyHelper = fn => fn(value);
  5877. const constHelper = constant(value);
  5878. const outputHelper = () => output;
  5879. const output = {
  5880. tag: true,
  5881. inner: value,
  5882. fold: (_onError, onValue) => onValue(value),
  5883. isValue: always,
  5884. isError: never,
  5885. map: mapper => Result.value(mapper(value)),
  5886. mapError: outputHelper,
  5887. bind: applyHelper,
  5888. exists: applyHelper,
  5889. forall: applyHelper,
  5890. getOr: constHelper,
  5891. or: outputHelper,
  5892. getOrThunk: constHelper,
  5893. orThunk: outputHelper,
  5894. getOrDie: constHelper,
  5895. each: fn => {
  5896. fn(value);
  5897. },
  5898. toOptional: () => Optional.some(value)
  5899. };
  5900. return output;
  5901. };
  5902. const error = error => {
  5903. const outputHelper = () => output;
  5904. const output = {
  5905. tag: false,
  5906. inner: error,
  5907. fold: (onError, _onValue) => onError(error),
  5908. isValue: never,
  5909. isError: always,
  5910. map: outputHelper,
  5911. mapError: mapper => Result.error(mapper(error)),
  5912. bind: outputHelper,
  5913. exists: never,
  5914. forall: always,
  5915. getOr: identity,
  5916. or: identity,
  5917. getOrThunk: apply$1,
  5918. orThunk: apply$1,
  5919. getOrDie: die(String(error)),
  5920. each: noop,
  5921. toOptional: Optional.none
  5922. };
  5923. return output;
  5924. };
  5925. const fromOption = (optional, err) => optional.fold(() => error(err), value$1);
  5926. const Result = {
  5927. value: value$1,
  5928. error,
  5929. fromOption
  5930. };
  5931. const generate = cases => {
  5932. if (!isArray$1(cases)) {
  5933. throw new Error('cases must be an array');
  5934. }
  5935. if (cases.length === 0) {
  5936. throw new Error('there must be at least one case');
  5937. }
  5938. const constructors = [];
  5939. const adt = {};
  5940. each$g(cases, (acase, count) => {
  5941. const keys$1 = keys(acase);
  5942. if (keys$1.length !== 1) {
  5943. throw new Error('one and only one name per case');
  5944. }
  5945. const key = keys$1[0];
  5946. const value = acase[key];
  5947. if (adt[key] !== undefined) {
  5948. throw new Error('duplicate key detected:' + key);
  5949. } else if (key === 'cata') {
  5950. throw new Error('cannot have a case named cata (sorry)');
  5951. } else if (!isArray$1(value)) {
  5952. throw new Error('case arguments must be an array');
  5953. }
  5954. constructors.push(key);
  5955. adt[key] = (...args) => {
  5956. const argLength = args.length;
  5957. if (argLength !== value.length) {
  5958. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  5959. }
  5960. const match = branches => {
  5961. const branchKeys = keys(branches);
  5962. if (constructors.length !== branchKeys.length) {
  5963. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  5964. }
  5965. const allReqd = forall(constructors, reqKey => {
  5966. return contains$2(branchKeys, reqKey);
  5967. });
  5968. if (!allReqd) {
  5969. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  5970. }
  5971. return branches[key].apply(null, args);
  5972. };
  5973. return {
  5974. fold: (...foldArgs) => {
  5975. if (foldArgs.length !== cases.length) {
  5976. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  5977. }
  5978. const target = foldArgs[count];
  5979. return target.apply(null, args);
  5980. },
  5981. match,
  5982. log: label => {
  5983. console.log(label, {
  5984. constructors,
  5985. constructor: key,
  5986. params: args
  5987. });
  5988. }
  5989. };
  5990. };
  5991. });
  5992. return adt;
  5993. };
  5994. const Adt = { generate };
  5995. Adt.generate([
  5996. {
  5997. bothErrors: [
  5998. 'error1',
  5999. 'error2'
  6000. ]
  6001. },
  6002. {
  6003. firstError: [
  6004. 'error1',
  6005. 'value2'
  6006. ]
  6007. },
  6008. {
  6009. secondError: [
  6010. 'value1',
  6011. 'error2'
  6012. ]
  6013. },
  6014. {
  6015. bothValues: [
  6016. 'value1',
  6017. 'value2'
  6018. ]
  6019. }
  6020. ]);
  6021. const partition$1 = results => {
  6022. const errors = [];
  6023. const values = [];
  6024. each$g(results, result => {
  6025. result.fold(err => {
  6026. errors.push(err);
  6027. }, value => {
  6028. values.push(value);
  6029. });
  6030. });
  6031. return {
  6032. errors,
  6033. values
  6034. };
  6035. };
  6036. const isInlinePattern = pattern => pattern.type === 'inline-command' || pattern.type === 'inline-format';
  6037. const isBlockPattern = pattern => pattern.type === 'block-command' || pattern.type === 'block-format';
  6038. const sortPatterns = patterns => sort(patterns, (a, b) => {
  6039. if (a.start.length === b.start.length) {
  6040. return 0;
  6041. }
  6042. return a.start.length > b.start.length ? -1 : 1;
  6043. });
  6044. const normalizePattern = pattern => {
  6045. const err = message => Result.error({
  6046. message,
  6047. pattern
  6048. });
  6049. const formatOrCmd = (name, onFormat, onCommand) => {
  6050. if (pattern.format !== undefined) {
  6051. let formats;
  6052. if (isArray$1(pattern.format)) {
  6053. if (!forall(pattern.format, isString)) {
  6054. return err(name + ' pattern has non-string items in the `format` array');
  6055. }
  6056. formats = pattern.format;
  6057. } else if (isString(pattern.format)) {
  6058. formats = [pattern.format];
  6059. } else {
  6060. return err(name + ' pattern has non-string `format` parameter');
  6061. }
  6062. return Result.value(onFormat(formats));
  6063. } else if (pattern.cmd !== undefined) {
  6064. if (!isString(pattern.cmd)) {
  6065. return err(name + ' pattern has non-string `cmd` parameter');
  6066. }
  6067. return Result.value(onCommand(pattern.cmd, pattern.value));
  6068. } else {
  6069. return err(name + ' pattern is missing both `format` and `cmd` parameters');
  6070. }
  6071. };
  6072. if (!isObject(pattern)) {
  6073. return err('Raw pattern is not an object');
  6074. }
  6075. if (!isString(pattern.start)) {
  6076. return err('Raw pattern is missing `start` parameter');
  6077. }
  6078. if (pattern.end !== undefined) {
  6079. if (!isString(pattern.end)) {
  6080. return err('Inline pattern has non-string `end` parameter');
  6081. }
  6082. if (pattern.start.length === 0 && pattern.end.length === 0) {
  6083. return err('Inline pattern has empty `start` and `end` parameters');
  6084. }
  6085. let start = pattern.start;
  6086. let end = pattern.end;
  6087. if (end.length === 0) {
  6088. end = start;
  6089. start = '';
  6090. }
  6091. return formatOrCmd('Inline', format => ({
  6092. type: 'inline-format',
  6093. start,
  6094. end,
  6095. format
  6096. }), (cmd, value) => ({
  6097. type: 'inline-command',
  6098. start,
  6099. end,
  6100. cmd,
  6101. value
  6102. }));
  6103. } else if (pattern.replacement !== undefined) {
  6104. if (!isString(pattern.replacement)) {
  6105. return err('Replacement pattern has non-string `replacement` parameter');
  6106. }
  6107. if (pattern.start.length === 0) {
  6108. return err('Replacement pattern has empty `start` parameter');
  6109. }
  6110. return Result.value({
  6111. type: 'inline-command',
  6112. start: '',
  6113. end: pattern.start,
  6114. cmd: 'mceInsertContent',
  6115. value: pattern.replacement
  6116. });
  6117. } else {
  6118. if (pattern.start.length === 0) {
  6119. return err('Block pattern has empty `start` parameter');
  6120. }
  6121. return formatOrCmd('Block', formats => ({
  6122. type: 'block-format',
  6123. start: pattern.start,
  6124. format: formats[0]
  6125. }), (command, commandValue) => ({
  6126. type: 'block-command',
  6127. start: pattern.start,
  6128. cmd: command,
  6129. value: commandValue
  6130. }));
  6131. }
  6132. };
  6133. const getBlockPatterns = patterns => sortPatterns(filter$6(patterns, isBlockPattern));
  6134. const getInlinePatterns = patterns => filter$6(patterns, isInlinePattern);
  6135. const createPatternSet = patterns => ({
  6136. inlinePatterns: getInlinePatterns(patterns),
  6137. blockPatterns: getBlockPatterns(patterns)
  6138. });
  6139. const fromRawPatterns = patterns => {
  6140. const normalized = partition$1(map$3(patterns, normalizePattern));
  6141. each$g(normalized.errors, err => console.error(err.message, err.pattern));
  6142. return normalized.values;
  6143. };
  6144. const deviceDetection$1 = detect$2().deviceType;
  6145. const isTouch = deviceDetection$1.isTouch();
  6146. const DOM$a = DOMUtils.DOM;
  6147. const getHash = value => {
  6148. const items = value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(',');
  6149. return foldl(items, (output, item) => {
  6150. const arr = item.split('=');
  6151. const key = arr[0];
  6152. const val = arr.length > 1 ? arr[1] : key;
  6153. output[trim$3(key)] = trim$3(val);
  6154. return output;
  6155. }, {});
  6156. };
  6157. const isRegExp = x => is$4(x, RegExp);
  6158. const option = name => editor => editor.options.get(name);
  6159. const stringOrObjectProcessor = value => isString(value) || isObject(value);
  6160. const bodyOptionProcessor = (editor, defaultValue = '') => value => {
  6161. const valid = isString(value);
  6162. if (valid) {
  6163. if (value.indexOf('=') !== -1) {
  6164. const bodyObj = getHash(value);
  6165. return {
  6166. value: get$a(bodyObj, editor.id).getOr(defaultValue),
  6167. valid
  6168. };
  6169. } else {
  6170. return {
  6171. value,
  6172. valid
  6173. };
  6174. }
  6175. } else {
  6176. return {
  6177. valid: false,
  6178. message: 'Must be a string.'
  6179. };
  6180. }
  6181. };
  6182. const register$7 = editor => {
  6183. const registerOption = editor.options.register;
  6184. registerOption('id', {
  6185. processor: 'string',
  6186. default: editor.id
  6187. });
  6188. registerOption('selector', { processor: 'string' });
  6189. registerOption('target', { processor: 'object' });
  6190. registerOption('suffix', { processor: 'string' });
  6191. registerOption('cache_suffix', { processor: 'string' });
  6192. registerOption('base_url', { processor: 'string' });
  6193. registerOption('referrer_policy', {
  6194. processor: 'string',
  6195. default: ''
  6196. });
  6197. registerOption('language_load', { processor: 'boolean' });
  6198. registerOption('inline', {
  6199. processor: 'boolean',
  6200. default: false
  6201. });
  6202. registerOption('iframe_attrs', {
  6203. processor: 'object',
  6204. default: {}
  6205. });
  6206. registerOption('doctype', {
  6207. processor: 'string',
  6208. default: '<!DOCTYPE html>'
  6209. });
  6210. registerOption('document_base_url', {
  6211. processor: 'string',
  6212. default: editor.documentBaseUrl
  6213. });
  6214. registerOption('body_id', {
  6215. processor: bodyOptionProcessor(editor, 'tinymce'),
  6216. default: 'tinymce'
  6217. });
  6218. registerOption('body_class', {
  6219. processor: bodyOptionProcessor(editor),
  6220. default: ''
  6221. });
  6222. registerOption('content_security_policy', {
  6223. processor: 'string',
  6224. default: ''
  6225. });
  6226. registerOption('br_in_pre', {
  6227. processor: 'boolean',
  6228. default: true
  6229. });
  6230. registerOption('forced_root_block', {
  6231. processor: value => {
  6232. const valid = isString(value) && isNotEmpty(value);
  6233. if (valid) {
  6234. return {
  6235. value,
  6236. valid
  6237. };
  6238. } else {
  6239. return {
  6240. valid: false,
  6241. message: 'Must be a non-empty string.'
  6242. };
  6243. }
  6244. },
  6245. default: 'p'
  6246. });
  6247. registerOption('forced_root_block_attrs', {
  6248. processor: 'object',
  6249. default: {}
  6250. });
  6251. registerOption('br_newline_selector', {
  6252. processor: 'string',
  6253. default: '.mce-toc h2,figcaption,caption'
  6254. });
  6255. registerOption('no_newline_selector', {
  6256. processor: 'string',
  6257. default: ''
  6258. });
  6259. registerOption('keep_styles', {
  6260. processor: 'boolean',
  6261. default: true
  6262. });
  6263. registerOption('end_container_on_empty_block', {
  6264. processor: 'boolean',
  6265. default: false
  6266. });
  6267. registerOption('font_size_style_values', {
  6268. processor: 'string',
  6269. default: 'xx-small,x-small,small,medium,large,x-large,xx-large'
  6270. });
  6271. registerOption('font_size_legacy_values', {
  6272. processor: 'string',
  6273. default: 'xx-small,small,medium,large,x-large,xx-large,300%'
  6274. });
  6275. registerOption('font_size_classes', {
  6276. processor: 'string',
  6277. default: ''
  6278. });
  6279. registerOption('automatic_uploads', {
  6280. processor: 'boolean',
  6281. default: true
  6282. });
  6283. registerOption('images_reuse_filename', {
  6284. processor: 'boolean',
  6285. default: false
  6286. });
  6287. registerOption('images_replace_blob_uris', {
  6288. processor: 'boolean',
  6289. default: true
  6290. });
  6291. registerOption('icons', {
  6292. processor: 'string',
  6293. default: ''
  6294. });
  6295. registerOption('icons_url', {
  6296. processor: 'string',
  6297. default: ''
  6298. });
  6299. registerOption('images_upload_url', {
  6300. processor: 'string',
  6301. default: ''
  6302. });
  6303. registerOption('images_upload_base_path', {
  6304. processor: 'string',
  6305. default: ''
  6306. });
  6307. registerOption('images_upload_base_path', {
  6308. processor: 'string',
  6309. default: ''
  6310. });
  6311. registerOption('images_upload_credentials', {
  6312. processor: 'boolean',
  6313. default: false
  6314. });
  6315. registerOption('images_upload_handler', { processor: 'function' });
  6316. registerOption('language', {
  6317. processor: 'string',
  6318. default: 'en'
  6319. });
  6320. registerOption('language_url', {
  6321. processor: 'string',
  6322. default: ''
  6323. });
  6324. registerOption('entity_encoding', {
  6325. processor: 'string',
  6326. default: 'named'
  6327. });
  6328. registerOption('indent', {
  6329. processor: 'boolean',
  6330. default: true
  6331. });
  6332. registerOption('indent_before', {
  6333. processor: 'string',
  6334. default: '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'
  6335. });
  6336. registerOption('indent_after', {
  6337. processor: 'string',
  6338. default: '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'
  6339. });
  6340. registerOption('indent_use_margin', {
  6341. processor: 'boolean',
  6342. default: false
  6343. });
  6344. registerOption('indentation', {
  6345. processor: 'string',
  6346. default: '40px'
  6347. });
  6348. registerOption('content_css', {
  6349. processor: value => {
  6350. const valid = value === false || isString(value) || isArrayOf(value, isString);
  6351. if (valid) {
  6352. if (isString(value)) {
  6353. return {
  6354. value: map$3(value.split(','), trim$3),
  6355. valid
  6356. };
  6357. } else if (isArray$1(value)) {
  6358. return {
  6359. value,
  6360. valid
  6361. };
  6362. } else if (value === false) {
  6363. return {
  6364. value: [],
  6365. valid
  6366. };
  6367. } else {
  6368. return {
  6369. value,
  6370. valid
  6371. };
  6372. }
  6373. } else {
  6374. return {
  6375. valid: false,
  6376. message: 'Must be false, a string or an array of strings.'
  6377. };
  6378. }
  6379. },
  6380. default: isInline(editor) ? [] : ['default']
  6381. });
  6382. registerOption('content_style', { processor: 'string' });
  6383. registerOption('content_css_cors', {
  6384. processor: 'boolean',
  6385. default: false
  6386. });
  6387. registerOption('font_css', {
  6388. processor: value => {
  6389. const valid = isString(value) || isArrayOf(value, isString);
  6390. if (valid) {
  6391. const newValue = isArray$1(value) ? value : map$3(value.split(','), trim$3);
  6392. return {
  6393. value: newValue,
  6394. valid
  6395. };
  6396. } else {
  6397. return {
  6398. valid: false,
  6399. message: 'Must be a string or an array of strings.'
  6400. };
  6401. }
  6402. },
  6403. default: []
  6404. });
  6405. registerOption('inline_boundaries', {
  6406. processor: 'boolean',
  6407. default: true
  6408. });
  6409. registerOption('inline_boundaries_selector', {
  6410. processor: 'string',
  6411. default: 'a[href],code,.mce-annotation'
  6412. });
  6413. registerOption('object_resizing', {
  6414. processor: value => {
  6415. const valid = isBoolean(value) || isString(value);
  6416. if (valid) {
  6417. if (value === false || deviceDetection$1.isiPhone() || deviceDetection$1.isiPad()) {
  6418. return {
  6419. value: '',
  6420. valid
  6421. };
  6422. } else {
  6423. return {
  6424. value: value === true ? 'table,img,figure.image,div,video,iframe' : value,
  6425. valid
  6426. };
  6427. }
  6428. } else {
  6429. return {
  6430. valid: false,
  6431. message: 'Must be boolean or a string'
  6432. };
  6433. }
  6434. },
  6435. default: !isTouch
  6436. });
  6437. registerOption('resize_img_proportional', {
  6438. processor: 'boolean',
  6439. default: true
  6440. });
  6441. registerOption('event_root', { processor: 'object' });
  6442. registerOption('service_message', { processor: 'string' });
  6443. registerOption('theme', {
  6444. processor: value => value === false || isString(value) || isFunction(value),
  6445. default: 'silver'
  6446. });
  6447. registerOption('theme_url', { processor: 'string' });
  6448. registerOption('formats', { processor: 'object' });
  6449. registerOption('format_empty_lines', {
  6450. processor: 'boolean',
  6451. default: false
  6452. });
  6453. registerOption('preview_styles', {
  6454. processor: value => {
  6455. const valid = value === false || isString(value);
  6456. if (valid) {
  6457. return {
  6458. value: value === false ? '' : value,
  6459. valid
  6460. };
  6461. } else {
  6462. return {
  6463. valid: false,
  6464. message: 'Must be false or a string'
  6465. };
  6466. }
  6467. },
  6468. default: 'font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow'
  6469. });
  6470. registerOption('custom_ui_selector', {
  6471. processor: 'string',
  6472. default: ''
  6473. });
  6474. registerOption('hidden_input', {
  6475. processor: 'boolean',
  6476. default: true
  6477. });
  6478. registerOption('submit_patch', {
  6479. processor: 'boolean',
  6480. default: true
  6481. });
  6482. registerOption('encoding', { processor: 'string' });
  6483. registerOption('add_form_submit_trigger', {
  6484. processor: 'boolean',
  6485. default: true
  6486. });
  6487. registerOption('add_unload_trigger', {
  6488. processor: 'boolean',
  6489. default: true
  6490. });
  6491. registerOption('custom_undo_redo_levels', {
  6492. processor: 'number',
  6493. default: 0
  6494. });
  6495. registerOption('disable_nodechange', {
  6496. processor: 'boolean',
  6497. default: false
  6498. });
  6499. registerOption('readonly', {
  6500. processor: 'boolean',
  6501. default: false
  6502. });
  6503. registerOption('plugins', {
  6504. processor: 'string[]',
  6505. default: []
  6506. });
  6507. registerOption('external_plugins', { processor: 'object' });
  6508. registerOption('forced_plugins', { processor: 'string[]' });
  6509. registerOption('model', {
  6510. processor: 'string',
  6511. default: editor.hasPlugin('rtc') ? 'plugin' : 'dom'
  6512. });
  6513. registerOption('model_url', { processor: 'string' });
  6514. registerOption('block_unsupported_drop', {
  6515. processor: 'boolean',
  6516. default: true
  6517. });
  6518. registerOption('visual', {
  6519. processor: 'boolean',
  6520. default: true
  6521. });
  6522. registerOption('visual_table_class', {
  6523. processor: 'string',
  6524. default: 'mce-item-table'
  6525. });
  6526. registerOption('visual_anchor_class', {
  6527. processor: 'string',
  6528. default: 'mce-item-anchor'
  6529. });
  6530. registerOption('iframe_aria_text', {
  6531. processor: 'string',
  6532. default: 'Rich Text Area. Press ALT-0 for help.'
  6533. });
  6534. registerOption('setup', { processor: 'function' });
  6535. registerOption('init_instance_callback', { processor: 'function' });
  6536. registerOption('url_converter', {
  6537. processor: 'function',
  6538. default: editor.convertURL
  6539. });
  6540. registerOption('url_converter_scope', {
  6541. processor: 'object',
  6542. default: editor
  6543. });
  6544. registerOption('urlconverter_callback', { processor: 'function' });
  6545. registerOption('allow_conditional_comments', {
  6546. processor: 'boolean',
  6547. default: false
  6548. });
  6549. registerOption('allow_html_data_urls', {
  6550. processor: 'boolean',
  6551. default: false
  6552. });
  6553. registerOption('allow_svg_data_urls', { processor: 'boolean' });
  6554. registerOption('allow_html_in_named_anchor', {
  6555. processor: 'boolean',
  6556. default: false
  6557. });
  6558. registerOption('allow_script_urls', {
  6559. processor: 'boolean',
  6560. default: false
  6561. });
  6562. registerOption('allow_unsafe_link_target', {
  6563. processor: 'boolean',
  6564. default: false
  6565. });
  6566. registerOption('convert_fonts_to_spans', {
  6567. processor: 'boolean',
  6568. default: true,
  6569. deprecated: true
  6570. });
  6571. registerOption('fix_list_elements', {
  6572. processor: 'boolean',
  6573. default: false
  6574. });
  6575. registerOption('preserve_cdata', {
  6576. processor: 'boolean',
  6577. default: false
  6578. });
  6579. registerOption('remove_trailing_brs', { processor: 'boolean' });
  6580. registerOption('inline_styles', {
  6581. processor: 'boolean',
  6582. default: true,
  6583. deprecated: true
  6584. });
  6585. registerOption('element_format', {
  6586. processor: 'string',
  6587. default: 'html'
  6588. });
  6589. registerOption('entities', { processor: 'string' });
  6590. registerOption('schema', {
  6591. processor: 'string',
  6592. default: 'html5'
  6593. });
  6594. registerOption('convert_urls', {
  6595. processor: 'boolean',
  6596. default: true
  6597. });
  6598. registerOption('relative_urls', {
  6599. processor: 'boolean',
  6600. default: true
  6601. });
  6602. registerOption('remove_script_host', {
  6603. processor: 'boolean',
  6604. default: true
  6605. });
  6606. registerOption('custom_elements', { processor: 'string' });
  6607. registerOption('extended_valid_elements', { processor: 'string' });
  6608. registerOption('invalid_elements', { processor: 'string' });
  6609. registerOption('invalid_styles', { processor: stringOrObjectProcessor });
  6610. registerOption('valid_children', { processor: 'string' });
  6611. registerOption('valid_classes', { processor: stringOrObjectProcessor });
  6612. registerOption('valid_elements', { processor: 'string' });
  6613. registerOption('valid_styles', { processor: stringOrObjectProcessor });
  6614. registerOption('verify_html', {
  6615. processor: 'boolean',
  6616. default: true
  6617. });
  6618. registerOption('auto_focus', { processor: value => isString(value) || value === true });
  6619. registerOption('browser_spellcheck', {
  6620. processor: 'boolean',
  6621. default: false
  6622. });
  6623. registerOption('protect', { processor: 'array' });
  6624. registerOption('images_file_types', {
  6625. processor: 'string',
  6626. default: 'jpeg,jpg,jpe,jfi,jif,jfif,png,gif,bmp,webp'
  6627. });
  6628. registerOption('deprecation_warnings', {
  6629. processor: 'boolean',
  6630. default: true
  6631. });
  6632. registerOption('a11y_advanced_options', {
  6633. processor: 'boolean',
  6634. default: false
  6635. });
  6636. registerOption('api_key', { processor: 'string' });
  6637. registerOption('paste_block_drop', {
  6638. processor: 'boolean',
  6639. default: false
  6640. });
  6641. registerOption('paste_data_images', {
  6642. processor: 'boolean',
  6643. default: true
  6644. });
  6645. registerOption('paste_preprocess', { processor: 'function' });
  6646. registerOption('paste_postprocess', { processor: 'function' });
  6647. registerOption('paste_webkit_styles', {
  6648. processor: 'string',
  6649. default: 'none'
  6650. });
  6651. registerOption('paste_remove_styles_if_webkit', {
  6652. processor: 'boolean',
  6653. default: true
  6654. });
  6655. registerOption('paste_merge_formats', {
  6656. processor: 'boolean',
  6657. default: true
  6658. });
  6659. registerOption('smart_paste', {
  6660. processor: 'boolean',
  6661. default: true
  6662. });
  6663. registerOption('paste_as_text', {
  6664. processor: 'boolean',
  6665. default: false
  6666. });
  6667. registerOption('paste_tab_spaces', {
  6668. processor: 'number',
  6669. default: 4
  6670. });
  6671. registerOption('text_patterns', {
  6672. processor: value => {
  6673. if (isArrayOf(value, isObject) || value === false) {
  6674. const patterns = value === false ? [] : value;
  6675. return {
  6676. value: fromRawPatterns(patterns),
  6677. valid: true
  6678. };
  6679. } else {
  6680. return {
  6681. valid: false,
  6682. message: 'Must be an array of objects or false.'
  6683. };
  6684. }
  6685. },
  6686. default: [
  6687. {
  6688. start: '*',
  6689. end: '*',
  6690. format: 'italic'
  6691. },
  6692. {
  6693. start: '**',
  6694. end: '**',
  6695. format: 'bold'
  6696. },
  6697. {
  6698. start: '#',
  6699. format: 'h1'
  6700. },
  6701. {
  6702. start: '##',
  6703. format: 'h2'
  6704. },
  6705. {
  6706. start: '###',
  6707. format: 'h3'
  6708. },
  6709. {
  6710. start: '####',
  6711. format: 'h4'
  6712. },
  6713. {
  6714. start: '#####',
  6715. format: 'h5'
  6716. },
  6717. {
  6718. start: '######',
  6719. format: 'h6'
  6720. },
  6721. {
  6722. start: '1. ',
  6723. cmd: 'InsertOrderedList'
  6724. },
  6725. {
  6726. start: '* ',
  6727. cmd: 'InsertUnorderedList'
  6728. },
  6729. {
  6730. start: '- ',
  6731. cmd: 'InsertUnorderedList'
  6732. }
  6733. ]
  6734. });
  6735. registerOption('noneditable_class', {
  6736. processor: 'string',
  6737. default: 'mceNonEditable'
  6738. });
  6739. registerOption('editable_class', {
  6740. processor: 'string',
  6741. default: 'mceEditable'
  6742. });
  6743. registerOption('noneditable_regexp', {
  6744. processor: value => {
  6745. if (isArrayOf(value, isRegExp)) {
  6746. return {
  6747. value,
  6748. valid: true
  6749. };
  6750. } else if (isRegExp(value)) {
  6751. return {
  6752. value: [value],
  6753. valid: true
  6754. };
  6755. } else {
  6756. return {
  6757. valid: false,
  6758. message: 'Must be a RegExp or an array of RegExp.'
  6759. };
  6760. }
  6761. },
  6762. default: []
  6763. });
  6764. registerOption('table_tab_navigation', {
  6765. processor: 'boolean',
  6766. default: true
  6767. });
  6768. editor.on('ScriptsLoaded', () => {
  6769. registerOption('directionality', {
  6770. processor: 'string',
  6771. default: I18n.isRtl() ? 'rtl' : undefined
  6772. });
  6773. registerOption('placeholder', {
  6774. processor: 'string',
  6775. default: DOM$a.getAttrib(editor.getElement(), 'placeholder')
  6776. });
  6777. });
  6778. };
  6779. const getIframeAttrs = option('iframe_attrs');
  6780. const getDocType = option('doctype');
  6781. const getDocumentBaseUrl = option('document_base_url');
  6782. const getBodyId = option('body_id');
  6783. const getBodyClass = option('body_class');
  6784. const getContentSecurityPolicy = option('content_security_policy');
  6785. const shouldPutBrInPre$1 = option('br_in_pre');
  6786. const getForcedRootBlock = option('forced_root_block');
  6787. const getForcedRootBlockAttrs = option('forced_root_block_attrs');
  6788. const getBrNewLineSelector = option('br_newline_selector');
  6789. const getNoNewLineSelector = option('no_newline_selector');
  6790. const shouldKeepStyles = option('keep_styles');
  6791. const shouldEndContainerOnEmptyBlock = option('end_container_on_empty_block');
  6792. const isAutomaticUploadsEnabled = option('automatic_uploads');
  6793. const shouldReuseFileName = option('images_reuse_filename');
  6794. const shouldReplaceBlobUris = option('images_replace_blob_uris');
  6795. const getIconPackName = option('icons');
  6796. const getIconsUrl = option('icons_url');
  6797. const getImageUploadUrl = option('images_upload_url');
  6798. const getImageUploadBasePath = option('images_upload_base_path');
  6799. const getImagesUploadCredentials = option('images_upload_credentials');
  6800. const getImagesUploadHandler = option('images_upload_handler');
  6801. const shouldUseContentCssCors = option('content_css_cors');
  6802. const getReferrerPolicy = option('referrer_policy');
  6803. const getLanguageCode = option('language');
  6804. const getLanguageUrl = option('language_url');
  6805. const shouldIndentUseMargin = option('indent_use_margin');
  6806. const getIndentation = option('indentation');
  6807. const getContentCss = option('content_css');
  6808. const getContentStyle = option('content_style');
  6809. const getFontCss = option('font_css');
  6810. const getDirectionality = option('directionality');
  6811. const getInlineBoundarySelector = option('inline_boundaries_selector');
  6812. const getObjectResizing = option('object_resizing');
  6813. const getResizeImgProportional = option('resize_img_proportional');
  6814. const getPlaceholder = option('placeholder');
  6815. const getEventRoot = option('event_root');
  6816. const getServiceMessage = option('service_message');
  6817. const getTheme = option('theme');
  6818. const getThemeUrl = option('theme_url');
  6819. const getModel = option('model');
  6820. const getModelUrl = option('model_url');
  6821. const isInlineBoundariesEnabled = option('inline_boundaries');
  6822. const getFormats = option('formats');
  6823. const getPreviewStyles = option('preview_styles');
  6824. const canFormatEmptyLines = option('format_empty_lines');
  6825. const getCustomUiSelector = option('custom_ui_selector');
  6826. const isInline = option('inline');
  6827. const hasHiddenInput = option('hidden_input');
  6828. const shouldPatchSubmit = option('submit_patch');
  6829. const shouldAddFormSubmitTrigger = option('add_form_submit_trigger');
  6830. const shouldAddUnloadTrigger = option('add_unload_trigger');
  6831. const getCustomUndoRedoLevels = option('custom_undo_redo_levels');
  6832. const shouldDisableNodeChange = option('disable_nodechange');
  6833. const isReadOnly$1 = option('readonly');
  6834. const hasContentCssCors = option('content_css_cors');
  6835. const getPlugins = option('plugins');
  6836. const getExternalPlugins$1 = option('external_plugins');
  6837. const shouldBlockUnsupportedDrop = option('block_unsupported_drop');
  6838. const isVisualAidsEnabled = option('visual');
  6839. const getVisualAidsTableClass = option('visual_table_class');
  6840. const getVisualAidsAnchorClass = option('visual_anchor_class');
  6841. const getIframeAriaText = option('iframe_aria_text');
  6842. const getSetupCallback = option('setup');
  6843. const getInitInstanceCallback = option('init_instance_callback');
  6844. const getUrlConverterCallback = option('urlconverter_callback');
  6845. const getAutoFocus = option('auto_focus');
  6846. const shouldBrowserSpellcheck = option('browser_spellcheck');
  6847. const getProtect = option('protect');
  6848. const shouldPasteBlockDrop = option('paste_block_drop');
  6849. const shouldPasteDataImages = option('paste_data_images');
  6850. const getPastePreProcess = option('paste_preprocess');
  6851. const getPastePostProcess = option('paste_postprocess');
  6852. const getPasteWebkitStyles = option('paste_webkit_styles');
  6853. const shouldPasteRemoveWebKitStyles = option('paste_remove_styles_if_webkit');
  6854. const shouldPasteMergeFormats = option('paste_merge_formats');
  6855. const isSmartPasteEnabled = option('smart_paste');
  6856. const isPasteAsTextEnabled = option('paste_as_text');
  6857. const getPasteTabSpaces = option('paste_tab_spaces');
  6858. const shouldAllowHtmlDataUrls = option('allow_html_data_urls');
  6859. const getTextPatterns = option('text_patterns');
  6860. const getNonEditableClass = option('noneditable_class');
  6861. const getEditableClass = option('editable_class');
  6862. const getNonEditableRegExps = option('noneditable_regexp');
  6863. const getFontStyleValues = editor => Tools.explode(editor.options.get('font_size_style_values'));
  6864. const getFontSizeClasses = editor => Tools.explode(editor.options.get('font_size_classes'));
  6865. const isEncodingXml = editor => editor.options.get('encoding') === 'xml';
  6866. const getAllowedImageFileTypes = editor => Tools.explode(editor.options.get('images_file_types'));
  6867. const hasTableTabNavigation = option('table_tab_navigation');
  6868. const isElement$3 = isElement$6;
  6869. const isText$3 = isText$8;
  6870. const removeNode$1 = node => {
  6871. const parentNode = node.parentNode;
  6872. if (parentNode) {
  6873. parentNode.removeChild(node);
  6874. }
  6875. };
  6876. const trimCount = text => {
  6877. const trimmedText = trim$1(text);
  6878. return {
  6879. count: text.length - trimmedText.length,
  6880. text: trimmedText
  6881. };
  6882. };
  6883. const deleteZwspChars = caretContainer => {
  6884. let idx;
  6885. while ((idx = caretContainer.data.lastIndexOf(ZWSP$1)) !== -1) {
  6886. caretContainer.deleteData(idx, 1);
  6887. }
  6888. };
  6889. const removeUnchanged = (caretContainer, pos) => {
  6890. remove$4(caretContainer);
  6891. return pos;
  6892. };
  6893. const removeTextAndReposition = (caretContainer, pos) => {
  6894. const before = trimCount(caretContainer.data.substr(0, pos.offset()));
  6895. const after = trimCount(caretContainer.data.substr(pos.offset()));
  6896. const text = before.text + after.text;
  6897. if (text.length > 0) {
  6898. deleteZwspChars(caretContainer);
  6899. return CaretPosition(caretContainer, pos.offset() - before.count);
  6900. } else {
  6901. return pos;
  6902. }
  6903. };
  6904. const removeElementAndReposition = (caretContainer, pos) => {
  6905. const parentNode = pos.container();
  6906. const newPosition = indexOf$1(from(parentNode.childNodes), caretContainer).map(index => {
  6907. return index < pos.offset() ? CaretPosition(parentNode, pos.offset() - 1) : pos;
  6908. }).getOr(pos);
  6909. remove$4(caretContainer);
  6910. return newPosition;
  6911. };
  6912. const removeTextCaretContainer = (caretContainer, pos) => isText$3(caretContainer) && pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  6913. const removeElementCaretContainer = (caretContainer, pos) => pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  6914. const removeAndReposition = (container, pos) => CaretPosition.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
  6915. const remove$4 = caretContainerNode => {
  6916. if (isElement$3(caretContainerNode) && isCaretContainer$2(caretContainerNode)) {
  6917. if (hasContent(caretContainerNode)) {
  6918. caretContainerNode.removeAttribute('data-mce-caret');
  6919. } else {
  6920. removeNode$1(caretContainerNode);
  6921. }
  6922. }
  6923. if (isText$3(caretContainerNode)) {
  6924. deleteZwspChars(caretContainerNode);
  6925. if (caretContainerNode.data.length === 0) {
  6926. removeNode$1(caretContainerNode);
  6927. }
  6928. }
  6929. };
  6930. const isContentEditableFalse$7 = isContentEditableFalse$a;
  6931. const isMedia$1 = isMedia$2;
  6932. const isTableCell$3 = isTableCell$5;
  6933. const inlineFakeCaretSelector = '*[contentEditable=false],video,audio,embed,object';
  6934. const getAbsoluteClientRect = (root, element, before) => {
  6935. const clientRect = collapse(element.getBoundingClientRect(), before);
  6936. let scrollX;
  6937. let scrollY;
  6938. if (root.tagName === 'BODY') {
  6939. const docElm = root.ownerDocument.documentElement;
  6940. scrollX = root.scrollLeft || docElm.scrollLeft;
  6941. scrollY = root.scrollTop || docElm.scrollTop;
  6942. } else {
  6943. const rootRect = root.getBoundingClientRect();
  6944. scrollX = root.scrollLeft - rootRect.left;
  6945. scrollY = root.scrollTop - rootRect.top;
  6946. }
  6947. clientRect.left += scrollX;
  6948. clientRect.right += scrollX;
  6949. clientRect.top += scrollY;
  6950. clientRect.bottom += scrollY;
  6951. clientRect.width = 1;
  6952. let margin = element.offsetWidth - element.clientWidth;
  6953. if (margin > 0) {
  6954. if (before) {
  6955. margin *= -1;
  6956. }
  6957. clientRect.left += margin;
  6958. clientRect.right += margin;
  6959. }
  6960. return clientRect;
  6961. };
  6962. const trimInlineCaretContainers = root => {
  6963. const fakeCaretTargetNodes = descendants(SugarElement.fromDom(root), inlineFakeCaretSelector);
  6964. for (let i = 0; i < fakeCaretTargetNodes.length; i++) {
  6965. const node = fakeCaretTargetNodes[i].dom;
  6966. let sibling = node.previousSibling;
  6967. if (endsWithCaretContainer$1(sibling)) {
  6968. const data = sibling.data;
  6969. if (data.length === 1) {
  6970. sibling.parentNode.removeChild(sibling);
  6971. } else {
  6972. sibling.deleteData(data.length - 1, 1);
  6973. }
  6974. }
  6975. sibling = node.nextSibling;
  6976. if (startsWithCaretContainer$1(sibling)) {
  6977. const data = sibling.data;
  6978. if (data.length === 1) {
  6979. sibling.parentNode.removeChild(sibling);
  6980. } else {
  6981. sibling.deleteData(0, 1);
  6982. }
  6983. }
  6984. }
  6985. };
  6986. const FakeCaret = (editor, root, isBlock, hasFocus) => {
  6987. const lastVisualCaret = value$2();
  6988. let cursorInterval;
  6989. let caretContainerNode;
  6990. const caretBlock = getForcedRootBlock(editor);
  6991. const dom = editor.dom;
  6992. const show = (before, element) => {
  6993. let rng;
  6994. hide();
  6995. if (isTableCell$3(element)) {
  6996. return null;
  6997. }
  6998. if (isBlock(element)) {
  6999. caretContainerNode = insertBlock(caretBlock, element, before);
  7000. const clientRect = getAbsoluteClientRect(root, element, before);
  7001. dom.setStyle(caretContainerNode, 'top', clientRect.top);
  7002. const caret = dom.create('div', {
  7003. 'class': 'mce-visual-caret',
  7004. 'data-mce-bogus': 'all'
  7005. });
  7006. dom.setStyles(caret, { ...clientRect });
  7007. dom.add(root, caret);
  7008. lastVisualCaret.set({
  7009. caret,
  7010. element,
  7011. before
  7012. });
  7013. if (before) {
  7014. dom.addClass(caret, 'mce-visual-caret-before');
  7015. }
  7016. startBlink();
  7017. rng = element.ownerDocument.createRange();
  7018. rng.setStart(caretContainerNode, 0);
  7019. rng.setEnd(caretContainerNode, 0);
  7020. } else {
  7021. caretContainerNode = insertInline$1(element, before);
  7022. rng = element.ownerDocument.createRange();
  7023. if (isInlineFakeCaretTarget(caretContainerNode.nextSibling)) {
  7024. rng.setStart(caretContainerNode, 0);
  7025. rng.setEnd(caretContainerNode, 0);
  7026. } else {
  7027. rng.setStart(caretContainerNode, 1);
  7028. rng.setEnd(caretContainerNode, 1);
  7029. }
  7030. return rng;
  7031. }
  7032. return rng;
  7033. };
  7034. const hide = () => {
  7035. trimInlineCaretContainers(root);
  7036. if (caretContainerNode) {
  7037. remove$4(caretContainerNode);
  7038. caretContainerNode = null;
  7039. }
  7040. lastVisualCaret.on(caretState => {
  7041. dom.remove(caretState.caret);
  7042. lastVisualCaret.clear();
  7043. });
  7044. if (cursorInterval) {
  7045. clearInterval(cursorInterval);
  7046. cursorInterval = undefined;
  7047. }
  7048. };
  7049. const startBlink = () => {
  7050. cursorInterval = setInterval(() => {
  7051. lastVisualCaret.on(caretState => {
  7052. if (hasFocus()) {
  7053. dom.toggleClass(caretState.caret, 'mce-visual-caret-hidden');
  7054. } else {
  7055. dom.addClass(caretState.caret, 'mce-visual-caret-hidden');
  7056. }
  7057. });
  7058. }, 500);
  7059. };
  7060. const reposition = () => {
  7061. lastVisualCaret.on(caretState => {
  7062. const clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
  7063. dom.setStyles(caretState.caret, { ...clientRect });
  7064. });
  7065. };
  7066. const destroy = () => clearInterval(cursorInterval);
  7067. const getCss = () => '.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;' + '}';
  7068. return {
  7069. show,
  7070. hide,
  7071. getCss,
  7072. reposition,
  7073. destroy
  7074. };
  7075. };
  7076. const isFakeCaretTableBrowser = () => Env.browser.isFirefox();
  7077. const isInlineFakeCaretTarget = node => isContentEditableFalse$7(node) || isMedia$1(node);
  7078. const isFakeCaretTarget = node => isInlineFakeCaretTarget(node) || isTable$3(node) && isFakeCaretTableBrowser();
  7079. const isContentEditableTrue$2 = isContentEditableTrue$4;
  7080. const isContentEditableFalse$6 = isContentEditableFalse$a;
  7081. const isMedia = isMedia$2;
  7082. const isBlockLike = matchStyleValues('display', 'block table table-cell table-caption list-item');
  7083. const isCaretContainer = isCaretContainer$2;
  7084. const isCaretContainerBlock = isCaretContainerBlock$1;
  7085. const isElement$2 = isElement$6;
  7086. const isCaretCandidate$1 = isCaretCandidate$3;
  7087. const isForwards = direction => direction > 0;
  7088. const isBackwards = direction => direction < 0;
  7089. const skipCaretContainers = (walk, shallow) => {
  7090. let node;
  7091. while (node = walk(shallow)) {
  7092. if (!isCaretContainerBlock(node)) {
  7093. return node;
  7094. }
  7095. }
  7096. return null;
  7097. };
  7098. const findNode = (node, direction, predicateFn, rootNode, shallow) => {
  7099. const walker = new DomTreeWalker(node, rootNode);
  7100. const isCefOrCaretContainer = isContentEditableFalse$6(node) || isCaretContainerBlock(node);
  7101. if (isBackwards(direction)) {
  7102. if (isCefOrCaretContainer) {
  7103. node = skipCaretContainers(walker.prev.bind(walker), true);
  7104. if (predicateFn(node)) {
  7105. return node;
  7106. }
  7107. }
  7108. while (node = skipCaretContainers(walker.prev.bind(walker), shallow)) {
  7109. if (predicateFn(node)) {
  7110. return node;
  7111. }
  7112. }
  7113. }
  7114. if (isForwards(direction)) {
  7115. if (isCefOrCaretContainer) {
  7116. node = skipCaretContainers(walker.next.bind(walker), true);
  7117. if (predicateFn(node)) {
  7118. return node;
  7119. }
  7120. }
  7121. while (node = skipCaretContainers(walker.next.bind(walker), shallow)) {
  7122. if (predicateFn(node)) {
  7123. return node;
  7124. }
  7125. }
  7126. }
  7127. return null;
  7128. };
  7129. const getEditingHost = (node, rootNode) => {
  7130. const isCETrue = node => isContentEditableTrue$2(node.dom);
  7131. const isRoot = node => node.dom === rootNode;
  7132. return ancestor$3(SugarElement.fromDom(node), isCETrue, isRoot).map(elm => elm.dom).getOr(rootNode);
  7133. };
  7134. const getParentBlock$3 = (node, rootNode) => {
  7135. while (node && node !== rootNode) {
  7136. if (isBlockLike(node)) {
  7137. return node;
  7138. }
  7139. node = node.parentNode;
  7140. }
  7141. return null;
  7142. };
  7143. const isInSameBlock = (caretPosition1, caretPosition2, rootNode) => getParentBlock$3(caretPosition1.container(), rootNode) === getParentBlock$3(caretPosition2.container(), rootNode);
  7144. const getChildNodeAtRelativeOffset = (relativeOffset, caretPosition) => {
  7145. if (!caretPosition) {
  7146. return null;
  7147. }
  7148. const container = caretPosition.container();
  7149. const offset = caretPosition.offset();
  7150. if (!isElement$2(container)) {
  7151. return null;
  7152. }
  7153. return container.childNodes[offset + relativeOffset];
  7154. };
  7155. const beforeAfter = (before, node) => {
  7156. const range = node.ownerDocument.createRange();
  7157. if (before) {
  7158. range.setStartBefore(node);
  7159. range.setEndBefore(node);
  7160. } else {
  7161. range.setStartAfter(node);
  7162. range.setEndAfter(node);
  7163. }
  7164. return range;
  7165. };
  7166. const isNodesInSameBlock = (root, node1, node2) => getParentBlock$3(node1, root) === getParentBlock$3(node2, root);
  7167. const lean = (left, root, node) => {
  7168. const siblingName = left ? 'previousSibling' : 'nextSibling';
  7169. while (node && node !== root) {
  7170. let sibling = node[siblingName];
  7171. if (isCaretContainer(sibling)) {
  7172. sibling = sibling[siblingName];
  7173. }
  7174. if (isContentEditableFalse$6(sibling) || isMedia(sibling)) {
  7175. if (isNodesInSameBlock(root, sibling, node)) {
  7176. return sibling;
  7177. }
  7178. break;
  7179. }
  7180. if (isCaretCandidate$1(sibling)) {
  7181. break;
  7182. }
  7183. node = node.parentNode;
  7184. }
  7185. return null;
  7186. };
  7187. const before$2 = curry(beforeAfter, true);
  7188. const after$2 = curry(beforeAfter, false);
  7189. const normalizeRange = (direction, root, range) => {
  7190. let node;
  7191. const leanLeft = curry(lean, true, root);
  7192. const leanRight = curry(lean, false, root);
  7193. let container = range.startContainer;
  7194. const offset = range.startOffset;
  7195. if (isCaretContainerBlock$1(container)) {
  7196. if (!isElement$2(container)) {
  7197. container = container.parentNode;
  7198. }
  7199. const location = container.getAttribute('data-mce-caret');
  7200. if (location === 'before') {
  7201. node = container.nextSibling;
  7202. if (isFakeCaretTarget(node)) {
  7203. return before$2(node);
  7204. }
  7205. }
  7206. if (location === 'after') {
  7207. node = container.previousSibling;
  7208. if (isFakeCaretTarget(node)) {
  7209. return after$2(node);
  7210. }
  7211. }
  7212. }
  7213. if (!range.collapsed) {
  7214. return range;
  7215. }
  7216. if (isText$8(container)) {
  7217. if (isCaretContainer(container)) {
  7218. if (direction === 1) {
  7219. node = leanRight(container);
  7220. if (node) {
  7221. return before$2(node);
  7222. }
  7223. node = leanLeft(container);
  7224. if (node) {
  7225. return after$2(node);
  7226. }
  7227. }
  7228. if (direction === -1) {
  7229. node = leanLeft(container);
  7230. if (node) {
  7231. return after$2(node);
  7232. }
  7233. node = leanRight(container);
  7234. if (node) {
  7235. return before$2(node);
  7236. }
  7237. }
  7238. return range;
  7239. }
  7240. if (endsWithCaretContainer$1(container) && offset >= container.data.length - 1) {
  7241. if (direction === 1) {
  7242. node = leanRight(container);
  7243. if (node) {
  7244. return before$2(node);
  7245. }
  7246. }
  7247. return range;
  7248. }
  7249. if (startsWithCaretContainer$1(container) && offset <= 1) {
  7250. if (direction === -1) {
  7251. node = leanLeft(container);
  7252. if (node) {
  7253. return after$2(node);
  7254. }
  7255. }
  7256. return range;
  7257. }
  7258. if (offset === container.data.length) {
  7259. node = leanRight(container);
  7260. if (node) {
  7261. return before$2(node);
  7262. }
  7263. return range;
  7264. }
  7265. if (offset === 0) {
  7266. node = leanLeft(container);
  7267. if (node) {
  7268. return after$2(node);
  7269. }
  7270. return range;
  7271. }
  7272. }
  7273. return range;
  7274. };
  7275. const getRelativeCefElm = (forward, caretPosition) => Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition)).filter(isContentEditableFalse$6);
  7276. const getNormalizedRangeEndPoint = (direction, root, range) => {
  7277. const normalizedRange = normalizeRange(direction, root, range);
  7278. if (direction === -1) {
  7279. return CaretPosition.fromRangeStart(normalizedRange);
  7280. }
  7281. return CaretPosition.fromRangeEnd(normalizedRange);
  7282. };
  7283. const getElementFromPosition = pos => Optional.from(pos.getNode()).map(SugarElement.fromDom);
  7284. const getElementFromPrevPosition = pos => Optional.from(pos.getNode(true)).map(SugarElement.fromDom);
  7285. const getVisualCaretPosition = (walkFn, caretPosition) => {
  7286. while (caretPosition = walkFn(caretPosition)) {
  7287. if (caretPosition.isVisible()) {
  7288. return caretPosition;
  7289. }
  7290. }
  7291. return caretPosition;
  7292. };
  7293. const isMoveInsideSameBlock = (from, to) => {
  7294. const inSameBlock = isInSameBlock(from, to);
  7295. if (!inSameBlock && isBr$5(from.getNode())) {
  7296. return true;
  7297. }
  7298. return inSameBlock;
  7299. };
  7300. var HDirection;
  7301. (function (HDirection) {
  7302. HDirection[HDirection['Backwards'] = -1] = 'Backwards';
  7303. HDirection[HDirection['Forwards'] = 1] = 'Forwards';
  7304. }(HDirection || (HDirection = {})));
  7305. const isContentEditableFalse$5 = isContentEditableFalse$a;
  7306. const isText$2 = isText$8;
  7307. const isElement$1 = isElement$6;
  7308. const isBr$1 = isBr$5;
  7309. const isCaretCandidate = isCaretCandidate$3;
  7310. const isAtomic = isAtomic$1;
  7311. const isEditableCaretCandidate = isEditableCaretCandidate$1;
  7312. const getParents$3 = (node, root) => {
  7313. const parents = [];
  7314. while (node && node !== root) {
  7315. parents.push(node);
  7316. node = node.parentNode;
  7317. }
  7318. return parents;
  7319. };
  7320. const nodeAtIndex = (container, offset) => {
  7321. if (container.hasChildNodes() && offset < container.childNodes.length) {
  7322. return container.childNodes[offset];
  7323. }
  7324. return null;
  7325. };
  7326. const getCaretCandidatePosition = (direction, node) => {
  7327. if (isForwards(direction)) {
  7328. if (isCaretCandidate(node.previousSibling) && !isText$2(node.previousSibling)) {
  7329. return CaretPosition.before(node);
  7330. }
  7331. if (isText$2(node)) {
  7332. return CaretPosition(node, 0);
  7333. }
  7334. }
  7335. if (isBackwards(direction)) {
  7336. if (isCaretCandidate(node.nextSibling) && !isText$2(node.nextSibling)) {
  7337. return CaretPosition.after(node);
  7338. }
  7339. if (isText$2(node)) {
  7340. return CaretPosition(node, node.data.length);
  7341. }
  7342. }
  7343. if (isBackwards(direction)) {
  7344. if (isBr$1(node)) {
  7345. return CaretPosition.before(node);
  7346. }
  7347. return CaretPosition.after(node);
  7348. }
  7349. return CaretPosition.before(node);
  7350. };
  7351. const moveForwardFromBr = (root, nextNode) => {
  7352. const nextSibling = nextNode.nextSibling;
  7353. if (nextSibling && isCaretCandidate(nextSibling)) {
  7354. if (isText$2(nextSibling)) {
  7355. return CaretPosition(nextSibling, 0);
  7356. } else {
  7357. return CaretPosition.before(nextSibling);
  7358. }
  7359. } else {
  7360. return findCaretPosition$1(HDirection.Forwards, CaretPosition.after(nextNode), root);
  7361. }
  7362. };
  7363. const findCaretPosition$1 = (direction, startPos, root) => {
  7364. let node;
  7365. let nextNode;
  7366. let innerNode;
  7367. let caretPosition;
  7368. if (!isElement$1(root) || !startPos) {
  7369. return null;
  7370. }
  7371. if (startPos.isEqual(CaretPosition.after(root)) && root.lastChild) {
  7372. caretPosition = CaretPosition.after(root.lastChild);
  7373. if (isBackwards(direction) && isCaretCandidate(root.lastChild) && isElement$1(root.lastChild)) {
  7374. return isBr$1(root.lastChild) ? CaretPosition.before(root.lastChild) : caretPosition;
  7375. }
  7376. } else {
  7377. caretPosition = startPos;
  7378. }
  7379. const container = caretPosition.container();
  7380. let offset = caretPosition.offset();
  7381. if (isText$2(container)) {
  7382. if (isBackwards(direction) && offset > 0) {
  7383. return CaretPosition(container, --offset);
  7384. }
  7385. if (isForwards(direction) && offset < container.length) {
  7386. return CaretPosition(container, ++offset);
  7387. }
  7388. node = container;
  7389. } else {
  7390. if (isBackwards(direction) && offset > 0) {
  7391. nextNode = nodeAtIndex(container, offset - 1);
  7392. if (isCaretCandidate(nextNode)) {
  7393. if (!isAtomic(nextNode)) {
  7394. innerNode = findNode(nextNode, direction, isEditableCaretCandidate, nextNode);
  7395. if (innerNode) {
  7396. if (isText$2(innerNode)) {
  7397. return CaretPosition(innerNode, innerNode.data.length);
  7398. }
  7399. return CaretPosition.after(innerNode);
  7400. }
  7401. }
  7402. if (isText$2(nextNode)) {
  7403. return CaretPosition(nextNode, nextNode.data.length);
  7404. }
  7405. return CaretPosition.before(nextNode);
  7406. }
  7407. }
  7408. if (isForwards(direction) && offset < container.childNodes.length) {
  7409. nextNode = nodeAtIndex(container, offset);
  7410. if (isCaretCandidate(nextNode)) {
  7411. if (isBr$1(nextNode)) {
  7412. return moveForwardFromBr(root, nextNode);
  7413. }
  7414. if (!isAtomic(nextNode)) {
  7415. innerNode = findNode(nextNode, direction, isEditableCaretCandidate, nextNode);
  7416. if (innerNode) {
  7417. if (isText$2(innerNode)) {
  7418. return CaretPosition(innerNode, 0);
  7419. }
  7420. return CaretPosition.before(innerNode);
  7421. }
  7422. }
  7423. if (isText$2(nextNode)) {
  7424. return CaretPosition(nextNode, 0);
  7425. }
  7426. return CaretPosition.after(nextNode);
  7427. }
  7428. }
  7429. node = nextNode ? nextNode : caretPosition.getNode();
  7430. }
  7431. if (isForwards(direction) && caretPosition.isAtEnd() || isBackwards(direction) && caretPosition.isAtStart()) {
  7432. node = findNode(node, direction, always, root, true);
  7433. if (isEditableCaretCandidate(node, root)) {
  7434. return getCaretCandidatePosition(direction, node);
  7435. }
  7436. }
  7437. nextNode = findNode(node, direction, isEditableCaretCandidate, root);
  7438. const rootContentEditableFalseElm = last$2(filter$6(getParents$3(container, root), isContentEditableFalse$5));
  7439. if (rootContentEditableFalseElm && (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
  7440. if (isForwards(direction)) {
  7441. caretPosition = CaretPosition.after(rootContentEditableFalseElm);
  7442. } else {
  7443. caretPosition = CaretPosition.before(rootContentEditableFalseElm);
  7444. }
  7445. return caretPosition;
  7446. }
  7447. if (nextNode) {
  7448. return getCaretCandidatePosition(direction, nextNode);
  7449. }
  7450. return null;
  7451. };
  7452. const CaretWalker = root => ({
  7453. next: caretPosition => {
  7454. return findCaretPosition$1(HDirection.Forwards, caretPosition, root);
  7455. },
  7456. prev: caretPosition => {
  7457. return findCaretPosition$1(HDirection.Backwards, caretPosition, root);
  7458. }
  7459. });
  7460. const walkToPositionIn = (forward, root, start) => {
  7461. const position = forward ? CaretPosition.before(start) : CaretPosition.after(start);
  7462. return fromPosition(forward, root, position);
  7463. };
  7464. const afterElement = node => isBr$5(node) ? CaretPosition.before(node) : CaretPosition.after(node);
  7465. const isBeforeOrStart = position => {
  7466. if (CaretPosition.isTextPosition(position)) {
  7467. return position.offset() === 0;
  7468. } else {
  7469. return isCaretCandidate$3(position.getNode());
  7470. }
  7471. };
  7472. const isAfterOrEnd = position => {
  7473. if (CaretPosition.isTextPosition(position)) {
  7474. const container = position.container();
  7475. return position.offset() === container.data.length;
  7476. } else {
  7477. return isCaretCandidate$3(position.getNode(true));
  7478. }
  7479. };
  7480. const isBeforeAfterSameElement = (from, to) => !CaretPosition.isTextPosition(from) && !CaretPosition.isTextPosition(to) && from.getNode() === to.getNode(true);
  7481. const isAtBr = position => !CaretPosition.isTextPosition(position) && isBr$5(position.getNode());
  7482. const shouldSkipPosition = (forward, from, to) => {
  7483. if (forward) {
  7484. return !isBeforeAfterSameElement(from, to) && !isAtBr(from) && isAfterOrEnd(from) && isBeforeOrStart(to);
  7485. } else {
  7486. return !isBeforeAfterSameElement(to, from) && isBeforeOrStart(from) && isAfterOrEnd(to);
  7487. }
  7488. };
  7489. const fromPosition = (forward, root, pos) => {
  7490. const walker = CaretWalker(root);
  7491. return Optional.from(forward ? walker.next(pos) : walker.prev(pos));
  7492. };
  7493. const navigate = (forward, root, from) => fromPosition(forward, root, from).bind(to => {
  7494. if (isInSameBlock(from, to, root) && shouldSkipPosition(forward, from, to)) {
  7495. return fromPosition(forward, root, to);
  7496. } else {
  7497. return Optional.some(to);
  7498. }
  7499. });
  7500. const navigateIgnore = (forward, root, from, ignoreFilter) => navigate(forward, root, from).bind(pos => ignoreFilter(pos) ? navigateIgnore(forward, root, pos, ignoreFilter) : Optional.some(pos));
  7501. const positionIn = (forward, element) => {
  7502. const startNode = forward ? element.firstChild : element.lastChild;
  7503. if (isText$8(startNode)) {
  7504. return Optional.some(CaretPosition(startNode, forward ? 0 : startNode.data.length));
  7505. } else if (startNode) {
  7506. if (isCaretCandidate$3(startNode)) {
  7507. return Optional.some(forward ? CaretPosition.before(startNode) : afterElement(startNode));
  7508. } else {
  7509. return walkToPositionIn(forward, element, startNode);
  7510. }
  7511. } else {
  7512. return Optional.none();
  7513. }
  7514. };
  7515. const nextPosition = curry(fromPosition, true);
  7516. const prevPosition = curry(fromPosition, false);
  7517. const firstPositionIn = curry(positionIn, true);
  7518. const lastPositionIn = curry(positionIn, false);
  7519. const CARET_ID$1 = '_mce_caret';
  7520. const isCaretNode = node => isElement$6(node) && node.id === CARET_ID$1;
  7521. const getParentCaretContainer = (body, node) => {
  7522. while (node && node !== body) {
  7523. if (node.id === CARET_ID$1) {
  7524. return node;
  7525. }
  7526. node = node.parentNode;
  7527. }
  7528. return null;
  7529. };
  7530. const isStringPathBookmark = bookmark => isString(bookmark.start);
  7531. const isRangeBookmark = bookmark => has$2(bookmark, 'rng');
  7532. const isIdBookmark = bookmark => has$2(bookmark, 'id');
  7533. const isIndexBookmark = bookmark => has$2(bookmark, 'name');
  7534. const isPathBookmark = bookmark => Tools.isArray(bookmark.start);
  7535. const addBogus = (dom, node) => {
  7536. if (isElement$6(node) && dom.isBlock(node) && !node.innerHTML) {
  7537. node.innerHTML = '<br data-mce-bogus="1" />';
  7538. }
  7539. return node;
  7540. };
  7541. const resolveCaretPositionBookmark = (dom, bookmark) => {
  7542. let pos;
  7543. const rng = dom.createRng();
  7544. pos = resolve$1(dom.getRoot(), bookmark.start);
  7545. rng.setStart(pos.container(), pos.offset());
  7546. pos = resolve$1(dom.getRoot(), bookmark.end);
  7547. rng.setEnd(pos.container(), pos.offset());
  7548. return rng;
  7549. };
  7550. const insertZwsp = (node, rng) => {
  7551. const textNode = node.ownerDocument.createTextNode(ZWSP$1);
  7552. node.appendChild(textNode);
  7553. rng.setStart(textNode, 0);
  7554. rng.setEnd(textNode, 0);
  7555. };
  7556. const isEmpty$1 = node => node.hasChildNodes() === false;
  7557. const tryFindRangePosition = (node, rng) => lastPositionIn(node).fold(never, pos => {
  7558. rng.setStart(pos.container(), pos.offset());
  7559. rng.setEnd(pos.container(), pos.offset());
  7560. return true;
  7561. });
  7562. const padEmptyCaretContainer = (root, node, rng) => {
  7563. if (isEmpty$1(node) && getParentCaretContainer(root, node)) {
  7564. insertZwsp(node, rng);
  7565. return true;
  7566. } else {
  7567. return false;
  7568. }
  7569. };
  7570. const setEndPoint = (dom, start, bookmark, rng) => {
  7571. const point = bookmark[start ? 'start' : 'end'];
  7572. let i, node, offset, children;
  7573. const root = dom.getRoot();
  7574. if (point) {
  7575. offset = point[0];
  7576. for (node = root, i = point.length - 1; i >= 1; i--) {
  7577. children = node.childNodes;
  7578. if (padEmptyCaretContainer(root, node, rng)) {
  7579. return true;
  7580. }
  7581. if (point[i] > children.length - 1) {
  7582. if (padEmptyCaretContainer(root, node, rng)) {
  7583. return true;
  7584. }
  7585. return tryFindRangePosition(node, rng);
  7586. }
  7587. node = children[point[i]];
  7588. }
  7589. if (node.nodeType === 3) {
  7590. offset = Math.min(point[0], node.nodeValue.length);
  7591. }
  7592. if (node.nodeType === 1) {
  7593. offset = Math.min(point[0], node.childNodes.length);
  7594. }
  7595. if (start) {
  7596. rng.setStart(node, offset);
  7597. } else {
  7598. rng.setEnd(node, offset);
  7599. }
  7600. }
  7601. return true;
  7602. };
  7603. const isValidTextNode = node => isText$8(node) && node.data.length > 0;
  7604. const restoreEndPoint = (dom, suffix, bookmark) => {
  7605. let marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev;
  7606. const keep = bookmark.keep;
  7607. let container, offset;
  7608. if (marker) {
  7609. node = marker.parentNode;
  7610. if (suffix === 'start') {
  7611. if (!keep) {
  7612. idx = dom.nodeIndex(marker);
  7613. } else {
  7614. if (marker.hasChildNodes()) {
  7615. node = marker.firstChild;
  7616. idx = 1;
  7617. } else if (isValidTextNode(marker.nextSibling)) {
  7618. node = marker.nextSibling;
  7619. idx = 0;
  7620. } else if (isValidTextNode(marker.previousSibling)) {
  7621. node = marker.previousSibling;
  7622. idx = marker.previousSibling.data.length;
  7623. } else {
  7624. node = marker.parentNode;
  7625. idx = dom.nodeIndex(marker) + 1;
  7626. }
  7627. }
  7628. container = node;
  7629. offset = idx;
  7630. } else {
  7631. if (!keep) {
  7632. idx = dom.nodeIndex(marker);
  7633. } else {
  7634. if (marker.hasChildNodes()) {
  7635. node = marker.firstChild;
  7636. idx = 1;
  7637. } else if (isValidTextNode(marker.previousSibling)) {
  7638. node = marker.previousSibling;
  7639. idx = marker.previousSibling.data.length;
  7640. } else {
  7641. node = marker.parentNode;
  7642. idx = dom.nodeIndex(marker);
  7643. }
  7644. }
  7645. container = node;
  7646. offset = idx;
  7647. }
  7648. if (!keep) {
  7649. prev = marker.previousSibling;
  7650. next = marker.nextSibling;
  7651. Tools.each(Tools.grep(marker.childNodes), node => {
  7652. if (isText$8(node)) {
  7653. node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
  7654. }
  7655. });
  7656. while (marker = dom.get(bookmark.id + '_' + suffix)) {
  7657. dom.remove(marker, true);
  7658. }
  7659. if (prev && next && prev.nodeType === next.nodeType && isText$8(prev) && !Env.browser.isOpera()) {
  7660. idx = prev.nodeValue.length;
  7661. prev.appendData(next.nodeValue);
  7662. dom.remove(next);
  7663. container = prev;
  7664. offset = idx;
  7665. }
  7666. }
  7667. return Optional.some(CaretPosition(container, offset));
  7668. } else {
  7669. return Optional.none();
  7670. }
  7671. };
  7672. const resolvePaths = (dom, bookmark) => {
  7673. const rng = dom.createRng();
  7674. if (setEndPoint(dom, true, bookmark, rng) && setEndPoint(dom, false, bookmark, rng)) {
  7675. return Optional.some(rng);
  7676. } else {
  7677. return Optional.none();
  7678. }
  7679. };
  7680. const resolveId = (dom, bookmark) => {
  7681. const startPos = restoreEndPoint(dom, 'start', bookmark);
  7682. const endPos = restoreEndPoint(dom, 'end', bookmark);
  7683. return lift2(startPos, endPos.or(startPos), (spos, epos) => {
  7684. const rng = dom.createRng();
  7685. rng.setStart(addBogus(dom, spos.container()), spos.offset());
  7686. rng.setEnd(addBogus(dom, epos.container()), epos.offset());
  7687. return rng;
  7688. });
  7689. };
  7690. const resolveIndex = (dom, bookmark) => Optional.from(dom.select(bookmark.name)[bookmark.index]).map(elm => {
  7691. const rng = dom.createRng();
  7692. rng.selectNode(elm);
  7693. return rng;
  7694. });
  7695. const resolve = (selection, bookmark) => {
  7696. const dom = selection.dom;
  7697. if (bookmark) {
  7698. if (isPathBookmark(bookmark)) {
  7699. return resolvePaths(dom, bookmark);
  7700. } else if (isStringPathBookmark(bookmark)) {
  7701. return Optional.some(resolveCaretPositionBookmark(dom, bookmark));
  7702. } else if (isIdBookmark(bookmark)) {
  7703. return resolveId(dom, bookmark);
  7704. } else if (isIndexBookmark(bookmark)) {
  7705. return resolveIndex(dom, bookmark);
  7706. } else if (isRangeBookmark(bookmark)) {
  7707. return Optional.some(bookmark.rng);
  7708. }
  7709. }
  7710. return Optional.none();
  7711. };
  7712. const getBookmark$1 = (selection, type, normalized) => {
  7713. return getBookmark$2(selection, type, normalized);
  7714. };
  7715. const moveToBookmark = (selection, bookmark) => {
  7716. resolve(selection, bookmark).each(rng => {
  7717. selection.setRng(rng);
  7718. });
  7719. };
  7720. const isBookmarkNode$1 = node => {
  7721. return isElement$6(node) && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
  7722. };
  7723. const is = expected => actual => expected === actual;
  7724. const isNbsp = is(nbsp);
  7725. const isWhiteSpace = chr => chr !== '' && ' \f\n\r\t\x0B'.indexOf(chr) !== -1;
  7726. const isContent = chr => !isWhiteSpace(chr) && !isNbsp(chr) && !isZwsp$1(chr);
  7727. const hexColour = value => ({ value });
  7728. const toHex = component => {
  7729. const hex = component.toString(16);
  7730. return (hex.length === 1 ? '0' + hex : hex).toUpperCase();
  7731. };
  7732. const fromRgba = rgbaColour => {
  7733. const value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue);
  7734. return hexColour(value);
  7735. };
  7736. const rgbRegex = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/i;
  7737. const rgbaRegex = /^\s*rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?(?:\.\d+)?)\s*\)\s*$/i;
  7738. const rgbaColour = (red, green, blue, alpha) => ({
  7739. red,
  7740. green,
  7741. blue,
  7742. alpha
  7743. });
  7744. const fromStringValues = (red, green, blue, alpha) => {
  7745. const r = parseInt(red, 10);
  7746. const g = parseInt(green, 10);
  7747. const b = parseInt(blue, 10);
  7748. const a = parseFloat(alpha);
  7749. return rgbaColour(r, g, b, a);
  7750. };
  7751. const fromString = rgbaString => {
  7752. if (rgbaString === 'transparent') {
  7753. return Optional.some(rgbaColour(0, 0, 0, 0));
  7754. }
  7755. const rgbMatch = rgbRegex.exec(rgbaString);
  7756. if (rgbMatch !== null) {
  7757. return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  7758. }
  7759. const rgbaMatch = rgbaRegex.exec(rgbaString);
  7760. if (rgbaMatch !== null) {
  7761. return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  7762. }
  7763. return Optional.none();
  7764. };
  7765. const rgbaToHexString = color => fromString(color).map(fromRgba).map(h => '#' + h.value).getOr(color);
  7766. const isNode = node => !!node.nodeType;
  7767. const isInlineBlock = node => {
  7768. return node && /^(IMG)$/.test(node.nodeName);
  7769. };
  7770. const moveStart = (dom, selection, rng) => {
  7771. const offset = rng.startOffset;
  7772. let container = rng.startContainer;
  7773. if (container === rng.endContainer) {
  7774. if (isInlineBlock(container.childNodes[offset])) {
  7775. return;
  7776. }
  7777. }
  7778. if (isElement$6(container)) {
  7779. const nodes = container.childNodes;
  7780. let walker;
  7781. if (offset < nodes.length) {
  7782. container = nodes[offset];
  7783. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  7784. } else {
  7785. container = nodes[nodes.length - 1];
  7786. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  7787. walker.next(true);
  7788. }
  7789. for (let node = walker.current(); node; node = walker.next()) {
  7790. if (isText$8(node) && !isWhiteSpaceNode$1(node)) {
  7791. rng.setStart(node, 0);
  7792. selection.setRng(rng);
  7793. return;
  7794. }
  7795. }
  7796. }
  7797. };
  7798. const getNonWhiteSpaceSibling = (node, next, inc) => {
  7799. if (node) {
  7800. const nextName = next ? 'nextSibling' : 'previousSibling';
  7801. for (node = inc ? node : node[nextName]; node; node = node[nextName]) {
  7802. if (isElement$6(node) || !isWhiteSpaceNode$1(node)) {
  7803. return node;
  7804. }
  7805. }
  7806. }
  7807. };
  7808. const isTextBlock$1 = (editor, name) => {
  7809. if (isNode(name)) {
  7810. name = name.nodeName;
  7811. }
  7812. return !!editor.schema.getTextBlockElements()[name.toLowerCase()];
  7813. };
  7814. const isValid = (ed, parent, child) => {
  7815. return ed.schema.isValidChild(parent, child);
  7816. };
  7817. const isWhiteSpaceNode$1 = (node, allowSpaces = false) => {
  7818. if (isNonNullable(node) && isText$8(node)) {
  7819. const data = allowSpaces ? node.data.replace(/ /g, '\xA0') : node.data;
  7820. return isWhitespaceText(data);
  7821. } else {
  7822. return false;
  7823. }
  7824. };
  7825. const isEmptyTextNode$1 = node => {
  7826. return isNonNullable(node) && isText$8(node) && node.length === 0;
  7827. };
  7828. const replaceVars = (value, vars) => {
  7829. if (isFunction(value)) {
  7830. value = value(vars);
  7831. } else if (isNonNullable(vars)) {
  7832. value = value.replace(/%(\w+)/g, (str, name) => {
  7833. return vars[name] || str;
  7834. });
  7835. }
  7836. return value;
  7837. };
  7838. const isEq$5 = (str1, str2) => {
  7839. str1 = str1 || '';
  7840. str2 = str2 || '';
  7841. str1 = '' + (str1.nodeName || str1);
  7842. str2 = '' + (str2.nodeName || str2);
  7843. return str1.toLowerCase() === str2.toLowerCase();
  7844. };
  7845. const normalizeStyleValue = (value, name) => {
  7846. if (name === 'color' || name === 'backgroundColor') {
  7847. value = rgbaToHexString(value);
  7848. }
  7849. if (name === 'fontWeight' && value === 700) {
  7850. value = 'bold';
  7851. }
  7852. if (name === 'fontFamily') {
  7853. value = value.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
  7854. }
  7855. return '' + value;
  7856. };
  7857. const getStyle = (dom, node, name) => {
  7858. return normalizeStyleValue(dom.getStyle(node, name), name);
  7859. };
  7860. const getTextDecoration = (dom, node) => {
  7861. let decoration;
  7862. dom.getParent(node, n => {
  7863. decoration = dom.getStyle(n, 'text-decoration');
  7864. return decoration && decoration !== 'none';
  7865. });
  7866. return decoration;
  7867. };
  7868. const getParents$2 = (dom, node, selector) => {
  7869. return dom.getParents(node, selector, dom.getRoot());
  7870. };
  7871. const isVariableFormatName = (editor, formatName) => {
  7872. const hasVariableValues = format => {
  7873. const isVariableValue = val => val.length > 1 && val.charAt(0) === '%';
  7874. return exists([
  7875. 'styles',
  7876. 'attributes'
  7877. ], key => get$a(format, key).exists(field => {
  7878. const fieldValues = isArray$1(field) ? field : values(field);
  7879. return exists(fieldValues, isVariableValue);
  7880. }));
  7881. };
  7882. return exists(editor.formatter.get(formatName), hasVariableValues);
  7883. };
  7884. const areSimilarFormats = (editor, formatName, otherFormatName) => {
  7885. const validKeys = [
  7886. 'inline',
  7887. 'block',
  7888. 'selector',
  7889. 'attributes',
  7890. 'styles',
  7891. 'classes'
  7892. ];
  7893. const filterObj = format => filter$5(format, (_, key) => exists(validKeys, validKey => validKey === key));
  7894. return exists(editor.formatter.get(formatName), fmt1 => {
  7895. const filteredFmt1 = filterObj(fmt1);
  7896. return exists(editor.formatter.get(otherFormatName), fmt2 => {
  7897. const filteredFmt2 = filterObj(fmt2);
  7898. return equal$1(filteredFmt1, filteredFmt2);
  7899. });
  7900. });
  7901. };
  7902. const isBlockFormat = format => hasNonNullableKey(format, 'block');
  7903. const isSelectorFormat = format => hasNonNullableKey(format, 'selector');
  7904. const isInlineFormat = format => hasNonNullableKey(format, 'inline');
  7905. const isMixedFormat = format => isSelectorFormat(format) && isInlineFormat(format) && is$2(get$a(format, 'mixed'), true);
  7906. const shouldExpandToSelector = format => isSelectorFormat(format) && format.expand !== false && !isInlineFormat(format);
  7907. const isBookmarkNode = isBookmarkNode$1;
  7908. const getParents$1 = getParents$2;
  7909. const isWhiteSpaceNode = isWhiteSpaceNode$1;
  7910. const isTextBlock = isTextBlock$1;
  7911. const isBogusBr = node => {
  7912. return isBr$5(node) && node.getAttribute('data-mce-bogus') && !node.nextSibling;
  7913. };
  7914. const findParentContentEditable = (dom, node) => {
  7915. let parent = node;
  7916. while (parent) {
  7917. if (isElement$6(parent) && dom.getContentEditable(parent)) {
  7918. return dom.getContentEditable(parent) === 'false' ? parent : node;
  7919. }
  7920. parent = parent.parentNode;
  7921. }
  7922. return node;
  7923. };
  7924. const walkText = (start, node, offset, predicate) => {
  7925. const str = node.data;
  7926. for (let i = offset; start ? i >= 0 : i < str.length; start ? i-- : i++) {
  7927. if (predicate(str.charAt(i))) {
  7928. return start ? i + 1 : i;
  7929. }
  7930. }
  7931. return -1;
  7932. };
  7933. const findSpace = (start, node, offset) => walkText(start, node, offset, c => isNbsp(c) || isWhiteSpace(c));
  7934. const findContent = (start, node, offset) => walkText(start, node, offset, isContent);
  7935. const findWordEndPoint = (dom, body, container, offset, start, includeTrailingSpaces) => {
  7936. let lastTextNode;
  7937. const rootNode = dom.getParent(container, dom.isBlock) || body;
  7938. const walk = (container, offset, pred) => {
  7939. const textSeeker = TextSeeker(dom);
  7940. const walker = start ? textSeeker.backwards : textSeeker.forwards;
  7941. return Optional.from(walker(container, offset, (text, textOffset) => {
  7942. if (isBookmarkNode(text.parentNode)) {
  7943. return -1;
  7944. } else {
  7945. lastTextNode = text;
  7946. return pred(start, text, textOffset);
  7947. }
  7948. }, rootNode));
  7949. };
  7950. const spaceResult = walk(container, offset, findSpace);
  7951. return spaceResult.bind(result => includeTrailingSpaces ? walk(result.container, result.offset + (start ? -1 : 0), findContent) : Optional.some(result)).orThunk(() => lastTextNode ? Optional.some({
  7952. container: lastTextNode,
  7953. offset: start ? 0 : lastTextNode.length
  7954. }) : Optional.none());
  7955. };
  7956. const findSelectorEndPoint = (dom, formatList, rng, container, siblingName) => {
  7957. if (isText$8(container) && isEmpty$3(container.data) && container[siblingName]) {
  7958. container = container[siblingName];
  7959. }
  7960. const parents = getParents$1(dom, container);
  7961. for (let i = 0; i < parents.length; i++) {
  7962. for (let y = 0; y < formatList.length; y++) {
  7963. const curFormat = formatList[y];
  7964. if (isNonNullable(curFormat.collapsed) && curFormat.collapsed !== rng.collapsed) {
  7965. continue;
  7966. }
  7967. if (isSelectorFormat(curFormat) && dom.is(parents[i], curFormat.selector)) {
  7968. return parents[i];
  7969. }
  7970. }
  7971. }
  7972. return container;
  7973. };
  7974. const findBlockEndPoint = (editor, formatList, container, siblingName) => {
  7975. let node = container;
  7976. const dom = editor.dom;
  7977. const root = dom.getRoot();
  7978. const format = formatList[0];
  7979. if (isBlockFormat(format)) {
  7980. node = format.wrapper ? null : dom.getParent(container, format.block, root);
  7981. }
  7982. if (!node) {
  7983. const scopeRoot = dom.getParent(container, 'LI,TD,TH');
  7984. node = dom.getParent(isText$8(container) ? container.parentNode : container, node => node !== root && isTextBlock(editor, node), scopeRoot);
  7985. }
  7986. if (node && isBlockFormat(format) && format.wrapper) {
  7987. node = getParents$1(dom, node, 'ul,ol').reverse()[0] || node;
  7988. }
  7989. if (!node) {
  7990. node = container;
  7991. while (node[siblingName] && !dom.isBlock(node[siblingName])) {
  7992. node = node[siblingName];
  7993. if (isEq$5(node, 'br')) {
  7994. break;
  7995. }
  7996. }
  7997. }
  7998. return node || container;
  7999. };
  8000. const isAtBlockBoundary$1 = (dom, root, container, siblingName) => {
  8001. const parent = container.parentNode;
  8002. if (isNonNullable(container[siblingName])) {
  8003. return false;
  8004. } else if (parent === root || isNullable(parent) || dom.isBlock(parent)) {
  8005. return true;
  8006. } else {
  8007. return isAtBlockBoundary$1(dom, root, parent, siblingName);
  8008. }
  8009. };
  8010. const findParentContainer = (dom, formatList, container, offset, start) => {
  8011. let parent = container;
  8012. const siblingName = start ? 'previousSibling' : 'nextSibling';
  8013. const root = dom.getRoot();
  8014. if (isText$8(container) && !isWhiteSpaceNode(container)) {
  8015. if (start ? offset > 0 : offset < container.data.length) {
  8016. return container;
  8017. }
  8018. }
  8019. while (true) {
  8020. if (!formatList[0].block_expand && dom.isBlock(parent)) {
  8021. return parent;
  8022. }
  8023. for (let sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
  8024. const allowSpaces = isText$8(sibling) && !isAtBlockBoundary$1(dom, root, sibling, siblingName);
  8025. if (!isBookmarkNode(sibling) && !isBogusBr(sibling) && !isWhiteSpaceNode(sibling, allowSpaces)) {
  8026. return parent;
  8027. }
  8028. }
  8029. if (parent === root || parent.parentNode === root) {
  8030. container = parent;
  8031. break;
  8032. }
  8033. parent = parent.parentNode;
  8034. }
  8035. return container;
  8036. };
  8037. const isSelfOrParentBookmark = container => isBookmarkNode(container.parentNode) || isBookmarkNode(container);
  8038. const expandRng = (editor, rng, formatList, includeTrailingSpace = false) => {
  8039. let {startContainer, startOffset, endContainer, endOffset} = rng;
  8040. const dom = editor.dom;
  8041. const format = formatList[0];
  8042. if (isElement$6(startContainer) && startContainer.hasChildNodes()) {
  8043. startContainer = getNode$1(startContainer, startOffset);
  8044. if (isText$8(startContainer)) {
  8045. startOffset = 0;
  8046. }
  8047. }
  8048. if (isElement$6(endContainer) && endContainer.hasChildNodes()) {
  8049. endContainer = getNode$1(endContainer, rng.collapsed ? endOffset : endOffset - 1);
  8050. if (isText$8(endContainer)) {
  8051. endOffset = endContainer.nodeValue.length;
  8052. }
  8053. }
  8054. startContainer = findParentContentEditable(dom, startContainer);
  8055. endContainer = findParentContentEditable(dom, endContainer);
  8056. if (isSelfOrParentBookmark(startContainer)) {
  8057. startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
  8058. if (rng.collapsed) {
  8059. startContainer = startContainer.previousSibling || startContainer;
  8060. } else {
  8061. startContainer = startContainer.nextSibling || startContainer;
  8062. }
  8063. if (isText$8(startContainer)) {
  8064. startOffset = rng.collapsed ? startContainer.length : 0;
  8065. }
  8066. }
  8067. if (isSelfOrParentBookmark(endContainer)) {
  8068. endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
  8069. if (rng.collapsed) {
  8070. endContainer = endContainer.nextSibling || endContainer;
  8071. } else {
  8072. endContainer = endContainer.previousSibling || endContainer;
  8073. }
  8074. if (isText$8(endContainer)) {
  8075. endOffset = rng.collapsed ? 0 : endContainer.length;
  8076. }
  8077. }
  8078. if (rng.collapsed) {
  8079. const startPoint = findWordEndPoint(dom, editor.getBody(), startContainer, startOffset, true, includeTrailingSpace);
  8080. startPoint.each(({container, offset}) => {
  8081. startContainer = container;
  8082. startOffset = offset;
  8083. });
  8084. const endPoint = findWordEndPoint(dom, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
  8085. endPoint.each(({container, offset}) => {
  8086. endContainer = container;
  8087. endOffset = offset;
  8088. });
  8089. }
  8090. if (isInlineFormat(format) || format.block_expand) {
  8091. if (!isInlineFormat(format) || (!isText$8(startContainer) || startOffset === 0)) {
  8092. startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  8093. }
  8094. if (!isInlineFormat(format) || (!isText$8(endContainer) || endOffset === endContainer.nodeValue.length)) {
  8095. endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  8096. }
  8097. }
  8098. if (shouldExpandToSelector(format)) {
  8099. startContainer = findSelectorEndPoint(dom, formatList, rng, startContainer, 'previousSibling');
  8100. endContainer = findSelectorEndPoint(dom, formatList, rng, endContainer, 'nextSibling');
  8101. }
  8102. if (isBlockFormat(format) || isSelectorFormat(format)) {
  8103. startContainer = findBlockEndPoint(editor, formatList, startContainer, 'previousSibling');
  8104. endContainer = findBlockEndPoint(editor, formatList, endContainer, 'nextSibling');
  8105. if (isBlockFormat(format)) {
  8106. if (!dom.isBlock(startContainer)) {
  8107. startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  8108. }
  8109. if (!dom.isBlock(endContainer)) {
  8110. endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  8111. }
  8112. }
  8113. }
  8114. if (isElement$6(startContainer)) {
  8115. startOffset = dom.nodeIndex(startContainer);
  8116. startContainer = startContainer.parentNode;
  8117. }
  8118. if (isElement$6(endContainer)) {
  8119. endOffset = dom.nodeIndex(endContainer) + 1;
  8120. endContainer = endContainer.parentNode;
  8121. }
  8122. return {
  8123. startContainer,
  8124. startOffset,
  8125. endContainer,
  8126. endOffset
  8127. };
  8128. };
  8129. const walk$3 = (dom, rng, callback) => {
  8130. const startOffset = rng.startOffset;
  8131. const startContainer = getNode$1(rng.startContainer, startOffset);
  8132. const endOffset = rng.endOffset;
  8133. const endContainer = getNode$1(rng.endContainer, endOffset - 1);
  8134. const exclude = nodes => {
  8135. const firstNode = nodes[0];
  8136. if (isText$8(firstNode) && firstNode === startContainer && startOffset >= firstNode.data.length) {
  8137. nodes.splice(0, 1);
  8138. }
  8139. const lastNode = nodes[nodes.length - 1];
  8140. if (endOffset === 0 && nodes.length > 0 && lastNode === endContainer && isText$8(lastNode)) {
  8141. nodes.splice(nodes.length - 1, 1);
  8142. }
  8143. return nodes;
  8144. };
  8145. const collectSiblings = (node, name, endNode) => {
  8146. const siblings = [];
  8147. for (; node && node !== endNode; node = node[name]) {
  8148. siblings.push(node);
  8149. }
  8150. return siblings;
  8151. };
  8152. const findEndPoint = (node, root) => dom.getParent(node, node => node.parentNode === root, root);
  8153. const walkBoundary = (startNode, endNode, next) => {
  8154. const siblingName = next ? 'nextSibling' : 'previousSibling';
  8155. for (let node = startNode, parent = node.parentNode; node && node !== endNode; node = parent) {
  8156. parent = node.parentNode;
  8157. const siblings = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
  8158. if (siblings.length) {
  8159. if (!next) {
  8160. siblings.reverse();
  8161. }
  8162. callback(exclude(siblings));
  8163. }
  8164. }
  8165. };
  8166. if (startContainer === endContainer) {
  8167. return callback(exclude([startContainer]));
  8168. }
  8169. const ancestor = dom.findCommonAncestor(startContainer, endContainer);
  8170. if (dom.isChildOf(startContainer, endContainer)) {
  8171. return walkBoundary(startContainer, ancestor, true);
  8172. }
  8173. if (dom.isChildOf(endContainer, startContainer)) {
  8174. return walkBoundary(endContainer, ancestor);
  8175. }
  8176. const startPoint = findEndPoint(startContainer, ancestor) || startContainer;
  8177. const endPoint = findEndPoint(endContainer, ancestor) || endContainer;
  8178. walkBoundary(startContainer, startPoint, true);
  8179. const siblings = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint === endContainer ? endPoint.nextSibling : endPoint);
  8180. if (siblings.length) {
  8181. callback(exclude(siblings));
  8182. }
  8183. walkBoundary(endContainer, endPoint);
  8184. };
  8185. const getRanges$1 = selection => {
  8186. const ranges = [];
  8187. if (selection) {
  8188. for (let i = 0; i < selection.rangeCount; i++) {
  8189. ranges.push(selection.getRangeAt(i));
  8190. }
  8191. }
  8192. return ranges;
  8193. };
  8194. const getSelectedNodes = ranges => {
  8195. return bind$3(ranges, range => {
  8196. const node = getSelectedNode(range);
  8197. return node ? [SugarElement.fromDom(node)] : [];
  8198. });
  8199. };
  8200. const hasMultipleRanges = selection => {
  8201. return getRanges$1(selection).length > 1;
  8202. };
  8203. const getCellsFromRanges = ranges => filter$6(getSelectedNodes(ranges), isTableCell$4);
  8204. const getCellsFromElement = elm => descendants(elm, 'td[data-mce-selected],th[data-mce-selected]');
  8205. const getCellsFromElementOrRanges = (ranges, element) => {
  8206. const selectedCells = getCellsFromElement(element);
  8207. return selectedCells.length > 0 ? selectedCells : getCellsFromRanges(ranges);
  8208. };
  8209. const getCellsFromEditor = editor => getCellsFromElementOrRanges(getRanges$1(editor.selection.getSel()), SugarElement.fromDom(editor.getBody()));
  8210. const getClosestTable = (cell, isRoot) => ancestor$2(cell, 'table', isRoot);
  8211. const getStartNode = rng => {
  8212. const sc = rng.startContainer, so = rng.startOffset;
  8213. if (isText$8(sc)) {
  8214. return so === 0 ? Optional.some(SugarElement.fromDom(sc)) : Optional.none();
  8215. } else {
  8216. return Optional.from(sc.childNodes[so]).map(SugarElement.fromDom);
  8217. }
  8218. };
  8219. const getEndNode = rng => {
  8220. const ec = rng.endContainer, eo = rng.endOffset;
  8221. if (isText$8(ec)) {
  8222. return eo === ec.data.length ? Optional.some(SugarElement.fromDom(ec)) : Optional.none();
  8223. } else {
  8224. return Optional.from(ec.childNodes[eo - 1]).map(SugarElement.fromDom);
  8225. }
  8226. };
  8227. const getFirstChildren = node => {
  8228. return firstChild(node).fold(constant([node]), child => {
  8229. return [node].concat(getFirstChildren(child));
  8230. });
  8231. };
  8232. const getLastChildren$1 = node => {
  8233. return lastChild(node).fold(constant([node]), child => {
  8234. if (name(child) === 'br') {
  8235. return prevSibling(child).map(sibling => {
  8236. return [node].concat(getLastChildren$1(sibling));
  8237. }).getOr([]);
  8238. } else {
  8239. return [node].concat(getLastChildren$1(child));
  8240. }
  8241. });
  8242. };
  8243. const hasAllContentsSelected = (elm, rng) => {
  8244. return lift2(getStartNode(rng), getEndNode(rng), (startNode, endNode) => {
  8245. const start = find$2(getFirstChildren(elm), curry(eq, startNode));
  8246. const end = find$2(getLastChildren$1(elm), curry(eq, endNode));
  8247. return start.isSome() && end.isSome();
  8248. }).getOr(false);
  8249. };
  8250. const moveEndPoint = (dom, rng, node, start) => {
  8251. const root = node, walker = new DomTreeWalker(node, root);
  8252. const moveCaretBeforeOnEnterElementsMap = filter$5(dom.schema.getMoveCaretBeforeOnEnterElements(), (_, name) => !contains$2([
  8253. 'td',
  8254. 'th',
  8255. 'table'
  8256. ], name.toLowerCase()));
  8257. do {
  8258. if (isText$8(node) && Tools.trim(node.nodeValue).length !== 0) {
  8259. if (start) {
  8260. rng.setStart(node, 0);
  8261. } else {
  8262. rng.setEnd(node, node.nodeValue.length);
  8263. }
  8264. return;
  8265. }
  8266. if (moveCaretBeforeOnEnterElementsMap[node.nodeName]) {
  8267. if (start) {
  8268. rng.setStartBefore(node);
  8269. } else {
  8270. if (node.nodeName === 'BR') {
  8271. rng.setEndBefore(node);
  8272. } else {
  8273. rng.setEndAfter(node);
  8274. }
  8275. }
  8276. return;
  8277. }
  8278. } while (node = start ? walker.next() : walker.prev());
  8279. if (root.nodeName === 'BODY') {
  8280. if (start) {
  8281. rng.setStart(root, 0);
  8282. } else {
  8283. rng.setEnd(root, root.childNodes.length);
  8284. }
  8285. }
  8286. };
  8287. const hasAnyRanges = editor => {
  8288. const sel = editor.selection.getSel();
  8289. return sel && sel.rangeCount > 0;
  8290. };
  8291. const runOnRanges = (editor, executor) => {
  8292. const fakeSelectionNodes = getCellsFromEditor(editor);
  8293. if (fakeSelectionNodes.length > 0) {
  8294. each$g(fakeSelectionNodes, elem => {
  8295. const node = elem.dom;
  8296. const fakeNodeRng = editor.dom.createRng();
  8297. fakeNodeRng.setStartBefore(node);
  8298. fakeNodeRng.setEndAfter(node);
  8299. executor(fakeNodeRng, true);
  8300. });
  8301. } else {
  8302. executor(editor.selection.getRng(), false);
  8303. }
  8304. };
  8305. const preserve = (selection, fillBookmark, executor) => {
  8306. const bookmark = getPersistentBookmark(selection, fillBookmark);
  8307. executor(bookmark);
  8308. selection.moveToBookmark(bookmark);
  8309. };
  8310. const NodeValue = (is, name) => {
  8311. const get = element => {
  8312. if (!is(element)) {
  8313. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  8314. }
  8315. return getOption(element).getOr('');
  8316. };
  8317. const getOption = element => is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  8318. const set = (element, value) => {
  8319. if (!is(element)) {
  8320. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  8321. }
  8322. element.dom.nodeValue = value;
  8323. };
  8324. return {
  8325. get,
  8326. getOption,
  8327. set
  8328. };
  8329. };
  8330. const api$1 = NodeValue(isText$9, 'text');
  8331. const get$3 = element => api$1.get(element);
  8332. const getOption = element => api$1.getOption(element);
  8333. const isZeroWidth = elem => isText$9(elem) && get$3(elem) === ZWSP$1;
  8334. const context = (editor, elem, wrapName, nodeName) => parent(elem).fold(() => 'skipping', parent => {
  8335. if (nodeName === 'br' || isZeroWidth(elem)) {
  8336. return 'valid';
  8337. } else if (isAnnotation(elem)) {
  8338. return 'existing';
  8339. } else if (isCaretNode(elem.dom)) {
  8340. return 'caret';
  8341. } else if (!isValid(editor, wrapName, nodeName) || !isValid(editor, name(parent), wrapName)) {
  8342. return 'invalid-child';
  8343. } else {
  8344. return 'valid';
  8345. }
  8346. });
  8347. const applyWordGrab = (editor, rng) => {
  8348. const r = expandRng(editor, rng, [{ inline: 'span' }]);
  8349. rng.setStart(r.startContainer, r.startOffset);
  8350. rng.setEnd(r.endContainer, r.endOffset);
  8351. editor.selection.setRng(rng);
  8352. };
  8353. const makeAnnotation = (eDoc, {uid = generate$1('mce-annotation'), ...data}, annotationName, decorate) => {
  8354. const master = SugarElement.fromTag('span', eDoc);
  8355. add$2(master, annotation());
  8356. set$2(master, `${ dataAnnotationId() }`, uid);
  8357. set$2(master, `${ dataAnnotation() }`, annotationName);
  8358. const {attributes = {}, classes = []} = decorate(uid, data);
  8359. setAll$1(master, attributes);
  8360. add(master, classes);
  8361. return master;
  8362. };
  8363. const annotate = (editor, rng, annotationName, decorate, data) => {
  8364. const newWrappers = [];
  8365. const master = makeAnnotation(editor.getDoc(), data, annotationName, decorate);
  8366. const wrapper = value$2();
  8367. const finishWrapper = () => {
  8368. wrapper.clear();
  8369. };
  8370. const getOrOpenWrapper = () => wrapper.get().getOrThunk(() => {
  8371. const nu = shallow$1(master);
  8372. newWrappers.push(nu);
  8373. wrapper.set(nu);
  8374. return nu;
  8375. });
  8376. const processElements = elems => {
  8377. each$g(elems, processElement);
  8378. };
  8379. const processElement = elem => {
  8380. const ctx = context(editor, elem, 'span', name(elem));
  8381. switch (ctx) {
  8382. case 'invalid-child': {
  8383. finishWrapper();
  8384. const children$1 = children(elem);
  8385. processElements(children$1);
  8386. finishWrapper();
  8387. break;
  8388. }
  8389. case 'valid': {
  8390. const w = getOrOpenWrapper();
  8391. wrap$2(elem, w);
  8392. break;
  8393. }
  8394. }
  8395. };
  8396. const processNodes = nodes => {
  8397. const elems = map$3(nodes, SugarElement.fromDom);
  8398. processElements(elems);
  8399. };
  8400. walk$3(editor.dom, rng, nodes => {
  8401. finishWrapper();
  8402. processNodes(nodes);
  8403. });
  8404. return newWrappers;
  8405. };
  8406. const annotateWithBookmark = (editor, name, settings, data) => {
  8407. editor.undoManager.transact(() => {
  8408. const selection = editor.selection;
  8409. const initialRng = selection.getRng();
  8410. const hasFakeSelection = getCellsFromEditor(editor).length > 0;
  8411. if (initialRng.collapsed && !hasFakeSelection) {
  8412. applyWordGrab(editor, initialRng);
  8413. }
  8414. if (selection.getRng().collapsed && !hasFakeSelection) {
  8415. const wrapper = makeAnnotation(editor.getDoc(), data, name, settings.decorate);
  8416. set(wrapper, nbsp);
  8417. selection.getRng().insertNode(wrapper.dom);
  8418. selection.select(wrapper.dom);
  8419. } else {
  8420. preserve(selection, false, () => {
  8421. runOnRanges(editor, selectionRng => {
  8422. annotate(editor, selectionRng, name, settings.decorate, data);
  8423. });
  8424. });
  8425. }
  8426. });
  8427. };
  8428. const Annotator = editor => {
  8429. const registry = create$b();
  8430. setup$w(editor, registry);
  8431. const changes = setup$x(editor, registry);
  8432. return {
  8433. register: (name, settings) => {
  8434. registry.register(name, settings);
  8435. },
  8436. annotate: (name, data) => {
  8437. registry.lookup(name).each(settings => {
  8438. annotateWithBookmark(editor, name, settings, data);
  8439. });
  8440. },
  8441. annotationChanged: (name, callback) => {
  8442. changes.addListener(name, callback);
  8443. },
  8444. remove: name => {
  8445. const bookmark = editor.selection.getBookmark();
  8446. identify(editor, Optional.some(name)).each(({elements}) => {
  8447. each$g(elements, unwrap);
  8448. });
  8449. editor.selection.moveToBookmark(bookmark);
  8450. },
  8451. removeAll: name => {
  8452. const bookmark = editor.selection.getBookmark();
  8453. each$f(findAll(editor, name), (spans, _) => each$g(spans, unwrap));
  8454. editor.selection.moveToBookmark(bookmark);
  8455. },
  8456. getAll: name => {
  8457. const directory = findAll(editor, name);
  8458. return map$2(directory, elems => map$3(elems, elem => elem.dom));
  8459. }
  8460. };
  8461. };
  8462. const BookmarkManager = selection => {
  8463. return {
  8464. getBookmark: curry(getBookmark$1, selection),
  8465. moveToBookmark: curry(moveToBookmark, selection)
  8466. };
  8467. };
  8468. BookmarkManager.isBookmarkNode = isBookmarkNode$1;
  8469. const isXYWithinRange = (clientX, clientY, range) => {
  8470. if (range.collapsed) {
  8471. return false;
  8472. } else {
  8473. return exists(range.getClientRects(), rect => containsXY(rect, clientX, clientY));
  8474. }
  8475. };
  8476. const firePreProcess = (editor, args) => editor.dispatch('PreProcess', args);
  8477. const firePostProcess = (editor, args) => editor.dispatch('PostProcess', args);
  8478. const fireRemove = editor => editor.dispatch('remove');
  8479. const fireDetach = editor => editor.dispatch('detach');
  8480. const fireSwitchMode = (editor, mode) => editor.dispatch('SwitchMode', { mode });
  8481. const fireObjectResizeStart = (editor, target, width, height, origin) => {
  8482. editor.dispatch('ObjectResizeStart', {
  8483. target,
  8484. width,
  8485. height,
  8486. origin
  8487. });
  8488. };
  8489. const fireObjectResized = (editor, target, width, height, origin) => {
  8490. editor.dispatch('ObjectResized', {
  8491. target,
  8492. width,
  8493. height,
  8494. origin
  8495. });
  8496. };
  8497. const firePreInit = editor => editor.dispatch('PreInit');
  8498. const firePostRender = editor => editor.dispatch('PostRender');
  8499. const fireInit = editor => editor.dispatch('Init');
  8500. const firePlaceholderToggle = (editor, state) => editor.dispatch('PlaceholderToggle', { state });
  8501. const fireError = (editor, errorType, error) => editor.dispatch(errorType, error);
  8502. const fireFormatApply = (editor, format, node, vars) => editor.dispatch('FormatApply', {
  8503. format,
  8504. node,
  8505. vars
  8506. });
  8507. const fireFormatRemove = (editor, format, node, vars) => editor.dispatch('FormatRemove', {
  8508. format,
  8509. node,
  8510. vars
  8511. });
  8512. const fireBeforeSetContent = (editor, args) => editor.dispatch('BeforeSetContent', args);
  8513. const fireSetContent = (editor, args) => editor.dispatch('SetContent', args);
  8514. const fireBeforeGetContent = (editor, args) => editor.dispatch('BeforeGetContent', args);
  8515. const fireGetContent = (editor, args) => editor.dispatch('GetContent', args);
  8516. const fireAutocompleterStart = (editor, args) => editor.dispatch('AutocompleterStart', args);
  8517. const fireAutocompleterUpdate = (editor, args) => editor.dispatch('AutocompleterUpdate', args);
  8518. const fireAutocompleterEnd = editor => editor.dispatch('AutocompleterEnd');
  8519. const firePastePreProcess = (editor, html, internal) => editor.dispatch('PastePreProcess', {
  8520. content: html,
  8521. internal
  8522. });
  8523. const firePastePostProcess = (editor, node, internal) => editor.dispatch('PastePostProcess', {
  8524. node,
  8525. internal
  8526. });
  8527. const firePastePlainTextToggle = (editor, state) => editor.dispatch('PastePlainTextToggle', { state });
  8528. const VK = {
  8529. BACKSPACE: 8,
  8530. DELETE: 46,
  8531. DOWN: 40,
  8532. ENTER: 13,
  8533. ESC: 27,
  8534. LEFT: 37,
  8535. RIGHT: 39,
  8536. SPACEBAR: 32,
  8537. TAB: 9,
  8538. UP: 38,
  8539. PAGE_UP: 33,
  8540. PAGE_DOWN: 34,
  8541. END: 35,
  8542. HOME: 36,
  8543. modifierPressed: e => {
  8544. return e.shiftKey || e.ctrlKey || e.altKey || VK.metaKeyPressed(e);
  8545. },
  8546. metaKeyPressed: e => {
  8547. return Env.os.isMacOS() || Env.os.isiOS() ? e.metaKey : e.ctrlKey && !e.altKey;
  8548. }
  8549. };
  8550. const ControlSelection = (selection, editor) => {
  8551. const elementSelectionAttr = 'data-mce-selected';
  8552. const dom = editor.dom, each = Tools.each;
  8553. let selectedElm, selectedElmGhost, resizeHelper, selectedHandle, resizeBackdrop;
  8554. let startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
  8555. let width, height;
  8556. const editableDoc = editor.getDoc(), rootDocument = document;
  8557. const abs = Math.abs, round = Math.round, rootElement = editor.getBody();
  8558. let startScrollWidth, startScrollHeight;
  8559. const resizeHandles = {
  8560. nw: [
  8561. 0,
  8562. 0,
  8563. -1,
  8564. -1
  8565. ],
  8566. ne: [
  8567. 1,
  8568. 0,
  8569. 1,
  8570. -1
  8571. ],
  8572. se: [
  8573. 1,
  8574. 1,
  8575. 1,
  8576. 1
  8577. ],
  8578. sw: [
  8579. 0,
  8580. 1,
  8581. -1,
  8582. 1
  8583. ]
  8584. };
  8585. const isImage = elm => isNonNullable(elm) && (isImg(elm) || editor.dom.is(elm, 'figure.image'));
  8586. const isMedia = elm => isMedia$2(elm) || dom.hasClass(elm, 'mce-preview-object');
  8587. const isEventOnImageOutsideRange = (evt, range) => {
  8588. if (evt.type === 'longpress' || evt.type.indexOf('touch') === 0) {
  8589. const touch = evt.touches[0];
  8590. return isImage(evt.target) && !isXYWithinRange(touch.clientX, touch.clientY, range);
  8591. } else {
  8592. return isImage(evt.target) && !isXYWithinRange(evt.clientX, evt.clientY, range);
  8593. }
  8594. };
  8595. const contextMenuSelectImage = evt => {
  8596. const target = evt.target;
  8597. if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) && !evt.isDefaultPrevented()) {
  8598. editor.selection.select(target);
  8599. }
  8600. };
  8601. const getResizeTargets = elm => {
  8602. if (dom.is(elm, 'figure.image')) {
  8603. return [elm.querySelector('img')];
  8604. } else if (dom.hasClass(elm, 'mce-preview-object') && isNonNullable(elm.firstElementChild)) {
  8605. return [
  8606. elm,
  8607. elm.firstElementChild
  8608. ];
  8609. } else {
  8610. return [elm];
  8611. }
  8612. };
  8613. const isResizable = elm => {
  8614. const selector = getObjectResizing(editor);
  8615. if (!selector) {
  8616. return false;
  8617. }
  8618. if (elm.getAttribute('data-mce-resize') === 'false') {
  8619. return false;
  8620. }
  8621. if (elm === editor.getBody()) {
  8622. return false;
  8623. }
  8624. if (dom.hasClass(elm, 'mce-preview-object')) {
  8625. return is$1(SugarElement.fromDom(elm.firstElementChild), selector);
  8626. } else {
  8627. return is$1(SugarElement.fromDom(elm), selector);
  8628. }
  8629. };
  8630. const createGhostElement = elm => {
  8631. if (isMedia(elm)) {
  8632. return dom.create('img', { src: Env.transparentSrc });
  8633. } else {
  8634. return elm.cloneNode(true);
  8635. }
  8636. };
  8637. const setSizeProp = (element, name, value) => {
  8638. if (isNonNullable(value)) {
  8639. const targets = getResizeTargets(element);
  8640. each$g(targets, target => {
  8641. if (target.style[name] || !editor.schema.isValid(target.nodeName.toLowerCase(), name)) {
  8642. dom.setStyle(target, name, value);
  8643. } else {
  8644. dom.setAttrib(target, name, '' + value);
  8645. }
  8646. });
  8647. }
  8648. };
  8649. const setGhostElmSize = (ghostElm, width, height) => {
  8650. setSizeProp(ghostElm, 'width', width);
  8651. setSizeProp(ghostElm, 'height', height);
  8652. };
  8653. const resizeGhostElement = e => {
  8654. let deltaX, deltaY, proportional;
  8655. let resizeHelperX, resizeHelperY;
  8656. deltaX = e.screenX - startX;
  8657. deltaY = e.screenY - startY;
  8658. width = deltaX * selectedHandle[2] + startW;
  8659. height = deltaY * selectedHandle[3] + startH;
  8660. width = width < 5 ? 5 : width;
  8661. height = height < 5 ? 5 : height;
  8662. if ((isImage(selectedElm) || isMedia(selectedElm)) && getResizeImgProportional(editor) !== false) {
  8663. proportional = !VK.modifierPressed(e);
  8664. } else {
  8665. proportional = VK.modifierPressed(e);
  8666. }
  8667. if (proportional) {
  8668. if (abs(deltaX) > abs(deltaY)) {
  8669. height = round(width * ratio);
  8670. width = round(height / ratio);
  8671. } else {
  8672. width = round(height / ratio);
  8673. height = round(width * ratio);
  8674. }
  8675. }
  8676. setGhostElmSize(selectedElmGhost, width, height);
  8677. resizeHelperX = selectedHandle.startPos.x + deltaX;
  8678. resizeHelperY = selectedHandle.startPos.y + deltaY;
  8679. resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
  8680. resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
  8681. dom.setStyles(resizeHelper, {
  8682. left: resizeHelperX,
  8683. top: resizeHelperY,
  8684. display: 'block'
  8685. });
  8686. resizeHelper.innerHTML = width + ' &times; ' + height;
  8687. if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
  8688. dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
  8689. }
  8690. if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
  8691. dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
  8692. }
  8693. deltaX = rootElement.scrollWidth - startScrollWidth;
  8694. deltaY = rootElement.scrollHeight - startScrollHeight;
  8695. if (deltaX + deltaY !== 0) {
  8696. dom.setStyles(resizeHelper, {
  8697. left: resizeHelperX - deltaX,
  8698. top: resizeHelperY - deltaY
  8699. });
  8700. }
  8701. if (!resizeStarted) {
  8702. fireObjectResizeStart(editor, selectedElm, startW, startH, 'corner-' + selectedHandle.name);
  8703. resizeStarted = true;
  8704. }
  8705. };
  8706. const endGhostResize = () => {
  8707. const wasResizeStarted = resizeStarted;
  8708. resizeStarted = false;
  8709. if (wasResizeStarted) {
  8710. setSizeProp(selectedElm, 'width', width);
  8711. setSizeProp(selectedElm, 'height', height);
  8712. }
  8713. dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
  8714. dom.unbind(editableDoc, 'mouseup', endGhostResize);
  8715. if (rootDocument !== editableDoc) {
  8716. dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
  8717. dom.unbind(rootDocument, 'mouseup', endGhostResize);
  8718. }
  8719. dom.remove(selectedElmGhost);
  8720. dom.remove(resizeHelper);
  8721. dom.remove(resizeBackdrop);
  8722. showResizeRect(selectedElm);
  8723. if (wasResizeStarted) {
  8724. fireObjectResized(editor, selectedElm, width, height, 'corner-' + selectedHandle.name);
  8725. dom.setAttrib(selectedElm, 'style', dom.getAttrib(selectedElm, 'style'));
  8726. }
  8727. editor.nodeChanged();
  8728. };
  8729. const showResizeRect = targetElm => {
  8730. unbindResizeHandleEvents();
  8731. const position = dom.getPos(targetElm, rootElement);
  8732. const selectedElmX = position.x;
  8733. const selectedElmY = position.y;
  8734. const rect = targetElm.getBoundingClientRect();
  8735. const targetWidth = rect.width || rect.right - rect.left;
  8736. const targetHeight = rect.height || rect.bottom - rect.top;
  8737. if (selectedElm !== targetElm) {
  8738. hideResizeRect();
  8739. selectedElm = targetElm;
  8740. width = height = 0;
  8741. }
  8742. const e = editor.dispatch('ObjectSelected', { target: targetElm });
  8743. const selectedValue = dom.getAttrib(selectedElm, elementSelectionAttr, '1');
  8744. if (isResizable(targetElm) && !e.isDefaultPrevented()) {
  8745. each(resizeHandles, (handle, name) => {
  8746. let handleElm;
  8747. const startDrag = e => {
  8748. const target = getResizeTargets(selectedElm)[0];
  8749. startX = e.screenX;
  8750. startY = e.screenY;
  8751. startW = target.clientWidth;
  8752. startH = target.clientHeight;
  8753. ratio = startH / startW;
  8754. selectedHandle = handle;
  8755. selectedHandle.name = name;
  8756. selectedHandle.startPos = {
  8757. x: targetWidth * handle[0] + selectedElmX,
  8758. y: targetHeight * handle[1] + selectedElmY
  8759. };
  8760. startScrollWidth = rootElement.scrollWidth;
  8761. startScrollHeight = rootElement.scrollHeight;
  8762. resizeBackdrop = dom.add(rootElement, 'div', {
  8763. 'class': 'mce-resize-backdrop',
  8764. 'data-mce-bogus': 'all'
  8765. });
  8766. dom.setStyles(resizeBackdrop, {
  8767. position: 'fixed',
  8768. left: '0',
  8769. top: '0',
  8770. width: '100%',
  8771. height: '100%'
  8772. });
  8773. selectedElmGhost = createGhostElement(selectedElm);
  8774. dom.addClass(selectedElmGhost, 'mce-clonedresizable');
  8775. dom.setAttrib(selectedElmGhost, 'data-mce-bogus', 'all');
  8776. selectedElmGhost.contentEditable = 'false';
  8777. dom.setStyles(selectedElmGhost, {
  8778. left: selectedElmX,
  8779. top: selectedElmY,
  8780. margin: 0
  8781. });
  8782. setGhostElmSize(selectedElmGhost, targetWidth, targetHeight);
  8783. selectedElmGhost.removeAttribute(elementSelectionAttr);
  8784. rootElement.appendChild(selectedElmGhost);
  8785. dom.bind(editableDoc, 'mousemove', resizeGhostElement);
  8786. dom.bind(editableDoc, 'mouseup', endGhostResize);
  8787. if (rootDocument !== editableDoc) {
  8788. dom.bind(rootDocument, 'mousemove', resizeGhostElement);
  8789. dom.bind(rootDocument, 'mouseup', endGhostResize);
  8790. }
  8791. resizeHelper = dom.add(rootElement, 'div', {
  8792. 'class': 'mce-resize-helper',
  8793. 'data-mce-bogus': 'all'
  8794. }, startW + ' &times; ' + startH);
  8795. };
  8796. handleElm = dom.get('mceResizeHandle' + name);
  8797. if (handleElm) {
  8798. dom.remove(handleElm);
  8799. }
  8800. handleElm = dom.add(rootElement, 'div', {
  8801. 'id': 'mceResizeHandle' + name,
  8802. 'data-mce-bogus': 'all',
  8803. 'class': 'mce-resizehandle',
  8804. 'unselectable': true,
  8805. 'style': 'cursor:' + name + '-resize; margin:0; padding:0'
  8806. });
  8807. dom.bind(handleElm, 'mousedown', e => {
  8808. e.stopImmediatePropagation();
  8809. e.preventDefault();
  8810. startDrag(e);
  8811. });
  8812. handle.elm = handleElm;
  8813. dom.setStyles(handleElm, {
  8814. left: targetWidth * handle[0] + selectedElmX - handleElm.offsetWidth / 2,
  8815. top: targetHeight * handle[1] + selectedElmY - handleElm.offsetHeight / 2
  8816. });
  8817. });
  8818. } else {
  8819. hideResizeRect();
  8820. }
  8821. if (!dom.getAttrib(selectedElm, elementSelectionAttr)) {
  8822. selectedElm.setAttribute(elementSelectionAttr, selectedValue);
  8823. }
  8824. };
  8825. const hideResizeRect = () => {
  8826. unbindResizeHandleEvents();
  8827. if (selectedElm) {
  8828. selectedElm.removeAttribute(elementSelectionAttr);
  8829. }
  8830. each$f(resizeHandles, (value, name) => {
  8831. const handleElm = dom.get('mceResizeHandle' + name);
  8832. if (handleElm) {
  8833. dom.unbind(handleElm);
  8834. dom.remove(handleElm);
  8835. }
  8836. });
  8837. };
  8838. const updateResizeRect = e => {
  8839. var _a;
  8840. let startElm, controlElm;
  8841. const isChildOrEqual = (node, parent) => {
  8842. if (node) {
  8843. do {
  8844. if (node === parent) {
  8845. return true;
  8846. }
  8847. } while (node = node.parentNode);
  8848. }
  8849. };
  8850. if (resizeStarted || editor.removed) {
  8851. return;
  8852. }
  8853. each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), img => {
  8854. img.removeAttribute(elementSelectionAttr);
  8855. });
  8856. controlElm = e.type === 'mousedown' ? e.target : selection.getNode();
  8857. controlElm = (_a = closest$3(SugarElement.fromDom(controlElm), 'table,img,figure.image,hr,video,span.mce-preview-object').getOrUndefined()) === null || _a === void 0 ? void 0 : _a.dom;
  8858. if (isChildOrEqual(controlElm, rootElement)) {
  8859. disableGeckoResize();
  8860. startElm = selection.getStart(true);
  8861. if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
  8862. showResizeRect(controlElm);
  8863. return;
  8864. }
  8865. }
  8866. hideResizeRect();
  8867. };
  8868. const unbindResizeHandleEvents = () => {
  8869. each$f(resizeHandles, handle => {
  8870. if (handle.elm) {
  8871. dom.unbind(handle.elm);
  8872. delete handle.elm;
  8873. }
  8874. });
  8875. };
  8876. const disableGeckoResize = () => {
  8877. try {
  8878. editor.getDoc().execCommand('enableObjectResizing', false, 'false');
  8879. } catch (ex) {
  8880. }
  8881. };
  8882. editor.on('init', () => {
  8883. disableGeckoResize();
  8884. const throttledUpdateResizeRect = first$1(e => {
  8885. if (!editor.composing) {
  8886. updateResizeRect(e);
  8887. }
  8888. }, 0);
  8889. editor.on('nodechange ResizeEditor ResizeWindow ResizeContent drop FullscreenStateChanged', throttledUpdateResizeRect.throttle);
  8890. editor.on('keyup compositionend', e => {
  8891. if (selectedElm && selectedElm.nodeName === 'TABLE') {
  8892. throttledUpdateResizeRect.throttle(e);
  8893. }
  8894. });
  8895. editor.on('hide blur', hideResizeRect);
  8896. editor.on('contextmenu longpress', contextMenuSelectImage, true);
  8897. });
  8898. editor.on('remove', unbindResizeHandleEvents);
  8899. const destroy = () => {
  8900. selectedElm = selectedElmGhost = resizeBackdrop = null;
  8901. };
  8902. return {
  8903. isResizable,
  8904. showResizeRect,
  8905. hideResizeRect,
  8906. updateResizeRect,
  8907. destroy
  8908. };
  8909. };
  8910. const setStart = (rng, situ) => {
  8911. situ.fold(e => {
  8912. rng.setStartBefore(e.dom);
  8913. }, (e, o) => {
  8914. rng.setStart(e.dom, o);
  8915. }, e => {
  8916. rng.setStartAfter(e.dom);
  8917. });
  8918. };
  8919. const setFinish = (rng, situ) => {
  8920. situ.fold(e => {
  8921. rng.setEndBefore(e.dom);
  8922. }, (e, o) => {
  8923. rng.setEnd(e.dom, o);
  8924. }, e => {
  8925. rng.setEndAfter(e.dom);
  8926. });
  8927. };
  8928. const relativeToNative = (win, startSitu, finishSitu) => {
  8929. const range = win.document.createRange();
  8930. setStart(range, startSitu);
  8931. setFinish(range, finishSitu);
  8932. return range;
  8933. };
  8934. const exactToNative = (win, start, soffset, finish, foffset) => {
  8935. const rng = win.document.createRange();
  8936. rng.setStart(start.dom, soffset);
  8937. rng.setEnd(finish.dom, foffset);
  8938. return rng;
  8939. };
  8940. const adt$3 = Adt.generate([
  8941. {
  8942. ltr: [
  8943. 'start',
  8944. 'soffset',
  8945. 'finish',
  8946. 'foffset'
  8947. ]
  8948. },
  8949. {
  8950. rtl: [
  8951. 'start',
  8952. 'soffset',
  8953. 'finish',
  8954. 'foffset'
  8955. ]
  8956. }
  8957. ]);
  8958. const fromRange = (win, type, range) => type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  8959. const getRanges = (win, selection) => selection.match({
  8960. domRange: rng => {
  8961. return {
  8962. ltr: constant(rng),
  8963. rtl: Optional.none
  8964. };
  8965. },
  8966. relative: (startSitu, finishSitu) => {
  8967. return {
  8968. ltr: cached(() => relativeToNative(win, startSitu, finishSitu)),
  8969. rtl: cached(() => Optional.some(relativeToNative(win, finishSitu, startSitu)))
  8970. };
  8971. },
  8972. exact: (start, soffset, finish, foffset) => {
  8973. return {
  8974. ltr: cached(() => exactToNative(win, start, soffset, finish, foffset)),
  8975. rtl: cached(() => Optional.some(exactToNative(win, finish, foffset, start, soffset)))
  8976. };
  8977. }
  8978. });
  8979. const doDiagnose = (win, ranges) => {
  8980. const rng = ranges.ltr();
  8981. if (rng.collapsed) {
  8982. const reversed = ranges.rtl().filter(rev => rev.collapsed === false);
  8983. return reversed.map(rev => adt$3.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset)).getOrThunk(() => fromRange(win, adt$3.ltr, rng));
  8984. } else {
  8985. return fromRange(win, adt$3.ltr, rng);
  8986. }
  8987. };
  8988. const diagnose = (win, selection) => {
  8989. const ranges = getRanges(win, selection);
  8990. return doDiagnose(win, ranges);
  8991. };
  8992. adt$3.ltr;
  8993. adt$3.rtl;
  8994. const create$9 = (start, soffset, finish, foffset) => ({
  8995. start,
  8996. soffset,
  8997. finish,
  8998. foffset
  8999. });
  9000. const SimRange = { create: create$9 };
  9001. const caretPositionFromPoint = (doc, x, y) => {
  9002. var _a, _b;
  9003. return Optional.from((_b = (_a = doc.dom).caretPositionFromPoint) === null || _b === void 0 ? void 0 : _b.call(_a, x, y)).bind(pos => {
  9004. if (pos.offsetNode === null) {
  9005. return Optional.none();
  9006. }
  9007. const r = doc.dom.createRange();
  9008. r.setStart(pos.offsetNode, pos.offset);
  9009. r.collapse();
  9010. return Optional.some(r);
  9011. });
  9012. };
  9013. const caretRangeFromPoint = (doc, x, y) => {
  9014. var _a, _b;
  9015. return Optional.from((_b = (_a = doc.dom).caretRangeFromPoint) === null || _b === void 0 ? void 0 : _b.call(_a, x, y));
  9016. };
  9017. const availableSearch = (() => {
  9018. if (document.caretPositionFromPoint) {
  9019. return caretPositionFromPoint;
  9020. } else if (document.caretRangeFromPoint) {
  9021. return caretRangeFromPoint;
  9022. } else {
  9023. return Optional.none;
  9024. }
  9025. })();
  9026. const fromPoint$1 = (win, x, y) => {
  9027. const doc = SugarElement.fromDom(win.document);
  9028. return availableSearch(doc, x, y).map(rng => SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset));
  9029. };
  9030. const adt$2 = Adt.generate([
  9031. { before: ['element'] },
  9032. {
  9033. on: [
  9034. 'element',
  9035. 'offset'
  9036. ]
  9037. },
  9038. { after: ['element'] }
  9039. ]);
  9040. const cata = (subject, onBefore, onOn, onAfter) => subject.fold(onBefore, onOn, onAfter);
  9041. const getStart$2 = situ => situ.fold(identity, identity, identity);
  9042. const before$1 = adt$2.before;
  9043. const on = adt$2.on;
  9044. const after$1 = adt$2.after;
  9045. const Situ = {
  9046. before: before$1,
  9047. on,
  9048. after: after$1,
  9049. cata,
  9050. getStart: getStart$2
  9051. };
  9052. const adt$1 = Adt.generate([
  9053. { domRange: ['rng'] },
  9054. {
  9055. relative: [
  9056. 'startSitu',
  9057. 'finishSitu'
  9058. ]
  9059. },
  9060. {
  9061. exact: [
  9062. 'start',
  9063. 'soffset',
  9064. 'finish',
  9065. 'foffset'
  9066. ]
  9067. }
  9068. ]);
  9069. const exactFromRange = simRange => adt$1.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  9070. const getStart$1 = selection => selection.match({
  9071. domRange: rng => SugarElement.fromDom(rng.startContainer),
  9072. relative: (startSitu, _finishSitu) => Situ.getStart(startSitu),
  9073. exact: (start, _soffset, _finish, _foffset) => start
  9074. });
  9075. const domRange = adt$1.domRange;
  9076. const relative = adt$1.relative;
  9077. const exact = adt$1.exact;
  9078. const getWin = selection => {
  9079. const start = getStart$1(selection);
  9080. return defaultView(start);
  9081. };
  9082. const range = SimRange.create;
  9083. const SimSelection = {
  9084. domRange,
  9085. relative,
  9086. exact,
  9087. exactFromRange,
  9088. getWin,
  9089. range
  9090. };
  9091. const beforeSpecial = (element, offset) => {
  9092. const name$1 = name(element);
  9093. if ('input' === name$1) {
  9094. return Situ.after(element);
  9095. } else if (!contains$2([
  9096. 'br',
  9097. 'img'
  9098. ], name$1)) {
  9099. return Situ.on(element, offset);
  9100. } else {
  9101. return offset === 0 ? Situ.before(element) : Situ.after(element);
  9102. }
  9103. };
  9104. const preprocessRelative = (startSitu, finishSitu) => {
  9105. const start = startSitu.fold(Situ.before, beforeSpecial, Situ.after);
  9106. const finish = finishSitu.fold(Situ.before, beforeSpecial, Situ.after);
  9107. return SimSelection.relative(start, finish);
  9108. };
  9109. const preprocessExact = (start, soffset, finish, foffset) => {
  9110. const startSitu = beforeSpecial(start, soffset);
  9111. const finishSitu = beforeSpecial(finish, foffset);
  9112. return SimSelection.relative(startSitu, finishSitu);
  9113. };
  9114. const preprocess = selection => selection.match({
  9115. domRange: rng => {
  9116. const start = SugarElement.fromDom(rng.startContainer);
  9117. const finish = SugarElement.fromDom(rng.endContainer);
  9118. return preprocessExact(start, rng.startOffset, finish, rng.endOffset);
  9119. },
  9120. relative: preprocessRelative,
  9121. exact: preprocessExact
  9122. });
  9123. const fromElements = (elements, scope) => {
  9124. const doc = scope || document;
  9125. const fragment = doc.createDocumentFragment();
  9126. each$g(elements, element => {
  9127. fragment.appendChild(element.dom);
  9128. });
  9129. return SugarElement.fromDom(fragment);
  9130. };
  9131. const toNative = selection => {
  9132. const win = SimSelection.getWin(selection).dom;
  9133. const getDomRange = (start, soffset, finish, foffset) => exactToNative(win, start, soffset, finish, foffset);
  9134. const filtered = preprocess(selection);
  9135. return diagnose(win, filtered).match({
  9136. ltr: getDomRange,
  9137. rtl: getDomRange
  9138. });
  9139. };
  9140. const getAtPoint = (win, x, y) => fromPoint$1(win, x, y);
  9141. const fromPoint = (clientX, clientY, doc) => getAtPoint(doc.defaultView, clientX, clientY).map(simRange => {
  9142. const rng = doc.createRange();
  9143. rng.setStart(simRange.start.dom, simRange.soffset);
  9144. rng.setEnd(simRange.finish.dom, simRange.foffset);
  9145. return rng;
  9146. }).getOrUndefined();
  9147. const isEq$4 = (rng1, rng2) => {
  9148. return rng1 && rng2 && (rng1.startContainer === rng2.startContainer && rng1.startOffset === rng2.startOffset) && (rng1.endContainer === rng2.endContainer && rng1.endOffset === rng2.endOffset);
  9149. };
  9150. const findParent = (node, rootNode, predicate) => {
  9151. while (node && node !== rootNode) {
  9152. if (predicate(node)) {
  9153. return node;
  9154. }
  9155. node = node.parentNode;
  9156. }
  9157. return null;
  9158. };
  9159. const hasParent$1 = (node, rootNode, predicate) => findParent(node, rootNode, predicate) !== null;
  9160. const hasParentWithName = (node, rootNode, name) => hasParent$1(node, rootNode, node => {
  9161. return node.nodeName === name;
  9162. });
  9163. const isTable = node => node && node.nodeName === 'TABLE';
  9164. const isTableCell$2 = node => node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  9165. const isCeFalseCaretContainer = (node, rootNode) => isCaretContainer$2(node) && hasParent$1(node, rootNode, isCaretNode) === false;
  9166. const hasBrBeforeAfter = (dom, node, left) => {
  9167. const walker = new DomTreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || dom.getRoot());
  9168. while (node = walker[left ? 'prev' : 'next']()) {
  9169. if (isBr$5(node)) {
  9170. return true;
  9171. }
  9172. }
  9173. };
  9174. const isPrevNode = (node, name) => node.previousSibling && node.previousSibling.nodeName === name;
  9175. const hasContentEditableFalseParent = (body, node) => {
  9176. while (node && node !== body) {
  9177. if (isContentEditableFalse$a(node)) {
  9178. return true;
  9179. }
  9180. node = node.parentNode;
  9181. }
  9182. return false;
  9183. };
  9184. const findTextNodeRelative = (dom, isAfterNode, collapsed, left, startNode) => {
  9185. let lastInlineElement;
  9186. const body = dom.getRoot();
  9187. let node;
  9188. const nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  9189. const parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body;
  9190. if (left && isBr$5(startNode) && isAfterNode && dom.isEmpty(parentBlockContainer)) {
  9191. return Optional.some(CaretPosition(startNode.parentNode, dom.nodeIndex(startNode)));
  9192. }
  9193. const walker = new DomTreeWalker(startNode, parentBlockContainer);
  9194. while (node = walker[left ? 'prev' : 'next']()) {
  9195. if (dom.getContentEditableParent(node) === 'false' || isCeFalseCaretContainer(node, body)) {
  9196. return Optional.none();
  9197. }
  9198. if (isText$8(node) && node.nodeValue.length > 0) {
  9199. if (hasParentWithName(node, body, 'A') === false) {
  9200. return Optional.some(CaretPosition(node, left ? node.nodeValue.length : 0));
  9201. }
  9202. return Optional.none();
  9203. }
  9204. if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  9205. return Optional.none();
  9206. }
  9207. lastInlineElement = node;
  9208. }
  9209. if (collapsed && lastInlineElement) {
  9210. return Optional.some(CaretPosition(lastInlineElement, 0));
  9211. }
  9212. return Optional.none();
  9213. };
  9214. const normalizeEndPoint = (dom, collapsed, start, rng) => {
  9215. let container, offset;
  9216. const body = dom.getRoot();
  9217. let node;
  9218. let directionLeft, normalized = false;
  9219. container = rng[(start ? 'start' : 'end') + 'Container'];
  9220. offset = rng[(start ? 'start' : 'end') + 'Offset'];
  9221. const isAfterNode = isElement$6(container) && offset === container.childNodes.length;
  9222. const nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  9223. directionLeft = start;
  9224. if (isCaretContainer$2(container)) {
  9225. return Optional.none();
  9226. }
  9227. if (isElement$6(container) && offset > container.childNodes.length - 1) {
  9228. directionLeft = false;
  9229. }
  9230. if (isDocument$1(container)) {
  9231. container = body;
  9232. offset = 0;
  9233. }
  9234. if (container === body) {
  9235. if (directionLeft) {
  9236. node = container.childNodes[offset > 0 ? offset - 1 : 0];
  9237. if (node) {
  9238. if (isCaretContainer$2(node)) {
  9239. return Optional.none();
  9240. }
  9241. if (nonEmptyElementsMap[node.nodeName] || isTable(node)) {
  9242. return Optional.none();
  9243. }
  9244. }
  9245. }
  9246. if (container.hasChildNodes()) {
  9247. offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
  9248. container = container.childNodes[offset];
  9249. offset = isText$8(container) && isAfterNode ? container.data.length : 0;
  9250. if (!collapsed && container === body.lastChild && isTable(container)) {
  9251. return Optional.none();
  9252. }
  9253. if (hasContentEditableFalseParent(body, container) || isCaretContainer$2(container)) {
  9254. return Optional.none();
  9255. }
  9256. if (container.hasChildNodes() && isTable(container) === false) {
  9257. node = container;
  9258. const walker = new DomTreeWalker(container, body);
  9259. do {
  9260. if (isContentEditableFalse$a(node) || isCaretContainer$2(node)) {
  9261. normalized = false;
  9262. break;
  9263. }
  9264. if (isText$8(node) && node.nodeValue.length > 0) {
  9265. offset = directionLeft ? 0 : node.nodeValue.length;
  9266. container = node;
  9267. normalized = true;
  9268. break;
  9269. }
  9270. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCell$2(node)) {
  9271. offset = dom.nodeIndex(node);
  9272. container = node.parentNode;
  9273. if (!directionLeft) {
  9274. offset++;
  9275. }
  9276. normalized = true;
  9277. break;
  9278. }
  9279. } while (node = directionLeft ? walker.next() : walker.prev());
  9280. }
  9281. }
  9282. }
  9283. if (collapsed) {
  9284. if (isText$8(container) && offset === 0) {
  9285. findTextNodeRelative(dom, isAfterNode, collapsed, true, container).each(pos => {
  9286. container = pos.container();
  9287. offset = pos.offset();
  9288. normalized = true;
  9289. });
  9290. }
  9291. if (isElement$6(container)) {
  9292. node = container.childNodes[offset];
  9293. if (!node) {
  9294. node = container.childNodes[offset - 1];
  9295. }
  9296. if (node && isBr$5(node) && !isPrevNode(node, 'A') && !hasBrBeforeAfter(dom, node, false) && !hasBrBeforeAfter(dom, node, true)) {
  9297. findTextNodeRelative(dom, isAfterNode, collapsed, true, node).each(pos => {
  9298. container = pos.container();
  9299. offset = pos.offset();
  9300. normalized = true;
  9301. });
  9302. }
  9303. }
  9304. }
  9305. if (directionLeft && !collapsed && isText$8(container) && offset === container.nodeValue.length) {
  9306. findTextNodeRelative(dom, isAfterNode, collapsed, false, container).each(pos => {
  9307. container = pos.container();
  9308. offset = pos.offset();
  9309. normalized = true;
  9310. });
  9311. }
  9312. return normalized ? Optional.some(CaretPosition(container, offset)) : Optional.none();
  9313. };
  9314. const normalize$2 = (dom, rng) => {
  9315. const collapsed = rng.collapsed, normRng = rng.cloneRange();
  9316. const startPos = CaretPosition.fromRangeStart(rng);
  9317. normalizeEndPoint(dom, collapsed, true, normRng).each(pos => {
  9318. if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
  9319. normRng.setStart(pos.container(), pos.offset());
  9320. }
  9321. });
  9322. if (!collapsed) {
  9323. normalizeEndPoint(dom, collapsed, false, normRng).each(pos => {
  9324. normRng.setEnd(pos.container(), pos.offset());
  9325. });
  9326. }
  9327. if (collapsed) {
  9328. normRng.collapse(true);
  9329. }
  9330. return isEq$4(rng, normRng) ? Optional.none() : Optional.some(normRng);
  9331. };
  9332. const splitText = (node, offset) => {
  9333. return node.splitText(offset);
  9334. };
  9335. const split = rng => {
  9336. let startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  9337. if (startContainer === endContainer && isText$8(startContainer)) {
  9338. if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  9339. endContainer = splitText(startContainer, startOffset);
  9340. startContainer = endContainer.previousSibling;
  9341. if (endOffset > startOffset) {
  9342. endOffset = endOffset - startOffset;
  9343. startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
  9344. endOffset = endContainer.nodeValue.length;
  9345. startOffset = 0;
  9346. } else {
  9347. endOffset = 0;
  9348. }
  9349. }
  9350. } else {
  9351. if (isText$8(startContainer) && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  9352. startContainer = splitText(startContainer, startOffset);
  9353. startOffset = 0;
  9354. }
  9355. if (isText$8(endContainer) && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
  9356. endContainer = splitText(endContainer, endOffset).previousSibling;
  9357. endOffset = endContainer.nodeValue.length;
  9358. }
  9359. }
  9360. return {
  9361. startContainer,
  9362. startOffset,
  9363. endContainer,
  9364. endOffset
  9365. };
  9366. };
  9367. const RangeUtils = dom => {
  9368. const walk = (rng, callback) => {
  9369. return walk$3(dom, rng, callback);
  9370. };
  9371. const split$1 = split;
  9372. const normalize = rng => {
  9373. return normalize$2(dom, rng).fold(never, normalizedRng => {
  9374. rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
  9375. rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
  9376. return true;
  9377. });
  9378. };
  9379. return {
  9380. walk,
  9381. split: split$1,
  9382. normalize
  9383. };
  9384. };
  9385. RangeUtils.compareRanges = isEq$4;
  9386. RangeUtils.getCaretRangeFromPoint = fromPoint;
  9387. RangeUtils.getSelectedNode = getSelectedNode;
  9388. RangeUtils.getNode = getNode$1;
  9389. const Dimension = (name, getOffset) => {
  9390. const set = (element, h) => {
  9391. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  9392. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  9393. }
  9394. const dom = element.dom;
  9395. if (isSupported$1(dom)) {
  9396. dom.style[name] = h + 'px';
  9397. }
  9398. };
  9399. const get = element => {
  9400. const r = getOffset(element);
  9401. if (r <= 0 || r === null) {
  9402. const css = get$7(element, name);
  9403. return parseFloat(css) || 0;
  9404. }
  9405. return r;
  9406. };
  9407. const getOuter = get;
  9408. const aggregate = (element, properties) => foldl(properties, (acc, property) => {
  9409. const val = get$7(element, property);
  9410. const value = val === undefined ? 0 : parseInt(val, 10);
  9411. return isNaN(value) ? acc : acc + value;
  9412. }, 0);
  9413. const max = (element, value, properties) => {
  9414. const cumulativeInclusions = aggregate(element, properties);
  9415. const absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  9416. return absoluteMax;
  9417. };
  9418. return {
  9419. set,
  9420. get,
  9421. getOuter,
  9422. aggregate,
  9423. max
  9424. };
  9425. };
  9426. const api = Dimension('height', element => {
  9427. const dom = element.dom;
  9428. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  9429. });
  9430. const get$2 = element => api.get(element);
  9431. const getDocument = () => SugarElement.fromDom(document);
  9432. const walkUp = (navigation, doc) => {
  9433. const frame = navigation.view(doc);
  9434. return frame.fold(constant([]), f => {
  9435. const parent = navigation.owner(f);
  9436. const rest = walkUp(navigation, parent);
  9437. return [f].concat(rest);
  9438. });
  9439. };
  9440. const pathTo = (element, navigation) => {
  9441. const d = navigation.owner(element);
  9442. return walkUp(navigation, d);
  9443. };
  9444. const view = doc => {
  9445. var _a;
  9446. const element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  9447. return element.map(SugarElement.fromDom);
  9448. };
  9449. const owner = element => documentOrOwner(element);
  9450. var Navigation = /*#__PURE__*/Object.freeze({
  9451. __proto__: null,
  9452. view: view,
  9453. owner: owner
  9454. });
  9455. const find = element => {
  9456. const doc = getDocument();
  9457. const scroll = get$5(doc);
  9458. const frames = pathTo(element, Navigation);
  9459. const offset = viewport(element);
  9460. const r = foldr(frames, (b, a) => {
  9461. const loc = viewport(a);
  9462. return {
  9463. left: b.left + loc.left,
  9464. top: b.top + loc.top
  9465. };
  9466. }, {
  9467. left: 0,
  9468. top: 0
  9469. });
  9470. return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  9471. };
  9472. const excludeFromDescend = element => name(element) === 'textarea';
  9473. const fireScrollIntoViewEvent = (editor, data) => {
  9474. const scrollEvent = editor.dispatch('ScrollIntoView', data);
  9475. return scrollEvent.isDefaultPrevented();
  9476. };
  9477. const fireAfterScrollIntoViewEvent = (editor, data) => {
  9478. editor.dispatch('AfterScrollIntoView', data);
  9479. };
  9480. const descend = (element, offset) => {
  9481. const children$1 = children(element);
  9482. if (children$1.length === 0 || excludeFromDescend(element)) {
  9483. return {
  9484. element,
  9485. offset
  9486. };
  9487. } else if (offset < children$1.length && !excludeFromDescend(children$1[offset])) {
  9488. return {
  9489. element: children$1[offset],
  9490. offset: 0
  9491. };
  9492. } else {
  9493. const last = children$1[children$1.length - 1];
  9494. if (excludeFromDescend(last)) {
  9495. return {
  9496. element,
  9497. offset
  9498. };
  9499. } else {
  9500. if (name(last) === 'img') {
  9501. return {
  9502. element: last,
  9503. offset: 1
  9504. };
  9505. } else if (isText$9(last)) {
  9506. return {
  9507. element: last,
  9508. offset: get$3(last).length
  9509. };
  9510. } else {
  9511. return {
  9512. element: last,
  9513. offset: children(last).length
  9514. };
  9515. }
  9516. }
  9517. }
  9518. };
  9519. const markerInfo = (element, cleanupFun) => {
  9520. const pos = absolute(element);
  9521. const height = get$2(element);
  9522. return {
  9523. element,
  9524. bottom: pos.top + height,
  9525. height,
  9526. pos,
  9527. cleanup: cleanupFun
  9528. };
  9529. };
  9530. const createMarker$1 = (element, offset) => {
  9531. const startPoint = descend(element, offset);
  9532. const span = SugarElement.fromHtml('<span data-mce-bogus="all" style="display: inline-block;">' + ZWSP$1 + '</span>');
  9533. before$3(startPoint.element, span);
  9534. return markerInfo(span, () => remove$5(span));
  9535. };
  9536. const elementMarker = element => markerInfo(SugarElement.fromDom(element), noop);
  9537. const withMarker = (editor, f, rng, alignToTop) => {
  9538. preserveWith(editor, (_s, _e) => applyWithMarker(editor, f, rng, alignToTop), rng);
  9539. };
  9540. const withScrollEvents = (editor, doc, f, marker, alignToTop) => {
  9541. const data = {
  9542. elm: marker.element.dom,
  9543. alignToTop
  9544. };
  9545. if (fireScrollIntoViewEvent(editor, data)) {
  9546. return;
  9547. }
  9548. const scrollTop = get$5(doc).top;
  9549. f(doc, scrollTop, marker, alignToTop);
  9550. fireAfterScrollIntoViewEvent(editor, data);
  9551. };
  9552. const applyWithMarker = (editor, f, rng, alignToTop) => {
  9553. const body = SugarElement.fromDom(editor.getBody());
  9554. const doc = SugarElement.fromDom(editor.getDoc());
  9555. reflow(body);
  9556. const marker = createMarker$1(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  9557. withScrollEvents(editor, doc, f, marker, alignToTop);
  9558. marker.cleanup();
  9559. };
  9560. const withElement = (editor, element, f, alignToTop) => {
  9561. const doc = SugarElement.fromDom(editor.getDoc());
  9562. withScrollEvents(editor, doc, f, elementMarker(element), alignToTop);
  9563. };
  9564. const preserveWith = (editor, f, rng) => {
  9565. const startElement = rng.startContainer;
  9566. const startOffset = rng.startOffset;
  9567. const endElement = rng.endContainer;
  9568. const endOffset = rng.endOffset;
  9569. f(SugarElement.fromDom(startElement), SugarElement.fromDom(endElement));
  9570. const newRng = editor.dom.createRng();
  9571. newRng.setStart(startElement, startOffset);
  9572. newRng.setEnd(endElement, endOffset);
  9573. editor.selection.setRng(rng);
  9574. };
  9575. const scrollToMarker = (marker, viewHeight, alignToTop, doc) => {
  9576. const pos = marker.pos;
  9577. if (alignToTop) {
  9578. to(pos.left, pos.top, doc);
  9579. } else {
  9580. const y = pos.top - viewHeight + marker.height;
  9581. to(pos.left, y, doc);
  9582. }
  9583. };
  9584. const intoWindowIfNeeded = (doc, scrollTop, viewHeight, marker, alignToTop) => {
  9585. const viewportBottom = viewHeight + scrollTop;
  9586. const markerTop = marker.pos.top;
  9587. const markerBottom = marker.bottom;
  9588. const largerThanViewport = markerBottom - markerTop >= viewHeight;
  9589. if (markerTop < scrollTop) {
  9590. scrollToMarker(marker, viewHeight, alignToTop !== false, doc);
  9591. } else if (markerTop > viewportBottom) {
  9592. const align = largerThanViewport ? alignToTop !== false : alignToTop === true;
  9593. scrollToMarker(marker, viewHeight, align, doc);
  9594. } else if (markerBottom > viewportBottom && !largerThanViewport) {
  9595. scrollToMarker(marker, viewHeight, alignToTop === true, doc);
  9596. }
  9597. };
  9598. const intoWindow = (doc, scrollTop, marker, alignToTop) => {
  9599. const viewHeight = doc.dom.defaultView.innerHeight;
  9600. intoWindowIfNeeded(doc, scrollTop, viewHeight, marker, alignToTop);
  9601. };
  9602. const intoFrame = (doc, scrollTop, marker, alignToTop) => {
  9603. const frameViewHeight = doc.dom.defaultView.innerHeight;
  9604. intoWindowIfNeeded(doc, scrollTop, frameViewHeight, marker, alignToTop);
  9605. const op = find(marker.element);
  9606. const viewportBounds = getBounds(window);
  9607. if (op.top < viewportBounds.y) {
  9608. intoView(marker.element, alignToTop !== false);
  9609. } else if (op.top > viewportBounds.bottom) {
  9610. intoView(marker.element, alignToTop === true);
  9611. }
  9612. };
  9613. const rangeIntoWindow = (editor, rng, alignToTop) => withMarker(editor, intoWindow, rng, alignToTop);
  9614. const elementIntoWindow = (editor, element, alignToTop) => withElement(editor, element, intoWindow, alignToTop);
  9615. const rangeIntoFrame = (editor, rng, alignToTop) => withMarker(editor, intoFrame, rng, alignToTop);
  9616. const elementIntoFrame = (editor, element, alignToTop) => withElement(editor, element, intoFrame, alignToTop);
  9617. const scrollElementIntoView = (editor, element, alignToTop) => {
  9618. const scroller = editor.inline ? elementIntoWindow : elementIntoFrame;
  9619. scroller(editor, element, alignToTop);
  9620. };
  9621. const scrollRangeIntoView = (editor, rng, alignToTop) => {
  9622. const scroller = editor.inline ? rangeIntoWindow : rangeIntoFrame;
  9623. scroller(editor, rng, alignToTop);
  9624. };
  9625. const focus$1 = element => element.dom.focus();
  9626. const hasFocus$1 = element => {
  9627. const root = getRootNode(element).dom;
  9628. return element.dom === root.activeElement;
  9629. };
  9630. const active$1 = (root = getDocument()) => Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  9631. const search = element => active$1(getRootNode(element)).filter(e => element.dom.contains(e.dom));
  9632. const clamp$1 = (offset, element) => {
  9633. const max = isText$9(element) ? get$3(element).length : children(element).length + 1;
  9634. if (offset > max) {
  9635. return max;
  9636. } else if (offset < 0) {
  9637. return 0;
  9638. }
  9639. return offset;
  9640. };
  9641. const normalizeRng = rng => SimSelection.range(rng.start, clamp$1(rng.soffset, rng.start), rng.finish, clamp$1(rng.foffset, rng.finish));
  9642. const isOrContains = (root, elm) => !isRestrictedNode(elm.dom) && (contains(root, elm) || eq(root, elm));
  9643. const isRngInRoot = root => rng => isOrContains(root, rng.start) && isOrContains(root, rng.finish);
  9644. const shouldStore = editor => editor.inline;
  9645. const nativeRangeToSelectionRange = r => SimSelection.range(SugarElement.fromDom(r.startContainer), r.startOffset, SugarElement.fromDom(r.endContainer), r.endOffset);
  9646. const readRange = win => {
  9647. const selection = win.getSelection();
  9648. const rng = !selection || selection.rangeCount === 0 ? Optional.none() : Optional.from(selection.getRangeAt(0));
  9649. return rng.map(nativeRangeToSelectionRange);
  9650. };
  9651. const getBookmark = root => {
  9652. const win = defaultView(root);
  9653. return readRange(win.dom).filter(isRngInRoot(root));
  9654. };
  9655. const validate = (root, bookmark) => Optional.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
  9656. const bookmarkToNativeRng = bookmark => {
  9657. const rng = document.createRange();
  9658. try {
  9659. rng.setStart(bookmark.start.dom, bookmark.soffset);
  9660. rng.setEnd(bookmark.finish.dom, bookmark.foffset);
  9661. return Optional.some(rng);
  9662. } catch (_) {
  9663. return Optional.none();
  9664. }
  9665. };
  9666. const store = editor => {
  9667. const newBookmark = shouldStore(editor) ? getBookmark(SugarElement.fromDom(editor.getBody())) : Optional.none();
  9668. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  9669. };
  9670. const getRng = editor => {
  9671. const bookmark = editor.bookmark ? editor.bookmark : Optional.none();
  9672. return bookmark.bind(x => validate(SugarElement.fromDom(editor.getBody()), x)).bind(bookmarkToNativeRng);
  9673. };
  9674. const restore = editor => {
  9675. getRng(editor).each(rng => editor.selection.setRng(rng));
  9676. };
  9677. const isEditorUIElement$1 = elm => {
  9678. const className = elm.className.toString();
  9679. return className.indexOf('tox-') !== -1 || className.indexOf('mce-') !== -1;
  9680. };
  9681. const FocusManager = { isEditorUIElement: isEditorUIElement$1 };
  9682. const wrappedSetTimeout = (callback, time) => {
  9683. if (!isNumber(time)) {
  9684. time = 0;
  9685. }
  9686. return setTimeout(callback, time);
  9687. };
  9688. const wrappedSetInterval = (callback, time) => {
  9689. if (!isNumber(time)) {
  9690. time = 0;
  9691. }
  9692. return setInterval(callback, time);
  9693. };
  9694. const Delay = {
  9695. setEditorTimeout: (editor, callback, time) => {
  9696. return wrappedSetTimeout(() => {
  9697. if (!editor.removed) {
  9698. callback();
  9699. }
  9700. }, time);
  9701. },
  9702. setEditorInterval: (editor, callback, time) => {
  9703. const timer = wrappedSetInterval(() => {
  9704. if (!editor.removed) {
  9705. callback();
  9706. } else {
  9707. clearInterval(timer);
  9708. }
  9709. }, time);
  9710. return timer;
  9711. }
  9712. };
  9713. const isManualNodeChange = e => {
  9714. return e.type === 'nodechange' && e.selectionChange;
  9715. };
  9716. const registerPageMouseUp = (editor, throttledStore) => {
  9717. const mouseUpPage = () => {
  9718. throttledStore.throttle();
  9719. };
  9720. DOMUtils.DOM.bind(document, 'mouseup', mouseUpPage);
  9721. editor.on('remove', () => {
  9722. DOMUtils.DOM.unbind(document, 'mouseup', mouseUpPage);
  9723. });
  9724. };
  9725. const registerMouseUp = (editor, throttledStore) => {
  9726. editor.on('mouseup touchend', _e => {
  9727. throttledStore.throttle();
  9728. });
  9729. };
  9730. const registerEditorEvents = (editor, throttledStore) => {
  9731. registerMouseUp(editor, throttledStore);
  9732. editor.on('keyup NodeChange AfterSetSelectionRange', e => {
  9733. if (!isManualNodeChange(e)) {
  9734. store(editor);
  9735. }
  9736. });
  9737. };
  9738. const register$6 = editor => {
  9739. const throttledStore = first$1(() => {
  9740. store(editor);
  9741. }, 0);
  9742. editor.on('init', () => {
  9743. if (editor.inline) {
  9744. registerPageMouseUp(editor, throttledStore);
  9745. }
  9746. registerEditorEvents(editor, throttledStore);
  9747. });
  9748. editor.on('remove', () => {
  9749. throttledStore.cancel();
  9750. });
  9751. };
  9752. let documentFocusInHandler;
  9753. const DOM$9 = DOMUtils.DOM;
  9754. const isEditorUIElement = elm => {
  9755. return FocusManager.isEditorUIElement(elm);
  9756. };
  9757. const isEditorContentAreaElement = elm => {
  9758. const classList = elm.classList;
  9759. if (classList !== undefined) {
  9760. return classList.contains('tox-edit-area') || classList.contains('tox-edit-area__iframe') || classList.contains('mce-content-body');
  9761. } else {
  9762. return false;
  9763. }
  9764. };
  9765. const isUIElement = (editor, elm) => {
  9766. const customSelector = getCustomUiSelector(editor);
  9767. const parent = DOM$9.getParent(elm, elm => {
  9768. return isEditorUIElement(elm) || (customSelector ? editor.dom.is(elm, customSelector) : false);
  9769. });
  9770. return parent !== null;
  9771. };
  9772. const getActiveElement = editor => {
  9773. try {
  9774. const root = getRootNode(SugarElement.fromDom(editor.getElement()));
  9775. return active$1(root).fold(() => document.body, x => x.dom);
  9776. } catch (ex) {
  9777. return document.body;
  9778. }
  9779. };
  9780. const registerEvents$1 = (editorManager, e) => {
  9781. const editor = e.editor;
  9782. register$6(editor);
  9783. editor.on('focusin', () => {
  9784. const focusedEditor = editorManager.focusedEditor;
  9785. if (focusedEditor !== editor) {
  9786. if (focusedEditor) {
  9787. focusedEditor.dispatch('blur', { focusedEditor: editor });
  9788. }
  9789. editorManager.setActive(editor);
  9790. editorManager.focusedEditor = editor;
  9791. editor.dispatch('focus', { blurredEditor: focusedEditor });
  9792. editor.focus(true);
  9793. }
  9794. });
  9795. editor.on('focusout', () => {
  9796. Delay.setEditorTimeout(editor, () => {
  9797. const focusedEditor = editorManager.focusedEditor;
  9798. if (!isUIElement(editor, getActiveElement(editor)) && focusedEditor === editor) {
  9799. editor.dispatch('blur', { focusedEditor: null });
  9800. editorManager.focusedEditor = null;
  9801. }
  9802. });
  9803. });
  9804. if (!documentFocusInHandler) {
  9805. documentFocusInHandler = e => {
  9806. const activeEditor = editorManager.activeEditor;
  9807. if (activeEditor) {
  9808. getOriginalEventTarget(e).each(target => {
  9809. if (target.ownerDocument === document) {
  9810. if (target !== document.body && !isUIElement(activeEditor, target) && editorManager.focusedEditor === activeEditor) {
  9811. activeEditor.dispatch('blur', { focusedEditor: null });
  9812. editorManager.focusedEditor = null;
  9813. }
  9814. }
  9815. });
  9816. }
  9817. };
  9818. DOM$9.bind(document, 'focusin', documentFocusInHandler);
  9819. }
  9820. };
  9821. const unregisterDocumentEvents = (editorManager, e) => {
  9822. if (editorManager.focusedEditor === e.editor) {
  9823. editorManager.focusedEditor = null;
  9824. }
  9825. if (!editorManager.activeEditor) {
  9826. DOM$9.unbind(document, 'focusin', documentFocusInHandler);
  9827. documentFocusInHandler = null;
  9828. }
  9829. };
  9830. const setup$v = editorManager => {
  9831. editorManager.on('AddEditor', curry(registerEvents$1, editorManager));
  9832. editorManager.on('RemoveEditor', curry(unregisterDocumentEvents, editorManager));
  9833. };
  9834. const getContentEditableHost = (editor, node) => editor.dom.getParent(node, node => editor.dom.getContentEditable(node) === 'true');
  9835. const getCollapsedNode = rng => rng.collapsed ? Optional.from(getNode$1(rng.startContainer, rng.startOffset)).map(SugarElement.fromDom) : Optional.none();
  9836. const getFocusInElement = (root, rng) => getCollapsedNode(rng).bind(node => {
  9837. if (isTableSection(node)) {
  9838. return Optional.some(node);
  9839. } else if (contains(root, node) === false) {
  9840. return Optional.some(root);
  9841. } else {
  9842. return Optional.none();
  9843. }
  9844. });
  9845. const normalizeSelection$1 = (editor, rng) => {
  9846. getFocusInElement(SugarElement.fromDom(editor.getBody()), rng).bind(elm => {
  9847. return firstPositionIn(elm.dom);
  9848. }).fold(() => {
  9849. editor.selection.normalize();
  9850. return;
  9851. }, caretPos => editor.selection.setRng(caretPos.toRange()));
  9852. };
  9853. const focusBody = body => {
  9854. if (body.setActive) {
  9855. try {
  9856. body.setActive();
  9857. } catch (ex) {
  9858. body.focus();
  9859. }
  9860. } else {
  9861. body.focus();
  9862. }
  9863. };
  9864. const hasElementFocus = elm => hasFocus$1(elm) || search(elm).isSome();
  9865. const hasIframeFocus = editor => editor.iframeElement && hasFocus$1(SugarElement.fromDom(editor.iframeElement));
  9866. const hasInlineFocus = editor => {
  9867. const rawBody = editor.getBody();
  9868. return rawBody && hasElementFocus(SugarElement.fromDom(rawBody));
  9869. };
  9870. const hasUiFocus = editor => {
  9871. const dos = getRootNode(SugarElement.fromDom(editor.getElement()));
  9872. return active$1(dos).filter(elem => !isEditorContentAreaElement(elem.dom) && isUIElement(editor, elem.dom)).isSome();
  9873. };
  9874. const hasFocus = editor => editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
  9875. const hasEditorOrUiFocus = editor => hasFocus(editor) || hasUiFocus(editor);
  9876. const focusEditor = editor => {
  9877. const selection = editor.selection;
  9878. const body = editor.getBody();
  9879. let rng = selection.getRng();
  9880. editor.quirks.refreshContentEditable();
  9881. if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  9882. getRng(editor).each(bookmarkRng => {
  9883. editor.selection.setRng(bookmarkRng);
  9884. rng = bookmarkRng;
  9885. });
  9886. }
  9887. const contentEditableHost = getContentEditableHost(editor, selection.getNode());
  9888. if (editor.dom.isChildOf(contentEditableHost, body)) {
  9889. focusBody(contentEditableHost);
  9890. normalizeSelection$1(editor, rng);
  9891. activateEditor(editor);
  9892. return;
  9893. }
  9894. if (!editor.inline) {
  9895. if (!Env.browser.isOpera()) {
  9896. focusBody(body);
  9897. }
  9898. editor.getWin().focus();
  9899. }
  9900. if (Env.browser.isFirefox() || editor.inline) {
  9901. focusBody(body);
  9902. normalizeSelection$1(editor, rng);
  9903. }
  9904. activateEditor(editor);
  9905. };
  9906. const activateEditor = editor => editor.editorManager.setActive(editor);
  9907. const focus = (editor, skipFocus) => {
  9908. if (editor.removed) {
  9909. return;
  9910. }
  9911. if (skipFocus) {
  9912. activateEditor(editor);
  9913. } else {
  9914. focusEditor(editor);
  9915. }
  9916. };
  9917. const getEndpointElement = (root, rng, start, real, resolve) => {
  9918. const container = start ? rng.startContainer : rng.endContainer;
  9919. const offset = start ? rng.startOffset : rng.endOffset;
  9920. return Optional.from(container).map(SugarElement.fromDom).map(elm => !real || !rng.collapsed ? child$1(elm, resolve(elm, offset)).getOr(elm) : elm).bind(elm => isElement$7(elm) ? Optional.some(elm) : parent(elm).filter(isElement$7)).map(elm => elm.dom).getOr(root);
  9921. };
  9922. const getStart = (root, rng, real) => getEndpointElement(root, rng, true, real, (elm, offset) => Math.min(childNodesCount(elm), offset));
  9923. const getEnd$1 = (root, rng, real) => getEndpointElement(root, rng, false, real, (elm, offset) => offset > 0 ? offset - 1 : offset);
  9924. const skipEmptyTextNodes = (node, forwards) => {
  9925. const orig = node;
  9926. while (node && isText$8(node) && node.length === 0) {
  9927. node = forwards ? node.nextSibling : node.previousSibling;
  9928. }
  9929. return node || orig;
  9930. };
  9931. const getNode = (root, rng) => {
  9932. let elm, startContainer, endContainer;
  9933. if (!rng) {
  9934. return root;
  9935. }
  9936. startContainer = rng.startContainer;
  9937. endContainer = rng.endContainer;
  9938. const startOffset = rng.startOffset;
  9939. const endOffset = rng.endOffset;
  9940. elm = rng.commonAncestorContainer;
  9941. if (!rng.collapsed) {
  9942. if (startContainer === endContainer) {
  9943. if (endOffset - startOffset < 2) {
  9944. if (startContainer.hasChildNodes()) {
  9945. elm = startContainer.childNodes[startOffset];
  9946. }
  9947. }
  9948. }
  9949. if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
  9950. if (startContainer.length === startOffset) {
  9951. startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
  9952. } else {
  9953. startContainer = startContainer.parentNode;
  9954. }
  9955. if (endOffset === 0) {
  9956. endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
  9957. } else {
  9958. endContainer = endContainer.parentNode;
  9959. }
  9960. if (startContainer && startContainer === endContainer) {
  9961. return startContainer;
  9962. }
  9963. }
  9964. }
  9965. if (elm && elm.nodeType === 3) {
  9966. return elm.parentNode;
  9967. }
  9968. return elm;
  9969. };
  9970. const getSelectedBlocks = (dom, rng, startElm, endElm) => {
  9971. let node;
  9972. const selectedBlocks = [];
  9973. const root = dom.getRoot();
  9974. startElm = dom.getParent(startElm || getStart(root, rng, rng.collapsed), dom.isBlock);
  9975. endElm = dom.getParent(endElm || getEnd$1(root, rng, rng.collapsed), dom.isBlock);
  9976. if (startElm && startElm !== root) {
  9977. selectedBlocks.push(startElm);
  9978. }
  9979. if (startElm && endElm && startElm !== endElm) {
  9980. node = startElm;
  9981. const walker = new DomTreeWalker(startElm, root);
  9982. while ((node = walker.next()) && node !== endElm) {
  9983. if (dom.isBlock(node)) {
  9984. selectedBlocks.push(node);
  9985. }
  9986. }
  9987. }
  9988. if (endElm && startElm !== endElm && endElm !== root) {
  9989. selectedBlocks.push(endElm);
  9990. }
  9991. return selectedBlocks;
  9992. };
  9993. const select = (dom, node, content) => Optional.from(node).map(node => {
  9994. const idx = dom.nodeIndex(node);
  9995. const rng = dom.createRng();
  9996. rng.setStart(node.parentNode, idx);
  9997. rng.setEnd(node.parentNode, idx + 1);
  9998. if (content) {
  9999. moveEndPoint(dom, rng, node, true);
  10000. moveEndPoint(dom, rng, node, false);
  10001. }
  10002. return rng;
  10003. });
  10004. const processRanges = (editor, ranges) => map$3(ranges, range => {
  10005. const evt = editor.dispatch('GetSelectionRange', { range });
  10006. return evt.range !== range ? evt.range : range;
  10007. });
  10008. const getEnd = element => name(element) === 'img' ? 1 : getOption(element).fold(() => children(element).length, v => v.length);
  10009. const isTextNodeWithCursorPosition = el => getOption(el).filter(text => text.trim().length !== 0 || text.indexOf(nbsp) > -1).isSome();
  10010. const elementsWithCursorPosition = [
  10011. 'img',
  10012. 'br'
  10013. ];
  10014. const isCursorPosition = elem => {
  10015. const hasCursorPosition = isTextNodeWithCursorPosition(elem);
  10016. return hasCursorPosition || contains$2(elementsWithCursorPosition, name(elem));
  10017. };
  10018. const first = element => descendant$1(element, isCursorPosition);
  10019. const last = element => descendantRtl(element, isCursorPosition);
  10020. const descendantRtl = (scope, predicate) => {
  10021. const descend = element => {
  10022. const children$1 = children(element);
  10023. for (let i = children$1.length - 1; i >= 0; i--) {
  10024. const child = children$1[i];
  10025. if (predicate(child)) {
  10026. return Optional.some(child);
  10027. }
  10028. const res = descend(child);
  10029. if (res.isSome()) {
  10030. return res;
  10031. }
  10032. }
  10033. return Optional.none();
  10034. };
  10035. return descend(scope);
  10036. };
  10037. const autocompleteSelector = '[data-mce-autocompleter]';
  10038. const create$8 = (editor, range) => {
  10039. if (findIn(SugarElement.fromDom(editor.getBody())).isNone()) {
  10040. const wrapper = SugarElement.fromHtml('<span data-mce-autocompleter="1" data-mce-bogus="1"></span>', editor.getDoc());
  10041. append$1(wrapper, SugarElement.fromDom(range.extractContents()));
  10042. range.insertNode(wrapper.dom);
  10043. parent(wrapper).each(elm => elm.dom.normalize());
  10044. last(wrapper).map(last => {
  10045. editor.selection.setCursorLocation(last.dom, getEnd(last));
  10046. });
  10047. }
  10048. };
  10049. const detect$1 = elm => closest$3(elm, autocompleteSelector);
  10050. const findIn = elm => descendant(elm, autocompleteSelector);
  10051. const remove$3 = (editor, elm) => findIn(elm).each(wrapper => {
  10052. const bookmark = editor.selection.getBookmark();
  10053. unwrap(wrapper);
  10054. editor.selection.moveToBookmark(bookmark);
  10055. });
  10056. const typeLookup = {
  10057. '#text': 3,
  10058. '#comment': 8,
  10059. '#cdata': 4,
  10060. '#pi': 7,
  10061. '#doctype': 10,
  10062. '#document-fragment': 11
  10063. };
  10064. const walk$2 = (node, root, prev) => {
  10065. const startName = prev ? 'lastChild' : 'firstChild';
  10066. const siblingName = prev ? 'prev' : 'next';
  10067. if (node[startName]) {
  10068. return node[startName];
  10069. }
  10070. if (node !== root) {
  10071. let sibling = node[siblingName];
  10072. if (sibling) {
  10073. return sibling;
  10074. }
  10075. for (let parent = node.parent; parent && parent !== root; parent = parent.parent) {
  10076. sibling = parent[siblingName];
  10077. if (sibling) {
  10078. return sibling;
  10079. }
  10080. }
  10081. }
  10082. };
  10083. const isEmptyTextNode = node => {
  10084. if (!isWhitespaceText(node.value)) {
  10085. return false;
  10086. }
  10087. const parentNode = node.parent;
  10088. if (parentNode && (parentNode.name !== 'span' || parentNode.attr('style')) && /^[ ]+$/.test(node.value)) {
  10089. return false;
  10090. }
  10091. return true;
  10092. };
  10093. const isNonEmptyElement = node => {
  10094. const isNamedAnchor = node.name === 'a' && !node.attr('href') && node.attr('id');
  10095. return node.attr('name') || node.attr('id') && !node.firstChild || node.attr('data-mce-bookmark') || isNamedAnchor;
  10096. };
  10097. class AstNode {
  10098. constructor(name, type) {
  10099. this.name = name;
  10100. this.type = type;
  10101. if (type === 1) {
  10102. this.attributes = [];
  10103. this.attributes.map = {};
  10104. }
  10105. }
  10106. static create(name, attrs) {
  10107. const node = new AstNode(name, typeLookup[name] || 1);
  10108. if (attrs) {
  10109. each$f(attrs, (value, attrName) => {
  10110. node.attr(attrName, value);
  10111. });
  10112. }
  10113. return node;
  10114. }
  10115. replace(node) {
  10116. const self = this;
  10117. if (node.parent) {
  10118. node.remove();
  10119. }
  10120. self.insert(node, self);
  10121. self.remove();
  10122. return self;
  10123. }
  10124. attr(name, value) {
  10125. const self = this;
  10126. let attrs;
  10127. if (typeof name !== 'string') {
  10128. if (name !== undefined && name !== null) {
  10129. each$f(name, (value, key) => {
  10130. self.attr(key, value);
  10131. });
  10132. }
  10133. return self;
  10134. }
  10135. if (attrs = self.attributes) {
  10136. if (value !== undefined) {
  10137. if (value === null) {
  10138. if (name in attrs.map) {
  10139. delete attrs.map[name];
  10140. let i = attrs.length;
  10141. while (i--) {
  10142. if (attrs[i].name === name) {
  10143. attrs.splice(i, 1);
  10144. return self;
  10145. }
  10146. }
  10147. }
  10148. return self;
  10149. }
  10150. if (name in attrs.map) {
  10151. let i = attrs.length;
  10152. while (i--) {
  10153. if (attrs[i].name === name) {
  10154. attrs[i].value = value;
  10155. break;
  10156. }
  10157. }
  10158. } else {
  10159. attrs.push({
  10160. name,
  10161. value
  10162. });
  10163. }
  10164. attrs.map[name] = value;
  10165. return self;
  10166. }
  10167. return attrs.map[name];
  10168. }
  10169. }
  10170. clone() {
  10171. const self = this;
  10172. const clone = new AstNode(self.name, self.type);
  10173. let selfAttrs;
  10174. if (selfAttrs = self.attributes) {
  10175. const cloneAttrs = [];
  10176. cloneAttrs.map = {};
  10177. for (let i = 0, l = selfAttrs.length; i < l; i++) {
  10178. const selfAttr = selfAttrs[i];
  10179. if (selfAttr.name !== 'id') {
  10180. cloneAttrs[cloneAttrs.length] = {
  10181. name: selfAttr.name,
  10182. value: selfAttr.value
  10183. };
  10184. cloneAttrs.map[selfAttr.name] = selfAttr.value;
  10185. }
  10186. }
  10187. clone.attributes = cloneAttrs;
  10188. }
  10189. clone.value = self.value;
  10190. return clone;
  10191. }
  10192. wrap(wrapper) {
  10193. const self = this;
  10194. self.parent.insert(wrapper, self);
  10195. wrapper.append(self);
  10196. return self;
  10197. }
  10198. unwrap() {
  10199. const self = this;
  10200. for (let node = self.firstChild; node;) {
  10201. const next = node.next;
  10202. self.insert(node, self, true);
  10203. node = next;
  10204. }
  10205. self.remove();
  10206. }
  10207. remove() {
  10208. const self = this, parent = self.parent, next = self.next, prev = self.prev;
  10209. if (parent) {
  10210. if (parent.firstChild === self) {
  10211. parent.firstChild = next;
  10212. if (next) {
  10213. next.prev = null;
  10214. }
  10215. } else {
  10216. prev.next = next;
  10217. }
  10218. if (parent.lastChild === self) {
  10219. parent.lastChild = prev;
  10220. if (prev) {
  10221. prev.next = null;
  10222. }
  10223. } else {
  10224. next.prev = prev;
  10225. }
  10226. self.parent = self.next = self.prev = null;
  10227. }
  10228. return self;
  10229. }
  10230. append(node) {
  10231. const self = this;
  10232. if (node.parent) {
  10233. node.remove();
  10234. }
  10235. const last = self.lastChild;
  10236. if (last) {
  10237. last.next = node;
  10238. node.prev = last;
  10239. self.lastChild = node;
  10240. } else {
  10241. self.lastChild = self.firstChild = node;
  10242. }
  10243. node.parent = self;
  10244. return node;
  10245. }
  10246. insert(node, refNode, before) {
  10247. if (node.parent) {
  10248. node.remove();
  10249. }
  10250. const parent = refNode.parent || this;
  10251. if (before) {
  10252. if (refNode === parent.firstChild) {
  10253. parent.firstChild = node;
  10254. } else {
  10255. refNode.prev.next = node;
  10256. }
  10257. node.prev = refNode.prev;
  10258. node.next = refNode;
  10259. refNode.prev = node;
  10260. } else {
  10261. if (refNode === parent.lastChild) {
  10262. parent.lastChild = node;
  10263. } else {
  10264. refNode.next.prev = node;
  10265. }
  10266. node.next = refNode.next;
  10267. node.prev = refNode;
  10268. refNode.next = node;
  10269. }
  10270. node.parent = parent;
  10271. return node;
  10272. }
  10273. getAll(name) {
  10274. const self = this;
  10275. const collection = [];
  10276. for (let node = self.firstChild; node; node = walk$2(node, self)) {
  10277. if (node.name === name) {
  10278. collection.push(node);
  10279. }
  10280. }
  10281. return collection;
  10282. }
  10283. children() {
  10284. const self = this;
  10285. const collection = [];
  10286. for (let node = self.firstChild; node; node = node.next) {
  10287. collection.push(node);
  10288. }
  10289. return collection;
  10290. }
  10291. empty() {
  10292. const self = this;
  10293. if (self.firstChild) {
  10294. const nodes = [];
  10295. for (let node = self.firstChild; node; node = walk$2(node, self)) {
  10296. nodes.push(node);
  10297. }
  10298. let i = nodes.length;
  10299. while (i--) {
  10300. const node = nodes[i];
  10301. node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
  10302. }
  10303. }
  10304. self.firstChild = self.lastChild = null;
  10305. return self;
  10306. }
  10307. isEmpty(elements, whitespace = {}, predicate) {
  10308. const self = this;
  10309. let node = self.firstChild;
  10310. if (isNonEmptyElement(self)) {
  10311. return false;
  10312. }
  10313. if (node) {
  10314. do {
  10315. if (node.type === 1) {
  10316. if (node.attr('data-mce-bogus')) {
  10317. continue;
  10318. }
  10319. if (elements[node.name]) {
  10320. return false;
  10321. }
  10322. if (isNonEmptyElement(node)) {
  10323. return false;
  10324. }
  10325. }
  10326. if (node.type === 8) {
  10327. return false;
  10328. }
  10329. if (node.type === 3 && !isEmptyTextNode(node)) {
  10330. return false;
  10331. }
  10332. if (node.type === 3 && node.parent && whitespace[node.parent.name] && isWhitespaceText(node.value)) {
  10333. return false;
  10334. }
  10335. if (predicate && predicate(node)) {
  10336. return false;
  10337. }
  10338. } while (node = walk$2(node, self));
  10339. }
  10340. return true;
  10341. }
  10342. walk(prev) {
  10343. return walk$2(this, null, prev);
  10344. }
  10345. }
  10346. const isConditionalComment = (html, startIndex) => /^\s*\[if [\w\W]+\]>.*<!\[endif\](--!?)?>/.test(html.substr(startIndex));
  10347. const findCommentEndIndex = (html, isBogus, startIndex = 0) => {
  10348. const lcHtml = html.toLowerCase();
  10349. if (lcHtml.indexOf('[if ', startIndex) !== -1 && isConditionalComment(lcHtml, startIndex)) {
  10350. const endIfIndex = lcHtml.indexOf('[endif]', startIndex);
  10351. return lcHtml.indexOf('>', endIfIndex);
  10352. } else {
  10353. if (isBogus) {
  10354. const endIndex = lcHtml.indexOf('>', startIndex);
  10355. return endIndex !== -1 ? endIndex : lcHtml.length;
  10356. } else {
  10357. const endCommentRegexp = /--!?>/g;
  10358. endCommentRegexp.lastIndex = startIndex;
  10359. const match = endCommentRegexp.exec(html);
  10360. return match ? match.index + match[0].length : lcHtml.length;
  10361. }
  10362. }
  10363. };
  10364. const findMatchingEndTagIndex = (schema, html, startIndex) => {
  10365. const startTagRegExp = /<([!?\/])?([A-Za-z0-9\-_:.]+)/g;
  10366. const endTagRegExp = /(?:\s(?:[^'">]+(?:"[^"]*"|'[^']*'))*[^"'>]*(?:"[^">]*|'[^'>]*)?|\s*|\/)>/g;
  10367. const voidElements = schema.getVoidElements();
  10368. let count = 1, index = startIndex;
  10369. while (count !== 0) {
  10370. startTagRegExp.lastIndex = index;
  10371. while (true) {
  10372. const startMatch = startTagRegExp.exec(html);
  10373. if (startMatch === null) {
  10374. return index;
  10375. } else if (startMatch[1] === '!') {
  10376. if (startsWith(startMatch[2], '--')) {
  10377. index = findCommentEndIndex(html, false, startMatch.index + '!--'.length);
  10378. } else {
  10379. index = findCommentEndIndex(html, true, startMatch.index + 1);
  10380. }
  10381. break;
  10382. } else {
  10383. endTagRegExp.lastIndex = startTagRegExp.lastIndex;
  10384. const endMatch = endTagRegExp.exec(html);
  10385. if (isNull(endMatch) || endMatch.index !== startTagRegExp.lastIndex) {
  10386. continue;
  10387. }
  10388. if (startMatch[1] === '/') {
  10389. count -= 1;
  10390. } else if (!has$2(voidElements, startMatch[2])) {
  10391. count += 1;
  10392. }
  10393. index = startTagRegExp.lastIndex + endMatch[0].length;
  10394. break;
  10395. }
  10396. }
  10397. }
  10398. return index;
  10399. };
  10400. const trimHtml$1 = (tempAttrs, html) => {
  10401. const trimContentRegExp = new RegExp(['\\s?(' + tempAttrs.join('|') + ')="[^"]+"'].join('|'), 'gi');
  10402. return html.replace(trimContentRegExp, '');
  10403. };
  10404. const trimInternal = (serializer, html) => {
  10405. const bogusAllRegExp = /<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g;
  10406. const schema = serializer.schema;
  10407. let content = trimHtml$1(serializer.getTempAttrs(), html);
  10408. const voidElements = schema.getVoidElements();
  10409. let matches;
  10410. while (matches = bogusAllRegExp.exec(content)) {
  10411. const index = bogusAllRegExp.lastIndex;
  10412. const matchLength = matches[0].length;
  10413. let endTagIndex;
  10414. if (voidElements[matches[1]]) {
  10415. endTagIndex = index;
  10416. } else {
  10417. endTagIndex = findMatchingEndTagIndex(schema, content, index);
  10418. }
  10419. content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
  10420. bogusAllRegExp.lastIndex = index - matchLength;
  10421. }
  10422. return trim$1(content);
  10423. };
  10424. const trimExternal = trimInternal;
  10425. const trimEmptyContents = (editor, html) => {
  10426. const blockName = getForcedRootBlock(editor);
  10427. const emptyRegExp = new RegExp(`^(<${ blockName }[^>]*>(&nbsp;|&#160;|\\s|\u00a0|<br \\/>|)<\\/${ blockName }>[\r\n]*|<br \\/>[\r\n]*)$`);
  10428. return html.replace(emptyRegExp, '');
  10429. };
  10430. const getContentFromBody = (editor, args, body) => {
  10431. let content;
  10432. if (args.format === 'raw') {
  10433. content = Tools.trim(trimExternal(editor.serializer, body.innerHTML));
  10434. } else if (args.format === 'text') {
  10435. content = editor.dom.isEmpty(body) ? '' : trim$1(body.innerText || body.textContent);
  10436. } else if (args.format === 'tree') {
  10437. content = editor.serializer.serialize(body, args);
  10438. } else {
  10439. content = trimEmptyContents(editor, editor.serializer.serialize(body, args));
  10440. }
  10441. const shouldTrim = args.format !== 'text' && !isWsPreserveElement(SugarElement.fromDom(body));
  10442. return shouldTrim && isString(content) ? Tools.trim(content) : content;
  10443. };
  10444. const getContentInternal = (editor, args) => Optional.from(editor.getBody()).fold(constant(args.format === 'tree' ? new AstNode('body', 11) : ''), body => getContentFromBody(editor, args, body));
  10445. const each$b = Tools.each;
  10446. const ElementUtils = dom => {
  10447. const compare = (node1, node2) => {
  10448. if (node1.nodeName !== node2.nodeName) {
  10449. return false;
  10450. }
  10451. const getAttribs = node => {
  10452. const attribs = {};
  10453. each$b(dom.getAttribs(node), attr => {
  10454. const name = attr.nodeName.toLowerCase();
  10455. if (name.indexOf('_') !== 0 && name !== 'style' && name.indexOf('data-') !== 0) {
  10456. attribs[name] = dom.getAttrib(node, name);
  10457. }
  10458. });
  10459. return attribs;
  10460. };
  10461. const compareObjects = (obj1, obj2) => {
  10462. let value, name;
  10463. for (name in obj1) {
  10464. if (has$2(obj1, name)) {
  10465. value = obj2[name];
  10466. if (typeof value === 'undefined') {
  10467. return false;
  10468. }
  10469. if (obj1[name] !== value) {
  10470. return false;
  10471. }
  10472. delete obj2[name];
  10473. }
  10474. }
  10475. for (name in obj2) {
  10476. if (has$2(obj2, name)) {
  10477. return false;
  10478. }
  10479. }
  10480. return true;
  10481. };
  10482. if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
  10483. return false;
  10484. }
  10485. if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
  10486. return false;
  10487. }
  10488. return !isBookmarkNode$1(node1) && !isBookmarkNode$1(node2);
  10489. };
  10490. return { compare };
  10491. };
  10492. const makeMap$1 = Tools.makeMap;
  10493. const Writer = settings => {
  10494. const html = [];
  10495. settings = settings || {};
  10496. const indent = settings.indent;
  10497. const indentBefore = makeMap$1(settings.indent_before || '');
  10498. const indentAfter = makeMap$1(settings.indent_after || '');
  10499. const encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
  10500. const htmlOutput = settings.element_format !== 'xhtml';
  10501. return {
  10502. start: (name, attrs, empty) => {
  10503. let i, l, attr, value;
  10504. if (indent && indentBefore[name] && html.length > 0) {
  10505. value = html[html.length - 1];
  10506. if (value.length > 0 && value !== '\n') {
  10507. html.push('\n');
  10508. }
  10509. }
  10510. html.push('<', name);
  10511. if (attrs) {
  10512. for (i = 0, l = attrs.length; i < l; i++) {
  10513. attr = attrs[i];
  10514. html.push(' ', attr.name, '="', encode(attr.value, true), '"');
  10515. }
  10516. }
  10517. if (!empty || htmlOutput) {
  10518. html[html.length] = '>';
  10519. } else {
  10520. html[html.length] = ' />';
  10521. }
  10522. if (empty && indent && indentAfter[name] && html.length > 0) {
  10523. value = html[html.length - 1];
  10524. if (value.length > 0 && value !== '\n') {
  10525. html.push('\n');
  10526. }
  10527. }
  10528. },
  10529. end: name => {
  10530. let value;
  10531. html.push('</', name, '>');
  10532. if (indent && indentAfter[name] && html.length > 0) {
  10533. value = html[html.length - 1];
  10534. if (value.length > 0 && value !== '\n') {
  10535. html.push('\n');
  10536. }
  10537. }
  10538. },
  10539. text: (text, raw) => {
  10540. if (text.length > 0) {
  10541. html[html.length] = raw ? text : encode(text);
  10542. }
  10543. },
  10544. cdata: text => {
  10545. html.push('<![CDATA[', text, ']]>');
  10546. },
  10547. comment: text => {
  10548. html.push('<!--', text, '-->');
  10549. },
  10550. pi: (name, text) => {
  10551. if (text) {
  10552. html.push('<?', name, ' ', encode(text), '?>');
  10553. } else {
  10554. html.push('<?', name, '?>');
  10555. }
  10556. if (indent) {
  10557. html.push('\n');
  10558. }
  10559. },
  10560. doctype: text => {
  10561. html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
  10562. },
  10563. reset: () => {
  10564. html.length = 0;
  10565. },
  10566. getContent: () => {
  10567. return html.join('').replace(/\n$/, '');
  10568. }
  10569. };
  10570. };
  10571. const HtmlSerializer = (settings, schema = Schema()) => {
  10572. const writer = Writer(settings);
  10573. settings = settings || {};
  10574. settings.validate = 'validate' in settings ? settings.validate : true;
  10575. const serialize = node => {
  10576. const validate = settings.validate;
  10577. const handlers = {
  10578. 3: node => {
  10579. writer.text(node.value, node.raw);
  10580. },
  10581. 8: node => {
  10582. writer.comment(node.value);
  10583. },
  10584. 7: node => {
  10585. writer.pi(node.name, node.value);
  10586. },
  10587. 10: node => {
  10588. writer.doctype(node.value);
  10589. },
  10590. 4: node => {
  10591. writer.cdata(node.value);
  10592. },
  10593. 11: node => {
  10594. if (node = node.firstChild) {
  10595. do {
  10596. walk(node);
  10597. } while (node = node.next);
  10598. }
  10599. }
  10600. };
  10601. writer.reset();
  10602. const walk = node => {
  10603. const handler = handlers[node.type];
  10604. if (!handler) {
  10605. const name = node.name;
  10606. const isEmpty = name in schema.getVoidElements();
  10607. let attrs = node.attributes;
  10608. if (validate && attrs && attrs.length > 1) {
  10609. const sortedAttrs = [];
  10610. sortedAttrs.map = {};
  10611. const elementRule = schema.getElementRule(node.name);
  10612. if (elementRule) {
  10613. for (let i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
  10614. const attrName = elementRule.attributesOrder[i];
  10615. if (attrName in attrs.map) {
  10616. const attrValue = attrs.map[attrName];
  10617. sortedAttrs.map[attrName] = attrValue;
  10618. sortedAttrs.push({
  10619. name: attrName,
  10620. value: attrValue
  10621. });
  10622. }
  10623. }
  10624. for (let i = 0, l = attrs.length; i < l; i++) {
  10625. const attrName = attrs[i].name;
  10626. if (!(attrName in sortedAttrs.map)) {
  10627. const attrValue = attrs.map[attrName];
  10628. sortedAttrs.map[attrName] = attrValue;
  10629. sortedAttrs.push({
  10630. name: attrName,
  10631. value: attrValue
  10632. });
  10633. }
  10634. }
  10635. attrs = sortedAttrs;
  10636. }
  10637. }
  10638. writer.start(name, attrs, isEmpty);
  10639. if (!isEmpty) {
  10640. let child = node.firstChild;
  10641. if (child) {
  10642. if ((name === 'pre' || name === 'textarea') && child.type === 3 && child.value[0] === '\n') {
  10643. writer.text('\n', true);
  10644. }
  10645. do {
  10646. walk(child);
  10647. } while (child = child.next);
  10648. }
  10649. writer.end(name);
  10650. }
  10651. } else {
  10652. handler(node);
  10653. }
  10654. };
  10655. if (node.type === 1 && !settings.inner) {
  10656. walk(node);
  10657. } else if (node.type === 3) {
  10658. handlers[3](node);
  10659. } else {
  10660. handlers[11](node);
  10661. }
  10662. return writer.getContent();
  10663. };
  10664. return { serialize };
  10665. };
  10666. const nonInheritableStyles = new Set();
  10667. (() => {
  10668. const nonInheritableStylesArr = [
  10669. 'margin',
  10670. 'margin-left',
  10671. 'margin-right',
  10672. 'margin-top',
  10673. 'margin-bottom',
  10674. 'padding',
  10675. 'padding-left',
  10676. 'padding-right',
  10677. 'padding-top',
  10678. 'padding-bottom',
  10679. 'border',
  10680. 'border-width',
  10681. 'border-style',
  10682. 'border-color',
  10683. 'background',
  10684. 'background-attachment',
  10685. 'background-clip',
  10686. 'background-color',
  10687. 'background-image',
  10688. 'background-origin',
  10689. 'background-position',
  10690. 'background-repeat',
  10691. 'background-size',
  10692. 'float',
  10693. 'position',
  10694. 'left',
  10695. 'right',
  10696. 'top',
  10697. 'bottom',
  10698. 'z-index',
  10699. 'display',
  10700. 'transform',
  10701. 'width',
  10702. 'max-width',
  10703. 'min-width',
  10704. 'height',
  10705. 'max-height',
  10706. 'min-height',
  10707. 'overflow',
  10708. 'overflow-x',
  10709. 'overflow-y',
  10710. 'text-overflow',
  10711. 'vertical-align',
  10712. 'transition',
  10713. 'transition-delay',
  10714. 'transition-duration',
  10715. 'transition-property',
  10716. 'transition-timing-function'
  10717. ];
  10718. each$g(nonInheritableStylesArr, style => {
  10719. nonInheritableStyles.add(style);
  10720. });
  10721. })();
  10722. const shorthandStyleProps = [
  10723. 'font',
  10724. 'text-decoration',
  10725. 'text-emphasis'
  10726. ];
  10727. const getStyleProps = (dom, node) => keys(dom.parseStyle(dom.getAttrib(node, 'style')));
  10728. const isNonInheritableStyle = style => nonInheritableStyles.has(style);
  10729. const hasInheritableStyles = (dom, node) => forall(getStyleProps(dom, node), style => !isNonInheritableStyle(style));
  10730. const getLonghandStyleProps = styles => filter$6(styles, style => exists(shorthandStyleProps, prop => startsWith(style, prop)));
  10731. const hasStyleConflict = (dom, node, parentNode) => {
  10732. const nodeStyleProps = getStyleProps(dom, node);
  10733. const parentNodeStyleProps = getStyleProps(dom, parentNode);
  10734. const valueMismatch = prop => {
  10735. var _a, _b;
  10736. const nodeValue = (_a = dom.getStyle(node, prop)) !== null && _a !== void 0 ? _a : '';
  10737. const parentValue = (_b = dom.getStyle(parentNode, prop)) !== null && _b !== void 0 ? _b : '';
  10738. return isNotEmpty(nodeValue) && isNotEmpty(parentValue) && nodeValue !== parentValue;
  10739. };
  10740. return exists(nodeStyleProps, nodeStyleProp => {
  10741. const propExists = props => exists(props, prop => prop === nodeStyleProp);
  10742. if (!propExists(parentNodeStyleProps) && propExists(shorthandStyleProps)) {
  10743. const longhandProps = getLonghandStyleProps(parentNodeStyleProps);
  10744. return exists(longhandProps, valueMismatch);
  10745. } else {
  10746. return valueMismatch(nodeStyleProp);
  10747. }
  10748. });
  10749. };
  10750. const isChar = (forward, predicate, pos) => Optional.from(pos.container()).filter(isText$8).exists(text => {
  10751. const delta = forward ? 0 : -1;
  10752. return predicate(text.data.charAt(pos.offset() + delta));
  10753. });
  10754. const isBeforeSpace = curry(isChar, true, isWhiteSpace);
  10755. const isAfterSpace = curry(isChar, false, isWhiteSpace);
  10756. const isEmptyText = pos => {
  10757. const container = pos.container();
  10758. return isText$8(container) && (container.data.length === 0 || isZwsp(container.data) && BookmarkManager.isBookmarkNode(container.parentNode));
  10759. };
  10760. const matchesElementPosition = (before, predicate) => pos => Optional.from(getChildNodeAtRelativeOffset(before ? 0 : -1, pos)).filter(predicate).isSome();
  10761. const isImageBlock = node => isImg(node) && get$7(SugarElement.fromDom(node), 'display') === 'block';
  10762. const isCefNode = node => isContentEditableFalse$a(node) && !isBogusAll$1(node);
  10763. const isBeforeImageBlock = matchesElementPosition(true, isImageBlock);
  10764. const isAfterImageBlock = matchesElementPosition(false, isImageBlock);
  10765. const isBeforeMedia = matchesElementPosition(true, isMedia$2);
  10766. const isAfterMedia = matchesElementPosition(false, isMedia$2);
  10767. const isBeforeTable = matchesElementPosition(true, isTable$3);
  10768. const isAfterTable = matchesElementPosition(false, isTable$3);
  10769. const isBeforeContentEditableFalse = matchesElementPosition(true, isCefNode);
  10770. const isAfterContentEditableFalse = matchesElementPosition(false, isCefNode);
  10771. const getLastChildren = elm => {
  10772. const children = [];
  10773. let rawNode = elm.dom;
  10774. while (rawNode) {
  10775. children.push(SugarElement.fromDom(rawNode));
  10776. rawNode = rawNode.lastChild;
  10777. }
  10778. return children;
  10779. };
  10780. const removeTrailingBr = elm => {
  10781. const allBrs = descendants(elm, 'br');
  10782. const brs = filter$6(getLastChildren(elm).slice(-1), isBr$4);
  10783. if (allBrs.length === brs.length) {
  10784. each$g(brs, remove$5);
  10785. }
  10786. };
  10787. const fillWithPaddingBr = elm => {
  10788. empty(elm);
  10789. append$1(elm, SugarElement.fromHtml('<br data-mce-bogus="1">'));
  10790. };
  10791. const trimBlockTrailingBr = elm => {
  10792. lastChild(elm).each(lastChild => {
  10793. prevSibling(lastChild).each(lastChildPrevSibling => {
  10794. if (isBlock$2(elm) && isBr$4(lastChild) && isBlock$2(lastChildPrevSibling)) {
  10795. remove$5(lastChild);
  10796. }
  10797. });
  10798. });
  10799. };
  10800. const dropLast = xs => xs.slice(0, -1);
  10801. const parentsUntil = (start, root, predicate) => {
  10802. if (contains(root, start)) {
  10803. return dropLast(parents$1(start, elm => {
  10804. return predicate(elm) || eq(elm, root);
  10805. }));
  10806. } else {
  10807. return [];
  10808. }
  10809. };
  10810. const parents = (start, root) => parentsUntil(start, root, never);
  10811. const parentsAndSelf = (start, root) => [start].concat(parents(start, root));
  10812. const navigateIgnoreEmptyTextNodes = (forward, root, from) => navigateIgnore(forward, root, from, isEmptyText);
  10813. const getClosestBlock$1 = (root, pos) => find$2(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  10814. const isAtBeforeAfterBlockBoundary = (forward, root, pos) => navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(newPos => getClosestBlock$1(root, pos).fold(() => isInSameBlock(newPos, pos, root.dom) === false, fromBlock => isInSameBlock(newPos, pos, root.dom) === false && contains(fromBlock, SugarElement.fromDom(newPos.container()))));
  10815. const isAtBlockBoundary = (forward, root, pos) => getClosestBlock$1(root, pos).fold(() => navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(newPos => isInSameBlock(newPos, pos, root.dom) === false), parent => navigateIgnoreEmptyTextNodes(forward, parent.dom, pos).isNone());
  10816. const isAtStartOfBlock = curry(isAtBlockBoundary, false);
  10817. const isAtEndOfBlock = curry(isAtBlockBoundary, true);
  10818. const isBeforeBlock = curry(isAtBeforeAfterBlockBoundary, false);
  10819. const isAfterBlock = curry(isAtBeforeAfterBlockBoundary, true);
  10820. const isBr = pos => getElementFromPosition(pos).exists(isBr$4);
  10821. const findBr = (forward, root, pos) => {
  10822. const parentBlocks = filter$6(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  10823. const scope = head(parentBlocks).getOr(root);
  10824. return fromPosition(forward, scope.dom, pos).filter(isBr);
  10825. };
  10826. const isBeforeBr$1 = (root, pos) => getElementFromPosition(pos).exists(isBr$4) || findBr(true, root, pos).isSome();
  10827. const isAfterBr = (root, pos) => getElementFromPrevPosition(pos).exists(isBr$4) || findBr(false, root, pos).isSome();
  10828. const findPreviousBr = curry(findBr, false);
  10829. const findNextBr = curry(findBr, true);
  10830. const isInMiddleOfText = pos => CaretPosition.isTextPosition(pos) && !pos.isAtStart() && !pos.isAtEnd();
  10831. const getClosestBlock = (root, pos) => {
  10832. const parentBlocks = filter$6(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  10833. return head(parentBlocks).getOr(root);
  10834. };
  10835. const hasSpaceBefore = (root, pos) => {
  10836. if (isInMiddleOfText(pos)) {
  10837. return isAfterSpace(pos);
  10838. } else {
  10839. return isAfterSpace(pos) || prevPosition(getClosestBlock(root, pos).dom, pos).exists(isAfterSpace);
  10840. }
  10841. };
  10842. const hasSpaceAfter = (root, pos) => {
  10843. if (isInMiddleOfText(pos)) {
  10844. return isBeforeSpace(pos);
  10845. } else {
  10846. return isBeforeSpace(pos) || nextPosition(getClosestBlock(root, pos).dom, pos).exists(isBeforeSpace);
  10847. }
  10848. };
  10849. const isPreValue = value => contains$2([
  10850. 'pre',
  10851. 'pre-wrap'
  10852. ], value);
  10853. const isInPre = pos => getElementFromPosition(pos).bind(elm => closest$4(elm, isElement$7)).exists(elm => isPreValue(get$7(elm, 'white-space')));
  10854. const isAtBeginningOfBody = (root, pos) => prevPosition(root.dom, pos).isNone();
  10855. const isAtEndOfBody = (root, pos) => nextPosition(root.dom, pos).isNone();
  10856. const isAtLineBoundary = (root, pos) => isAtBeginningOfBody(root, pos) || isAtEndOfBody(root, pos) || isAtStartOfBlock(root, pos) || isAtEndOfBlock(root, pos) || isAfterBr(root, pos) || isBeforeBr$1(root, pos);
  10857. const needsToHaveNbsp = (root, pos) => {
  10858. if (isInPre(pos)) {
  10859. return false;
  10860. } else {
  10861. return isAtLineBoundary(root, pos) || hasSpaceBefore(root, pos) || hasSpaceAfter(root, pos);
  10862. }
  10863. };
  10864. const needsToBeNbspLeft = (root, pos) => {
  10865. if (isInPre(pos)) {
  10866. return false;
  10867. } else {
  10868. return isAtStartOfBlock(root, pos) || isBeforeBlock(root, pos) || isAfterBr(root, pos) || hasSpaceBefore(root, pos);
  10869. }
  10870. };
  10871. const leanRight = pos => {
  10872. const container = pos.container();
  10873. const offset = pos.offset();
  10874. if (isText$8(container) && offset < container.data.length) {
  10875. return CaretPosition(container, offset + 1);
  10876. } else {
  10877. return pos;
  10878. }
  10879. };
  10880. const needsToBeNbspRight = (root, pos) => {
  10881. if (isInPre(pos)) {
  10882. return false;
  10883. } else {
  10884. return isAtEndOfBlock(root, pos) || isAfterBlock(root, pos) || isBeforeBr$1(root, pos) || hasSpaceAfter(root, pos);
  10885. }
  10886. };
  10887. const needsToBeNbsp = (root, pos) => needsToBeNbspLeft(root, pos) || needsToBeNbspRight(root, leanRight(pos));
  10888. const isNbspAt = (text, offset) => isNbsp(text.charAt(offset));
  10889. const hasNbsp = pos => {
  10890. const container = pos.container();
  10891. return isText$8(container) && contains$1(container.data, nbsp);
  10892. };
  10893. const normalizeNbspMiddle = text => {
  10894. const chars = text.split('');
  10895. return map$3(chars, (chr, i) => {
  10896. if (isNbsp(chr) && i > 0 && i < chars.length - 1 && isContent(chars[i - 1]) && isContent(chars[i + 1])) {
  10897. return ' ';
  10898. } else {
  10899. return chr;
  10900. }
  10901. }).join('');
  10902. };
  10903. const normalizeNbspAtStart = (root, node) => {
  10904. const text = node.data;
  10905. const firstPos = CaretPosition(node, 0);
  10906. if (isNbspAt(text, 0) && !needsToBeNbsp(root, firstPos)) {
  10907. node.data = ' ' + text.slice(1);
  10908. return true;
  10909. } else {
  10910. return false;
  10911. }
  10912. };
  10913. const normalizeNbspInMiddleOfTextNode = node => {
  10914. const text = node.data;
  10915. const newText = normalizeNbspMiddle(text);
  10916. if (newText !== text) {
  10917. node.data = newText;
  10918. return true;
  10919. } else {
  10920. return false;
  10921. }
  10922. };
  10923. const normalizeNbspAtEnd = (root, node) => {
  10924. const text = node.data;
  10925. const lastPos = CaretPosition(node, text.length - 1);
  10926. if (isNbspAt(text, text.length - 1) && !needsToBeNbsp(root, lastPos)) {
  10927. node.data = text.slice(0, -1) + ' ';
  10928. return true;
  10929. } else {
  10930. return false;
  10931. }
  10932. };
  10933. const normalizeNbsps = (root, pos) => Optional.some(pos).filter(hasNbsp).bind(pos => {
  10934. const container = pos.container();
  10935. const normalized = normalizeNbspAtStart(root, container) || normalizeNbspInMiddleOfTextNode(container) || normalizeNbspAtEnd(root, container);
  10936. return normalized ? Optional.some(pos) : Optional.none();
  10937. });
  10938. const normalizeNbspsInEditor = editor => {
  10939. const root = SugarElement.fromDom(editor.getBody());
  10940. if (editor.selection.isCollapsed()) {
  10941. normalizeNbsps(root, CaretPosition.fromRangeStart(editor.selection.getRng())).each(pos => {
  10942. editor.selection.setRng(pos.toRange());
  10943. });
  10944. }
  10945. };
  10946. const normalize$1 = (node, offset, count) => {
  10947. if (count === 0) {
  10948. return;
  10949. }
  10950. const elm = SugarElement.fromDom(node);
  10951. const root = ancestor$3(elm, isBlock$2).getOr(elm);
  10952. const whitespace = node.data.slice(offset, offset + count);
  10953. const isEndOfContent = offset + count >= node.data.length && needsToBeNbspRight(root, CaretPosition(node, node.data.length));
  10954. const isStartOfContent = offset === 0 && needsToBeNbspLeft(root, CaretPosition(node, 0));
  10955. node.replaceData(offset, count, normalize$4(whitespace, 4, isStartOfContent, isEndOfContent));
  10956. };
  10957. const normalizeWhitespaceAfter = (node, offset) => {
  10958. const content = node.data.slice(offset);
  10959. const whitespaceCount = content.length - lTrim(content).length;
  10960. normalize$1(node, offset, whitespaceCount);
  10961. };
  10962. const normalizeWhitespaceBefore = (node, offset) => {
  10963. const content = node.data.slice(0, offset);
  10964. const whitespaceCount = content.length - rTrim(content).length;
  10965. normalize$1(node, offset - whitespaceCount, whitespaceCount);
  10966. };
  10967. const mergeTextNodes = (prevNode, nextNode, normalizeWhitespace, mergeToPrev = true) => {
  10968. const whitespaceOffset = rTrim(prevNode.data).length;
  10969. const newNode = mergeToPrev ? prevNode : nextNode;
  10970. const removeNode = mergeToPrev ? nextNode : prevNode;
  10971. if (mergeToPrev) {
  10972. newNode.appendData(removeNode.data);
  10973. } else {
  10974. newNode.insertData(0, removeNode.data);
  10975. }
  10976. remove$5(SugarElement.fromDom(removeNode));
  10977. if (normalizeWhitespace) {
  10978. normalizeWhitespaceAfter(newNode, whitespaceOffset);
  10979. }
  10980. return newNode;
  10981. };
  10982. const needsReposition = (pos, elm) => {
  10983. const container = pos.container();
  10984. const offset = pos.offset();
  10985. return CaretPosition.isTextPosition(pos) === false && container === elm.parentNode && offset > CaretPosition.before(elm).offset();
  10986. };
  10987. const reposition = (elm, pos) => needsReposition(pos, elm) ? CaretPosition(pos.container(), pos.offset() - 1) : pos;
  10988. const beforeOrStartOf = node => isText$8(node) ? CaretPosition(node, 0) : CaretPosition.before(node);
  10989. const afterOrEndOf = node => isText$8(node) ? CaretPosition(node, node.data.length) : CaretPosition.after(node);
  10990. const getPreviousSiblingCaretPosition = elm => {
  10991. if (isCaretCandidate$3(elm.previousSibling)) {
  10992. return Optional.some(afterOrEndOf(elm.previousSibling));
  10993. } else {
  10994. return elm.previousSibling ? lastPositionIn(elm.previousSibling) : Optional.none();
  10995. }
  10996. };
  10997. const getNextSiblingCaretPosition = elm => {
  10998. if (isCaretCandidate$3(elm.nextSibling)) {
  10999. return Optional.some(beforeOrStartOf(elm.nextSibling));
  11000. } else {
  11001. return elm.nextSibling ? firstPositionIn(elm.nextSibling) : Optional.none();
  11002. }
  11003. };
  11004. const findCaretPositionBackwardsFromElm = (rootElement, elm) => {
  11005. const startPosition = CaretPosition.before(elm.previousSibling ? elm.previousSibling : elm.parentNode);
  11006. return prevPosition(rootElement, startPosition).fold(() => nextPosition(rootElement, CaretPosition.after(elm)), Optional.some);
  11007. };
  11008. const findCaretPositionForwardsFromElm = (rootElement, elm) => nextPosition(rootElement, CaretPosition.after(elm)).fold(() => prevPosition(rootElement, CaretPosition.before(elm)), Optional.some);
  11009. const findCaretPositionBackwards = (rootElement, elm) => getPreviousSiblingCaretPosition(elm).orThunk(() => getNextSiblingCaretPosition(elm)).orThunk(() => findCaretPositionBackwardsFromElm(rootElement, elm));
  11010. const findCaretPositionForward = (rootElement, elm) => getNextSiblingCaretPosition(elm).orThunk(() => getPreviousSiblingCaretPosition(elm)).orThunk(() => findCaretPositionForwardsFromElm(rootElement, elm));
  11011. const findCaretPosition = (forward, rootElement, elm) => forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
  11012. const findCaretPosOutsideElmAfterDelete = (forward, rootElement, elm) => findCaretPosition(forward, rootElement, elm).map(curry(reposition, elm));
  11013. const setSelection$1 = (editor, forward, pos) => {
  11014. pos.fold(() => {
  11015. editor.focus();
  11016. }, pos => {
  11017. editor.selection.setRng(pos.toRange(), forward);
  11018. });
  11019. };
  11020. const eqRawNode = rawNode => elm => elm.dom === rawNode;
  11021. const isBlock = (editor, elm) => elm && has$2(editor.schema.getBlockElements(), name(elm));
  11022. const paddEmptyBlock = elm => {
  11023. if (isEmpty$2(elm)) {
  11024. const br = SugarElement.fromHtml('<br data-mce-bogus="1">');
  11025. empty(elm);
  11026. append$1(elm, br);
  11027. return Optional.some(CaretPosition.before(br.dom));
  11028. } else {
  11029. return Optional.none();
  11030. }
  11031. };
  11032. const deleteNormalized = (elm, afterDeletePosOpt, normalizeWhitespace) => {
  11033. const prevTextOpt = prevSibling(elm).filter(isText$9);
  11034. const nextTextOpt = nextSibling(elm).filter(isText$9);
  11035. remove$5(elm);
  11036. return lift3(prevTextOpt, nextTextOpt, afterDeletePosOpt, (prev, next, pos) => {
  11037. const prevNode = prev.dom, nextNode = next.dom;
  11038. const offset = prevNode.data.length;
  11039. mergeTextNodes(prevNode, nextNode, normalizeWhitespace);
  11040. return pos.container() === nextNode ? CaretPosition(prevNode, offset) : pos;
  11041. }).orThunk(() => {
  11042. if (normalizeWhitespace) {
  11043. prevTextOpt.each(elm => normalizeWhitespaceBefore(elm.dom, elm.dom.length));
  11044. nextTextOpt.each(elm => normalizeWhitespaceAfter(elm.dom, 0));
  11045. }
  11046. return afterDeletePosOpt;
  11047. });
  11048. };
  11049. const isInlineElement = (editor, element) => has$2(editor.schema.getTextInlineElements(), name(element));
  11050. const deleteElement$2 = (editor, forward, elm, moveCaret = true) => {
  11051. const afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom);
  11052. const parentBlock = ancestor$3(elm, curry(isBlock, editor), eqRawNode(editor.getBody()));
  11053. const normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos, isInlineElement(editor, elm));
  11054. if (editor.dom.isEmpty(editor.getBody())) {
  11055. editor.setContent('');
  11056. editor.selection.setCursorLocation();
  11057. } else {
  11058. parentBlock.bind(paddEmptyBlock).fold(() => {
  11059. if (moveCaret) {
  11060. setSelection$1(editor, forward, normalizedAfterDeletePos);
  11061. }
  11062. }, paddPos => {
  11063. if (moveCaret) {
  11064. setSelection$1(editor, forward, Optional.some(paddPos));
  11065. }
  11066. });
  11067. }
  11068. };
  11069. const isRootFromElement = root => cur => eq(root, cur);
  11070. const getTableCells = table => descendants(table, 'td,th');
  11071. const getTableDetailsFromRange = (rng, isRoot) => {
  11072. const getTable = node => getClosestTable(SugarElement.fromDom(node), isRoot);
  11073. const startTable = getTable(rng.startContainer);
  11074. const endTable = getTable(rng.endContainer);
  11075. const isStartInTable = startTable.isSome();
  11076. const isEndInTable = endTable.isSome();
  11077. const isSameTable = lift2(startTable, endTable, eq).getOr(false);
  11078. const isMultiTable = !isSameTable && isStartInTable && isEndInTable;
  11079. return {
  11080. startTable,
  11081. endTable,
  11082. isStartInTable,
  11083. isEndInTable,
  11084. isSameTable,
  11085. isMultiTable
  11086. };
  11087. };
  11088. const tableCellRng = (start, end) => ({
  11089. start,
  11090. end
  11091. });
  11092. const tableSelection = (rng, table, cells) => ({
  11093. rng,
  11094. table,
  11095. cells
  11096. });
  11097. const deleteAction = Adt.generate([
  11098. {
  11099. singleCellTable: [
  11100. 'rng',
  11101. 'cell'
  11102. ]
  11103. },
  11104. { fullTable: ['table'] },
  11105. {
  11106. partialTable: [
  11107. 'cells',
  11108. 'outsideDetails'
  11109. ]
  11110. },
  11111. {
  11112. multiTable: [
  11113. 'startTableCells',
  11114. 'endTableCells',
  11115. 'betweenRng'
  11116. ]
  11117. }
  11118. ]);
  11119. const getClosestCell$1 = (container, isRoot) => closest$3(SugarElement.fromDom(container), 'td,th', isRoot);
  11120. const isExpandedCellRng = cellRng => !eq(cellRng.start, cellRng.end);
  11121. const getTableFromCellRng = (cellRng, isRoot) => getClosestTable(cellRng.start, isRoot).bind(startParentTable => getClosestTable(cellRng.end, isRoot).bind(endParentTable => someIf(eq(startParentTable, endParentTable), startParentTable)));
  11122. const isSingleCellTable = (cellRng, isRoot) => !isExpandedCellRng(cellRng) && getTableFromCellRng(cellRng, isRoot).exists(table => {
  11123. const rows = table.dom.rows;
  11124. return rows.length === 1 && rows[0].cells.length === 1;
  11125. });
  11126. const getCellRng = (rng, isRoot) => {
  11127. const startCell = getClosestCell$1(rng.startContainer, isRoot);
  11128. const endCell = getClosestCell$1(rng.endContainer, isRoot);
  11129. return lift2(startCell, endCell, tableCellRng);
  11130. };
  11131. const getCellRangeFromStartTable = isRoot => startCell => getClosestTable(startCell, isRoot).bind(table => last$3(getTableCells(table)).map(endCell => tableCellRng(startCell, endCell)));
  11132. const getCellRangeFromEndTable = isRoot => endCell => getClosestTable(endCell, isRoot).bind(table => head(getTableCells(table)).map(startCell => tableCellRng(startCell, endCell)));
  11133. const getTableSelectionFromCellRng = isRoot => cellRng => getTableFromCellRng(cellRng, isRoot).map(table => tableSelection(cellRng, table, getTableCells(table)));
  11134. const getTableSelections = (cellRng, selectionDetails, rng, isRoot) => {
  11135. if (rng.collapsed || !cellRng.forall(isExpandedCellRng)) {
  11136. return Optional.none();
  11137. } else if (selectionDetails.isSameTable) {
  11138. const sameTableSelection = cellRng.bind(getTableSelectionFromCellRng(isRoot));
  11139. return Optional.some({
  11140. start: sameTableSelection,
  11141. end: sameTableSelection
  11142. });
  11143. } else {
  11144. const startCell = getClosestCell$1(rng.startContainer, isRoot);
  11145. const endCell = getClosestCell$1(rng.endContainer, isRoot);
  11146. const startTableSelection = startCell.bind(getCellRangeFromStartTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  11147. const endTableSelection = endCell.bind(getCellRangeFromEndTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  11148. return Optional.some({
  11149. start: startTableSelection,
  11150. end: endTableSelection
  11151. });
  11152. }
  11153. };
  11154. const getCellIndex = (cells, cell) => findIndex$2(cells, x => eq(x, cell));
  11155. const getSelectedCells = tableSelection => lift2(getCellIndex(tableSelection.cells, tableSelection.rng.start), getCellIndex(tableSelection.cells, tableSelection.rng.end), (startIndex, endIndex) => tableSelection.cells.slice(startIndex, endIndex + 1));
  11156. const isSingleCellTableContentSelected = (optCellRng, rng, isRoot) => optCellRng.exists(cellRng => isSingleCellTable(cellRng, isRoot) && hasAllContentsSelected(cellRng.start, rng));
  11157. const unselectCells = (rng, selectionDetails) => {
  11158. const {startTable, endTable} = selectionDetails;
  11159. const otherContentRng = rng.cloneRange();
  11160. startTable.each(table => otherContentRng.setStartAfter(table.dom));
  11161. endTable.each(table => otherContentRng.setEndBefore(table.dom));
  11162. return otherContentRng;
  11163. };
  11164. const handleSingleTable = (cellRng, selectionDetails, rng, isRoot) => getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(({start, end}) => start.or(end)).bind(tableSelection => {
  11165. const {isSameTable} = selectionDetails;
  11166. const selectedCells = getSelectedCells(tableSelection).getOr([]);
  11167. if (isSameTable && tableSelection.cells.length === selectedCells.length) {
  11168. return Optional.some(deleteAction.fullTable(tableSelection.table));
  11169. } else if (selectedCells.length > 0) {
  11170. if (isSameTable) {
  11171. return Optional.some(deleteAction.partialTable(selectedCells, Optional.none()));
  11172. } else {
  11173. const otherContentRng = unselectCells(rng, selectionDetails);
  11174. return Optional.some(deleteAction.partialTable(selectedCells, Optional.some({
  11175. ...selectionDetails,
  11176. rng: otherContentRng
  11177. })));
  11178. }
  11179. } else {
  11180. return Optional.none();
  11181. }
  11182. });
  11183. const handleMultiTable = (cellRng, selectionDetails, rng, isRoot) => getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(({start, end}) => {
  11184. const startTableSelectedCells = start.bind(getSelectedCells).getOr([]);
  11185. const endTableSelectedCells = end.bind(getSelectedCells).getOr([]);
  11186. if (startTableSelectedCells.length > 0 && endTableSelectedCells.length > 0) {
  11187. const otherContentRng = unselectCells(rng, selectionDetails);
  11188. return Optional.some(deleteAction.multiTable(startTableSelectedCells, endTableSelectedCells, otherContentRng));
  11189. } else {
  11190. return Optional.none();
  11191. }
  11192. });
  11193. const getActionFromRange = (root, rng) => {
  11194. const isRoot = isRootFromElement(root);
  11195. const optCellRng = getCellRng(rng, isRoot);
  11196. const selectionDetails = getTableDetailsFromRange(rng, isRoot);
  11197. if (isSingleCellTableContentSelected(optCellRng, rng, isRoot)) {
  11198. return optCellRng.map(cellRng => deleteAction.singleCellTable(rng, cellRng.start));
  11199. } else if (selectionDetails.isMultiTable) {
  11200. return handleMultiTable(optCellRng, selectionDetails, rng, isRoot);
  11201. } else {
  11202. return handleSingleTable(optCellRng, selectionDetails, rng, isRoot);
  11203. }
  11204. };
  11205. const freefallRtl = root => {
  11206. const child = isComment$1(root) ? prevSibling(root) : lastChild(root);
  11207. return child.bind(freefallRtl).orThunk(() => Optional.some(root));
  11208. };
  11209. const cleanCells = cells => each$g(cells, cell => {
  11210. remove$a(cell, 'contenteditable');
  11211. fillWithPaddingBr(cell);
  11212. });
  11213. const getOutsideBlock = (editor, container) => Optional.from(editor.dom.getParent(container, editor.dom.isBlock)).map(SugarElement.fromDom);
  11214. const handleEmptyBlock = (editor, startInTable, emptyBlock) => {
  11215. emptyBlock.each(block => {
  11216. if (startInTable) {
  11217. remove$5(block);
  11218. } else {
  11219. fillWithPaddingBr(block);
  11220. editor.selection.setCursorLocation(block.dom, 0);
  11221. }
  11222. });
  11223. };
  11224. const deleteContentInsideCell = (editor, cell, rng, isFirstCellInSelection) => {
  11225. const insideTableRng = rng.cloneRange();
  11226. if (isFirstCellInSelection) {
  11227. insideTableRng.setStart(rng.startContainer, rng.startOffset);
  11228. insideTableRng.setEndAfter(cell.dom.lastChild);
  11229. } else {
  11230. insideTableRng.setStartBefore(cell.dom.firstChild);
  11231. insideTableRng.setEnd(rng.endContainer, rng.endOffset);
  11232. }
  11233. deleteCellContents(editor, insideTableRng, cell, false).each(action => action());
  11234. };
  11235. const collapseAndRestoreCellSelection = editor => {
  11236. const selectedCells = getCellsFromEditor(editor);
  11237. const selectedNode = SugarElement.fromDom(editor.selection.getNode());
  11238. if (isTableCell$5(selectedNode.dom) && isEmpty$2(selectedNode)) {
  11239. editor.selection.setCursorLocation(selectedNode.dom, 0);
  11240. } else {
  11241. editor.selection.collapse(true);
  11242. }
  11243. if (selectedCells.length > 1 && exists(selectedCells, cell => eq(cell, selectedNode))) {
  11244. set$2(selectedNode, 'data-mce-selected', '1');
  11245. }
  11246. };
  11247. const emptySingleTableCells = (editor, cells, outsideDetails) => Optional.some(() => {
  11248. const editorRng = editor.selection.getRng();
  11249. const cellsToClean = outsideDetails.bind(({rng, isStartInTable}) => {
  11250. const outsideBlock = getOutsideBlock(editor, isStartInTable ? rng.endContainer : rng.startContainer);
  11251. rng.deleteContents();
  11252. handleEmptyBlock(editor, isStartInTable, outsideBlock.filter(isEmpty$2));
  11253. const endPointCell = isStartInTable ? cells[0] : cells[cells.length - 1];
  11254. deleteContentInsideCell(editor, endPointCell, editorRng, isStartInTable);
  11255. if (!isEmpty$2(endPointCell)) {
  11256. return Optional.some(isStartInTable ? cells.slice(1) : cells.slice(0, -1));
  11257. } else {
  11258. return Optional.none();
  11259. }
  11260. }).getOr(cells);
  11261. cleanCells(cellsToClean);
  11262. collapseAndRestoreCellSelection(editor);
  11263. });
  11264. const emptyMultiTableCells = (editor, startTableCells, endTableCells, betweenRng) => Optional.some(() => {
  11265. const rng = editor.selection.getRng();
  11266. const startCell = startTableCells[0];
  11267. const endCell = endTableCells[endTableCells.length - 1];
  11268. deleteContentInsideCell(editor, startCell, rng, true);
  11269. deleteContentInsideCell(editor, endCell, rng, false);
  11270. const startTableCellsToClean = isEmpty$2(startCell) ? startTableCells : startTableCells.slice(1);
  11271. const endTableCellsToClean = isEmpty$2(endCell) ? endTableCells : endTableCells.slice(0, -1);
  11272. cleanCells(startTableCellsToClean.concat(endTableCellsToClean));
  11273. betweenRng.deleteContents();
  11274. collapseAndRestoreCellSelection(editor);
  11275. });
  11276. const deleteCellContents = (editor, rng, cell, moveSelection = true) => Optional.some(() => {
  11277. rng.deleteContents();
  11278. const lastNode = freefallRtl(cell).getOr(cell);
  11279. const lastBlock = SugarElement.fromDom(editor.dom.getParent(lastNode.dom, editor.dom.isBlock));
  11280. if (isEmpty$2(lastBlock)) {
  11281. fillWithPaddingBr(lastBlock);
  11282. if (moveSelection) {
  11283. editor.selection.setCursorLocation(lastBlock.dom, 0);
  11284. }
  11285. }
  11286. if (!eq(cell, lastBlock)) {
  11287. const additionalCleanupNodes = is$2(parent(lastBlock), cell) ? [] : siblings(lastBlock);
  11288. each$g(additionalCleanupNodes.concat(children(cell)), node => {
  11289. if (!eq(node, lastBlock) && !contains(node, lastBlock) && isEmpty$2(node)) {
  11290. remove$5(node);
  11291. }
  11292. });
  11293. }
  11294. });
  11295. const deleteTableElement = (editor, table) => Optional.some(() => deleteElement$2(editor, false, table));
  11296. const deleteCellRange = (editor, rootElm, rng) => getActionFromRange(rootElm, rng).bind(action => action.fold(curry(deleteCellContents, editor), curry(deleteTableElement, editor), curry(emptySingleTableCells, editor), curry(emptyMultiTableCells, editor)));
  11297. const deleteCaptionRange = (editor, caption) => emptyElement(editor, caption);
  11298. const deleteTableRange = (editor, rootElm, rng, startElm) => getParentCaption(rootElm, startElm).fold(() => deleteCellRange(editor, rootElm, rng), caption => deleteCaptionRange(editor, caption));
  11299. const deleteRange$2 = (editor, startElm, selectedCells) => {
  11300. const rootNode = SugarElement.fromDom(editor.getBody());
  11301. const rng = editor.selection.getRng();
  11302. return selectedCells.length !== 0 ? emptySingleTableCells(editor, selectedCells, Optional.none()) : deleteTableRange(editor, rootNode, rng, startElm);
  11303. };
  11304. const getParentCell = (rootElm, elm) => find$2(parentsAndSelf(elm, rootElm), isTableCell$4);
  11305. const getParentCaption = (rootElm, elm) => find$2(parentsAndSelf(elm, rootElm), isTag('caption'));
  11306. const deleteBetweenCells = (editor, rootElm, forward, fromCell, from) => navigate(forward, editor.getBody(), from).bind(to => getParentCell(rootElm, SugarElement.fromDom(to.getNode())).bind(toCell => eq(toCell, fromCell) ? Optional.none() : Optional.some(noop)));
  11307. const emptyElement = (editor, elm) => Optional.some(() => {
  11308. fillWithPaddingBr(elm);
  11309. editor.selection.setCursorLocation(elm.dom, 0);
  11310. });
  11311. const isDeleteOfLastCharPos = (fromCaption, forward, from, to) => firstPositionIn(fromCaption.dom).bind(first => lastPositionIn(fromCaption.dom).map(last => forward ? from.isEqual(first) && to.isEqual(last) : from.isEqual(last) && to.isEqual(first))).getOr(true);
  11312. const emptyCaretCaption = (editor, elm) => emptyElement(editor, elm);
  11313. const validateCaretCaption = (rootElm, fromCaption, to) => getParentCaption(rootElm, SugarElement.fromDom(to.getNode())).fold(() => Optional.some(noop), toCaption => someIf(!eq(toCaption, fromCaption), noop));
  11314. const deleteCaretInsideCaption = (editor, rootElm, forward, fromCaption, from) => navigate(forward, editor.getBody(), from).fold(() => Optional.some(noop), to => isDeleteOfLastCharPos(fromCaption, forward, from, to) ? emptyCaretCaption(editor, fromCaption) : validateCaretCaption(rootElm, fromCaption, to));
  11315. const deleteCaretCells = (editor, forward, rootElm, startElm) => {
  11316. const from = CaretPosition.fromRangeStart(editor.selection.getRng());
  11317. return getParentCell(rootElm, startElm).bind(fromCell => isEmpty$2(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from));
  11318. };
  11319. const deleteCaretCaption = (editor, forward, rootElm, fromCaption) => {
  11320. const from = CaretPosition.fromRangeStart(editor.selection.getRng());
  11321. return isEmpty$2(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from);
  11322. };
  11323. const isNearTable = (forward, pos) => forward ? isBeforeTable(pos) : isAfterTable(pos);
  11324. const isBeforeOrAfterTable = (editor, forward) => {
  11325. const fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  11326. return isNearTable(forward, fromPos) || fromPosition(forward, editor.getBody(), fromPos).exists(pos => isNearTable(forward, pos));
  11327. };
  11328. const deleteCaret$3 = (editor, forward, startElm) => {
  11329. const rootElm = SugarElement.fromDom(editor.getBody());
  11330. return getParentCaption(rootElm, startElm).fold(() => deleteCaretCells(editor, forward, rootElm, startElm).orThunk(() => someIf(isBeforeOrAfterTable(editor, forward), noop)), fromCaption => deleteCaretCaption(editor, forward, rootElm, fromCaption));
  11331. };
  11332. const backspaceDelete$9 = (editor, forward) => {
  11333. const startElm = SugarElement.fromDom(editor.selection.getStart(true));
  11334. const cells = getCellsFromEditor(editor);
  11335. return editor.selection.isCollapsed() && cells.length === 0 ? deleteCaret$3(editor, forward, startElm) : deleteRange$2(editor, startElm, cells);
  11336. };
  11337. const getContentEditableRoot$1 = (root, node) => {
  11338. while (node && node !== root) {
  11339. if (isContentEditableTrue$4(node) || isContentEditableFalse$a(node)) {
  11340. return node;
  11341. }
  11342. node = node.parentNode;
  11343. }
  11344. return null;
  11345. };
  11346. const traverse = (node, fn) => {
  11347. fn(node);
  11348. if (node.firstChild) {
  11349. traverse(node.firstChild, fn);
  11350. }
  11351. if (node.next) {
  11352. traverse(node.next, fn);
  11353. }
  11354. };
  11355. const matchNode$1 = (nodeFilters, attributeFilters, node, matches) => {
  11356. const name = node.name;
  11357. for (let ni = 0, nl = nodeFilters.length; ni < nl; ni++) {
  11358. const filter = nodeFilters[ni];
  11359. if (filter.name === name) {
  11360. const match = matches.nodes[name];
  11361. if (match) {
  11362. match.nodes.push(node);
  11363. } else {
  11364. matches.nodes[name] = {
  11365. filter,
  11366. nodes: [node]
  11367. };
  11368. }
  11369. }
  11370. }
  11371. if (node.attributes) {
  11372. for (let ai = 0, al = attributeFilters.length; ai < al; ai++) {
  11373. const filter = attributeFilters[ai];
  11374. const attrName = filter.name;
  11375. if (attrName in node.attributes.map) {
  11376. const match = matches.attributes[attrName];
  11377. if (match) {
  11378. match.nodes.push(node);
  11379. } else {
  11380. matches.attributes[attrName] = {
  11381. filter,
  11382. nodes: [node]
  11383. };
  11384. }
  11385. }
  11386. }
  11387. }
  11388. };
  11389. const findMatchingNodes = (nodeFilters, attributeFilters, node) => {
  11390. const matches = {
  11391. nodes: {},
  11392. attributes: {}
  11393. };
  11394. if (node.firstChild) {
  11395. traverse(node.firstChild, node => {
  11396. matchNode$1(nodeFilters, attributeFilters, node, matches);
  11397. });
  11398. }
  11399. return matches;
  11400. };
  11401. const runFilters = (matches, args) => {
  11402. const run = matchRecord => {
  11403. each$f(matchRecord, match => {
  11404. const nodes = filter$6(match.nodes, node => isNonNullable(node.parent));
  11405. each$g(match.filter.callbacks, callback => {
  11406. callback(nodes, match.filter.name, args);
  11407. });
  11408. });
  11409. };
  11410. run(matches.nodes);
  11411. run(matches.attributes);
  11412. };
  11413. const filter$3 = (nodeFilters, attributeFilters, node, args = {}) => {
  11414. const matches = findMatchingNodes(nodeFilters, attributeFilters, node);
  11415. runFilters(matches, args);
  11416. };
  11417. const paddEmptyNode = (settings, args, blockElements, node) => {
  11418. if (args.insert && blockElements[node.name]) {
  11419. node.empty().append(new AstNode('br', 1));
  11420. } else {
  11421. node.empty().append(new AstNode('#text', 3)).value = nbsp;
  11422. }
  11423. };
  11424. const isPaddedWithNbsp = node => hasOnlyChild(node, '#text') && node.firstChild.value === nbsp;
  11425. const hasOnlyChild = (node, name) => node && node.firstChild && node.firstChild === node.lastChild && node.firstChild.name === name;
  11426. const isPadded = (schema, node) => {
  11427. const rule = schema.getElementRule(node.name);
  11428. return rule && rule.paddEmpty;
  11429. };
  11430. const isEmpty = (schema, nonEmptyElements, whitespaceElements, node) => node.isEmpty(nonEmptyElements, whitespaceElements, node => isPadded(schema, node));
  11431. const isLineBreakNode = (node, blockElements) => node && (node.name in blockElements || node.name === 'br');
  11432. const removeOrUnwrapInvalidNode = (node, schema, originalNodeParent = node.parent) => {
  11433. if (schema.getSpecialElements()[node.name]) {
  11434. node.empty().remove();
  11435. } else {
  11436. const children = node.children();
  11437. for (const childNode of children) {
  11438. if (!schema.isValidChild(originalNodeParent.name, childNode.name)) {
  11439. removeOrUnwrapInvalidNode(childNode, schema, originalNodeParent);
  11440. }
  11441. }
  11442. node.unwrap();
  11443. }
  11444. };
  11445. const cleanInvalidNodes = (nodes, schema, onCreate = noop) => {
  11446. const textBlockElements = schema.getTextBlockElements();
  11447. const nonEmptyElements = schema.getNonEmptyElements();
  11448. const whitespaceElements = schema.getWhitespaceElements();
  11449. const nonSplittableElements = Tools.makeMap('tr,td,th,tbody,thead,tfoot,table');
  11450. const fixed = new Set();
  11451. for (let ni = 0; ni < nodes.length; ni++) {
  11452. const node = nodes[ni];
  11453. let parent;
  11454. let newParent;
  11455. let tempNode;
  11456. if (!node.parent || fixed.has(node)) {
  11457. continue;
  11458. }
  11459. if (textBlockElements[node.name] && node.parent.name === 'li') {
  11460. let sibling = node.next;
  11461. while (sibling) {
  11462. if (textBlockElements[sibling.name]) {
  11463. sibling.name = 'li';
  11464. fixed.add(sibling);
  11465. node.parent.insert(sibling, node.parent);
  11466. } else {
  11467. break;
  11468. }
  11469. sibling = sibling.next;
  11470. }
  11471. node.unwrap();
  11472. continue;
  11473. }
  11474. const parents = [node];
  11475. for (parent = node.parent; parent && !schema.isValidChild(parent.name, node.name) && !nonSplittableElements[parent.name]; parent = parent.parent) {
  11476. parents.push(parent);
  11477. }
  11478. if (parent && parents.length > 1) {
  11479. if (schema.isValidChild(parent.name, node.name)) {
  11480. parents.reverse();
  11481. newParent = parents[0].clone();
  11482. onCreate(newParent);
  11483. let currentNode = newParent;
  11484. for (let i = 0; i < parents.length - 1; i++) {
  11485. if (schema.isValidChild(currentNode.name, parents[i].name)) {
  11486. tempNode = parents[i].clone();
  11487. onCreate(tempNode);
  11488. currentNode.append(tempNode);
  11489. } else {
  11490. tempNode = currentNode;
  11491. }
  11492. for (let childNode = parents[i].firstChild; childNode && childNode !== parents[i + 1];) {
  11493. const nextNode = childNode.next;
  11494. tempNode.append(childNode);
  11495. childNode = nextNode;
  11496. }
  11497. currentNode = tempNode;
  11498. }
  11499. if (!isEmpty(schema, nonEmptyElements, whitespaceElements, newParent)) {
  11500. parent.insert(newParent, parents[0], true);
  11501. parent.insert(node, newParent);
  11502. } else {
  11503. parent.insert(node, parents[0], true);
  11504. }
  11505. parent = parents[0];
  11506. if (isEmpty(schema, nonEmptyElements, whitespaceElements, parent) || hasOnlyChild(parent, 'br')) {
  11507. parent.empty().remove();
  11508. }
  11509. } else {
  11510. removeOrUnwrapInvalidNode(node, schema);
  11511. }
  11512. } else if (node.parent) {
  11513. if (node.name === 'li') {
  11514. let sibling = node.prev;
  11515. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  11516. sibling.append(node);
  11517. continue;
  11518. }
  11519. sibling = node.next;
  11520. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  11521. sibling.insert(node, sibling.firstChild, true);
  11522. continue;
  11523. }
  11524. const wrapper = new AstNode('ul', 1);
  11525. onCreate(wrapper);
  11526. node.wrap(wrapper);
  11527. continue;
  11528. }
  11529. if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
  11530. const wrapper = new AstNode('div', 1);
  11531. onCreate(wrapper);
  11532. node.wrap(wrapper);
  11533. } else {
  11534. removeOrUnwrapInvalidNode(node, schema);
  11535. }
  11536. }
  11537. }
  11538. };
  11539. const createRange = (sc, so, ec, eo) => {
  11540. const rng = document.createRange();
  11541. rng.setStart(sc, so);
  11542. rng.setEnd(ec, eo);
  11543. return rng;
  11544. };
  11545. const normalizeBlockSelectionRange = rng => {
  11546. const startPos = CaretPosition.fromRangeStart(rng);
  11547. const endPos = CaretPosition.fromRangeEnd(rng);
  11548. const rootNode = rng.commonAncestorContainer;
  11549. return fromPosition(false, rootNode, endPos).map(newEndPos => {
  11550. if (!isInSameBlock(startPos, endPos, rootNode) && isInSameBlock(startPos, newEndPos, rootNode)) {
  11551. return createRange(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
  11552. } else {
  11553. return rng;
  11554. }
  11555. }).getOr(rng);
  11556. };
  11557. const normalize = rng => rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
  11558. const hasOnlyOneChild$1 = node => {
  11559. return node.firstChild && node.firstChild === node.lastChild;
  11560. };
  11561. const isPaddingNode = node => {
  11562. return node.name === 'br' || node.value === nbsp;
  11563. };
  11564. const isPaddedEmptyBlock = (schema, node) => {
  11565. const blockElements = schema.getBlockElements();
  11566. return blockElements[node.name] && hasOnlyOneChild$1(node) && isPaddingNode(node.firstChild);
  11567. };
  11568. const isEmptyFragmentElement = (schema, node) => {
  11569. const nonEmptyElements = schema.getNonEmptyElements();
  11570. return node && (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
  11571. };
  11572. const isListFragment = (schema, fragment) => {
  11573. let firstChild = fragment.firstChild;
  11574. let lastChild = fragment.lastChild;
  11575. if (firstChild && firstChild.name === 'meta') {
  11576. firstChild = firstChild.next;
  11577. }
  11578. if (lastChild && lastChild.attr('id') === 'mce_marker') {
  11579. lastChild = lastChild.prev;
  11580. }
  11581. if (isEmptyFragmentElement(schema, lastChild)) {
  11582. lastChild = lastChild.prev;
  11583. }
  11584. if (!firstChild || firstChild !== lastChild) {
  11585. return false;
  11586. }
  11587. return firstChild.name === 'ul' || firstChild.name === 'ol';
  11588. };
  11589. const cleanupDomFragment = domFragment => {
  11590. const firstChild = domFragment.firstChild;
  11591. const lastChild = domFragment.lastChild;
  11592. if (firstChild && firstChild.nodeName === 'META') {
  11593. firstChild.parentNode.removeChild(firstChild);
  11594. }
  11595. if (lastChild && lastChild.id === 'mce_marker') {
  11596. lastChild.parentNode.removeChild(lastChild);
  11597. }
  11598. return domFragment;
  11599. };
  11600. const toDomFragment = (dom, serializer, fragment) => {
  11601. const html = serializer.serialize(fragment);
  11602. const domFragment = dom.createFragment(html);
  11603. return cleanupDomFragment(domFragment);
  11604. };
  11605. const listItems = elm => {
  11606. return filter$6(elm.childNodes, child => {
  11607. return child.nodeName === 'LI';
  11608. });
  11609. };
  11610. const isPadding = node => {
  11611. return node.data === nbsp || isBr$5(node);
  11612. };
  11613. const isListItemPadded = node => {
  11614. return node && node.firstChild && node.firstChild === node.lastChild && isPadding(node.firstChild);
  11615. };
  11616. const isEmptyOrPadded = elm => {
  11617. return !elm.firstChild || isListItemPadded(elm);
  11618. };
  11619. const trimListItems = elms => {
  11620. return elms.length > 0 && isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
  11621. };
  11622. const getParentLi = (dom, node) => {
  11623. const parentBlock = dom.getParent(node, dom.isBlock);
  11624. return parentBlock && parentBlock.nodeName === 'LI' ? parentBlock : null;
  11625. };
  11626. const isParentBlockLi = (dom, node) => {
  11627. return !!getParentLi(dom, node);
  11628. };
  11629. const getSplit = (parentNode, rng) => {
  11630. const beforeRng = rng.cloneRange();
  11631. const afterRng = rng.cloneRange();
  11632. beforeRng.setStartBefore(parentNode);
  11633. afterRng.setEndAfter(parentNode);
  11634. return [
  11635. beforeRng.cloneContents(),
  11636. afterRng.cloneContents()
  11637. ];
  11638. };
  11639. const findFirstIn = (node, rootNode) => {
  11640. const caretPos = CaretPosition.before(node);
  11641. const caretWalker = CaretWalker(rootNode);
  11642. const newCaretPos = caretWalker.next(caretPos);
  11643. return newCaretPos ? newCaretPos.toRange() : null;
  11644. };
  11645. const findLastOf = (node, rootNode) => {
  11646. const caretPos = CaretPosition.after(node);
  11647. const caretWalker = CaretWalker(rootNode);
  11648. const newCaretPos = caretWalker.prev(caretPos);
  11649. return newCaretPos ? newCaretPos.toRange() : null;
  11650. };
  11651. const insertMiddle = (target, elms, rootNode, rng) => {
  11652. const parts = getSplit(target, rng);
  11653. const parentElm = target.parentNode;
  11654. parentElm.insertBefore(parts[0], target);
  11655. Tools.each(elms, li => {
  11656. parentElm.insertBefore(li, target);
  11657. });
  11658. parentElm.insertBefore(parts[1], target);
  11659. parentElm.removeChild(target);
  11660. return findLastOf(elms[elms.length - 1], rootNode);
  11661. };
  11662. const insertBefore$1 = (target, elms, rootNode) => {
  11663. const parentElm = target.parentNode;
  11664. Tools.each(elms, elm => {
  11665. parentElm.insertBefore(elm, target);
  11666. });
  11667. return findFirstIn(target, rootNode);
  11668. };
  11669. const insertAfter$1 = (target, elms, rootNode, dom) => {
  11670. dom.insertAfter(elms.reverse(), target);
  11671. return findLastOf(elms[0], rootNode);
  11672. };
  11673. const insertAtCaret$1 = (serializer, dom, rng, fragment) => {
  11674. const domFragment = toDomFragment(dom, serializer, fragment);
  11675. const liTarget = getParentLi(dom, rng.startContainer);
  11676. const liElms = trimListItems(listItems(domFragment.firstChild));
  11677. const BEGINNING = 1, END = 2;
  11678. const rootNode = dom.getRoot();
  11679. const isAt = location => {
  11680. const caretPos = CaretPosition.fromRangeStart(rng);
  11681. const caretWalker = CaretWalker(dom.getRoot());
  11682. const newPos = location === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
  11683. return newPos ? getParentLi(dom, newPos.getNode()) !== liTarget : true;
  11684. };
  11685. if (isAt(BEGINNING)) {
  11686. return insertBefore$1(liTarget, liElms, rootNode);
  11687. } else if (isAt(END)) {
  11688. return insertAfter$1(liTarget, liElms, rootNode, dom);
  11689. }
  11690. return insertMiddle(liTarget, liElms, rootNode, rng);
  11691. };
  11692. const isTableCell$1 = isTableCell$5;
  11693. const isTableCellContentSelected = (dom, rng, cell) => {
  11694. if (cell !== null) {
  11695. const endCell = dom.getParent(rng.endContainer, isTableCell$1);
  11696. return cell === endCell && hasAllContentsSelected(SugarElement.fromDom(cell), rng);
  11697. } else {
  11698. return false;
  11699. }
  11700. };
  11701. const validInsertion = (editor, value, parentNode) => {
  11702. if (parentNode.getAttribute('data-mce-bogus') === 'all') {
  11703. parentNode.parentNode.insertBefore(editor.dom.createFragment(value), parentNode);
  11704. } else {
  11705. const node = parentNode.firstChild;
  11706. const node2 = parentNode.lastChild;
  11707. if (!node || node === node2 && node.nodeName === 'BR') {
  11708. editor.dom.setHTML(parentNode, value);
  11709. } else {
  11710. editor.selection.setContent(value, { no_events: true });
  11711. }
  11712. }
  11713. };
  11714. const trimBrsFromTableCell = (dom, elm) => {
  11715. Optional.from(dom.getParent(elm, 'td,th')).map(SugarElement.fromDom).each(trimBlockTrailingBr);
  11716. };
  11717. const reduceInlineTextElements = (editor, merge) => {
  11718. const textInlineElements = editor.schema.getTextInlineElements();
  11719. const dom = editor.dom;
  11720. if (merge) {
  11721. const root = editor.getBody();
  11722. const elementUtils = ElementUtils(dom);
  11723. Tools.each(dom.select('*[data-mce-fragment]'), node => {
  11724. const isInline = isNonNullable(textInlineElements[node.nodeName.toLowerCase()]);
  11725. if (isInline && hasInheritableStyles(dom, node)) {
  11726. for (let parentNode = node.parentNode; isNonNullable(parentNode) && parentNode !== root; parentNode = parentNode.parentNode) {
  11727. const styleConflict = hasStyleConflict(dom, node, parentNode);
  11728. if (styleConflict) {
  11729. break;
  11730. }
  11731. if (elementUtils.compare(parentNode, node)) {
  11732. dom.remove(node, true);
  11733. break;
  11734. }
  11735. }
  11736. }
  11737. });
  11738. }
  11739. };
  11740. const markFragmentElements = fragment => {
  11741. let node = fragment;
  11742. while (node = node.walk()) {
  11743. if (node.type === 1) {
  11744. node.attr('data-mce-fragment', '1');
  11745. }
  11746. }
  11747. };
  11748. const unmarkFragmentElements = elm => {
  11749. Tools.each(elm.getElementsByTagName('*'), elm => {
  11750. elm.removeAttribute('data-mce-fragment');
  11751. });
  11752. };
  11753. const isPartOfFragment = node => {
  11754. return !!node.getAttribute('data-mce-fragment');
  11755. };
  11756. const canHaveChildren = (editor, node) => {
  11757. return node && !editor.schema.getVoidElements()[node.nodeName];
  11758. };
  11759. const moveSelectionToMarker = (editor, marker) => {
  11760. let nextRng;
  11761. const dom = editor.dom;
  11762. const selection = editor.selection;
  11763. if (!marker) {
  11764. return;
  11765. }
  11766. selection.scrollIntoView(marker);
  11767. const parentEditableElm = getContentEditableRoot$1(editor.getBody(), marker);
  11768. if (dom.getContentEditable(parentEditableElm) === 'false') {
  11769. dom.remove(marker);
  11770. selection.select(parentEditableElm);
  11771. return;
  11772. }
  11773. let rng = dom.createRng();
  11774. const node = marker.previousSibling;
  11775. if (isText$8(node)) {
  11776. rng.setStart(node, node.nodeValue.length);
  11777. const node2 = marker.nextSibling;
  11778. if (isText$8(node2)) {
  11779. node.appendData(node2.data);
  11780. node2.parentNode.removeChild(node2);
  11781. }
  11782. } else {
  11783. rng.setStartBefore(marker);
  11784. rng.setEndBefore(marker);
  11785. }
  11786. const findNextCaretRng = rng => {
  11787. let caretPos = CaretPosition.fromRangeStart(rng);
  11788. const caretWalker = CaretWalker(editor.getBody());
  11789. caretPos = caretWalker.next(caretPos);
  11790. if (caretPos) {
  11791. return caretPos.toRange();
  11792. }
  11793. };
  11794. const parentBlock = dom.getParent(marker, dom.isBlock);
  11795. dom.remove(marker);
  11796. if (parentBlock && dom.isEmpty(parentBlock)) {
  11797. empty(SugarElement.fromDom(parentBlock));
  11798. rng.setStart(parentBlock, 0);
  11799. rng.setEnd(parentBlock, 0);
  11800. if (!isTableCell$1(parentBlock) && !isPartOfFragment(parentBlock) && (nextRng = findNextCaretRng(rng))) {
  11801. rng = nextRng;
  11802. dom.remove(parentBlock);
  11803. } else {
  11804. dom.add(parentBlock, dom.create('br', { 'data-mce-bogus': '1' }));
  11805. }
  11806. }
  11807. selection.setRng(rng);
  11808. };
  11809. const deleteSelectedContent = editor => {
  11810. const dom = editor.dom;
  11811. const rng = normalize(editor.selection.getRng());
  11812. editor.selection.setRng(rng);
  11813. const startCell = dom.getParent(rng.startContainer, isTableCell$1);
  11814. if (isTableCellContentSelected(dom, rng, startCell)) {
  11815. deleteCellContents(editor, rng, SugarElement.fromDom(startCell));
  11816. } else {
  11817. editor.getDoc().execCommand('Delete', false, null);
  11818. }
  11819. };
  11820. const insertHtmlAtCaret = (editor, value, details) => {
  11821. let parentNode;
  11822. let rng, node;
  11823. const selection = editor.selection;
  11824. const dom = editor.dom;
  11825. const parser = editor.parser;
  11826. const merge = details.merge;
  11827. const serializer = HtmlSerializer({ validate: true }, editor.schema);
  11828. const bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>';
  11829. if (value.indexOf('{$caret}') === -1) {
  11830. value += '{$caret}';
  11831. }
  11832. value = value.replace(/\{\$caret\}/, bookmarkHtml);
  11833. rng = selection.getRng();
  11834. const caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
  11835. const body = editor.getBody();
  11836. if (caretElement === body && selection.isCollapsed()) {
  11837. if (dom.isBlock(body.firstChild) && canHaveChildren(editor, body.firstChild) && dom.isEmpty(body.firstChild)) {
  11838. rng = dom.createRng();
  11839. rng.setStart(body.firstChild, 0);
  11840. rng.setEnd(body.firstChild, 0);
  11841. selection.setRng(rng);
  11842. }
  11843. }
  11844. if (!selection.isCollapsed()) {
  11845. deleteSelectedContent(editor);
  11846. }
  11847. parentNode = selection.getNode();
  11848. const parserArgs = {
  11849. context: parentNode.nodeName.toLowerCase(),
  11850. data: details.data,
  11851. insert: true
  11852. };
  11853. const fragment = parser.parse(value, parserArgs);
  11854. if (details.paste === true && isListFragment(editor.schema, fragment) && isParentBlockLi(dom, parentNode)) {
  11855. rng = insertAtCaret$1(serializer, dom, selection.getRng(), fragment);
  11856. selection.setRng(rng);
  11857. return value;
  11858. }
  11859. markFragmentElements(fragment);
  11860. node = fragment.lastChild;
  11861. if (node.attr('id') === 'mce_marker') {
  11862. const marker = node;
  11863. for (node = node.prev; node; node = node.walk(true)) {
  11864. if (node.type === 3 || !dom.isBlock(node.name)) {
  11865. if (editor.schema.isValidChild(node.parent.name, 'span')) {
  11866. node.parent.insert(marker, node, node.name === 'br');
  11867. }
  11868. break;
  11869. }
  11870. }
  11871. }
  11872. editor._selectionOverrides.showBlockCaretContainer(parentNode);
  11873. if (!parserArgs.invalid) {
  11874. value = serializer.serialize(fragment);
  11875. validInsertion(editor, value, parentNode);
  11876. } else {
  11877. editor.selection.setContent(bookmarkHtml);
  11878. parentNode = selection.getNode();
  11879. const rootNode = editor.getBody();
  11880. if (parentNode.nodeType === 9) {
  11881. parentNode = node = rootNode;
  11882. } else {
  11883. node = parentNode;
  11884. }
  11885. while (node !== rootNode) {
  11886. parentNode = node;
  11887. node = node.parentNode;
  11888. }
  11889. value = parentNode === rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
  11890. const root = parser.parse(value);
  11891. for (let markerNode = root; markerNode; markerNode = markerNode.walk()) {
  11892. if (markerNode.attr('id') === 'mce_marker') {
  11893. markerNode.replace(fragment);
  11894. break;
  11895. }
  11896. }
  11897. const toExtract = fragment.children();
  11898. const parent = fragment.parent.name;
  11899. fragment.unwrap();
  11900. const invalidChildren = filter$6(toExtract, node => !editor.schema.isValidChild(parent, node.name));
  11901. cleanInvalidNodes(invalidChildren, editor.schema);
  11902. filter$3(parser.getNodeFilters(), parser.getAttributeFilters(), root);
  11903. value = serializer.serialize(root);
  11904. if (parentNode === rootNode) {
  11905. dom.setHTML(rootNode, value);
  11906. } else {
  11907. dom.setOuterHTML(parentNode, value);
  11908. }
  11909. }
  11910. reduceInlineTextElements(editor, merge);
  11911. moveSelectionToMarker(editor, dom.get('mce_marker'));
  11912. unmarkFragmentElements(editor.getBody());
  11913. trimBrsFromTableCell(dom, selection.getStart());
  11914. return value;
  11915. };
  11916. const isTreeNode = content => content instanceof AstNode;
  11917. const moveSelection = editor => {
  11918. if (hasFocus(editor)) {
  11919. firstPositionIn(editor.getBody()).each(pos => {
  11920. const node = pos.getNode();
  11921. const caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  11922. editor.selection.setRng(caretPos.toRange());
  11923. });
  11924. }
  11925. };
  11926. const setEditorHtml = (editor, html, noSelection) => {
  11927. editor.dom.setHTML(editor.getBody(), html);
  11928. if (noSelection !== true) {
  11929. moveSelection(editor);
  11930. }
  11931. };
  11932. const setContentString = (editor, body, content, args) => {
  11933. if (content.length === 0 || /^\s+$/.test(content)) {
  11934. const padd = '<br data-mce-bogus="1">';
  11935. if (body.nodeName === 'TABLE') {
  11936. content = '<tr><td>' + padd + '</td></tr>';
  11937. } else if (/^(UL|OL)$/.test(body.nodeName)) {
  11938. content = '<li>' + padd + '</li>';
  11939. }
  11940. const forcedRootBlockName = getForcedRootBlock(editor);
  11941. if (editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
  11942. content = padd;
  11943. content = editor.dom.createHTML(forcedRootBlockName, getForcedRootBlockAttrs(editor), content);
  11944. } else if (!content) {
  11945. content = padd;
  11946. }
  11947. setEditorHtml(editor, content, args.no_selection);
  11948. return {
  11949. content,
  11950. html: content
  11951. };
  11952. } else {
  11953. if (args.format !== 'raw') {
  11954. content = HtmlSerializer({ validate: false }, editor.schema).serialize(editor.parser.parse(content, {
  11955. isRootContent: true,
  11956. insert: true
  11957. }));
  11958. }
  11959. const trimmedHtml = isWsPreserveElement(SugarElement.fromDom(body)) ? content : Tools.trim(content);
  11960. setEditorHtml(editor, trimmedHtml, args.no_selection);
  11961. return {
  11962. content: trimmedHtml,
  11963. html: trimmedHtml
  11964. };
  11965. }
  11966. };
  11967. const setContentTree = (editor, body, content, args) => {
  11968. filter$3(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
  11969. const html = HtmlSerializer({ validate: false }, editor.schema).serialize(content);
  11970. const trimmedHtml = isWsPreserveElement(SugarElement.fromDom(body)) ? html : Tools.trim(html);
  11971. setEditorHtml(editor, trimmedHtml, args.no_selection);
  11972. return {
  11973. content,
  11974. html: trimmedHtml
  11975. };
  11976. };
  11977. const setContentInternal = (editor, content, args) => {
  11978. return Optional.from(editor.getBody()).map(body => {
  11979. if (isTreeNode(content)) {
  11980. return setContentTree(editor, body, content, args);
  11981. } else {
  11982. return setContentString(editor, body, content, args);
  11983. }
  11984. }).getOr({
  11985. content,
  11986. html: isTreeNode(args.content) ? '' : args.content
  11987. });
  11988. };
  11989. const sibling = (scope, predicate) => sibling$1(scope, predicate).isSome();
  11990. const ensureIsRoot = isRoot => isFunction(isRoot) ? isRoot : never;
  11991. const ancestor = (scope, transform, isRoot) => {
  11992. let element = scope.dom;
  11993. const stop = ensureIsRoot(isRoot);
  11994. while (element.parentNode) {
  11995. element = element.parentNode;
  11996. const el = SugarElement.fromDom(element);
  11997. const transformed = transform(el);
  11998. if (transformed.isSome()) {
  11999. return transformed;
  12000. } else if (stop(el)) {
  12001. break;
  12002. }
  12003. }
  12004. return Optional.none();
  12005. };
  12006. const closest$2 = (scope, transform, isRoot) => {
  12007. const current = transform(scope);
  12008. const stop = ensureIsRoot(isRoot);
  12009. return current.orThunk(() => stop(scope) ? Optional.none() : ancestor(scope, transform, stop));
  12010. };
  12011. const isEq$3 = isEq$5;
  12012. const matchesUnInheritedFormatSelector = (ed, node, name) => {
  12013. const formatList = ed.formatter.get(name);
  12014. if (formatList) {
  12015. for (let i = 0; i < formatList.length; i++) {
  12016. const format = formatList[i];
  12017. if (isSelectorFormat(format) && format.inherit === false && ed.dom.is(node, format.selector)) {
  12018. return true;
  12019. }
  12020. }
  12021. }
  12022. return false;
  12023. };
  12024. const matchParents = (editor, node, name, vars, similar) => {
  12025. const root = editor.dom.getRoot();
  12026. if (node === root) {
  12027. return false;
  12028. }
  12029. node = editor.dom.getParent(node, node => {
  12030. if (matchesUnInheritedFormatSelector(editor, node, name)) {
  12031. return true;
  12032. }
  12033. return node.parentNode === root || !!matchNode(editor, node, name, vars, true);
  12034. });
  12035. return !!matchNode(editor, node, name, vars, similar);
  12036. };
  12037. const matchName = (dom, node, format) => {
  12038. if (isInlineFormat(format) && isEq$3(node, format.inline)) {
  12039. return true;
  12040. }
  12041. if (isBlockFormat(format) && isEq$3(node, format.block)) {
  12042. return true;
  12043. }
  12044. if (isSelectorFormat(format)) {
  12045. return isElement$6(node) && dom.is(node, format.selector);
  12046. }
  12047. return false;
  12048. };
  12049. const matchItems = (dom, node, format, itemName, similar, vars) => {
  12050. const items = format[itemName];
  12051. if (isFunction(format.onmatch)) {
  12052. return format.onmatch(node, format, itemName);
  12053. }
  12054. if (items) {
  12055. if (isUndefined(items.length)) {
  12056. for (const key in items) {
  12057. if (has$2(items, key)) {
  12058. const value = itemName === 'attributes' ? dom.getAttrib(node, key) : getStyle(dom, node, key);
  12059. const expectedValue = replaceVars(items[key], vars);
  12060. const isEmptyValue = isNullable(value) || isEmpty$3(value);
  12061. if (isEmptyValue && isNullable(expectedValue)) {
  12062. continue;
  12063. }
  12064. if (similar && isEmptyValue && !format.exact) {
  12065. return false;
  12066. }
  12067. if ((!similar || format.exact) && !isEq$3(value, normalizeStyleValue(expectedValue, key))) {
  12068. return false;
  12069. }
  12070. }
  12071. }
  12072. } else {
  12073. for (let i = 0; i < items.length; i++) {
  12074. if (itemName === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(dom, node, items[i])) {
  12075. return true;
  12076. }
  12077. }
  12078. }
  12079. }
  12080. return true;
  12081. };
  12082. const matchNode = (ed, node, name, vars, similar) => {
  12083. const formatList = ed.formatter.get(name);
  12084. const dom = ed.dom;
  12085. if (formatList && node) {
  12086. for (let i = 0; i < formatList.length; i++) {
  12087. const format = formatList[i];
  12088. if (matchName(ed.dom, node, format) && matchItems(dom, node, format, 'attributes', similar, vars) && matchItems(dom, node, format, 'styles', similar, vars)) {
  12089. const classes = format.classes;
  12090. if (classes) {
  12091. for (let x = 0; x < classes.length; x++) {
  12092. if (!ed.dom.hasClass(node, replaceVars(classes[x], vars))) {
  12093. return;
  12094. }
  12095. }
  12096. }
  12097. return format;
  12098. }
  12099. }
  12100. }
  12101. };
  12102. const match$2 = (editor, name, vars, node, similar) => {
  12103. if (node) {
  12104. return matchParents(editor, node, name, vars, similar);
  12105. }
  12106. node = editor.selection.getNode();
  12107. if (matchParents(editor, node, name, vars, similar)) {
  12108. return true;
  12109. }
  12110. const startNode = editor.selection.getStart();
  12111. if (startNode !== node) {
  12112. if (matchParents(editor, startNode, name, vars, similar)) {
  12113. return true;
  12114. }
  12115. }
  12116. return false;
  12117. };
  12118. const matchAll = (editor, names, vars) => {
  12119. const matchedFormatNames = [];
  12120. const checkedMap = {};
  12121. const startElement = editor.selection.getStart();
  12122. editor.dom.getParent(startElement, node => {
  12123. for (let i = 0; i < names.length; i++) {
  12124. const name = names[i];
  12125. if (!checkedMap[name] && matchNode(editor, node, name, vars)) {
  12126. checkedMap[name] = true;
  12127. matchedFormatNames.push(name);
  12128. }
  12129. }
  12130. }, editor.dom.getRoot());
  12131. return matchedFormatNames;
  12132. };
  12133. const closest$1 = (editor, names) => {
  12134. const isRoot = elm => eq(elm, SugarElement.fromDom(editor.getBody()));
  12135. const match = (elm, name) => matchNode(editor, elm.dom, name) ? Optional.some(name) : Optional.none();
  12136. return Optional.from(editor.selection.getStart(true)).bind(rawElm => closest$2(SugarElement.fromDom(rawElm), elm => findMap(names, name => match(elm, name)), isRoot)).getOrNull();
  12137. };
  12138. const canApply = (editor, name) => {
  12139. const formatList = editor.formatter.get(name);
  12140. const dom = editor.dom;
  12141. if (formatList) {
  12142. const startNode = editor.selection.getStart();
  12143. const parents = getParents$2(dom, startNode);
  12144. for (let x = formatList.length - 1; x >= 0; x--) {
  12145. const format = formatList[x];
  12146. if (!isSelectorFormat(format)) {
  12147. return true;
  12148. }
  12149. for (let i = parents.length - 1; i >= 0; i--) {
  12150. if (dom.is(parents[i], format.selector)) {
  12151. return true;
  12152. }
  12153. }
  12154. }
  12155. }
  12156. return false;
  12157. };
  12158. const matchAllOnNode = (editor, node, formatNames) => foldl(formatNames, (acc, name) => {
  12159. const matchSimilar = isVariableFormatName(editor, name);
  12160. if (editor.formatter.matchNode(node, name, {}, matchSimilar)) {
  12161. return acc.concat([name]);
  12162. } else {
  12163. return acc;
  12164. }
  12165. }, []);
  12166. const ZWSP = ZWSP$1, CARET_ID = '_mce_caret';
  12167. const importNode = (ownerDocument, node) => {
  12168. return ownerDocument.importNode(node, true);
  12169. };
  12170. const getEmptyCaretContainers = node => {
  12171. const nodes = [];
  12172. while (node) {
  12173. if (node.nodeType === 3 && node.nodeValue !== ZWSP || node.childNodes.length > 1) {
  12174. return [];
  12175. }
  12176. if (node.nodeType === 1) {
  12177. nodes.push(node);
  12178. }
  12179. node = node.firstChild;
  12180. }
  12181. return nodes;
  12182. };
  12183. const isCaretContainerEmpty = node => {
  12184. return getEmptyCaretContainers(node).length > 0;
  12185. };
  12186. const findFirstTextNode = node => {
  12187. if (node) {
  12188. const walker = new DomTreeWalker(node, node);
  12189. for (node = walker.current(); node; node = walker.next()) {
  12190. if (isText$8(node)) {
  12191. return node;
  12192. }
  12193. }
  12194. }
  12195. return null;
  12196. };
  12197. const createCaretContainer = fill => {
  12198. const caretContainer = SugarElement.fromTag('span');
  12199. setAll$1(caretContainer, {
  12200. 'id': CARET_ID,
  12201. 'data-mce-bogus': '1',
  12202. 'data-mce-type': 'format-caret'
  12203. });
  12204. if (fill) {
  12205. append$1(caretContainer, SugarElement.fromText(ZWSP));
  12206. }
  12207. return caretContainer;
  12208. };
  12209. const trimZwspFromCaretContainer = caretContainerNode => {
  12210. const textNode = findFirstTextNode(caretContainerNode);
  12211. if (textNode && textNode.nodeValue.charAt(0) === ZWSP) {
  12212. textNode.deleteData(0, 1);
  12213. }
  12214. return textNode;
  12215. };
  12216. const removeCaretContainerNode = (editor, node, moveCaret = true) => {
  12217. const dom = editor.dom, selection = editor.selection;
  12218. if (isCaretContainerEmpty(node)) {
  12219. deleteElement$2(editor, false, SugarElement.fromDom(node), moveCaret);
  12220. } else {
  12221. const rng = selection.getRng();
  12222. const block = dom.getParent(node, dom.isBlock);
  12223. const startContainer = rng.startContainer;
  12224. const startOffset = rng.startOffset;
  12225. const endContainer = rng.endContainer;
  12226. const endOffset = rng.endOffset;
  12227. const textNode = trimZwspFromCaretContainer(node);
  12228. dom.remove(node, true);
  12229. if (startContainer === textNode && startOffset > 0) {
  12230. rng.setStart(textNode, startOffset - 1);
  12231. }
  12232. if (endContainer === textNode && endOffset > 0) {
  12233. rng.setEnd(textNode, endOffset - 1);
  12234. }
  12235. if (block && dom.isEmpty(block)) {
  12236. fillWithPaddingBr(SugarElement.fromDom(block));
  12237. }
  12238. selection.setRng(rng);
  12239. }
  12240. };
  12241. const removeCaretContainer = (editor, node, moveCaret = true) => {
  12242. const dom = editor.dom, selection = editor.selection;
  12243. if (!node) {
  12244. node = getParentCaretContainer(editor.getBody(), selection.getStart());
  12245. if (!node) {
  12246. while (node = dom.get(CARET_ID)) {
  12247. removeCaretContainerNode(editor, node, false);
  12248. }
  12249. }
  12250. } else {
  12251. removeCaretContainerNode(editor, node, moveCaret);
  12252. }
  12253. };
  12254. const insertCaretContainerNode = (editor, caretContainer, formatNode) => {
  12255. const dom = editor.dom, block = dom.getParent(formatNode, curry(isTextBlock$1, editor));
  12256. if (block && dom.isEmpty(block)) {
  12257. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  12258. } else {
  12259. removeTrailingBr(SugarElement.fromDom(formatNode));
  12260. if (dom.isEmpty(formatNode)) {
  12261. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  12262. } else {
  12263. dom.insertAfter(caretContainer, formatNode);
  12264. }
  12265. }
  12266. };
  12267. const appendNode = (parentNode, node) => {
  12268. parentNode.appendChild(node);
  12269. return node;
  12270. };
  12271. const insertFormatNodesIntoCaretContainer = (formatNodes, caretContainer) => {
  12272. const innerMostFormatNode = foldr(formatNodes, (parentNode, formatNode) => {
  12273. return appendNode(parentNode, formatNode.cloneNode(false));
  12274. }, caretContainer);
  12275. return appendNode(innerMostFormatNode, innerMostFormatNode.ownerDocument.createTextNode(ZWSP));
  12276. };
  12277. const cleanFormatNode = (editor, caretContainer, formatNode, name, vars, similar) => {
  12278. const formatter = editor.formatter;
  12279. const dom = editor.dom;
  12280. const validFormats = filter$6(keys(formatter.get()), formatName => formatName !== name && !contains$1(formatName, 'removeformat'));
  12281. const matchedFormats = matchAllOnNode(editor, formatNode, validFormats);
  12282. const uniqueFormats = filter$6(matchedFormats, fmtName => !areSimilarFormats(editor, fmtName, name));
  12283. if (uniqueFormats.length > 0) {
  12284. const clonedFormatNode = formatNode.cloneNode(false);
  12285. dom.add(caretContainer, clonedFormatNode);
  12286. formatter.remove(name, vars, clonedFormatNode, similar);
  12287. dom.remove(clonedFormatNode);
  12288. return Optional.some(clonedFormatNode);
  12289. } else {
  12290. return Optional.none();
  12291. }
  12292. };
  12293. const applyCaretFormat = (editor, name, vars) => {
  12294. let caretContainer, textNode;
  12295. const selection = editor.selection;
  12296. const selectionRng = selection.getRng();
  12297. let offset = selectionRng.startOffset;
  12298. const container = selectionRng.startContainer;
  12299. const text = container.nodeValue;
  12300. caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
  12301. if (caretContainer) {
  12302. textNode = findFirstTextNode(caretContainer);
  12303. }
  12304. const wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
  12305. if (text && offset > 0 && offset < text.length && wordcharRegex.test(text.charAt(offset)) && wordcharRegex.test(text.charAt(offset - 1))) {
  12306. const bookmark = selection.getBookmark();
  12307. selectionRng.collapse(true);
  12308. let rng = expandRng(editor, selectionRng, editor.formatter.get(name));
  12309. rng = split(rng);
  12310. editor.formatter.apply(name, vars, rng);
  12311. selection.moveToBookmark(bookmark);
  12312. } else {
  12313. if (!caretContainer || textNode.nodeValue !== ZWSP) {
  12314. caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom);
  12315. textNode = caretContainer.firstChild;
  12316. selectionRng.insertNode(caretContainer);
  12317. offset = 1;
  12318. editor.formatter.apply(name, vars, caretContainer);
  12319. } else {
  12320. editor.formatter.apply(name, vars, caretContainer);
  12321. }
  12322. selection.setCursorLocation(textNode, offset);
  12323. }
  12324. };
  12325. const removeCaretFormat = (editor, name, vars, similar) => {
  12326. const dom = editor.dom;
  12327. const selection = editor.selection;
  12328. let hasContentAfter, node, formatNode;
  12329. const parents = [];
  12330. const rng = selection.getRng();
  12331. const container = rng.startContainer;
  12332. const offset = rng.startOffset;
  12333. node = container;
  12334. if (container.nodeType === 3) {
  12335. if (offset !== container.nodeValue.length) {
  12336. hasContentAfter = true;
  12337. }
  12338. node = node.parentNode;
  12339. }
  12340. while (node) {
  12341. if (matchNode(editor, node, name, vars, similar)) {
  12342. formatNode = node;
  12343. break;
  12344. }
  12345. if (node.nextSibling) {
  12346. hasContentAfter = true;
  12347. }
  12348. parents.push(node);
  12349. node = node.parentNode;
  12350. }
  12351. if (!formatNode) {
  12352. return;
  12353. }
  12354. if (hasContentAfter) {
  12355. const bookmark = selection.getBookmark();
  12356. rng.collapse(true);
  12357. let expandedRng = expandRng(editor, rng, editor.formatter.get(name), true);
  12358. expandedRng = split(expandedRng);
  12359. editor.formatter.remove(name, vars, expandedRng, similar);
  12360. selection.moveToBookmark(bookmark);
  12361. } else {
  12362. const caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
  12363. const newCaretContainer = createCaretContainer(false).dom;
  12364. insertCaretContainerNode(editor, newCaretContainer, caretContainer !== null ? caretContainer : formatNode);
  12365. const cleanedFormatNode = cleanFormatNode(editor, newCaretContainer, formatNode, name, vars, similar);
  12366. const caretTextNode = insertFormatNodesIntoCaretContainer(parents.concat(cleanedFormatNode.toArray()), newCaretContainer);
  12367. removeCaretContainerNode(editor, caretContainer, false);
  12368. selection.setCursorLocation(caretTextNode, 1);
  12369. if (dom.isEmpty(formatNode)) {
  12370. dom.remove(formatNode);
  12371. }
  12372. }
  12373. };
  12374. const disableCaretContainer = (editor, keyCode) => {
  12375. const selection = editor.selection, body = editor.getBody();
  12376. removeCaretContainer(editor, null, false);
  12377. if ((keyCode === 8 || keyCode === 46) && selection.isCollapsed() && selection.getStart().innerHTML === ZWSP) {
  12378. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  12379. }
  12380. if (keyCode === 37 || keyCode === 39) {
  12381. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  12382. }
  12383. };
  12384. const setup$u = editor => {
  12385. editor.on('mouseup keydown', e => {
  12386. disableCaretContainer(editor, e.keyCode);
  12387. });
  12388. };
  12389. const replaceWithCaretFormat = (targetNode, formatNodes) => {
  12390. const caretContainer = createCaretContainer(false);
  12391. const innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom);
  12392. before$3(SugarElement.fromDom(targetNode), caretContainer);
  12393. remove$5(SugarElement.fromDom(targetNode));
  12394. return CaretPosition(innerMost, 0);
  12395. };
  12396. const isFormatElement = (editor, element) => {
  12397. const inlineElements = editor.schema.getTextInlineElements();
  12398. return has$2(inlineElements, name(element)) && !isCaretNode(element.dom) && !isBogus$2(element.dom);
  12399. };
  12400. const isEmptyCaretFormatElement = element => {
  12401. return isCaretNode(element.dom) && isCaretContainerEmpty(element.dom);
  12402. };
  12403. const postProcessHooks = {};
  12404. const filter$2 = filter$4;
  12405. const each$a = each$e;
  12406. const addPostProcessHook = (name, hook) => {
  12407. const hooks = postProcessHooks[name];
  12408. if (!hooks) {
  12409. postProcessHooks[name] = [];
  12410. }
  12411. postProcessHooks[name].push(hook);
  12412. };
  12413. const postProcess$1 = (name, editor) => {
  12414. each$a(postProcessHooks[name], hook => {
  12415. hook(editor);
  12416. });
  12417. };
  12418. addPostProcessHook('pre', editor => {
  12419. const rng = editor.selection.getRng();
  12420. let blocks;
  12421. const hasPreSibling = pre => {
  12422. return isPre(pre.previousSibling) && indexOf(blocks, pre.previousSibling) !== -1;
  12423. };
  12424. const joinPre = (pre1, pre2) => {
  12425. const sPre2 = SugarElement.fromDom(pre2);
  12426. const doc = documentOrOwner(sPre2).dom;
  12427. remove$5(sPre2);
  12428. append(SugarElement.fromDom(pre1), [
  12429. SugarElement.fromTag('br', doc),
  12430. SugarElement.fromTag('br', doc),
  12431. ...children(sPre2)
  12432. ]);
  12433. };
  12434. const isPre = matchNodeNames(['pre']);
  12435. if (!rng.collapsed) {
  12436. blocks = editor.selection.getSelectedBlocks();
  12437. each$a(filter$2(filter$2(blocks, isPre), hasPreSibling), pre => {
  12438. joinPre(pre.previousSibling, pre);
  12439. });
  12440. }
  12441. });
  12442. const each$9 = Tools.each;
  12443. const isElementNode$1 = node => isElement$6(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  12444. const findElementSibling = (node, siblingName) => {
  12445. for (let sibling = node; sibling; sibling = sibling[siblingName]) {
  12446. if (isText$8(sibling) && isNotEmpty(sibling.data)) {
  12447. return node;
  12448. }
  12449. if (isElement$6(sibling) && !isBookmarkNode$1(sibling)) {
  12450. return sibling;
  12451. }
  12452. }
  12453. return node;
  12454. };
  12455. const mergeSiblingsNodes = (dom, prev, next) => {
  12456. const elementUtils = ElementUtils(dom);
  12457. if (prev && next) {
  12458. prev = findElementSibling(prev, 'previousSibling');
  12459. next = findElementSibling(next, 'nextSibling');
  12460. if (elementUtils.compare(prev, next)) {
  12461. for (let sibling = prev.nextSibling; sibling && sibling !== next;) {
  12462. const tmpSibling = sibling;
  12463. sibling = sibling.nextSibling;
  12464. prev.appendChild(tmpSibling);
  12465. }
  12466. dom.remove(next);
  12467. Tools.each(Tools.grep(next.childNodes), node => {
  12468. prev.appendChild(node);
  12469. });
  12470. return prev;
  12471. }
  12472. }
  12473. return next;
  12474. };
  12475. const mergeSiblings = (dom, format, vars, node) => {
  12476. if (node && format.merge_siblings !== false) {
  12477. const newNode = mergeSiblingsNodes(dom, getNonWhiteSpaceSibling(node), node);
  12478. mergeSiblingsNodes(dom, newNode, getNonWhiteSpaceSibling(newNode, true));
  12479. }
  12480. };
  12481. const clearChildStyles = (dom, format, node) => {
  12482. if (format.clear_child_styles) {
  12483. const selector = format.links ? '*:not(a)' : '*';
  12484. each$9(dom.select(selector, node), node => {
  12485. if (isElementNode$1(node)) {
  12486. each$9(format.styles, (value, name) => {
  12487. dom.setStyle(node, name, '');
  12488. });
  12489. }
  12490. });
  12491. }
  12492. };
  12493. const processChildElements = (node, filter, process) => {
  12494. each$9(node.childNodes, node => {
  12495. if (isElementNode$1(node)) {
  12496. if (filter(node)) {
  12497. process(node);
  12498. }
  12499. if (node.hasChildNodes()) {
  12500. processChildElements(node, filter, process);
  12501. }
  12502. }
  12503. });
  12504. };
  12505. const unwrapEmptySpan = (dom, node) => {
  12506. if (node.nodeName === 'SPAN' && dom.getAttribs(node).length === 0) {
  12507. dom.remove(node, true);
  12508. }
  12509. };
  12510. const hasStyle = (dom, name) => node => !!(node && getStyle(dom, node, name));
  12511. const applyStyle = (dom, name, value) => node => {
  12512. dom.setStyle(node, name, value);
  12513. if (node.getAttribute('style') === '') {
  12514. node.removeAttribute('style');
  12515. }
  12516. unwrapEmptySpan(dom, node);
  12517. };
  12518. const removeResult = Adt.generate([
  12519. { keep: [] },
  12520. { rename: ['name'] },
  12521. { removed: [] }
  12522. ]);
  12523. const MCE_ATTR_RE = /^(src|href|style)$/;
  12524. const each$8 = Tools.each;
  12525. const isEq$2 = isEq$5;
  12526. const isTableCellOrRow = node => /^(TR|TH|TD)$/.test(node.nodeName);
  12527. const isChildOfInlineParent = (dom, node, parent) => dom.isChildOf(node, parent) && node !== parent && !dom.isBlock(parent);
  12528. const getContainer = (ed, rng, start) => {
  12529. let container = rng[start ? 'startContainer' : 'endContainer'];
  12530. let offset = rng[start ? 'startOffset' : 'endOffset'];
  12531. if (isElement$6(container)) {
  12532. const lastIdx = container.childNodes.length - 1;
  12533. if (!start && offset) {
  12534. offset--;
  12535. }
  12536. container = container.childNodes[offset > lastIdx ? lastIdx : offset];
  12537. }
  12538. if (isText$8(container) && start && offset >= container.nodeValue.length) {
  12539. container = new DomTreeWalker(container, ed.getBody()).next() || container;
  12540. }
  12541. if (isText$8(container) && !start && offset === 0) {
  12542. container = new DomTreeWalker(container, ed.getBody()).prev() || container;
  12543. }
  12544. return container;
  12545. };
  12546. const normalizeTableSelection = (node, start) => {
  12547. const prop = start ? 'firstChild' : 'lastChild';
  12548. if (isTableCellOrRow(node) && node[prop]) {
  12549. const childNode = node[prop];
  12550. if (node.nodeName === 'TR') {
  12551. return childNode[prop] || childNode;
  12552. } else {
  12553. return childNode;
  12554. }
  12555. }
  12556. return node;
  12557. };
  12558. const wrap$1 = (dom, node, name, attrs) => {
  12559. const wrapper = dom.create(name, attrs);
  12560. node.parentNode.insertBefore(wrapper, node);
  12561. wrapper.appendChild(node);
  12562. return wrapper;
  12563. };
  12564. const wrapWithSiblings = (dom, node, next, name, attrs) => {
  12565. const start = SugarElement.fromDom(node);
  12566. const wrapper = SugarElement.fromDom(dom.create(name, attrs));
  12567. const siblings = next ? nextSiblings(start) : prevSiblings(start);
  12568. append(wrapper, siblings);
  12569. if (next) {
  12570. before$3(start, wrapper);
  12571. prepend(wrapper, start);
  12572. } else {
  12573. after$4(start, wrapper);
  12574. append$1(wrapper, start);
  12575. }
  12576. return wrapper.dom;
  12577. };
  12578. const isColorFormatAndAnchor = (node, format) => format.links && node.nodeName === 'A';
  12579. const removeNode = (ed, node, format) => {
  12580. const parentNode = node.parentNode;
  12581. let rootBlockElm;
  12582. const dom = ed.dom;
  12583. const forcedRootBlock = getForcedRootBlock(ed);
  12584. if (isBlockFormat(format)) {
  12585. if (parentNode === dom.getRoot()) {
  12586. if (!format.list_block || !isEq$2(node, format.list_block)) {
  12587. each$g(from(node.childNodes), node => {
  12588. if (isValid(ed, forcedRootBlock, node.nodeName.toLowerCase())) {
  12589. if (!rootBlockElm) {
  12590. rootBlockElm = wrap$1(dom, node, forcedRootBlock);
  12591. dom.setAttribs(rootBlockElm, getForcedRootBlockAttrs(ed));
  12592. } else {
  12593. rootBlockElm.appendChild(node);
  12594. }
  12595. } else {
  12596. rootBlockElm = null;
  12597. }
  12598. });
  12599. }
  12600. }
  12601. }
  12602. if (isMixedFormat(format) && !isEq$2(format.inline, node)) {
  12603. return;
  12604. }
  12605. dom.remove(node, true);
  12606. };
  12607. const removeFormatInternal = (ed, format, vars, node, compareNode) => {
  12608. let stylesModified;
  12609. const dom = ed.dom;
  12610. if (!matchName(dom, node, format) && !isColorFormatAndAnchor(node, format)) {
  12611. return removeResult.keep();
  12612. }
  12613. const elm = node;
  12614. if (isInlineFormat(format) && format.remove === 'all' && isArray$1(format.preserve_attributes)) {
  12615. const attrsToPreserve = filter$6(dom.getAttribs(elm), attr => contains$2(format.preserve_attributes, attr.name.toLowerCase()));
  12616. dom.removeAllAttribs(elm);
  12617. each$g(attrsToPreserve, attr => dom.setAttrib(elm, attr.name, attr.value));
  12618. if (attrsToPreserve.length > 0) {
  12619. return removeResult.rename('span');
  12620. }
  12621. }
  12622. if (format.remove !== 'all') {
  12623. each$8(format.styles, (value, name) => {
  12624. value = normalizeStyleValue(replaceVars(value, vars), name + '');
  12625. if (isNumber(name)) {
  12626. name = value;
  12627. compareNode = null;
  12628. }
  12629. if (format.remove_similar || (!compareNode || isEq$2(getStyle(dom, compareNode, name), value))) {
  12630. dom.setStyle(elm, name, '');
  12631. }
  12632. stylesModified = true;
  12633. });
  12634. if (stylesModified && dom.getAttrib(elm, 'style') === '') {
  12635. elm.removeAttribute('style');
  12636. elm.removeAttribute('data-mce-style');
  12637. }
  12638. each$8(format.attributes, (value, name) => {
  12639. let valueOut;
  12640. value = replaceVars(value, vars);
  12641. if (isNumber(name)) {
  12642. name = value;
  12643. compareNode = null;
  12644. }
  12645. if (format.remove_similar || (!compareNode || isEq$2(dom.getAttrib(compareNode, name), value))) {
  12646. if (name === 'class') {
  12647. value = dom.getAttrib(elm, name);
  12648. if (value) {
  12649. valueOut = '';
  12650. each$g(value.split(/\s+/), cls => {
  12651. if (/mce\-\w+/.test(cls)) {
  12652. valueOut += (valueOut ? ' ' : '') + cls;
  12653. }
  12654. });
  12655. if (valueOut) {
  12656. dom.setAttrib(elm, name, valueOut);
  12657. return;
  12658. }
  12659. }
  12660. }
  12661. if (MCE_ATTR_RE.test(name)) {
  12662. elm.removeAttribute('data-mce-' + name);
  12663. }
  12664. if (name === 'style' && matchNodeNames(['li'])(elm) && dom.getStyle(elm, 'list-style-type') === 'none') {
  12665. elm.removeAttribute(name);
  12666. dom.setStyle(elm, 'list-style-type', 'none');
  12667. return;
  12668. }
  12669. if (name === 'class') {
  12670. elm.removeAttribute('className');
  12671. }
  12672. elm.removeAttribute(name);
  12673. }
  12674. });
  12675. each$8(format.classes, value => {
  12676. value = replaceVars(value, vars);
  12677. if (!compareNode || dom.hasClass(compareNode, value)) {
  12678. dom.removeClass(elm, value);
  12679. }
  12680. });
  12681. const attrs = dom.getAttribs(elm);
  12682. for (let i = 0; i < attrs.length; i++) {
  12683. const attrName = attrs[i].nodeName;
  12684. if (attrName.indexOf('_') !== 0 && attrName.indexOf('data-') !== 0) {
  12685. return removeResult.keep();
  12686. }
  12687. }
  12688. }
  12689. if (format.remove !== 'none') {
  12690. removeNode(ed, elm, format);
  12691. return removeResult.removed();
  12692. }
  12693. return removeResult.keep();
  12694. };
  12695. const removeFormat$1 = (ed, format, vars, node, compareNode) => removeFormatInternal(ed, format, vars, node, compareNode).fold(never, newName => {
  12696. ed.dom.rename(node, newName);
  12697. return true;
  12698. }, always);
  12699. const findFormatRoot = (editor, container, name, vars, similar) => {
  12700. let formatRoot;
  12701. each$g(getParents$2(editor.dom, container.parentNode).reverse(), parent => {
  12702. if (!formatRoot && parent.id !== '_start' && parent.id !== '_end') {
  12703. const format = matchNode(editor, parent, name, vars, similar);
  12704. if (format && format.split !== false) {
  12705. formatRoot = parent;
  12706. }
  12707. }
  12708. });
  12709. return formatRoot;
  12710. };
  12711. const removeFormatFromClone = (editor, format, vars, clone) => removeFormatInternal(editor, format, vars, clone, clone).fold(constant(clone), newName => {
  12712. const fragment = editor.dom.createFragment();
  12713. fragment.appendChild(clone);
  12714. return editor.dom.rename(clone, newName);
  12715. }, constant(null));
  12716. const wrapAndSplit = (editor, formatList, formatRoot, container, target, split, format, vars) => {
  12717. let clone, lastClone, firstClone;
  12718. const dom = editor.dom;
  12719. if (formatRoot) {
  12720. const formatRootParent = formatRoot.parentNode;
  12721. for (let parent = container.parentNode; parent && parent !== formatRootParent; parent = parent.parentNode) {
  12722. clone = dom.clone(parent, false);
  12723. for (let i = 0; i < formatList.length; i++) {
  12724. clone = removeFormatFromClone(editor, formatList[i], vars, clone);
  12725. if (clone === null) {
  12726. break;
  12727. }
  12728. }
  12729. if (clone) {
  12730. if (lastClone) {
  12731. clone.appendChild(lastClone);
  12732. }
  12733. if (!firstClone) {
  12734. firstClone = clone;
  12735. }
  12736. lastClone = clone;
  12737. }
  12738. }
  12739. if (split && (!format.mixed || !dom.isBlock(formatRoot))) {
  12740. container = dom.split(formatRoot, container);
  12741. }
  12742. if (lastClone) {
  12743. target.parentNode.insertBefore(lastClone, target);
  12744. firstClone.appendChild(target);
  12745. if (isInlineFormat(format)) {
  12746. mergeSiblings(dom, format, vars, lastClone);
  12747. }
  12748. }
  12749. }
  12750. return container;
  12751. };
  12752. const remove$2 = (ed, name, vars, node, similar) => {
  12753. const formatList = ed.formatter.get(name);
  12754. const format = formatList[0];
  12755. let contentEditable = true;
  12756. const dom = ed.dom;
  12757. const selection = ed.selection;
  12758. const splitToFormatRoot = container => {
  12759. const formatRoot = findFormatRoot(ed, container, name, vars, similar);
  12760. return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format, vars);
  12761. };
  12762. const isRemoveBookmarkNode = node => isBookmarkNode$1(node) && isElement$6(node) && (node.id === '_start' || node.id === '_end');
  12763. const removeNodeFormat = node => exists(formatList, fmt => removeFormat$1(ed, fmt, vars, node, node));
  12764. const process = node => {
  12765. let lastContentEditable = true;
  12766. let hasContentEditableState = false;
  12767. if (isElement$6(node) && dom.getContentEditable(node)) {
  12768. lastContentEditable = contentEditable;
  12769. contentEditable = dom.getContentEditable(node) === 'true';
  12770. hasContentEditableState = true;
  12771. }
  12772. const children = from(node.childNodes);
  12773. if (contentEditable && !hasContentEditableState) {
  12774. const removed = removeNodeFormat(node);
  12775. const currentNodeMatches = removed || exists(formatList, f => matchName(dom, node, f));
  12776. const parentNode = node.parentNode;
  12777. if (!currentNodeMatches && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  12778. removeNodeFormat(parentNode);
  12779. }
  12780. }
  12781. if (format.deep) {
  12782. if (children.length) {
  12783. for (let i = 0; i < children.length; i++) {
  12784. process(children[i]);
  12785. }
  12786. if (hasContentEditableState) {
  12787. contentEditable = lastContentEditable;
  12788. }
  12789. }
  12790. }
  12791. const textDecorations = [
  12792. 'underline',
  12793. 'line-through',
  12794. 'overline'
  12795. ];
  12796. each$g(textDecorations, decoration => {
  12797. if (isElement$6(node) && ed.dom.getStyle(node, 'text-decoration') === decoration && node.parentNode && getTextDecoration(dom, node.parentNode) === decoration) {
  12798. removeFormat$1(ed, {
  12799. deep: false,
  12800. exact: true,
  12801. inline: 'span',
  12802. styles: { textDecoration: decoration }
  12803. }, null, node);
  12804. }
  12805. });
  12806. };
  12807. const unwrap = start => {
  12808. const node = dom.get(start ? '_start' : '_end');
  12809. let out = node[start ? 'firstChild' : 'lastChild'];
  12810. if (isRemoveBookmarkNode(out)) {
  12811. out = out[start ? 'firstChild' : 'lastChild'];
  12812. }
  12813. if (isText$8(out) && out.data.length === 0) {
  12814. out = start ? node.previousSibling || node.nextSibling : node.nextSibling || node.previousSibling;
  12815. }
  12816. dom.remove(node, true);
  12817. return out;
  12818. };
  12819. const removeRngStyle = rng => {
  12820. let startContainer, endContainer;
  12821. let expandedRng = expandRng(ed, rng, formatList, rng.collapsed);
  12822. if (format.split) {
  12823. expandedRng = split(expandedRng);
  12824. startContainer = getContainer(ed, expandedRng, true);
  12825. endContainer = getContainer(ed, expandedRng);
  12826. if (startContainer !== endContainer) {
  12827. startContainer = normalizeTableSelection(startContainer, true);
  12828. endContainer = normalizeTableSelection(endContainer, false);
  12829. if (isChildOfInlineParent(dom, startContainer, endContainer)) {
  12830. const marker = Optional.from(startContainer.firstChild).getOr(startContainer);
  12831. splitToFormatRoot(wrapWithSiblings(dom, marker, true, 'span', {
  12832. 'id': '_start',
  12833. 'data-mce-type': 'bookmark'
  12834. }));
  12835. unwrap(true);
  12836. return;
  12837. }
  12838. if (isChildOfInlineParent(dom, endContainer, startContainer)) {
  12839. const marker = Optional.from(endContainer.lastChild).getOr(endContainer);
  12840. splitToFormatRoot(wrapWithSiblings(dom, marker, false, 'span', {
  12841. 'id': '_end',
  12842. 'data-mce-type': 'bookmark'
  12843. }));
  12844. unwrap(false);
  12845. return;
  12846. }
  12847. startContainer = wrap$1(dom, startContainer, 'span', {
  12848. 'id': '_start',
  12849. 'data-mce-type': 'bookmark'
  12850. });
  12851. endContainer = wrap$1(dom, endContainer, 'span', {
  12852. 'id': '_end',
  12853. 'data-mce-type': 'bookmark'
  12854. });
  12855. const newRng = dom.createRng();
  12856. newRng.setStartAfter(startContainer);
  12857. newRng.setEndBefore(endContainer);
  12858. walk$3(dom, newRng, nodes => {
  12859. each$g(nodes, n => {
  12860. if (!isBookmarkNode$1(n) && !isBookmarkNode$1(n.parentNode)) {
  12861. splitToFormatRoot(n);
  12862. }
  12863. });
  12864. });
  12865. splitToFormatRoot(startContainer);
  12866. splitToFormatRoot(endContainer);
  12867. startContainer = unwrap(true);
  12868. endContainer = unwrap();
  12869. } else {
  12870. startContainer = endContainer = splitToFormatRoot(startContainer);
  12871. }
  12872. expandedRng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
  12873. expandedRng.startOffset = dom.nodeIndex(startContainer);
  12874. expandedRng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
  12875. expandedRng.endOffset = dom.nodeIndex(endContainer) + 1;
  12876. }
  12877. walk$3(dom, expandedRng, nodes => {
  12878. each$g(nodes, process);
  12879. });
  12880. };
  12881. if (node) {
  12882. if (isNode(node)) {
  12883. const rng = dom.createRng();
  12884. rng.setStartBefore(node);
  12885. rng.setEndAfter(node);
  12886. removeRngStyle(rng);
  12887. } else {
  12888. removeRngStyle(node);
  12889. }
  12890. fireFormatRemove(ed, name, node, vars);
  12891. return;
  12892. }
  12893. if (dom.getContentEditable(selection.getNode()) === 'false') {
  12894. node = selection.getNode();
  12895. for (let i = 0; i < formatList.length; i++) {
  12896. if (formatList[i].ceFalseOverride) {
  12897. if (removeFormat$1(ed, formatList[i], vars, node, node)) {
  12898. break;
  12899. }
  12900. }
  12901. }
  12902. fireFormatRemove(ed, name, node, vars);
  12903. return;
  12904. }
  12905. if (!selection.isCollapsed() || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  12906. preserve(selection, true, () => {
  12907. runOnRanges(ed, removeRngStyle);
  12908. });
  12909. if (isInlineFormat(format) && match$2(ed, name, vars, selection.getStart())) {
  12910. moveStart(dom, selection, selection.getRng());
  12911. }
  12912. ed.nodeChanged();
  12913. } else {
  12914. removeCaretFormat(ed, name, vars, similar);
  12915. }
  12916. fireFormatRemove(ed, name, node, vars);
  12917. };
  12918. const each$7 = Tools.each;
  12919. const mergeTextDecorationsAndColor = (dom, format, vars, node) => {
  12920. const processTextDecorationsAndColor = n => {
  12921. if (n.nodeType === 1 && n.parentNode && n.parentNode.nodeType === 1) {
  12922. const textDecoration = getTextDecoration(dom, n.parentNode);
  12923. if (dom.getStyle(n, 'color') && textDecoration) {
  12924. dom.setStyle(n, 'text-decoration', textDecoration);
  12925. } else if (dom.getStyle(n, 'text-decoration') === textDecoration) {
  12926. dom.setStyle(n, 'text-decoration', null);
  12927. }
  12928. }
  12929. };
  12930. if (format.styles && (format.styles.color || format.styles.textDecoration)) {
  12931. Tools.walk(node, processTextDecorationsAndColor, 'childNodes');
  12932. processTextDecorationsAndColor(node);
  12933. }
  12934. };
  12935. const mergeBackgroundColorAndFontSize = (dom, format, vars, node) => {
  12936. if (format.styles && format.styles.backgroundColor) {
  12937. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'backgroundColor', replaceVars(format.styles.backgroundColor, vars)));
  12938. }
  12939. };
  12940. const mergeSubSup = (dom, format, vars, node) => {
  12941. if (isInlineFormat(format) && (format.inline === 'sub' || format.inline === 'sup')) {
  12942. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'fontSize', ''));
  12943. dom.remove(dom.select(format.inline === 'sup' ? 'sub' : 'sup', node), true);
  12944. }
  12945. };
  12946. const mergeWithChildren = (editor, formatList, vars, node) => {
  12947. each$7(formatList, format => {
  12948. if (isInlineFormat(format)) {
  12949. each$7(editor.dom.select(format.inline, node), child => {
  12950. if (!isElementNode$1(child)) {
  12951. return;
  12952. }
  12953. removeFormat$1(editor, format, vars, child, format.exact ? child : null);
  12954. });
  12955. }
  12956. clearChildStyles(editor.dom, format, node);
  12957. });
  12958. };
  12959. const mergeWithParents = (editor, format, name, vars, node) => {
  12960. if (matchNode(editor, node.parentNode, name, vars)) {
  12961. if (removeFormat$1(editor, format, vars, node)) {
  12962. return;
  12963. }
  12964. }
  12965. if (format.merge_with_parents) {
  12966. editor.dom.getParent(node.parentNode, parent => {
  12967. if (matchNode(editor, parent, name, vars)) {
  12968. removeFormat$1(editor, format, vars, node);
  12969. return true;
  12970. }
  12971. });
  12972. }
  12973. };
  12974. const each$6 = Tools.each;
  12975. const isElementNode = node => {
  12976. return isElement$6(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  12977. };
  12978. const canFormatBR = (editor, format, node, parentName) => {
  12979. if (canFormatEmptyLines(editor) && isInlineFormat(format)) {
  12980. const validBRParentElements = getTextRootBlockElements(editor.schema);
  12981. const hasCaretNodeSibling = sibling(SugarElement.fromDom(node), sibling => isCaretNode(sibling.dom));
  12982. return hasNonNullableKey(validBRParentElements, parentName) && isEmpty$2(SugarElement.fromDom(node.parentNode), false) && !hasCaretNodeSibling;
  12983. } else {
  12984. return false;
  12985. }
  12986. };
  12987. const applyFormat$1 = (ed, name, vars, node) => {
  12988. const formatList = ed.formatter.get(name);
  12989. const format = formatList[0];
  12990. const isCollapsed = !node && ed.selection.isCollapsed();
  12991. const dom = ed.dom;
  12992. const selection = ed.selection;
  12993. const setElementFormat = (elm, fmt = format) => {
  12994. if (isFunction(fmt.onformat)) {
  12995. fmt.onformat(elm, fmt, vars, node);
  12996. }
  12997. each$6(fmt.styles, (value, name) => {
  12998. dom.setStyle(elm, name, replaceVars(value, vars));
  12999. });
  13000. if (fmt.styles) {
  13001. const styleVal = dom.getAttrib(elm, 'style');
  13002. if (styleVal) {
  13003. dom.setAttrib(elm, 'data-mce-style', styleVal);
  13004. }
  13005. }
  13006. each$6(fmt.attributes, (value, name) => {
  13007. dom.setAttrib(elm, name, replaceVars(value, vars));
  13008. });
  13009. each$6(fmt.classes, value => {
  13010. value = replaceVars(value, vars);
  13011. if (!dom.hasClass(elm, value)) {
  13012. dom.addClass(elm, value);
  13013. }
  13014. });
  13015. };
  13016. const applyNodeStyle = (formatList, node) => {
  13017. let found = false;
  13018. each$6(formatList, format => {
  13019. if (!isSelectorFormat(format)) {
  13020. return false;
  13021. }
  13022. if (isNonNullable(format.collapsed) && format.collapsed !== isCollapsed) {
  13023. return;
  13024. }
  13025. if (dom.is(node, format.selector) && !isCaretNode(node)) {
  13026. setElementFormat(node, format);
  13027. found = true;
  13028. return false;
  13029. }
  13030. });
  13031. return found;
  13032. };
  13033. const createWrapElement = wrapName => {
  13034. if (isString(wrapName)) {
  13035. const wrapElm = dom.create(wrapName);
  13036. setElementFormat(wrapElm);
  13037. return wrapElm;
  13038. } else {
  13039. return null;
  13040. }
  13041. };
  13042. const applyRngStyle = (dom, rng, nodeSpecific) => {
  13043. const newWrappers = [];
  13044. let contentEditable = true;
  13045. const wrapName = format.inline || format.block;
  13046. const wrapElm = createWrapElement(wrapName);
  13047. walk$3(dom, rng, nodes => {
  13048. let currentWrapElm;
  13049. const process = node => {
  13050. let hasContentEditableState = false;
  13051. let lastContentEditable = contentEditable;
  13052. const nodeName = node.nodeName.toLowerCase();
  13053. const parentNode = node.parentNode;
  13054. const parentName = parentNode.nodeName.toLowerCase();
  13055. if (isElement$6(node) && dom.getContentEditable(node)) {
  13056. lastContentEditable = contentEditable;
  13057. contentEditable = dom.getContentEditable(node) === 'true';
  13058. hasContentEditableState = true;
  13059. }
  13060. if (isBr$5(node) && !canFormatBR(ed, format, node, parentName)) {
  13061. currentWrapElm = null;
  13062. if (isBlockFormat(format)) {
  13063. dom.remove(node);
  13064. }
  13065. return;
  13066. }
  13067. if (isBlockFormat(format) && format.wrapper && matchNode(ed, node, name, vars)) {
  13068. currentWrapElm = null;
  13069. return;
  13070. }
  13071. if (contentEditable && !hasContentEditableState && isBlockFormat(format) && !format.wrapper && isTextBlock$1(ed, nodeName) && isValid(ed, parentName, wrapName)) {
  13072. const elm = dom.rename(node, wrapName);
  13073. setElementFormat(elm);
  13074. newWrappers.push(elm);
  13075. currentWrapElm = null;
  13076. return;
  13077. }
  13078. if (isSelectorFormat(format)) {
  13079. let found = applyNodeStyle(formatList, node);
  13080. if (!found && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  13081. found = applyNodeStyle(formatList, parentNode);
  13082. }
  13083. if (!isInlineFormat(format) || found) {
  13084. currentWrapElm = null;
  13085. return;
  13086. }
  13087. }
  13088. if (contentEditable && !hasContentEditableState && isValid(ed, wrapName, nodeName) && isValid(ed, parentName, wrapName) && !(!nodeSpecific && isText$8(node) && isZwsp(node.data)) && !isCaretNode(node) && (!isInlineFormat(format) || !dom.isBlock(node))) {
  13089. if (!currentWrapElm) {
  13090. currentWrapElm = dom.clone(wrapElm, false);
  13091. node.parentNode.insertBefore(currentWrapElm, node);
  13092. newWrappers.push(currentWrapElm);
  13093. }
  13094. currentWrapElm.appendChild(node);
  13095. } else {
  13096. currentWrapElm = null;
  13097. each$g(from(node.childNodes), process);
  13098. if (hasContentEditableState) {
  13099. contentEditable = lastContentEditable;
  13100. }
  13101. currentWrapElm = null;
  13102. }
  13103. };
  13104. each$g(nodes, process);
  13105. });
  13106. if (format.links === true) {
  13107. each$g(newWrappers, node => {
  13108. const process = node => {
  13109. if (node.nodeName === 'A') {
  13110. setElementFormat(node, format);
  13111. }
  13112. each$g(from(node.childNodes), process);
  13113. };
  13114. process(node);
  13115. });
  13116. }
  13117. each$g(newWrappers, node => {
  13118. const getChildCount = node => {
  13119. let count = 0;
  13120. each$g(node.childNodes, node => {
  13121. if (!isEmptyTextNode$1(node) && !isBookmarkNode$1(node)) {
  13122. count++;
  13123. }
  13124. });
  13125. return count;
  13126. };
  13127. const mergeStyles = node => {
  13128. const childElement = find$2(node.childNodes, isElementNode).filter(child => matchName(dom, child, format));
  13129. return childElement.map(child => {
  13130. const clone = dom.clone(child, false);
  13131. setElementFormat(clone);
  13132. dom.replace(clone, node, true);
  13133. dom.remove(child, true);
  13134. return clone;
  13135. }).getOr(node);
  13136. };
  13137. const childCount = getChildCount(node);
  13138. if ((newWrappers.length > 1 || !dom.isBlock(node)) && childCount === 0) {
  13139. dom.remove(node, true);
  13140. return;
  13141. }
  13142. if (isInlineFormat(format) || isBlockFormat(format) && format.wrapper) {
  13143. if (!format.exact && childCount === 1) {
  13144. node = mergeStyles(node);
  13145. }
  13146. mergeWithChildren(ed, formatList, vars, node);
  13147. mergeWithParents(ed, format, name, vars, node);
  13148. mergeBackgroundColorAndFontSize(dom, format, vars, node);
  13149. mergeTextDecorationsAndColor(dom, format, vars, node);
  13150. mergeSubSup(dom, format, vars, node);
  13151. mergeSiblings(dom, format, vars, node);
  13152. }
  13153. });
  13154. };
  13155. if (dom.getContentEditable(selection.getNode()) === 'false') {
  13156. node = selection.getNode();
  13157. for (let i = 0, l = formatList.length; i < l; i++) {
  13158. const formatItem = formatList[i];
  13159. if (formatItem.ceFalseOverride && isSelectorFormat(formatItem) && dom.is(node, formatItem.selector)) {
  13160. setElementFormat(node, formatItem);
  13161. break;
  13162. }
  13163. }
  13164. fireFormatApply(ed, name, node, vars);
  13165. return;
  13166. }
  13167. if (format) {
  13168. if (node) {
  13169. if (isNode(node)) {
  13170. if (!applyNodeStyle(formatList, node)) {
  13171. const rng = dom.createRng();
  13172. rng.setStartBefore(node);
  13173. rng.setEndAfter(node);
  13174. applyRngStyle(dom, expandRng(ed, rng, formatList), true);
  13175. }
  13176. } else {
  13177. applyRngStyle(dom, node, true);
  13178. }
  13179. } else {
  13180. if (!isCollapsed || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  13181. selection.setRng(normalize(selection.getRng()));
  13182. preserve(selection, true, () => {
  13183. runOnRanges(ed, (selectionRng, fake) => {
  13184. const expandedRng = fake ? selectionRng : expandRng(ed, selectionRng, formatList);
  13185. applyRngStyle(dom, expandedRng, false);
  13186. });
  13187. });
  13188. moveStart(dom, selection, selection.getRng());
  13189. ed.nodeChanged();
  13190. } else {
  13191. applyCaretFormat(ed, name, vars);
  13192. }
  13193. }
  13194. postProcess$1(name, ed);
  13195. }
  13196. fireFormatApply(ed, name, node, vars);
  13197. };
  13198. const hasVars = value => has$2(value, 'vars');
  13199. const setup$t = (registeredFormatListeners, editor) => {
  13200. registeredFormatListeners.set({});
  13201. editor.on('NodeChange', e => {
  13202. updateAndFireChangeCallbacks(editor, e.element, registeredFormatListeners.get());
  13203. });
  13204. editor.on('FormatApply FormatRemove', e => {
  13205. const element = Optional.from(e.node).map(nodeOrRange => isNode(nodeOrRange) ? nodeOrRange : nodeOrRange.startContainer).bind(node => isElement$6(node) ? Optional.some(node) : Optional.from(node.parentElement)).getOrThunk(() => fallbackElement(editor));
  13206. updateAndFireChangeCallbacks(editor, element, registeredFormatListeners.get());
  13207. });
  13208. };
  13209. const fallbackElement = editor => editor.selection.getStart();
  13210. const matchingNode = (editor, parents, format, similar, vars) => {
  13211. const isMatchingNode = node => {
  13212. const matchingFormat = editor.formatter.matchNode(node, format, vars !== null && vars !== void 0 ? vars : {}, similar);
  13213. return !isUndefined(matchingFormat);
  13214. };
  13215. const isUnableToMatch = node => {
  13216. if (matchesUnInheritedFormatSelector(editor, node, format)) {
  13217. return true;
  13218. } else {
  13219. if (!similar) {
  13220. return isNonNullable(editor.formatter.matchNode(node, format, vars, true));
  13221. } else {
  13222. return false;
  13223. }
  13224. }
  13225. };
  13226. return findUntil$1(parents, isMatchingNode, isUnableToMatch);
  13227. };
  13228. const getParents = (editor, elm) => {
  13229. const element = elm !== null && elm !== void 0 ? elm : fallbackElement(editor);
  13230. return filter$6(getParents$2(editor.dom, element), node => isElement$6(node) && !isBogus$2(node));
  13231. };
  13232. const updateAndFireChangeCallbacks = (editor, elm, registeredCallbacks) => {
  13233. const parents = getParents(editor, elm);
  13234. each$f(registeredCallbacks, (data, format) => {
  13235. const runIfChanged = spec => {
  13236. const match = matchingNode(editor, parents, format, spec.similar, hasVars(spec) ? spec.vars : undefined);
  13237. const isSet = match.isSome();
  13238. if (spec.state.get() !== isSet) {
  13239. spec.state.set(isSet);
  13240. const node = match.getOr(elm);
  13241. if (hasVars(spec)) {
  13242. spec.callback(isSet, {
  13243. node,
  13244. format,
  13245. parents
  13246. });
  13247. } else {
  13248. each$g(spec.callbacks, callback => callback(isSet, {
  13249. node,
  13250. format,
  13251. parents
  13252. }));
  13253. }
  13254. }
  13255. };
  13256. each$g([
  13257. data.withSimilar,
  13258. data.withoutSimilar
  13259. ], runIfChanged);
  13260. each$g(data.withVars, runIfChanged);
  13261. });
  13262. };
  13263. const addListeners = (editor, registeredFormatListeners, formats, callback, similar, vars) => {
  13264. const formatChangeItems = registeredFormatListeners.get();
  13265. each$g(formats.split(','), format => {
  13266. const group = get$a(formatChangeItems, format).getOrThunk(() => {
  13267. const base = {
  13268. withSimilar: {
  13269. state: Cell(false),
  13270. similar: true,
  13271. callbacks: []
  13272. },
  13273. withoutSimilar: {
  13274. state: Cell(false),
  13275. similar: false,
  13276. callbacks: []
  13277. },
  13278. withVars: []
  13279. };
  13280. formatChangeItems[format] = base;
  13281. return base;
  13282. });
  13283. const getCurrent = () => {
  13284. const parents = getParents(editor);
  13285. return matchingNode(editor, parents, format, similar, vars).isSome();
  13286. };
  13287. if (isUndefined(vars)) {
  13288. const toAppendTo = similar ? group.withSimilar : group.withoutSimilar;
  13289. toAppendTo.callbacks.push(callback);
  13290. if (toAppendTo.callbacks.length === 1) {
  13291. toAppendTo.state.set(getCurrent());
  13292. }
  13293. } else {
  13294. group.withVars.push({
  13295. state: Cell(getCurrent()),
  13296. similar,
  13297. vars,
  13298. callback
  13299. });
  13300. }
  13301. });
  13302. registeredFormatListeners.set(formatChangeItems);
  13303. };
  13304. const removeListeners = (registeredFormatListeners, formats, callback) => {
  13305. const formatChangeItems = registeredFormatListeners.get();
  13306. each$g(formats.split(','), format => get$a(formatChangeItems, format).each(group => {
  13307. formatChangeItems[format] = {
  13308. withSimilar: {
  13309. ...group.withSimilar,
  13310. callbacks: filter$6(group.withSimilar.callbacks, cb => cb !== callback)
  13311. },
  13312. withoutSimilar: {
  13313. ...group.withoutSimilar,
  13314. callbacks: filter$6(group.withoutSimilar.callbacks, cb => cb !== callback)
  13315. },
  13316. withVars: filter$6(group.withVars, item => item.callback !== callback)
  13317. };
  13318. }));
  13319. registeredFormatListeners.set(formatChangeItems);
  13320. };
  13321. const formatChangedInternal = (editor, registeredFormatListeners, formats, callback, similar, vars) => {
  13322. if (registeredFormatListeners.get() === null) {
  13323. setup$t(registeredFormatListeners, editor);
  13324. }
  13325. addListeners(editor, registeredFormatListeners, formats, callback, similar, vars);
  13326. return { unbind: () => removeListeners(registeredFormatListeners, formats, callback) };
  13327. };
  13328. const toggle = (editor, name, vars, node) => {
  13329. const fmt = editor.formatter.get(name);
  13330. if (match$2(editor, name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) {
  13331. remove$2(editor, name, vars, node);
  13332. } else {
  13333. applyFormat$1(editor, name, vars, node);
  13334. }
  13335. };
  13336. function _toConsumableArray(arr) {
  13337. if (Array.isArray(arr)) {
  13338. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
  13339. arr2[i] = arr[i];
  13340. }
  13341. return arr2;
  13342. } else {
  13343. return Array.from(arr);
  13344. }
  13345. }
  13346. var hasOwnProperty = Object.hasOwnProperty, setPrototypeOf = Object.setPrototypeOf, isFrozen = Object.isFrozen, getPrototypeOf = Object.getPrototypeOf, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  13347. var freeze = Object.freeze, seal = Object.seal, create$7 = Object.create;
  13348. var _ref = typeof Reflect !== 'undefined' && Reflect, apply = _ref.apply, construct = _ref.construct;
  13349. if (!apply) {
  13350. apply = function apply(fun, thisValue, args) {
  13351. return fun.apply(thisValue, args);
  13352. };
  13353. }
  13354. if (!freeze) {
  13355. freeze = function freeze(x) {
  13356. return x;
  13357. };
  13358. }
  13359. if (!seal) {
  13360. seal = function seal(x) {
  13361. return x;
  13362. };
  13363. }
  13364. if (!construct) {
  13365. construct = function construct(Func, args) {
  13366. return new (Function.prototype.bind.apply(Func, [null].concat(_toConsumableArray(args))))();
  13367. };
  13368. }
  13369. var arrayForEach = unapply(Array.prototype.forEach);
  13370. var arrayPop = unapply(Array.prototype.pop);
  13371. var arrayPush = unapply(Array.prototype.push);
  13372. var stringToLowerCase = unapply(String.prototype.toLowerCase);
  13373. var stringMatch = unapply(String.prototype.match);
  13374. var stringReplace = unapply(String.prototype.replace);
  13375. var stringIndexOf = unapply(String.prototype.indexOf);
  13376. var stringTrim = unapply(String.prototype.trim);
  13377. var regExpTest = unapply(RegExp.prototype.test);
  13378. var typeErrorCreate = unconstruct(TypeError);
  13379. function unapply(func) {
  13380. return function (thisArg) {
  13381. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  13382. args[_key - 1] = arguments[_key];
  13383. }
  13384. return apply(func, thisArg, args);
  13385. };
  13386. }
  13387. function unconstruct(func) {
  13388. return function () {
  13389. for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  13390. args[_key2] = arguments[_key2];
  13391. }
  13392. return construct(func, args);
  13393. };
  13394. }
  13395. function addToSet(set, array) {
  13396. if (setPrototypeOf) {
  13397. setPrototypeOf(set, null);
  13398. }
  13399. var l = array.length;
  13400. while (l--) {
  13401. var element = array[l];
  13402. if (typeof element === 'string') {
  13403. var lcElement = stringToLowerCase(element);
  13404. if (lcElement !== element) {
  13405. if (!isFrozen(array)) {
  13406. array[l] = lcElement;
  13407. }
  13408. element = lcElement;
  13409. }
  13410. }
  13411. set[element] = true;
  13412. }
  13413. return set;
  13414. }
  13415. function clone(object) {
  13416. var newObject = create$7(null);
  13417. var property = void 0;
  13418. for (property in object) {
  13419. if (apply(hasOwnProperty, object, [property])) {
  13420. newObject[property] = object[property];
  13421. }
  13422. }
  13423. return newObject;
  13424. }
  13425. function lookupGetter(object, prop) {
  13426. while (object !== null) {
  13427. var desc = getOwnPropertyDescriptor(object, prop);
  13428. if (desc) {
  13429. if (desc.get) {
  13430. return unapply(desc.get);
  13431. }
  13432. if (typeof desc.value === 'function') {
  13433. return unapply(desc.value);
  13434. }
  13435. }
  13436. object = getPrototypeOf(object);
  13437. }
  13438. function fallbackValue(element) {
  13439. console.warn('fallback value for', element);
  13440. return null;
  13441. }
  13442. return fallbackValue;
  13443. }
  13444. var html = freeze([
  13445. 'a',
  13446. 'abbr',
  13447. 'acronym',
  13448. 'address',
  13449. 'area',
  13450. 'article',
  13451. 'aside',
  13452. 'audio',
  13453. 'b',
  13454. 'bdi',
  13455. 'bdo',
  13456. 'big',
  13457. 'blink',
  13458. 'blockquote',
  13459. 'body',
  13460. 'br',
  13461. 'button',
  13462. 'canvas',
  13463. 'caption',
  13464. 'center',
  13465. 'cite',
  13466. 'code',
  13467. 'col',
  13468. 'colgroup',
  13469. 'content',
  13470. 'data',
  13471. 'datalist',
  13472. 'dd',
  13473. 'decorator',
  13474. 'del',
  13475. 'details',
  13476. 'dfn',
  13477. 'dialog',
  13478. 'dir',
  13479. 'div',
  13480. 'dl',
  13481. 'dt',
  13482. 'element',
  13483. 'em',
  13484. 'fieldset',
  13485. 'figcaption',
  13486. 'figure',
  13487. 'font',
  13488. 'footer',
  13489. 'form',
  13490. 'h1',
  13491. 'h2',
  13492. 'h3',
  13493. 'h4',
  13494. 'h5',
  13495. 'h6',
  13496. 'head',
  13497. 'header',
  13498. 'hgroup',
  13499. 'hr',
  13500. 'html',
  13501. 'i',
  13502. 'img',
  13503. 'input',
  13504. 'ins',
  13505. 'kbd',
  13506. 'label',
  13507. 'legend',
  13508. 'li',
  13509. 'main',
  13510. 'map',
  13511. 'mark',
  13512. 'marquee',
  13513. 'menu',
  13514. 'menuitem',
  13515. 'meter',
  13516. 'nav',
  13517. 'nobr',
  13518. 'ol',
  13519. 'optgroup',
  13520. 'option',
  13521. 'output',
  13522. 'p',
  13523. 'picture',
  13524. 'pre',
  13525. 'progress',
  13526. 'q',
  13527. 'rp',
  13528. 'rt',
  13529. 'ruby',
  13530. 's',
  13531. 'samp',
  13532. 'section',
  13533. 'select',
  13534. 'shadow',
  13535. 'small',
  13536. 'source',
  13537. 'spacer',
  13538. 'span',
  13539. 'strike',
  13540. 'strong',
  13541. 'style',
  13542. 'sub',
  13543. 'summary',
  13544. 'sup',
  13545. 'table',
  13546. 'tbody',
  13547. 'td',
  13548. 'template',
  13549. 'textarea',
  13550. 'tfoot',
  13551. 'th',
  13552. 'thead',
  13553. 'time',
  13554. 'tr',
  13555. 'track',
  13556. 'tt',
  13557. 'u',
  13558. 'ul',
  13559. 'var',
  13560. 'video',
  13561. 'wbr'
  13562. ]);
  13563. var svg = freeze([
  13564. 'svg',
  13565. 'a',
  13566. 'altglyph',
  13567. 'altglyphdef',
  13568. 'altglyphitem',
  13569. 'animatecolor',
  13570. 'animatemotion',
  13571. 'animatetransform',
  13572. 'circle',
  13573. 'clippath',
  13574. 'defs',
  13575. 'desc',
  13576. 'ellipse',
  13577. 'filter',
  13578. 'font',
  13579. 'g',
  13580. 'glyph',
  13581. 'glyphref',
  13582. 'hkern',
  13583. 'image',
  13584. 'line',
  13585. 'lineargradient',
  13586. 'marker',
  13587. 'mask',
  13588. 'metadata',
  13589. 'mpath',
  13590. 'path',
  13591. 'pattern',
  13592. 'polygon',
  13593. 'polyline',
  13594. 'radialgradient',
  13595. 'rect',
  13596. 'stop',
  13597. 'style',
  13598. 'switch',
  13599. 'symbol',
  13600. 'text',
  13601. 'textpath',
  13602. 'title',
  13603. 'tref',
  13604. 'tspan',
  13605. 'view',
  13606. 'vkern'
  13607. ]);
  13608. var svgFilters = freeze([
  13609. 'feBlend',
  13610. 'feColorMatrix',
  13611. 'feComponentTransfer',
  13612. 'feComposite',
  13613. 'feConvolveMatrix',
  13614. 'feDiffuseLighting',
  13615. 'feDisplacementMap',
  13616. 'feDistantLight',
  13617. 'feFlood',
  13618. 'feFuncA',
  13619. 'feFuncB',
  13620. 'feFuncG',
  13621. 'feFuncR',
  13622. 'feGaussianBlur',
  13623. 'feImage',
  13624. 'feMerge',
  13625. 'feMergeNode',
  13626. 'feMorphology',
  13627. 'feOffset',
  13628. 'fePointLight',
  13629. 'feSpecularLighting',
  13630. 'feSpotLight',
  13631. 'feTile',
  13632. 'feTurbulence'
  13633. ]);
  13634. var svgDisallowed = freeze([
  13635. 'animate',
  13636. 'color-profile',
  13637. 'cursor',
  13638. 'discard',
  13639. 'fedropshadow',
  13640. 'font-face',
  13641. 'font-face-format',
  13642. 'font-face-name',
  13643. 'font-face-src',
  13644. 'font-face-uri',
  13645. 'foreignobject',
  13646. 'hatch',
  13647. 'hatchpath',
  13648. 'mesh',
  13649. 'meshgradient',
  13650. 'meshpatch',
  13651. 'meshrow',
  13652. 'missing-glyph',
  13653. 'script',
  13654. 'set',
  13655. 'solidcolor',
  13656. 'unknown',
  13657. 'use'
  13658. ]);
  13659. var mathMl = freeze([
  13660. 'math',
  13661. 'menclose',
  13662. 'merror',
  13663. 'mfenced',
  13664. 'mfrac',
  13665. 'mglyph',
  13666. 'mi',
  13667. 'mlabeledtr',
  13668. 'mmultiscripts',
  13669. 'mn',
  13670. 'mo',
  13671. 'mover',
  13672. 'mpadded',
  13673. 'mphantom',
  13674. 'mroot',
  13675. 'mrow',
  13676. 'ms',
  13677. 'mspace',
  13678. 'msqrt',
  13679. 'mstyle',
  13680. 'msub',
  13681. 'msup',
  13682. 'msubsup',
  13683. 'mtable',
  13684. 'mtd',
  13685. 'mtext',
  13686. 'mtr',
  13687. 'munder',
  13688. 'munderover'
  13689. ]);
  13690. var mathMlDisallowed = freeze([
  13691. 'maction',
  13692. 'maligngroup',
  13693. 'malignmark',
  13694. 'mlongdiv',
  13695. 'mscarries',
  13696. 'mscarry',
  13697. 'msgroup',
  13698. 'mstack',
  13699. 'msline',
  13700. 'msrow',
  13701. 'semantics',
  13702. 'annotation',
  13703. 'annotation-xml',
  13704. 'mprescripts',
  13705. 'none'
  13706. ]);
  13707. var text = freeze(['#text']);
  13708. var html$1 = freeze([
  13709. 'accept',
  13710. 'action',
  13711. 'align',
  13712. 'alt',
  13713. 'autocapitalize',
  13714. 'autocomplete',
  13715. 'autopictureinpicture',
  13716. 'autoplay',
  13717. 'background',
  13718. 'bgcolor',
  13719. 'border',
  13720. 'capture',
  13721. 'cellpadding',
  13722. 'cellspacing',
  13723. 'checked',
  13724. 'cite',
  13725. 'class',
  13726. 'clear',
  13727. 'color',
  13728. 'cols',
  13729. 'colspan',
  13730. 'controls',
  13731. 'controlslist',
  13732. 'coords',
  13733. 'crossorigin',
  13734. 'datetime',
  13735. 'decoding',
  13736. 'default',
  13737. 'dir',
  13738. 'disabled',
  13739. 'disablepictureinpicture',
  13740. 'disableremoteplayback',
  13741. 'download',
  13742. 'draggable',
  13743. 'enctype',
  13744. 'enterkeyhint',
  13745. 'face',
  13746. 'for',
  13747. 'headers',
  13748. 'height',
  13749. 'hidden',
  13750. 'high',
  13751. 'href',
  13752. 'hreflang',
  13753. 'id',
  13754. 'inputmode',
  13755. 'integrity',
  13756. 'ismap',
  13757. 'kind',
  13758. 'label',
  13759. 'lang',
  13760. 'list',
  13761. 'loading',
  13762. 'loop',
  13763. 'low',
  13764. 'max',
  13765. 'maxlength',
  13766. 'media',
  13767. 'method',
  13768. 'min',
  13769. 'minlength',
  13770. 'multiple',
  13771. 'muted',
  13772. 'name',
  13773. 'nonce',
  13774. 'noshade',
  13775. 'novalidate',
  13776. 'nowrap',
  13777. 'open',
  13778. 'optimum',
  13779. 'pattern',
  13780. 'placeholder',
  13781. 'playsinline',
  13782. 'poster',
  13783. 'preload',
  13784. 'pubdate',
  13785. 'radiogroup',
  13786. 'readonly',
  13787. 'rel',
  13788. 'required',
  13789. 'rev',
  13790. 'reversed',
  13791. 'role',
  13792. 'rows',
  13793. 'rowspan',
  13794. 'spellcheck',
  13795. 'scope',
  13796. 'selected',
  13797. 'shape',
  13798. 'size',
  13799. 'sizes',
  13800. 'span',
  13801. 'srclang',
  13802. 'start',
  13803. 'src',
  13804. 'srcset',
  13805. 'step',
  13806. 'style',
  13807. 'summary',
  13808. 'tabindex',
  13809. 'title',
  13810. 'translate',
  13811. 'type',
  13812. 'usemap',
  13813. 'valign',
  13814. 'value',
  13815. 'width',
  13816. 'xmlns',
  13817. 'slot'
  13818. ]);
  13819. var svg$1 = freeze([
  13820. 'accent-height',
  13821. 'accumulate',
  13822. 'additive',
  13823. 'alignment-baseline',
  13824. 'ascent',
  13825. 'attributename',
  13826. 'attributetype',
  13827. 'azimuth',
  13828. 'basefrequency',
  13829. 'baseline-shift',
  13830. 'begin',
  13831. 'bias',
  13832. 'by',
  13833. 'class',
  13834. 'clip',
  13835. 'clippathunits',
  13836. 'clip-path',
  13837. 'clip-rule',
  13838. 'color',
  13839. 'color-interpolation',
  13840. 'color-interpolation-filters',
  13841. 'color-profile',
  13842. 'color-rendering',
  13843. 'cx',
  13844. 'cy',
  13845. 'd',
  13846. 'dx',
  13847. 'dy',
  13848. 'diffuseconstant',
  13849. 'direction',
  13850. 'display',
  13851. 'divisor',
  13852. 'dur',
  13853. 'edgemode',
  13854. 'elevation',
  13855. 'end',
  13856. 'fill',
  13857. 'fill-opacity',
  13858. 'fill-rule',
  13859. 'filter',
  13860. 'filterunits',
  13861. 'flood-color',
  13862. 'flood-opacity',
  13863. 'font-family',
  13864. 'font-size',
  13865. 'font-size-adjust',
  13866. 'font-stretch',
  13867. 'font-style',
  13868. 'font-variant',
  13869. 'font-weight',
  13870. 'fx',
  13871. 'fy',
  13872. 'g1',
  13873. 'g2',
  13874. 'glyph-name',
  13875. 'glyphref',
  13876. 'gradientunits',
  13877. 'gradienttransform',
  13878. 'height',
  13879. 'href',
  13880. 'id',
  13881. 'image-rendering',
  13882. 'in',
  13883. 'in2',
  13884. 'k',
  13885. 'k1',
  13886. 'k2',
  13887. 'k3',
  13888. 'k4',
  13889. 'kerning',
  13890. 'keypoints',
  13891. 'keysplines',
  13892. 'keytimes',
  13893. 'lang',
  13894. 'lengthadjust',
  13895. 'letter-spacing',
  13896. 'kernelmatrix',
  13897. 'kernelunitlength',
  13898. 'lighting-color',
  13899. 'local',
  13900. 'marker-end',
  13901. 'marker-mid',
  13902. 'marker-start',
  13903. 'markerheight',
  13904. 'markerunits',
  13905. 'markerwidth',
  13906. 'maskcontentunits',
  13907. 'maskunits',
  13908. 'max',
  13909. 'mask',
  13910. 'media',
  13911. 'method',
  13912. 'mode',
  13913. 'min',
  13914. 'name',
  13915. 'numoctaves',
  13916. 'offset',
  13917. 'operator',
  13918. 'opacity',
  13919. 'order',
  13920. 'orient',
  13921. 'orientation',
  13922. 'origin',
  13923. 'overflow',
  13924. 'paint-order',
  13925. 'path',
  13926. 'pathlength',
  13927. 'patterncontentunits',
  13928. 'patterntransform',
  13929. 'patternunits',
  13930. 'points',
  13931. 'preservealpha',
  13932. 'preserveaspectratio',
  13933. 'primitiveunits',
  13934. 'r',
  13935. 'rx',
  13936. 'ry',
  13937. 'radius',
  13938. 'refx',
  13939. 'refy',
  13940. 'repeatcount',
  13941. 'repeatdur',
  13942. 'restart',
  13943. 'result',
  13944. 'rotate',
  13945. 'scale',
  13946. 'seed',
  13947. 'shape-rendering',
  13948. 'specularconstant',
  13949. 'specularexponent',
  13950. 'spreadmethod',
  13951. 'startoffset',
  13952. 'stddeviation',
  13953. 'stitchtiles',
  13954. 'stop-color',
  13955. 'stop-opacity',
  13956. 'stroke-dasharray',
  13957. 'stroke-dashoffset',
  13958. 'stroke-linecap',
  13959. 'stroke-linejoin',
  13960. 'stroke-miterlimit',
  13961. 'stroke-opacity',
  13962. 'stroke',
  13963. 'stroke-width',
  13964. 'style',
  13965. 'surfacescale',
  13966. 'systemlanguage',
  13967. 'tabindex',
  13968. 'targetx',
  13969. 'targety',
  13970. 'transform',
  13971. 'transform-origin',
  13972. 'text-anchor',
  13973. 'text-decoration',
  13974. 'text-rendering',
  13975. 'textlength',
  13976. 'type',
  13977. 'u1',
  13978. 'u2',
  13979. 'unicode',
  13980. 'values',
  13981. 'viewbox',
  13982. 'visibility',
  13983. 'version',
  13984. 'vert-adv-y',
  13985. 'vert-origin-x',
  13986. 'vert-origin-y',
  13987. 'width',
  13988. 'word-spacing',
  13989. 'wrap',
  13990. 'writing-mode',
  13991. 'xchannelselector',
  13992. 'ychannelselector',
  13993. 'x',
  13994. 'x1',
  13995. 'x2',
  13996. 'xmlns',
  13997. 'y',
  13998. 'y1',
  13999. 'y2',
  14000. 'z',
  14001. 'zoomandpan'
  14002. ]);
  14003. var mathMl$1 = freeze([
  14004. 'accent',
  14005. 'accentunder',
  14006. 'align',
  14007. 'bevelled',
  14008. 'close',
  14009. 'columnsalign',
  14010. 'columnlines',
  14011. 'columnspan',
  14012. 'denomalign',
  14013. 'depth',
  14014. 'dir',
  14015. 'display',
  14016. 'displaystyle',
  14017. 'encoding',
  14018. 'fence',
  14019. 'frame',
  14020. 'height',
  14021. 'href',
  14022. 'id',
  14023. 'largeop',
  14024. 'length',
  14025. 'linethickness',
  14026. 'lspace',
  14027. 'lquote',
  14028. 'mathbackground',
  14029. 'mathcolor',
  14030. 'mathsize',
  14031. 'mathvariant',
  14032. 'maxsize',
  14033. 'minsize',
  14034. 'movablelimits',
  14035. 'notation',
  14036. 'numalign',
  14037. 'open',
  14038. 'rowalign',
  14039. 'rowlines',
  14040. 'rowspacing',
  14041. 'rowspan',
  14042. 'rspace',
  14043. 'rquote',
  14044. 'scriptlevel',
  14045. 'scriptminsize',
  14046. 'scriptsizemultiplier',
  14047. 'selection',
  14048. 'separator',
  14049. 'separators',
  14050. 'stretchy',
  14051. 'subscriptshift',
  14052. 'supscriptshift',
  14053. 'symmetric',
  14054. 'voffset',
  14055. 'width',
  14056. 'xmlns'
  14057. ]);
  14058. var xml = freeze([
  14059. 'xlink:href',
  14060. 'xml:id',
  14061. 'xlink:title',
  14062. 'xml:space',
  14063. 'xmlns:xlink'
  14064. ]);
  14065. var MUSTACHE_EXPR = seal(/\{\{[\s\S]*|[\s\S]*\}\}/gm);
  14066. var ERB_EXPR = seal(/<%[\s\S]*|[\s\S]*%>/gm);
  14067. var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/);
  14068. var ARIA_ATTR = seal(/^aria-[\-\w]+$/);
  14069. var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i);
  14070. var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
  14071. var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g);
  14072. var DOCTYPE_NAME = seal(/^html$/i);
  14073. var _typeof = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? function (obj) {
  14074. return typeof obj;
  14075. } : function (obj) {
  14076. return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
  14077. };
  14078. function _toConsumableArray$1(arr) {
  14079. if (Array.isArray(arr)) {
  14080. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
  14081. arr2[i] = arr[i];
  14082. }
  14083. return arr2;
  14084. } else {
  14085. return Array.from(arr);
  14086. }
  14087. }
  14088. var getGlobal = function getGlobal() {
  14089. return typeof window === 'undefined' ? null : window;
  14090. };
  14091. var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
  14092. if ((typeof trustedTypes === 'undefined' ? 'undefined' : _typeof(trustedTypes)) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
  14093. return null;
  14094. }
  14095. var suffix = null;
  14096. var ATTR_NAME = 'data-tt-policy-suffix';
  14097. if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
  14098. suffix = document.currentScript.getAttribute(ATTR_NAME);
  14099. }
  14100. var policyName = 'dompurify' + (suffix ? '#' + suffix : '');
  14101. try {
  14102. return trustedTypes.createPolicy(policyName, {
  14103. createHTML: function createHTML(html$$1) {
  14104. return html$$1;
  14105. }
  14106. });
  14107. } catch (_) {
  14108. console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
  14109. return null;
  14110. }
  14111. };
  14112. function createDOMPurify() {
  14113. var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
  14114. var DOMPurify = function DOMPurify(root) {
  14115. return createDOMPurify(root);
  14116. };
  14117. DOMPurify.version = '2.3.6';
  14118. DOMPurify.removed = [];
  14119. if (!window || !window.document || window.document.nodeType !== 9) {
  14120. DOMPurify.isSupported = false;
  14121. return DOMPurify;
  14122. }
  14123. var originalDocument = window.document;
  14124. var document = window.document;
  14125. var DocumentFragment = window.DocumentFragment, HTMLTemplateElement = window.HTMLTemplateElement, Node = window.Node, Element = window.Element, NodeFilter = window.NodeFilter, _window$NamedNodeMap = window.NamedNodeMap, NamedNodeMap = _window$NamedNodeMap === undefined ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap, HTMLFormElement = window.HTMLFormElement, DOMParser = window.DOMParser, trustedTypes = window.trustedTypes;
  14126. var ElementPrototype = Element.prototype;
  14127. var cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
  14128. var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
  14129. var getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
  14130. var getParentNode = lookupGetter(ElementPrototype, 'parentNode');
  14131. if (typeof HTMLTemplateElement === 'function') {
  14132. var template = document.createElement('template');
  14133. if (template.content && template.content.ownerDocument) {
  14134. document = template.content.ownerDocument;
  14135. }
  14136. }
  14137. var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
  14138. var emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML('') : '';
  14139. var _document = document, implementation = _document.implementation, createNodeIterator = _document.createNodeIterator, createDocumentFragment = _document.createDocumentFragment, getElementsByTagName = _document.getElementsByTagName;
  14140. var importNode = originalDocument.importNode;
  14141. var documentMode = {};
  14142. try {
  14143. documentMode = clone(document).documentMode ? document.documentMode : {};
  14144. } catch (_) {
  14145. }
  14146. var hooks = {};
  14147. DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9;
  14148. var MUSTACHE_EXPR$$1 = MUSTACHE_EXPR, ERB_EXPR$$1 = ERB_EXPR, DATA_ATTR$$1 = DATA_ATTR, ARIA_ATTR$$1 = ARIA_ATTR, IS_SCRIPT_OR_DATA$$1 = IS_SCRIPT_OR_DATA, ATTR_WHITESPACE$$1 = ATTR_WHITESPACE;
  14149. var IS_ALLOWED_URI$$1 = IS_ALLOWED_URI;
  14150. var ALLOWED_TAGS = null;
  14151. var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(html), _toConsumableArray$1(svg), _toConsumableArray$1(svgFilters), _toConsumableArray$1(mathMl), _toConsumableArray$1(text)));
  14152. var ALLOWED_ATTR = null;
  14153. var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray$1(html$1), _toConsumableArray$1(svg$1), _toConsumableArray$1(mathMl$1), _toConsumableArray$1(xml)));
  14154. var CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
  14155. tagNameCheck: {
  14156. writable: true,
  14157. configurable: false,
  14158. enumerable: true,
  14159. value: null
  14160. },
  14161. attributeNameCheck: {
  14162. writable: true,
  14163. configurable: false,
  14164. enumerable: true,
  14165. value: null
  14166. },
  14167. allowCustomizedBuiltInElements: {
  14168. writable: true,
  14169. configurable: false,
  14170. enumerable: true,
  14171. value: false
  14172. }
  14173. }));
  14174. var FORBID_TAGS = null;
  14175. var FORBID_ATTR = null;
  14176. var ALLOW_ARIA_ATTR = true;
  14177. var ALLOW_DATA_ATTR = true;
  14178. var ALLOW_UNKNOWN_PROTOCOLS = false;
  14179. var SAFE_FOR_TEMPLATES = false;
  14180. var WHOLE_DOCUMENT = false;
  14181. var SET_CONFIG = false;
  14182. var FORCE_BODY = false;
  14183. var RETURN_DOM = false;
  14184. var RETURN_DOM_FRAGMENT = false;
  14185. var RETURN_TRUSTED_TYPE = false;
  14186. var SANITIZE_DOM = true;
  14187. var KEEP_CONTENT = true;
  14188. var IN_PLACE = false;
  14189. var USE_PROFILES = {};
  14190. var FORBID_CONTENTS = null;
  14191. var DEFAULT_FORBID_CONTENTS = addToSet({}, [
  14192. 'annotation-xml',
  14193. 'audio',
  14194. 'colgroup',
  14195. 'desc',
  14196. 'foreignobject',
  14197. 'head',
  14198. 'iframe',
  14199. 'math',
  14200. 'mi',
  14201. 'mn',
  14202. 'mo',
  14203. 'ms',
  14204. 'mtext',
  14205. 'noembed',
  14206. 'noframes',
  14207. 'noscript',
  14208. 'plaintext',
  14209. 'script',
  14210. 'style',
  14211. 'svg',
  14212. 'template',
  14213. 'thead',
  14214. 'title',
  14215. 'video',
  14216. 'xmp'
  14217. ]);
  14218. var DATA_URI_TAGS = null;
  14219. var DEFAULT_DATA_URI_TAGS = addToSet({}, [
  14220. 'audio',
  14221. 'video',
  14222. 'img',
  14223. 'source',
  14224. 'image',
  14225. 'track'
  14226. ]);
  14227. var URI_SAFE_ATTRIBUTES = null;
  14228. var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, [
  14229. 'alt',
  14230. 'class',
  14231. 'for',
  14232. 'id',
  14233. 'label',
  14234. 'name',
  14235. 'pattern',
  14236. 'placeholder',
  14237. 'role',
  14238. 'summary',
  14239. 'title',
  14240. 'value',
  14241. 'style',
  14242. 'xmlns'
  14243. ]);
  14244. var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
  14245. var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
  14246. var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
  14247. var NAMESPACE = HTML_NAMESPACE;
  14248. var IS_EMPTY_INPUT = false;
  14249. var PARSER_MEDIA_TYPE = void 0;
  14250. var SUPPORTED_PARSER_MEDIA_TYPES = [
  14251. 'application/xhtml+xml',
  14252. 'text/html'
  14253. ];
  14254. var DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
  14255. var transformCaseFunc = void 0;
  14256. var CONFIG = null;
  14257. var formElement = document.createElement('form');
  14258. var isRegexOrFunction = function isRegexOrFunction(testValue) {
  14259. return testValue instanceof RegExp || testValue instanceof Function;
  14260. };
  14261. var _parseConfig = function _parseConfig(cfg) {
  14262. if (CONFIG && CONFIG === cfg) {
  14263. return;
  14264. }
  14265. if (!cfg || (typeof cfg === 'undefined' ? 'undefined' : _typeof(cfg)) !== 'object') {
  14266. cfg = {};
  14267. }
  14268. cfg = clone(cfg);
  14269. ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
  14270. ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
  14271. URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES;
  14272. DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS;
  14273. FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS) : DEFAULT_FORBID_CONTENTS;
  14274. FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};
  14275. FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};
  14276. USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
  14277. ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false;
  14278. ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false;
  14279. ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false;
  14280. SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false;
  14281. WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false;
  14282. RETURN_DOM = cfg.RETURN_DOM || false;
  14283. RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false;
  14284. RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false;
  14285. FORCE_BODY = cfg.FORCE_BODY || false;
  14286. SANITIZE_DOM = cfg.SANITIZE_DOM !== false;
  14287. KEEP_CONTENT = cfg.KEEP_CONTENT !== false;
  14288. IN_PLACE = cfg.IN_PLACE || false;
  14289. IS_ALLOWED_URI$$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$$1;
  14290. NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
  14291. if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
  14292. CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
  14293. }
  14294. if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
  14295. CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
  14296. }
  14297. if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
  14298. CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
  14299. }
  14300. PARSER_MEDIA_TYPE = SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE;
  14301. transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? function (x) {
  14302. return x;
  14303. } : stringToLowerCase;
  14304. if (SAFE_FOR_TEMPLATES) {
  14305. ALLOW_DATA_ATTR = false;
  14306. }
  14307. if (RETURN_DOM_FRAGMENT) {
  14308. RETURN_DOM = true;
  14309. }
  14310. if (USE_PROFILES) {
  14311. ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(text)));
  14312. ALLOWED_ATTR = [];
  14313. if (USE_PROFILES.html === true) {
  14314. addToSet(ALLOWED_TAGS, html);
  14315. addToSet(ALLOWED_ATTR, html$1);
  14316. }
  14317. if (USE_PROFILES.svg === true) {
  14318. addToSet(ALLOWED_TAGS, svg);
  14319. addToSet(ALLOWED_ATTR, svg$1);
  14320. addToSet(ALLOWED_ATTR, xml);
  14321. }
  14322. if (USE_PROFILES.svgFilters === true) {
  14323. addToSet(ALLOWED_TAGS, svgFilters);
  14324. addToSet(ALLOWED_ATTR, svg$1);
  14325. addToSet(ALLOWED_ATTR, xml);
  14326. }
  14327. if (USE_PROFILES.mathMl === true) {
  14328. addToSet(ALLOWED_TAGS, mathMl);
  14329. addToSet(ALLOWED_ATTR, mathMl$1);
  14330. addToSet(ALLOWED_ATTR, xml);
  14331. }
  14332. }
  14333. if (cfg.ADD_TAGS) {
  14334. if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
  14335. ALLOWED_TAGS = clone(ALLOWED_TAGS);
  14336. }
  14337. addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
  14338. }
  14339. if (cfg.ADD_ATTR) {
  14340. if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
  14341. ALLOWED_ATTR = clone(ALLOWED_ATTR);
  14342. }
  14343. addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
  14344. }
  14345. if (cfg.ADD_URI_SAFE_ATTR) {
  14346. addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
  14347. }
  14348. if (cfg.FORBID_CONTENTS) {
  14349. if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
  14350. FORBID_CONTENTS = clone(FORBID_CONTENTS);
  14351. }
  14352. addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS);
  14353. }
  14354. if (KEEP_CONTENT) {
  14355. ALLOWED_TAGS['#text'] = true;
  14356. }
  14357. if (WHOLE_DOCUMENT) {
  14358. addToSet(ALLOWED_TAGS, [
  14359. 'html',
  14360. 'head',
  14361. 'body'
  14362. ]);
  14363. }
  14364. if (ALLOWED_TAGS.table) {
  14365. addToSet(ALLOWED_TAGS, ['tbody']);
  14366. delete FORBID_TAGS.tbody;
  14367. }
  14368. if (freeze) {
  14369. freeze(cfg);
  14370. }
  14371. CONFIG = cfg;
  14372. };
  14373. var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, [
  14374. 'mi',
  14375. 'mo',
  14376. 'mn',
  14377. 'ms',
  14378. 'mtext'
  14379. ]);
  14380. var HTML_INTEGRATION_POINTS = addToSet({}, [
  14381. 'foreignobject',
  14382. 'desc',
  14383. 'title',
  14384. 'annotation-xml'
  14385. ]);
  14386. var COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, [
  14387. 'title',
  14388. 'style',
  14389. 'font',
  14390. 'a',
  14391. 'script'
  14392. ]);
  14393. var ALL_SVG_TAGS = addToSet({}, svg);
  14394. addToSet(ALL_SVG_TAGS, svgFilters);
  14395. addToSet(ALL_SVG_TAGS, svgDisallowed);
  14396. var ALL_MATHML_TAGS = addToSet({}, mathMl);
  14397. addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
  14398. var _checkValidNamespace = function _checkValidNamespace(element) {
  14399. var parent = getParentNode(element);
  14400. if (!parent || !parent.tagName) {
  14401. parent = {
  14402. namespaceURI: HTML_NAMESPACE,
  14403. tagName: 'template'
  14404. };
  14405. }
  14406. var tagName = stringToLowerCase(element.tagName);
  14407. var parentTagName = stringToLowerCase(parent.tagName);
  14408. if (element.namespaceURI === SVG_NAMESPACE) {
  14409. if (parent.namespaceURI === HTML_NAMESPACE) {
  14410. return tagName === 'svg';
  14411. }
  14412. if (parent.namespaceURI === MATHML_NAMESPACE) {
  14413. return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
  14414. }
  14415. return Boolean(ALL_SVG_TAGS[tagName]);
  14416. }
  14417. if (element.namespaceURI === MATHML_NAMESPACE) {
  14418. if (parent.namespaceURI === HTML_NAMESPACE) {
  14419. return tagName === 'math';
  14420. }
  14421. if (parent.namespaceURI === SVG_NAMESPACE) {
  14422. return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
  14423. }
  14424. return Boolean(ALL_MATHML_TAGS[tagName]);
  14425. }
  14426. if (element.namespaceURI === HTML_NAMESPACE) {
  14427. if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
  14428. return false;
  14429. }
  14430. if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
  14431. return false;
  14432. }
  14433. return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
  14434. }
  14435. return false;
  14436. };
  14437. var _forceRemove = function _forceRemove(node) {
  14438. arrayPush(DOMPurify.removed, { element: node });
  14439. try {
  14440. node.parentNode.removeChild(node);
  14441. } catch (_) {
  14442. try {
  14443. node.outerHTML = emptyHTML;
  14444. } catch (_) {
  14445. node.remove();
  14446. }
  14447. }
  14448. };
  14449. var _removeAttribute = function _removeAttribute(name, node) {
  14450. try {
  14451. arrayPush(DOMPurify.removed, {
  14452. attribute: node.getAttributeNode(name),
  14453. from: node
  14454. });
  14455. } catch (_) {
  14456. arrayPush(DOMPurify.removed, {
  14457. attribute: null,
  14458. from: node
  14459. });
  14460. }
  14461. node.removeAttribute(name);
  14462. if (name === 'is' && !ALLOWED_ATTR[name]) {
  14463. if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
  14464. try {
  14465. _forceRemove(node);
  14466. } catch (_) {
  14467. }
  14468. } else {
  14469. try {
  14470. node.setAttribute(name, '');
  14471. } catch (_) {
  14472. }
  14473. }
  14474. }
  14475. };
  14476. var _initDocument = function _initDocument(dirty) {
  14477. var doc = void 0;
  14478. var leadingWhitespace = void 0;
  14479. if (FORCE_BODY) {
  14480. dirty = '<remove></remove>' + dirty;
  14481. } else {
  14482. var matches = stringMatch(dirty, /^[\r\n\t ]+/);
  14483. leadingWhitespace = matches && matches[0];
  14484. }
  14485. if (PARSER_MEDIA_TYPE === 'application/xhtml+xml') {
  14486. dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
  14487. }
  14488. var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
  14489. if (NAMESPACE === HTML_NAMESPACE) {
  14490. try {
  14491. doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
  14492. } catch (_) {
  14493. }
  14494. }
  14495. if (!doc || !doc.documentElement) {
  14496. doc = implementation.createDocument(NAMESPACE, 'template', null);
  14497. try {
  14498. doc.documentElement.innerHTML = IS_EMPTY_INPUT ? '' : dirtyPayload;
  14499. } catch (_) {
  14500. }
  14501. }
  14502. var body = doc.body || doc.documentElement;
  14503. if (dirty && leadingWhitespace) {
  14504. body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
  14505. }
  14506. if (NAMESPACE === HTML_NAMESPACE) {
  14507. return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
  14508. }
  14509. return WHOLE_DOCUMENT ? doc.documentElement : body;
  14510. };
  14511. var _createIterator = function _createIterator(root) {
  14512. return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
  14513. };
  14514. var _isClobbered = function _isClobbered(elm) {
  14515. return elm instanceof HTMLFormElement && (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function');
  14516. };
  14517. var _isNode = function _isNode(object) {
  14518. return (typeof Node === 'undefined' ? 'undefined' : _typeof(Node)) === 'object' ? object instanceof Node : object && (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
  14519. };
  14520. var _executeHook = function _executeHook(entryPoint, currentNode, data) {
  14521. if (!hooks[entryPoint]) {
  14522. return;
  14523. }
  14524. arrayForEach(hooks[entryPoint], function (hook) {
  14525. hook.call(DOMPurify, currentNode, data, CONFIG);
  14526. });
  14527. };
  14528. var _sanitizeElements = function _sanitizeElements(currentNode) {
  14529. var content = void 0;
  14530. _executeHook('beforeSanitizeElements', currentNode, null);
  14531. if (_isClobbered(currentNode)) {
  14532. _forceRemove(currentNode);
  14533. return true;
  14534. }
  14535. if (regExpTest(/[\u0080-\uFFFF]/, currentNode.nodeName)) {
  14536. _forceRemove(currentNode);
  14537. return true;
  14538. }
  14539. var tagName = transformCaseFunc(currentNode.nodeName);
  14540. _executeHook('uponSanitizeElement', currentNode, {
  14541. tagName: tagName,
  14542. allowedTags: ALLOWED_TAGS
  14543. });
  14544. if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
  14545. _forceRemove(currentNode);
  14546. return true;
  14547. }
  14548. if (tagName === 'select' && regExpTest(/<template/i, currentNode.innerHTML)) {
  14549. _forceRemove(currentNode);
  14550. return true;
  14551. }
  14552. if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
  14553. if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
  14554. if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName))
  14555. return false;
  14556. if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName))
  14557. return false;
  14558. }
  14559. if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
  14560. var parentNode = getParentNode(currentNode) || currentNode.parentNode;
  14561. var childNodes = getChildNodes(currentNode) || currentNode.childNodes;
  14562. if (childNodes && parentNode) {
  14563. var childCount = childNodes.length;
  14564. for (var i = childCount - 1; i >= 0; --i) {
  14565. parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
  14566. }
  14567. }
  14568. }
  14569. _forceRemove(currentNode);
  14570. return true;
  14571. }
  14572. if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
  14573. _forceRemove(currentNode);
  14574. return true;
  14575. }
  14576. if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
  14577. _forceRemove(currentNode);
  14578. return true;
  14579. }
  14580. if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
  14581. content = currentNode.textContent;
  14582. content = stringReplace(content, MUSTACHE_EXPR$$1, ' ');
  14583. content = stringReplace(content, ERB_EXPR$$1, ' ');
  14584. if (currentNode.textContent !== content) {
  14585. arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
  14586. currentNode.textContent = content;
  14587. }
  14588. }
  14589. _executeHook('afterSanitizeElements', currentNode, null);
  14590. return false;
  14591. };
  14592. var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
  14593. if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
  14594. return false;
  14595. }
  14596. if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$$1, lcName));
  14597. else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$$1, lcName));
  14598. else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
  14599. if (_basicCustomElementTest(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value)));
  14600. else {
  14601. return false;
  14602. }
  14603. } else if (URI_SAFE_ATTRIBUTES[lcName]);
  14604. else if (regExpTest(IS_ALLOWED_URI$$1, stringReplace(value, ATTR_WHITESPACE$$1, '')));
  14605. else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]);
  14606. else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$$1, stringReplace(value, ATTR_WHITESPACE$$1, '')));
  14607. else if (!value);
  14608. else {
  14609. return false;
  14610. }
  14611. return true;
  14612. };
  14613. var _basicCustomElementTest = function _basicCustomElementTest(tagName) {
  14614. return tagName.indexOf('-') > 0;
  14615. };
  14616. var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
  14617. var attr = void 0;
  14618. var value = void 0;
  14619. var lcName = void 0;
  14620. var l = void 0;
  14621. _executeHook('beforeSanitizeAttributes', currentNode, null);
  14622. var attributes = currentNode.attributes;
  14623. if (!attributes) {
  14624. return;
  14625. }
  14626. var hookEvent = {
  14627. attrName: '',
  14628. attrValue: '',
  14629. keepAttr: true,
  14630. allowedAttributes: ALLOWED_ATTR
  14631. };
  14632. l = attributes.length;
  14633. while (l--) {
  14634. attr = attributes[l];
  14635. var _attr = attr, name = _attr.name, namespaceURI = _attr.namespaceURI;
  14636. value = stringTrim(attr.value);
  14637. lcName = transformCaseFunc(name);
  14638. var initValue = value;
  14639. hookEvent.attrName = lcName;
  14640. hookEvent.attrValue = value;
  14641. hookEvent.keepAttr = true;
  14642. hookEvent.forceKeepAttr = undefined;
  14643. _executeHook('uponSanitizeAttribute', currentNode, hookEvent);
  14644. value = hookEvent.attrValue;
  14645. if (hookEvent.forceKeepAttr) {
  14646. continue;
  14647. }
  14648. if (!hookEvent.keepAttr) {
  14649. _removeAttribute(name, currentNode);
  14650. continue;
  14651. }
  14652. if (regExpTest(/\/>/i, value)) {
  14653. _removeAttribute(name, currentNode);
  14654. continue;
  14655. }
  14656. if (SAFE_FOR_TEMPLATES) {
  14657. value = stringReplace(value, MUSTACHE_EXPR$$1, ' ');
  14658. value = stringReplace(value, ERB_EXPR$$1, ' ');
  14659. }
  14660. var lcTag = transformCaseFunc(currentNode.nodeName);
  14661. if (!_isValidAttribute(lcTag, lcName, value)) {
  14662. _removeAttribute(name, currentNode);
  14663. continue;
  14664. }
  14665. if (value !== initValue) {
  14666. try {
  14667. if (namespaceURI) {
  14668. currentNode.setAttributeNS(namespaceURI, name, value);
  14669. } else {
  14670. currentNode.setAttribute(name, value);
  14671. }
  14672. } catch (_) {
  14673. _removeAttribute(name, currentNode);
  14674. }
  14675. }
  14676. }
  14677. _executeHook('afterSanitizeAttributes', currentNode, null);
  14678. };
  14679. var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
  14680. var shadowNode = void 0;
  14681. var shadowIterator = _createIterator(fragment);
  14682. _executeHook('beforeSanitizeShadowDOM', fragment, null);
  14683. while (shadowNode = shadowIterator.nextNode()) {
  14684. _executeHook('uponSanitizeShadowNode', shadowNode, null);
  14685. if (_sanitizeElements(shadowNode)) {
  14686. continue;
  14687. }
  14688. if (shadowNode.content instanceof DocumentFragment) {
  14689. _sanitizeShadowDOM(shadowNode.content);
  14690. }
  14691. _sanitizeAttributes(shadowNode);
  14692. }
  14693. _executeHook('afterSanitizeShadowDOM', fragment, null);
  14694. };
  14695. DOMPurify.sanitize = function (dirty, cfg) {
  14696. var body = void 0;
  14697. var importedNode = void 0;
  14698. var currentNode = void 0;
  14699. var oldNode = void 0;
  14700. var returnNode = void 0;
  14701. IS_EMPTY_INPUT = !dirty;
  14702. if (IS_EMPTY_INPUT) {
  14703. dirty = '<!-->';
  14704. }
  14705. if (typeof dirty !== 'string' && !_isNode(dirty)) {
  14706. if (typeof dirty.toString !== 'function') {
  14707. throw typeErrorCreate('toString is not a function');
  14708. } else {
  14709. dirty = dirty.toString();
  14710. if (typeof dirty !== 'string') {
  14711. throw typeErrorCreate('dirty is not a string, aborting');
  14712. }
  14713. }
  14714. }
  14715. if (!DOMPurify.isSupported) {
  14716. if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
  14717. if (typeof dirty === 'string') {
  14718. return window.toStaticHTML(dirty);
  14719. }
  14720. if (_isNode(dirty)) {
  14721. return window.toStaticHTML(dirty.outerHTML);
  14722. }
  14723. }
  14724. return dirty;
  14725. }
  14726. if (!SET_CONFIG) {
  14727. _parseConfig(cfg);
  14728. }
  14729. DOMPurify.removed = [];
  14730. if (typeof dirty === 'string') {
  14731. IN_PLACE = false;
  14732. }
  14733. if (IN_PLACE) {
  14734. if (dirty.nodeName) {
  14735. var tagName = transformCaseFunc(dirty.nodeName);
  14736. if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
  14737. throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
  14738. }
  14739. }
  14740. } else if (dirty instanceof Node) {
  14741. body = _initDocument('<!---->');
  14742. importedNode = body.ownerDocument.importNode(dirty, true);
  14743. if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
  14744. body = importedNode;
  14745. } else if (importedNode.nodeName === 'HTML') {
  14746. body = importedNode;
  14747. } else {
  14748. body.appendChild(importedNode);
  14749. }
  14750. } else {
  14751. if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && dirty.indexOf('<') === -1) {
  14752. return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
  14753. }
  14754. body = _initDocument(dirty);
  14755. if (!body) {
  14756. return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
  14757. }
  14758. }
  14759. if (body && FORCE_BODY) {
  14760. _forceRemove(body.firstChild);
  14761. }
  14762. var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
  14763. while (currentNode = nodeIterator.nextNode()) {
  14764. if (currentNode.nodeType === 3 && currentNode === oldNode) {
  14765. continue;
  14766. }
  14767. if (_sanitizeElements(currentNode)) {
  14768. continue;
  14769. }
  14770. if (currentNode.content instanceof DocumentFragment) {
  14771. _sanitizeShadowDOM(currentNode.content);
  14772. }
  14773. _sanitizeAttributes(currentNode);
  14774. oldNode = currentNode;
  14775. }
  14776. oldNode = null;
  14777. if (IN_PLACE) {
  14778. return dirty;
  14779. }
  14780. if (RETURN_DOM) {
  14781. if (RETURN_DOM_FRAGMENT) {
  14782. returnNode = createDocumentFragment.call(body.ownerDocument);
  14783. while (body.firstChild) {
  14784. returnNode.appendChild(body.firstChild);
  14785. }
  14786. } else {
  14787. returnNode = body;
  14788. }
  14789. if (ALLOWED_ATTR.shadowroot) {
  14790. returnNode = importNode.call(originalDocument, returnNode, true);
  14791. }
  14792. return returnNode;
  14793. }
  14794. var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
  14795. if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
  14796. serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
  14797. }
  14798. if (SAFE_FOR_TEMPLATES) {
  14799. serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$$1, ' ');
  14800. serializedHTML = stringReplace(serializedHTML, ERB_EXPR$$1, ' ');
  14801. }
  14802. return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
  14803. };
  14804. DOMPurify.setConfig = function (cfg) {
  14805. _parseConfig(cfg);
  14806. SET_CONFIG = true;
  14807. };
  14808. DOMPurify.clearConfig = function () {
  14809. CONFIG = null;
  14810. SET_CONFIG = false;
  14811. };
  14812. DOMPurify.isValidAttribute = function (tag, attr, value) {
  14813. if (!CONFIG) {
  14814. _parseConfig({});
  14815. }
  14816. var lcTag = transformCaseFunc(tag);
  14817. var lcName = transformCaseFunc(attr);
  14818. return _isValidAttribute(lcTag, lcName, value);
  14819. };
  14820. DOMPurify.addHook = function (entryPoint, hookFunction) {
  14821. if (typeof hookFunction !== 'function') {
  14822. return;
  14823. }
  14824. hooks[entryPoint] = hooks[entryPoint] || [];
  14825. arrayPush(hooks[entryPoint], hookFunction);
  14826. };
  14827. DOMPurify.removeHook = function (entryPoint) {
  14828. if (hooks[entryPoint]) {
  14829. arrayPop(hooks[entryPoint]);
  14830. }
  14831. };
  14832. DOMPurify.removeHooks = function (entryPoint) {
  14833. if (hooks[entryPoint]) {
  14834. hooks[entryPoint] = [];
  14835. }
  14836. };
  14837. DOMPurify.removeAllHooks = function () {
  14838. hooks = {};
  14839. };
  14840. return DOMPurify;
  14841. }
  14842. var purify = createDOMPurify();
  14843. const removeAttrs = (node, names) => {
  14844. each$g(names, name => {
  14845. node.attr(name, null);
  14846. });
  14847. };
  14848. const addFontToSpansFilter = (domParser, styles, fontSizes) => {
  14849. domParser.addNodeFilter('font', nodes => {
  14850. each$g(nodes, node => {
  14851. const props = styles.parse(node.attr('style'));
  14852. const color = node.attr('color');
  14853. const face = node.attr('face');
  14854. const size = node.attr('size');
  14855. if (color) {
  14856. props.color = color;
  14857. }
  14858. if (face) {
  14859. props['font-family'] = face;
  14860. }
  14861. if (size) {
  14862. props['font-size'] = fontSizes[parseInt(node.attr('size'), 10) - 1];
  14863. }
  14864. node.name = 'span';
  14865. node.attr('style', styles.serialize(props));
  14866. removeAttrs(node, [
  14867. 'color',
  14868. 'face',
  14869. 'size'
  14870. ]);
  14871. });
  14872. });
  14873. };
  14874. const addStrikeFilter = (domParser, schema, styles) => {
  14875. domParser.addNodeFilter('strike', nodes => {
  14876. const convertToSTag = schema.type !== 'html4';
  14877. each$g(nodes, node => {
  14878. if (convertToSTag) {
  14879. node.name = 's';
  14880. } else {
  14881. const props = styles.parse(node.attr('style'));
  14882. props['text-decoration'] = 'line-through';
  14883. node.name = 'span';
  14884. node.attr('style', styles.serialize(props));
  14885. }
  14886. });
  14887. });
  14888. };
  14889. const addFilters = (domParser, settings, schema) => {
  14890. const styles = Styles();
  14891. if (settings.convert_fonts_to_spans) {
  14892. addFontToSpansFilter(domParser, styles, Tools.explode(settings.font_size_legacy_values));
  14893. }
  14894. addStrikeFilter(domParser, schema, styles);
  14895. };
  14896. const register$5 = (domParser, settings, schema) => {
  14897. if (settings.inline_styles) {
  14898. addFilters(domParser, settings, schema);
  14899. }
  14900. };
  14901. const blobUriToBlob = url => {
  14902. return new Promise((resolve, reject) => {
  14903. const rejectWithError = () => {
  14904. reject('Cannot convert ' + url + ' to Blob. Resource might not exist or is inaccessible.');
  14905. };
  14906. try {
  14907. const xhr = new XMLHttpRequest();
  14908. xhr.open('GET', url, true);
  14909. xhr.responseType = 'blob';
  14910. xhr.onload = () => {
  14911. if (xhr.status === 200) {
  14912. resolve(xhr.response);
  14913. } else {
  14914. rejectWithError();
  14915. }
  14916. };
  14917. xhr.onerror = rejectWithError;
  14918. xhr.send();
  14919. } catch (ex) {
  14920. rejectWithError();
  14921. }
  14922. });
  14923. };
  14924. const parseDataUri$1 = uri => {
  14925. let type;
  14926. const uriParts = decodeURIComponent(uri).split(',');
  14927. const matches = /data:([^;]+)/.exec(uriParts[0]);
  14928. if (matches) {
  14929. type = matches[1];
  14930. }
  14931. return {
  14932. type,
  14933. data: uriParts[1]
  14934. };
  14935. };
  14936. const buildBlob = (type, data) => {
  14937. let str;
  14938. try {
  14939. str = atob(data);
  14940. } catch (e) {
  14941. return Optional.none();
  14942. }
  14943. const arr = new Uint8Array(str.length);
  14944. for (let i = 0; i < arr.length; i++) {
  14945. arr[i] = str.charCodeAt(i);
  14946. }
  14947. return Optional.some(new Blob([arr], { type }));
  14948. };
  14949. const dataUriToBlob = uri => {
  14950. return new Promise(resolve => {
  14951. const {type, data} = parseDataUri$1(uri);
  14952. buildBlob(type, data).fold(() => resolve(new Blob([])), resolve);
  14953. });
  14954. };
  14955. const uriToBlob = url => {
  14956. if (url.indexOf('blob:') === 0) {
  14957. return blobUriToBlob(url);
  14958. }
  14959. if (url.indexOf('data:') === 0) {
  14960. return dataUriToBlob(url);
  14961. }
  14962. return null;
  14963. };
  14964. const blobToDataUri = blob => {
  14965. return new Promise(resolve => {
  14966. const reader = new FileReader();
  14967. reader.onloadend = () => {
  14968. resolve(reader.result);
  14969. };
  14970. reader.readAsDataURL(blob);
  14971. });
  14972. };
  14973. let count$1 = 0;
  14974. const uniqueId$1 = prefix => {
  14975. return (prefix || 'blobid') + count$1++;
  14976. };
  14977. const imageToBlobInfo = (blobCache, img, resolve, reject) => {
  14978. let base64, blobInfo;
  14979. if (img.src.indexOf('blob:') === 0) {
  14980. blobInfo = blobCache.getByUri(img.src);
  14981. if (blobInfo) {
  14982. resolve({
  14983. image: img,
  14984. blobInfo
  14985. });
  14986. } else {
  14987. uriToBlob(img.src).then(blob => {
  14988. blobToDataUri(blob).then(dataUri => {
  14989. base64 = parseDataUri$1(dataUri).data;
  14990. blobInfo = blobCache.create(uniqueId$1(), blob, base64);
  14991. blobCache.add(blobInfo);
  14992. resolve({
  14993. image: img,
  14994. blobInfo
  14995. });
  14996. });
  14997. }, err => {
  14998. reject(err);
  14999. });
  15000. }
  15001. return;
  15002. }
  15003. const {data, type} = parseDataUri$1(img.src);
  15004. base64 = data;
  15005. blobInfo = blobCache.getByData(base64, type);
  15006. if (blobInfo) {
  15007. resolve({
  15008. image: img,
  15009. blobInfo
  15010. });
  15011. } else {
  15012. uriToBlob(img.src).then(blob => {
  15013. blobInfo = blobCache.create(uniqueId$1(), blob, base64);
  15014. blobCache.add(blobInfo);
  15015. resolve({
  15016. image: img,
  15017. blobInfo
  15018. });
  15019. }, err => {
  15020. reject(err);
  15021. });
  15022. }
  15023. };
  15024. const getAllImages = elm => {
  15025. return elm ? from(elm.getElementsByTagName('img')) : [];
  15026. };
  15027. const ImageScanner = (uploadStatus, blobCache) => {
  15028. const cachedPromises = {};
  15029. const findAll = (elm, predicate) => {
  15030. if (!predicate) {
  15031. predicate = always;
  15032. }
  15033. const images = filter$6(getAllImages(elm), img => {
  15034. const src = img.src;
  15035. if (img.hasAttribute('data-mce-bogus')) {
  15036. return false;
  15037. }
  15038. if (img.hasAttribute('data-mce-placeholder')) {
  15039. return false;
  15040. }
  15041. if (!src || src === Env.transparentSrc) {
  15042. return false;
  15043. }
  15044. if (src.indexOf('blob:') === 0) {
  15045. return !uploadStatus.isUploaded(src) && predicate(img);
  15046. }
  15047. if (src.indexOf('data:') === 0) {
  15048. return predicate(img);
  15049. }
  15050. return false;
  15051. });
  15052. const promises = map$3(images, img => {
  15053. if (cachedPromises[img.src] !== undefined) {
  15054. return new Promise(resolve => {
  15055. cachedPromises[img.src].then(imageInfo => {
  15056. if (typeof imageInfo === 'string') {
  15057. return imageInfo;
  15058. }
  15059. resolve({
  15060. image: img,
  15061. blobInfo: imageInfo.blobInfo
  15062. });
  15063. });
  15064. });
  15065. }
  15066. const newPromise = new Promise((resolve, reject) => {
  15067. imageToBlobInfo(blobCache, img, resolve, reject);
  15068. }).then(result => {
  15069. delete cachedPromises[result.image.src];
  15070. return result;
  15071. }).catch(error => {
  15072. delete cachedPromises[img.src];
  15073. return error;
  15074. });
  15075. cachedPromises[img.src] = newPromise;
  15076. return newPromise;
  15077. });
  15078. return Promise.all(promises);
  15079. };
  15080. return { findAll };
  15081. };
  15082. const parseDataUri = uri => {
  15083. const matches = /data:([^;]+);base64,([a-z0-9\+\/=\s]+)/i.exec(uri);
  15084. if (matches) {
  15085. return Optional.some({
  15086. type: matches[1],
  15087. data: decodeURIComponent(matches[2])
  15088. });
  15089. } else {
  15090. return Optional.none();
  15091. }
  15092. };
  15093. const isBogusImage = img => isNonNullable(img.attr('data-mce-bogus'));
  15094. const isInternalImageSource = img => img.attr('src') === Env.transparentSrc || isNonNullable(img.attr('data-mce-placeholder'));
  15095. const registerBase64ImageFilter = (parser, settings) => {
  15096. const {blob_cache: blobCache} = settings;
  15097. const processImage = img => {
  15098. const inputSrc = img.attr('src');
  15099. if (isInternalImageSource(img) || isBogusImage(img)) {
  15100. return;
  15101. }
  15102. parseDataUri(inputSrc).bind(({type, data}) => Optional.from(blobCache.getByData(data, type)).orThunk(() => buildBlob(type, data).map(blob => {
  15103. const blobInfo = blobCache.create(uniqueId$1(), blob, data);
  15104. blobCache.add(blobInfo);
  15105. return blobInfo;
  15106. }))).each(blobInfo => {
  15107. img.attr('src', blobInfo.blobUri());
  15108. });
  15109. };
  15110. if (blobCache) {
  15111. parser.addAttributeFilter('src', nodes => each$g(nodes, processImage));
  15112. }
  15113. };
  15114. const register$4 = (parser, settings) => {
  15115. const schema = parser.schema;
  15116. if (settings.remove_trailing_brs) {
  15117. parser.addNodeFilter('br', (nodes, _, args) => {
  15118. const blockElements = Tools.extend({}, schema.getBlockElements());
  15119. const nonEmptyElements = schema.getNonEmptyElements();
  15120. const whitespaceElements = schema.getWhitespaceElements();
  15121. blockElements.body = 1;
  15122. for (let i = 0, l = nodes.length; i < l; i++) {
  15123. let node = nodes[i];
  15124. let parent = node.parent;
  15125. if (blockElements[node.parent.name] && node === parent.lastChild) {
  15126. let prev = node.prev;
  15127. while (prev) {
  15128. const prevName = prev.name;
  15129. if (prevName !== 'span' || prev.attr('data-mce-type') !== 'bookmark') {
  15130. if (prevName === 'br') {
  15131. node = null;
  15132. }
  15133. break;
  15134. }
  15135. prev = prev.prev;
  15136. }
  15137. if (node) {
  15138. node.remove();
  15139. if (isEmpty(schema, nonEmptyElements, whitespaceElements, parent)) {
  15140. const elementRule = schema.getElementRule(parent.name);
  15141. if (elementRule) {
  15142. if (elementRule.removeEmpty) {
  15143. parent.remove();
  15144. } else if (elementRule.paddEmpty) {
  15145. paddEmptyNode(settings, args, blockElements, parent);
  15146. }
  15147. }
  15148. }
  15149. }
  15150. } else {
  15151. let lastParent = node;
  15152. while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) {
  15153. lastParent = parent;
  15154. if (blockElements[parent.name]) {
  15155. break;
  15156. }
  15157. parent = parent.parent;
  15158. }
  15159. if (lastParent === parent) {
  15160. const textNode = new AstNode('#text', 3);
  15161. textNode.value = nbsp;
  15162. node.replace(textNode);
  15163. }
  15164. }
  15165. }
  15166. });
  15167. }
  15168. parser.addAttributeFilter('href', nodes => {
  15169. let i = nodes.length;
  15170. const appendRel = rel => {
  15171. const parts = rel.split(' ').filter(p => p.length > 0);
  15172. return parts.concat(['noopener']).sort().join(' ');
  15173. };
  15174. const addNoOpener = rel => {
  15175. const newRel = rel ? Tools.trim(rel) : '';
  15176. if (!/\b(noopener)\b/g.test(newRel)) {
  15177. return appendRel(newRel);
  15178. } else {
  15179. return newRel;
  15180. }
  15181. };
  15182. if (!settings.allow_unsafe_link_target) {
  15183. while (i--) {
  15184. const node = nodes[i];
  15185. if (node.name === 'a' && node.attr('target') === '_blank') {
  15186. node.attr('rel', addNoOpener(node.attr('rel')));
  15187. }
  15188. }
  15189. }
  15190. });
  15191. if (!settings.allow_html_in_named_anchor) {
  15192. parser.addAttributeFilter('id,name', nodes => {
  15193. let i = nodes.length, sibling, prevSibling, parent, node;
  15194. while (i--) {
  15195. node = nodes[i];
  15196. if (node.name === 'a' && node.firstChild && !node.attr('href')) {
  15197. parent = node.parent;
  15198. sibling = node.lastChild;
  15199. do {
  15200. prevSibling = sibling.prev;
  15201. parent.insert(sibling, node);
  15202. sibling = prevSibling;
  15203. } while (sibling);
  15204. }
  15205. }
  15206. });
  15207. }
  15208. if (settings.fix_list_elements) {
  15209. parser.addNodeFilter('ul,ol', nodes => {
  15210. let i = nodes.length, node, parentNode;
  15211. while (i--) {
  15212. node = nodes[i];
  15213. parentNode = node.parent;
  15214. if (parentNode.name === 'ul' || parentNode.name === 'ol') {
  15215. if (node.prev && node.prev.name === 'li') {
  15216. node.prev.append(node);
  15217. } else {
  15218. const li = new AstNode('li', 1);
  15219. li.attr('style', 'list-style-type: none');
  15220. node.wrap(li);
  15221. }
  15222. }
  15223. }
  15224. });
  15225. }
  15226. if (settings.validate && schema.getValidClasses()) {
  15227. parser.addAttributeFilter('class', nodes => {
  15228. const validClasses = schema.getValidClasses();
  15229. let i = nodes.length;
  15230. while (i--) {
  15231. const node = nodes[i];
  15232. const classList = node.attr('class').split(' ');
  15233. let classValue = '';
  15234. for (let ci = 0; ci < classList.length; ci++) {
  15235. const className = classList[ci];
  15236. let valid = false;
  15237. let validClassesMap = validClasses['*'];
  15238. if (validClassesMap && validClassesMap[className]) {
  15239. valid = true;
  15240. }
  15241. validClassesMap = validClasses[node.name];
  15242. if (!valid && validClassesMap && validClassesMap[className]) {
  15243. valid = true;
  15244. }
  15245. if (valid) {
  15246. if (classValue) {
  15247. classValue += ' ';
  15248. }
  15249. classValue += className;
  15250. }
  15251. }
  15252. if (!classValue.length) {
  15253. classValue = null;
  15254. }
  15255. node.attr('class', classValue);
  15256. }
  15257. });
  15258. }
  15259. registerBase64ImageFilter(parser, settings);
  15260. };
  15261. const each$5 = Tools.each, trim = Tools.trim;
  15262. const queryParts = 'source protocol authority userInfo user password host port relative path directory file query anchor'.split(' ');
  15263. const DEFAULT_PORTS = {
  15264. ftp: 21,
  15265. http: 80,
  15266. https: 443,
  15267. mailto: 25
  15268. };
  15269. const safeSvgDataUrlElements = [
  15270. 'img',
  15271. 'video'
  15272. ];
  15273. const blockSvgDataUris = (allowSvgDataUrls, tagName) => {
  15274. if (isNonNullable(allowSvgDataUrls)) {
  15275. return !allowSvgDataUrls;
  15276. } else {
  15277. return isNonNullable(tagName) ? !contains$2(safeSvgDataUrlElements, tagName) : true;
  15278. }
  15279. };
  15280. const decodeUri = encodedUri => {
  15281. try {
  15282. return decodeURIComponent(encodedUri);
  15283. } catch (ex) {
  15284. return unescape(encodedUri);
  15285. }
  15286. };
  15287. const isInvalidUri = (settings, uri, tagName) => {
  15288. const decodedUri = decodeUri(uri);
  15289. if (settings.allow_script_urls) {
  15290. return false;
  15291. } else if (/((java|vb)script|mhtml):/i.test(decodedUri)) {
  15292. return true;
  15293. } else if (settings.allow_html_data_urls) {
  15294. return false;
  15295. } else if (/^data:image\//i.test(decodedUri)) {
  15296. return blockSvgDataUris(settings.allow_svg_data_urls, tagName) && /^data:image\/svg\+xml/i.test(decodedUri);
  15297. } else {
  15298. return /^data:/i.test(decodedUri);
  15299. }
  15300. };
  15301. class URI {
  15302. constructor(url, settings) {
  15303. url = trim(url);
  15304. this.settings = settings || {};
  15305. const baseUri = this.settings.base_uri;
  15306. const self = this;
  15307. if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
  15308. self.source = url;
  15309. return;
  15310. }
  15311. const isProtocolRelative = url.indexOf('//') === 0;
  15312. if (url.indexOf('/') === 0 && !isProtocolRelative) {
  15313. url = (baseUri ? baseUri.protocol || 'http' : 'http') + '://mce_host' + url;
  15314. }
  15315. if (!/^[\w\-]*:?\/\//.test(url)) {
  15316. const baseUrl = this.settings.base_uri ? this.settings.base_uri.path : new URI(document.location.href).directory;
  15317. if (this.settings.base_uri && this.settings.base_uri.protocol == '') {
  15318. url = '//mce_host' + self.toAbsPath(baseUrl, url);
  15319. } else {
  15320. const match = /([^#?]*)([#?]?.*)/.exec(url);
  15321. url = (baseUri && baseUri.protocol || 'http') + '://mce_host' + self.toAbsPath(baseUrl, match[1]) + match[2];
  15322. }
  15323. }
  15324. url = url.replace(/@@/g, '(mce_at)');
  15325. const urlMatch = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?(\[[a-zA-Z0-9:.%]+\]|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
  15326. each$5(queryParts, (v, i) => {
  15327. let part = urlMatch[i];
  15328. if (part) {
  15329. part = part.replace(/\(mce_at\)/g, '@@');
  15330. }
  15331. self[v] = part;
  15332. });
  15333. if (baseUri) {
  15334. if (!self.protocol) {
  15335. self.protocol = baseUri.protocol;
  15336. }
  15337. if (!self.userInfo) {
  15338. self.userInfo = baseUri.userInfo;
  15339. }
  15340. if (!self.port && self.host === 'mce_host') {
  15341. self.port = baseUri.port;
  15342. }
  15343. if (!self.host || self.host === 'mce_host') {
  15344. self.host = baseUri.host;
  15345. }
  15346. self.source = '';
  15347. }
  15348. if (isProtocolRelative) {
  15349. self.protocol = '';
  15350. }
  15351. }
  15352. static parseDataUri(uri) {
  15353. let type;
  15354. const uriComponents = decodeURIComponent(uri).split(',');
  15355. const matches = /data:([^;]+)/.exec(uriComponents[0]);
  15356. if (matches) {
  15357. type = matches[1];
  15358. }
  15359. return {
  15360. type,
  15361. data: uriComponents[1]
  15362. };
  15363. }
  15364. static isDomSafe(uri, context, options = {}) {
  15365. if (options.allow_script_urls) {
  15366. return true;
  15367. } else {
  15368. const decodedUri = Entities.decode(uri).replace(/[\s\u0000-\u001F]+/g, '');
  15369. return !isInvalidUri(options, decodedUri, context);
  15370. }
  15371. }
  15372. static getDocumentBaseUrl(loc) {
  15373. let baseUrl;
  15374. if (loc.protocol.indexOf('http') !== 0 && loc.protocol !== 'file:') {
  15375. baseUrl = loc.href;
  15376. } else {
  15377. baseUrl = loc.protocol + '//' + loc.host + loc.pathname;
  15378. }
  15379. if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
  15380. baseUrl = baseUrl.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  15381. if (!/[\/\\]$/.test(baseUrl)) {
  15382. baseUrl += '/';
  15383. }
  15384. }
  15385. return baseUrl;
  15386. }
  15387. setPath(path) {
  15388. const pathMatch = /^(.*?)\/?(\w+)?$/.exec(path);
  15389. this.path = pathMatch[0];
  15390. this.directory = pathMatch[1];
  15391. this.file = pathMatch[2];
  15392. this.source = '';
  15393. this.getURI();
  15394. }
  15395. toRelative(uri) {
  15396. let output;
  15397. if (uri === './') {
  15398. return uri;
  15399. }
  15400. const relativeUri = new URI(uri, { base_uri: this });
  15401. if (relativeUri.host !== 'mce_host' && this.host !== relativeUri.host && relativeUri.host || this.port !== relativeUri.port || this.protocol !== relativeUri.protocol && relativeUri.protocol !== '') {
  15402. return relativeUri.getURI();
  15403. }
  15404. const tu = this.getURI(), uu = relativeUri.getURI();
  15405. if (tu === uu || tu.charAt(tu.length - 1) === '/' && tu.substr(0, tu.length - 1) === uu) {
  15406. return tu;
  15407. }
  15408. output = this.toRelPath(this.path, relativeUri.path);
  15409. if (relativeUri.query) {
  15410. output += '?' + relativeUri.query;
  15411. }
  15412. if (relativeUri.anchor) {
  15413. output += '#' + relativeUri.anchor;
  15414. }
  15415. return output;
  15416. }
  15417. toAbsolute(uri, noHost) {
  15418. const absoluteUri = new URI(uri, { base_uri: this });
  15419. return absoluteUri.getURI(noHost && this.isSameOrigin(absoluteUri));
  15420. }
  15421. isSameOrigin(uri) {
  15422. if (this.host == uri.host && this.protocol == uri.protocol) {
  15423. if (this.port == uri.port) {
  15424. return true;
  15425. }
  15426. const defaultPort = DEFAULT_PORTS[this.protocol];
  15427. if (defaultPort && (this.port || defaultPort) == (uri.port || defaultPort)) {
  15428. return true;
  15429. }
  15430. }
  15431. return false;
  15432. }
  15433. toRelPath(base, path) {
  15434. let breakPoint = 0, out = '', i, l;
  15435. const normalizedBase = base.substring(0, base.lastIndexOf('/')).split('/');
  15436. const items = path.split('/');
  15437. if (normalizedBase.length >= items.length) {
  15438. for (i = 0, l = normalizedBase.length; i < l; i++) {
  15439. if (i >= items.length || normalizedBase[i] !== items[i]) {
  15440. breakPoint = i + 1;
  15441. break;
  15442. }
  15443. }
  15444. }
  15445. if (normalizedBase.length < items.length) {
  15446. for (i = 0, l = items.length; i < l; i++) {
  15447. if (i >= normalizedBase.length || normalizedBase[i] !== items[i]) {
  15448. breakPoint = i + 1;
  15449. break;
  15450. }
  15451. }
  15452. }
  15453. if (breakPoint === 1) {
  15454. return path;
  15455. }
  15456. for (i = 0, l = normalizedBase.length - (breakPoint - 1); i < l; i++) {
  15457. out += '../';
  15458. }
  15459. for (i = breakPoint - 1, l = items.length; i < l; i++) {
  15460. if (i !== breakPoint - 1) {
  15461. out += '/' + items[i];
  15462. } else {
  15463. out += items[i];
  15464. }
  15465. }
  15466. return out;
  15467. }
  15468. toAbsPath(base, path) {
  15469. let i, nb = 0, o = [], outPath;
  15470. const tr = /\/$/.test(path) ? '/' : '';
  15471. let normalizedBase = base.split('/');
  15472. const normalizedPath = path.split('/');
  15473. each$5(normalizedBase, k => {
  15474. if (k) {
  15475. o.push(k);
  15476. }
  15477. });
  15478. normalizedBase = o;
  15479. for (i = normalizedPath.length - 1, o = []; i >= 0; i--) {
  15480. if (normalizedPath[i].length === 0 || normalizedPath[i] === '.') {
  15481. continue;
  15482. }
  15483. if (normalizedPath[i] === '..') {
  15484. nb++;
  15485. continue;
  15486. }
  15487. if (nb > 0) {
  15488. nb--;
  15489. continue;
  15490. }
  15491. o.push(normalizedPath[i]);
  15492. }
  15493. i = normalizedBase.length - nb;
  15494. if (i <= 0) {
  15495. outPath = reverse(o).join('/');
  15496. } else {
  15497. outPath = normalizedBase.slice(0, i).join('/') + '/' + reverse(o).join('/');
  15498. }
  15499. if (outPath.indexOf('/') !== 0) {
  15500. outPath = '/' + outPath;
  15501. }
  15502. if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) {
  15503. outPath += tr;
  15504. }
  15505. return outPath;
  15506. }
  15507. getURI(noProtoHost = false) {
  15508. let s;
  15509. if (!this.source || noProtoHost) {
  15510. s = '';
  15511. if (!noProtoHost) {
  15512. if (this.protocol) {
  15513. s += this.protocol + '://';
  15514. } else {
  15515. s += '//';
  15516. }
  15517. if (this.userInfo) {
  15518. s += this.userInfo + '@';
  15519. }
  15520. if (this.host) {
  15521. s += this.host;
  15522. }
  15523. if (this.port) {
  15524. s += ':' + this.port;
  15525. }
  15526. }
  15527. if (this.path) {
  15528. s += this.path;
  15529. }
  15530. if (this.query) {
  15531. s += '?' + this.query;
  15532. }
  15533. if (this.anchor) {
  15534. s += '#' + this.anchor;
  15535. }
  15536. this.source = s;
  15537. }
  15538. return this.source;
  15539. }
  15540. }
  15541. const makeMap = Tools.makeMap, each$4 = Tools.each, explode$1 = Tools.explode, extend$1 = Tools.extend;
  15542. const basePurifyConfig = {
  15543. IN_PLACE: true,
  15544. ALLOW_UNKNOWN_PROTOCOLS: true,
  15545. ALLOWED_TAGS: [
  15546. '#comment',
  15547. '#cdata-section',
  15548. 'body'
  15549. ],
  15550. ALLOWED_ATTR: []
  15551. };
  15552. const filteredUrlAttrs = Tools.makeMap('src,href,data,background,action,formaction,poster,xlink:href');
  15553. const internalElementAttr = 'data-mce-type';
  15554. const getPurifyConfig = (settings, mimeType) => {
  15555. const config = { ...basePurifyConfig };
  15556. config.PARSER_MEDIA_TYPE = mimeType;
  15557. if (settings.allow_script_urls) {
  15558. config.ALLOWED_URI_REGEXP = /.*/;
  15559. } else if (settings.allow_html_data_urls) {
  15560. config.ALLOWED_URI_REGEXP = /^(?!(\w+script|mhtml):)/i;
  15561. }
  15562. return config;
  15563. };
  15564. const setupPurify = (settings, schema) => {
  15565. const purify$1 = purify();
  15566. const validate = settings.validate;
  15567. let uid = 0;
  15568. purify$1.addHook('uponSanitizeElement', (ele, evt) => {
  15569. var _a, _b;
  15570. if (ele.nodeType === COMMENT && !settings.allow_conditional_comments && /^\[if/i.test(ele.nodeValue)) {
  15571. ele.nodeValue = ' ' + ele.nodeValue;
  15572. }
  15573. const tagName = evt.tagName;
  15574. if (ele.nodeType !== ELEMENT || tagName === 'body') {
  15575. return;
  15576. }
  15577. const element = SugarElement.fromDom(ele);
  15578. const isInternalElement = has$1(element, internalElementAttr);
  15579. const bogus = get$9(element, 'data-mce-bogus');
  15580. if (!isInternalElement && isString(bogus)) {
  15581. if (bogus === 'all') {
  15582. remove$5(element);
  15583. } else {
  15584. unwrap(element);
  15585. }
  15586. return;
  15587. }
  15588. const rule = schema.getElementRule(tagName.toLowerCase());
  15589. if (validate && !rule) {
  15590. unwrap(element);
  15591. return;
  15592. } else {
  15593. evt.allowedTags[tagName] = true;
  15594. }
  15595. if (validate && !isInternalElement) {
  15596. each$g((_a = rule.attributesForced) !== null && _a !== void 0 ? _a : [], attr => {
  15597. set$2(element, attr.name, attr.value === '{$uid}' ? `mce_${ uid++ }` : attr.value);
  15598. });
  15599. each$g((_b = rule.attributesDefault) !== null && _b !== void 0 ? _b : [], attr => {
  15600. if (!has$1(element, attr.name)) {
  15601. set$2(element, attr.name, attr.value === '{$uid}' ? `mce_${ uid++ }` : attr.value);
  15602. }
  15603. });
  15604. if (rule.attributesRequired && !exists(rule.attributesRequired, attr => has$1(element, attr))) {
  15605. unwrap(element);
  15606. return;
  15607. }
  15608. if (rule.removeEmptyAttrs && hasNone(element)) {
  15609. unwrap(element);
  15610. return;
  15611. }
  15612. if (rule.outputName && rule.outputName !== tagName.toLowerCase()) {
  15613. mutate(element, rule.outputName);
  15614. }
  15615. }
  15616. });
  15617. purify$1.addHook('uponSanitizeAttribute', (ele, evt) => {
  15618. const tagName = ele.tagName.toLowerCase();
  15619. const {attrName, attrValue} = evt;
  15620. evt.keepAttr = !validate || schema.isValid(tagName, attrName) || startsWith(attrName, 'data-') || startsWith(attrName, 'aria-');
  15621. if (attrName in filteredUrlAttrs && isInvalidUri(settings, attrValue, tagName)) {
  15622. evt.keepAttr = false;
  15623. }
  15624. if (evt.keepAttr) {
  15625. evt.allowedAttributes[attrName] = true;
  15626. if (attrName in schema.getBoolAttrs()) {
  15627. evt.attrValue = attrName;
  15628. }
  15629. if (settings.allow_svg_data_urls && startsWith(attrValue, 'data:image/svg+xml')) {
  15630. evt.forceKeepAttr = true;
  15631. }
  15632. } else if (ele.hasAttribute(internalElementAttr) && (attrName === 'id' || attrName === 'class' || attrName === 'style')) {
  15633. evt.forceKeepAttr = true;
  15634. }
  15635. });
  15636. return purify$1;
  15637. };
  15638. const transferChildren = (parent, nativeParent, specialElements) => {
  15639. const parentName = parent.name;
  15640. const isSpecial = parentName in specialElements && parentName !== 'title' && parentName !== 'textarea';
  15641. const childNodes = nativeParent.childNodes;
  15642. for (let ni = 0, nl = childNodes.length; ni < nl; ni++) {
  15643. const nativeChild = childNodes[ni];
  15644. const child = new AstNode(nativeChild.nodeName.toLowerCase(), nativeChild.nodeType);
  15645. if (isElement$6(nativeChild)) {
  15646. const attributes = nativeChild.attributes;
  15647. for (let ai = 0, al = attributes.length; ai < al; ai++) {
  15648. const attr = attributes[ai];
  15649. child.attr(attr.name, attr.value);
  15650. }
  15651. } else if (isText$8(nativeChild)) {
  15652. child.value = nativeChild.data;
  15653. if (isSpecial) {
  15654. child.raw = true;
  15655. }
  15656. } else if (isComment(nativeChild) || isCData(nativeChild) || isPi(nativeChild)) {
  15657. child.value = nativeChild.data;
  15658. }
  15659. transferChildren(child, nativeChild, specialElements);
  15660. parent.append(child);
  15661. }
  15662. };
  15663. const walkTree = (root, preprocessors, postprocessors) => {
  15664. const traverseOrder = [];
  15665. for (let node = root, lastNode = node; isNonNullable(node); lastNode = node, node = node.walk()) {
  15666. each$g(preprocessors, preprocess => preprocess(node));
  15667. if (isNullable(node.parent) && node !== root) {
  15668. node = lastNode;
  15669. } else {
  15670. traverseOrder.push(node);
  15671. }
  15672. }
  15673. for (let i = traverseOrder.length - 1; i >= 0; i--) {
  15674. const node = traverseOrder[i];
  15675. each$g(postprocessors, postprocess => postprocess(node));
  15676. }
  15677. };
  15678. const whitespaceCleaner = (root, schema, settings, args) => {
  15679. const validate = settings.validate;
  15680. const nonEmptyElements = schema.getNonEmptyElements();
  15681. const whitespaceElements = schema.getWhitespaceElements();
  15682. const blockElements = extend$1(makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  15683. const textRootBlockElements = getTextRootBlockElements(schema);
  15684. const allWhiteSpaceRegExp = /[ \t\r\n]+/g;
  15685. const startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  15686. const endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  15687. const hasWhitespaceParent = node => {
  15688. node = node.parent;
  15689. while (isNonNullable(node)) {
  15690. if (node.name in whitespaceElements) {
  15691. return true;
  15692. } else {
  15693. node = node.parent;
  15694. }
  15695. }
  15696. return false;
  15697. };
  15698. const isTextRootBlockEmpty = node => {
  15699. let tempNode = node;
  15700. while (isNonNullable(tempNode)) {
  15701. if (tempNode.name in textRootBlockElements) {
  15702. return isEmpty(schema, nonEmptyElements, whitespaceElements, tempNode);
  15703. } else {
  15704. tempNode = tempNode.parent;
  15705. }
  15706. }
  15707. return false;
  15708. };
  15709. const isAtEdgeOfBlock = (node, start) => {
  15710. const neighbour = start ? node.prev : node.next;
  15711. if (isNonNullable(neighbour)) {
  15712. return false;
  15713. }
  15714. return node.parent.name in blockElements && (node.parent !== root || args.isRootContent);
  15715. };
  15716. const preprocess = node => {
  15717. if (node.type === 3) {
  15718. if (!hasWhitespaceParent(node)) {
  15719. let text = node.value;
  15720. text = text.replace(allWhiteSpaceRegExp, ' ');
  15721. if (isLineBreakNode(node.prev, blockElements) || isAtEdgeOfBlock(node, true)) {
  15722. text = text.replace(startWhiteSpaceRegExp, '');
  15723. }
  15724. if (text.length === 0) {
  15725. node.remove();
  15726. } else {
  15727. node.value = text;
  15728. }
  15729. }
  15730. }
  15731. };
  15732. const postprocess = node => {
  15733. var _a;
  15734. if (node.type === 1) {
  15735. const elementRule = schema.getElementRule(node.name);
  15736. if (validate && elementRule) {
  15737. const isNodeEmpty = isEmpty(schema, nonEmptyElements, whitespaceElements, node);
  15738. if (elementRule.paddInEmptyBlock && isNodeEmpty && isTextRootBlockEmpty(node)) {
  15739. paddEmptyNode(settings, args, blockElements, node);
  15740. } else if (elementRule.removeEmpty && isNodeEmpty) {
  15741. if (blockElements[node.name]) {
  15742. node.remove();
  15743. } else {
  15744. node.unwrap();
  15745. }
  15746. } else if (elementRule.paddEmpty && (isNodeEmpty || isPaddedWithNbsp(node))) {
  15747. paddEmptyNode(settings, args, blockElements, node);
  15748. }
  15749. }
  15750. } else if (node.type === 3) {
  15751. if (!hasWhitespaceParent(node)) {
  15752. let text = node.value;
  15753. if (blockElements[(_a = node.next) === null || _a === void 0 ? void 0 : _a.name] || isAtEdgeOfBlock(node, false)) {
  15754. text = text.replace(endWhiteSpaceRegExp, '');
  15755. }
  15756. if (text.length === 0) {
  15757. node.remove();
  15758. } else {
  15759. node.value = text;
  15760. }
  15761. }
  15762. }
  15763. };
  15764. return [
  15765. preprocess,
  15766. postprocess
  15767. ];
  15768. };
  15769. const getRootBlockName = (settings, args) => {
  15770. var _a;
  15771. const name = (_a = args.forced_root_block) !== null && _a !== void 0 ? _a : settings.forced_root_block;
  15772. if (name === false) {
  15773. return '';
  15774. } else if (name === true) {
  15775. return 'p';
  15776. } else {
  15777. return name;
  15778. }
  15779. };
  15780. const DomParser = (settings = {}, schema = Schema()) => {
  15781. const nodeFilters = {};
  15782. const attributeFilters = [];
  15783. const defaultedSettings = {
  15784. validate: true,
  15785. root_name: 'body',
  15786. ...settings
  15787. };
  15788. const parser = new DOMParser();
  15789. const purify = setupPurify(defaultedSettings, schema);
  15790. const parseAndSanitizeWithContext = (html, rootName, format = 'html') => {
  15791. const mimeType = format === 'xhtml' ? 'application/xhtml+xml' : 'text/html';
  15792. const isSpecialRoot = has$2(schema.getSpecialElements(), rootName.toLowerCase());
  15793. const content = isSpecialRoot ? `<${ rootName }>${ html }</${ rootName }>` : html;
  15794. const wrappedHtml = format === 'xhtml' ? `<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>${ content }</body></html>` : `<body>${ content }</body>`;
  15795. const body = parser.parseFromString(wrappedHtml, mimeType).body;
  15796. purify.sanitize(body, getPurifyConfig(defaultedSettings, mimeType));
  15797. purify.removed = [];
  15798. return isSpecialRoot ? body.firstChild : body;
  15799. };
  15800. const addNodeFilter = (name, callback) => {
  15801. each$4(explode$1(name), name => {
  15802. let list = nodeFilters[name];
  15803. if (!list) {
  15804. nodeFilters[name] = list = [];
  15805. }
  15806. list.push(callback);
  15807. });
  15808. };
  15809. const getNodeFilters = () => {
  15810. const out = [];
  15811. for (const name in nodeFilters) {
  15812. if (has$2(nodeFilters, name)) {
  15813. out.push({
  15814. name,
  15815. callbacks: nodeFilters[name]
  15816. });
  15817. }
  15818. }
  15819. return out;
  15820. };
  15821. const addAttributeFilter = (name, callback) => {
  15822. each$4(explode$1(name), name => {
  15823. let i;
  15824. for (i = 0; i < attributeFilters.length; i++) {
  15825. if (attributeFilters[i].name === name) {
  15826. attributeFilters[i].callbacks.push(callback);
  15827. return;
  15828. }
  15829. }
  15830. attributeFilters.push({
  15831. name,
  15832. callbacks: [callback]
  15833. });
  15834. });
  15835. };
  15836. const getAttributeFilters = () => [].concat(attributeFilters);
  15837. const findInvalidChildren = (node, invalidChildren) => {
  15838. const parent = node.parent;
  15839. if (parent && schema.children[node.name] && !schema.isValidChild(parent.name, node.name)) {
  15840. invalidChildren.push(node);
  15841. }
  15842. };
  15843. const addRootBlocks = (rootNode, rootBlockName) => {
  15844. const blockElements = extend$1(makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  15845. const startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  15846. const endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  15847. let node = rootNode.firstChild, rootBlockNode = null;
  15848. const trim = rootBlock => {
  15849. if (rootBlock) {
  15850. node = rootBlock.firstChild;
  15851. if (node && node.type === 3) {
  15852. node.value = node.value.replace(startWhiteSpaceRegExp, '');
  15853. }
  15854. node = rootBlock.lastChild;
  15855. if (node && node.type === 3) {
  15856. node.value = node.value.replace(endWhiteSpaceRegExp, '');
  15857. }
  15858. }
  15859. };
  15860. if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
  15861. return;
  15862. }
  15863. while (node) {
  15864. const next = node.next;
  15865. if (node.type === 3 || node.type === 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr(internalElementAttr)) {
  15866. if (!rootBlockNode) {
  15867. rootBlockNode = new AstNode(rootBlockName, 1);
  15868. rootBlockNode.attr(defaultedSettings.forced_root_block_attrs);
  15869. rootNode.insert(rootBlockNode, node);
  15870. rootBlockNode.append(node);
  15871. } else {
  15872. rootBlockNode.append(node);
  15873. }
  15874. } else {
  15875. trim(rootBlockNode);
  15876. rootBlockNode = null;
  15877. }
  15878. node = next;
  15879. }
  15880. trim(rootBlockNode);
  15881. };
  15882. const parse = (html, args = {}) => {
  15883. var _a;
  15884. const validate = defaultedSettings.validate;
  15885. const rootName = (_a = args.context) !== null && _a !== void 0 ? _a : defaultedSettings.root_name;
  15886. const element = parseAndSanitizeWithContext(html, rootName, args.format);
  15887. const rootNode = new AstNode(rootName, 11);
  15888. transferChildren(rootNode, element, schema.getSpecialElements());
  15889. const [whitespacePre, whitespacePost] = whitespaceCleaner(rootNode, schema, defaultedSettings, args);
  15890. const invalidChildren = [];
  15891. const invalidFinder = validate ? node => findInvalidChildren(node, invalidChildren) : noop;
  15892. const nodeFilters = getNodeFilters();
  15893. const matches = {
  15894. nodes: {},
  15895. attributes: {}
  15896. };
  15897. const matchFinder = node => matchNode$1(nodeFilters, attributeFilters, node, matches);
  15898. walkTree(rootNode, [
  15899. whitespacePre,
  15900. matchFinder
  15901. ], [
  15902. whitespacePost,
  15903. invalidFinder
  15904. ]);
  15905. invalidChildren.reverse();
  15906. if (validate && invalidChildren.length > 0) {
  15907. if (args.context) {
  15908. const {
  15909. pass: topLevelChildren,
  15910. fail: otherChildren
  15911. } = partition$2(invalidChildren, child => child.parent === rootNode);
  15912. cleanInvalidNodes(otherChildren, schema, matchFinder);
  15913. args.invalid = topLevelChildren.length > 0;
  15914. } else {
  15915. cleanInvalidNodes(invalidChildren, schema, matchFinder);
  15916. }
  15917. }
  15918. const rootBlockName = getRootBlockName(defaultedSettings, args);
  15919. if (rootBlockName && (rootNode.name === 'body' || args.isRootContent)) {
  15920. addRootBlocks(rootNode, rootBlockName);
  15921. }
  15922. if (!args.invalid) {
  15923. runFilters(matches, args);
  15924. }
  15925. return rootNode;
  15926. };
  15927. const exports = {
  15928. schema,
  15929. addAttributeFilter,
  15930. getAttributeFilters,
  15931. addNodeFilter,
  15932. getNodeFilters,
  15933. parse
  15934. };
  15935. register$4(exports, defaultedSettings);
  15936. register$5(exports, defaultedSettings, schema);
  15937. return exports;
  15938. };
  15939. const serializeContent = content => isTreeNode(content) ? HtmlSerializer({ validate: false }).serialize(content) : content;
  15940. const withSerializedContent = (content, fireEvent) => {
  15941. const serializedContent = serializeContent(content);
  15942. const eventArgs = fireEvent(serializedContent);
  15943. if (eventArgs.isDefaultPrevented()) {
  15944. return eventArgs;
  15945. } else if (isTreeNode(content)) {
  15946. if (eventArgs.content !== serializedContent) {
  15947. const rootNode = DomParser({
  15948. validate: false,
  15949. forced_root_block: false
  15950. }).parse(eventArgs.content, { context: content.name });
  15951. return {
  15952. ...eventArgs,
  15953. content: rootNode
  15954. };
  15955. } else {
  15956. return {
  15957. ...eventArgs,
  15958. content
  15959. };
  15960. }
  15961. } else {
  15962. return eventArgs;
  15963. }
  15964. };
  15965. const preProcessGetContent = (editor, args) => {
  15966. if (args.no_events) {
  15967. return Result.value(args);
  15968. } else {
  15969. const eventArgs = fireBeforeGetContent(editor, args);
  15970. if (eventArgs.isDefaultPrevented()) {
  15971. return Result.error(fireGetContent(editor, {
  15972. content: '',
  15973. ...eventArgs
  15974. }).content);
  15975. } else {
  15976. return Result.value(eventArgs);
  15977. }
  15978. }
  15979. };
  15980. const postProcessGetContent = (editor, content, args) => {
  15981. if (args.no_events) {
  15982. return content;
  15983. } else {
  15984. const processedEventArgs = withSerializedContent(content, c => fireGetContent(editor, {
  15985. ...args,
  15986. content: c
  15987. }));
  15988. return processedEventArgs.content;
  15989. }
  15990. };
  15991. const preProcessSetContent = (editor, args) => {
  15992. if (args.no_events) {
  15993. return Result.value(args);
  15994. } else {
  15995. const processedEventArgs = withSerializedContent(args.content, content => fireBeforeSetContent(editor, {
  15996. ...args,
  15997. content
  15998. }));
  15999. if (processedEventArgs.isDefaultPrevented()) {
  16000. fireSetContent(editor, processedEventArgs);
  16001. return Result.error(undefined);
  16002. } else {
  16003. return Result.value(processedEventArgs);
  16004. }
  16005. }
  16006. };
  16007. const postProcessSetContent = (editor, content, args) => {
  16008. if (!args.no_events) {
  16009. fireSetContent(editor, {
  16010. ...args,
  16011. content
  16012. });
  16013. }
  16014. };
  16015. const tableModel = (element, width, rows) => ({
  16016. element,
  16017. width,
  16018. rows
  16019. });
  16020. const tableRow = (element, cells) => ({
  16021. element,
  16022. cells
  16023. });
  16024. const cellPosition = (x, y) => ({
  16025. x,
  16026. y
  16027. });
  16028. const getSpan = (td, key) => {
  16029. const value = parseInt(get$9(td, key), 10);
  16030. return isNaN(value) ? 1 : value;
  16031. };
  16032. const fillout = (table, x, y, tr, td) => {
  16033. const rowspan = getSpan(td, 'rowspan');
  16034. const colspan = getSpan(td, 'colspan');
  16035. const rows = table.rows;
  16036. for (let y2 = y; y2 < y + rowspan; y2++) {
  16037. if (!rows[y2]) {
  16038. rows[y2] = tableRow(deep$1(tr), []);
  16039. }
  16040. for (let x2 = x; x2 < x + colspan; x2++) {
  16041. const cells = rows[y2].cells;
  16042. cells[x2] = y2 === y && x2 === x ? td : shallow$1(td);
  16043. }
  16044. }
  16045. };
  16046. const cellExists = (table, x, y) => {
  16047. const rows = table.rows;
  16048. const cells = rows[y] ? rows[y].cells : [];
  16049. return !!cells[x];
  16050. };
  16051. const skipCellsX = (table, x, y) => {
  16052. while (cellExists(table, x, y)) {
  16053. x++;
  16054. }
  16055. return x;
  16056. };
  16057. const getWidth = rows => {
  16058. return foldl(rows, (acc, row) => {
  16059. return row.cells.length > acc ? row.cells.length : acc;
  16060. }, 0);
  16061. };
  16062. const findElementPos = (table, element) => {
  16063. const rows = table.rows;
  16064. for (let y = 0; y < rows.length; y++) {
  16065. const cells = rows[y].cells;
  16066. for (let x = 0; x < cells.length; x++) {
  16067. if (eq(cells[x], element)) {
  16068. return Optional.some(cellPosition(x, y));
  16069. }
  16070. }
  16071. }
  16072. return Optional.none();
  16073. };
  16074. const extractRows = (table, sx, sy, ex, ey) => {
  16075. const newRows = [];
  16076. const rows = table.rows;
  16077. for (let y = sy; y <= ey; y++) {
  16078. const cells = rows[y].cells;
  16079. const slice = sx < ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
  16080. newRows.push(tableRow(rows[y].element, slice));
  16081. }
  16082. return newRows;
  16083. };
  16084. const subTable = (table, startPos, endPos) => {
  16085. const sx = startPos.x, sy = startPos.y;
  16086. const ex = endPos.x, ey = endPos.y;
  16087. const newRows = sy < ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
  16088. return tableModel(table.element, getWidth(newRows), newRows);
  16089. };
  16090. const createDomTable = (table, rows) => {
  16091. const tableElement = shallow$1(table.element);
  16092. const tableBody = SugarElement.fromTag('tbody');
  16093. append(tableBody, rows);
  16094. append$1(tableElement, tableBody);
  16095. return tableElement;
  16096. };
  16097. const modelRowsToDomRows = table => {
  16098. return map$3(table.rows, row => {
  16099. const cells = map$3(row.cells, cell => {
  16100. const td = deep$1(cell);
  16101. remove$a(td, 'colspan');
  16102. remove$a(td, 'rowspan');
  16103. return td;
  16104. });
  16105. const tr = shallow$1(row.element);
  16106. append(tr, cells);
  16107. return tr;
  16108. });
  16109. };
  16110. const fromDom = tableElm => {
  16111. const table = tableModel(shallow$1(tableElm), 0, []);
  16112. each$g(descendants(tableElm, 'tr'), (tr, y) => {
  16113. each$g(descendants(tr, 'td,th'), (td, x) => {
  16114. fillout(table, skipCellsX(table, x, y), y, tr, td);
  16115. });
  16116. });
  16117. return tableModel(table.element, getWidth(table.rows), table.rows);
  16118. };
  16119. const toDom = table => {
  16120. return createDomTable(table, modelRowsToDomRows(table));
  16121. };
  16122. const subsection = (table, startElement, endElement) => {
  16123. return findElementPos(table, startElement).bind(startPos => {
  16124. return findElementPos(table, endElement).map(endPos => {
  16125. return subTable(table, startPos, endPos);
  16126. });
  16127. });
  16128. };
  16129. const findParentListContainer = parents => find$2(parents, elm => name(elm) === 'ul' || name(elm) === 'ol');
  16130. const getFullySelectedListWrappers = (parents, rng) => find$2(parents, elm => name(elm) === 'li' && hasAllContentsSelected(elm, rng)).fold(constant([]), _li => findParentListContainer(parents).map(listCont => {
  16131. const listElm = SugarElement.fromTag(name(listCont));
  16132. const listStyles = filter$5(getAllRaw(listCont), (_style, name) => startsWith(name, 'list-style'));
  16133. setAll(listElm, listStyles);
  16134. return [
  16135. SugarElement.fromTag('li'),
  16136. listElm
  16137. ];
  16138. }).getOr([]));
  16139. const wrap = (innerElm, elms) => {
  16140. const wrapped = foldl(elms, (acc, elm) => {
  16141. append$1(elm, acc);
  16142. return elm;
  16143. }, innerElm);
  16144. return elms.length > 0 ? fromElements([wrapped]) : wrapped;
  16145. };
  16146. const directListWrappers = commonAnchorContainer => {
  16147. if (isListItem(commonAnchorContainer)) {
  16148. return parent(commonAnchorContainer).filter(isList).fold(constant([]), listElm => [
  16149. commonAnchorContainer,
  16150. listElm
  16151. ]);
  16152. } else {
  16153. return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
  16154. }
  16155. };
  16156. const getWrapElements = (rootNode, rng) => {
  16157. const commonAnchorContainer = SugarElement.fromDom(rng.commonAncestorContainer);
  16158. const parents = parentsAndSelf(commonAnchorContainer, rootNode);
  16159. const wrapElements = filter$6(parents, elm => isInline$1(elm) || isHeading(elm));
  16160. const listWrappers = getFullySelectedListWrappers(parents, rng);
  16161. const allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
  16162. return map$3(allWrappers, shallow$1);
  16163. };
  16164. const emptyFragment = () => fromElements([]);
  16165. const getFragmentFromRange = (rootNode, rng) => wrap(SugarElement.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
  16166. const getParentTable = (rootElm, cell) => ancestor$2(cell, 'table', curry(eq, rootElm));
  16167. const getTableFragment = (rootNode, selectedTableCells) => getParentTable(rootNode, selectedTableCells[0]).bind(tableElm => {
  16168. const firstCell = selectedTableCells[0];
  16169. const lastCell = selectedTableCells[selectedTableCells.length - 1];
  16170. const fullTableModel = fromDom(tableElm);
  16171. return subsection(fullTableModel, firstCell, lastCell).map(sectionedTableModel => fromElements([toDom(sectionedTableModel)]));
  16172. }).getOrThunk(emptyFragment);
  16173. const getSelectionFragment = (rootNode, ranges) => ranges.length > 0 && ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
  16174. const read$3 = (rootNode, ranges) => {
  16175. const selectedCells = getCellsFromElementOrRanges(ranges, rootNode);
  16176. return selectedCells.length > 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
  16177. };
  16178. const isCollapsibleWhitespace = (text, index) => index >= 0 && index < text.length && isWhiteSpace(text.charAt(index));
  16179. const getInnerText = bin => {
  16180. return trim$1(bin.innerText);
  16181. };
  16182. const getContextNodeName = parentBlockOpt => parentBlockOpt.map(block => block.nodeName).getOr('div').toLowerCase();
  16183. const getTextContent = editor => Optional.from(editor.selection.getRng()).map(rng => {
  16184. const parentBlockOpt = Optional.from(editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock));
  16185. const body = editor.getBody();
  16186. const contextNodeName = getContextNodeName(parentBlockOpt);
  16187. const bin = editor.dom.add(body, contextNodeName, {
  16188. 'data-mce-bogus': 'all',
  16189. 'style': 'overflow: hidden; opacity: 0;'
  16190. }, rng.cloneContents());
  16191. const text = getInnerText(bin);
  16192. const nonRenderedText = trim$1(bin.textContent);
  16193. editor.dom.remove(bin);
  16194. if (isCollapsibleWhitespace(nonRenderedText, 0) || isCollapsibleWhitespace(nonRenderedText, nonRenderedText.length - 1)) {
  16195. const parentBlock = parentBlockOpt.getOr(body);
  16196. const parentBlockText = getInnerText(parentBlock);
  16197. const textIndex = parentBlockText.indexOf(text);
  16198. if (textIndex === -1) {
  16199. return text;
  16200. } else {
  16201. const hasProceedingSpace = isCollapsibleWhitespace(parentBlockText, textIndex - 1);
  16202. const hasTrailingSpace = isCollapsibleWhitespace(parentBlockText, textIndex + text.length);
  16203. return (hasProceedingSpace ? ' ' : '') + text + (hasTrailingSpace ? ' ' : '');
  16204. }
  16205. } else {
  16206. return text;
  16207. }
  16208. }).getOr('');
  16209. const getSerializedContent = (editor, args) => {
  16210. const rng = editor.selection.getRng(), tmpElm = editor.dom.create('body');
  16211. const sel = editor.selection.getSel();
  16212. const ranges = processRanges(editor, getRanges$1(sel));
  16213. const fragment = args.contextual ? read$3(SugarElement.fromDom(editor.getBody()), ranges).dom : rng.cloneContents();
  16214. if (fragment) {
  16215. tmpElm.appendChild(fragment);
  16216. }
  16217. return editor.selection.serializer.serialize(tmpElm, args);
  16218. };
  16219. const extractSelectedContent = (editor, args) => {
  16220. if (args.format === 'text') {
  16221. return getTextContent(editor);
  16222. } else {
  16223. const content = getSerializedContent(editor, args);
  16224. if (args.format === 'tree') {
  16225. return content;
  16226. } else {
  16227. return editor.selection.isCollapsed() ? '' : content;
  16228. }
  16229. }
  16230. };
  16231. const setupArgs$3 = (args, format) => ({
  16232. ...args,
  16233. format,
  16234. get: true,
  16235. selection: true,
  16236. getInner: true
  16237. });
  16238. const getSelectedContentInternal = (editor, format, args = {}) => {
  16239. const defaultedArgs = setupArgs$3(args, format);
  16240. return preProcessGetContent(editor, defaultedArgs).fold(identity, updatedArgs => {
  16241. const content = extractSelectedContent(editor, updatedArgs);
  16242. return postProcessGetContent(editor, content, updatedArgs);
  16243. });
  16244. };
  16245. const KEEP = 0, INSERT = 1, DELETE = 2;
  16246. const diff = (left, right) => {
  16247. const size = left.length + right.length + 2;
  16248. const vDown = new Array(size);
  16249. const vUp = new Array(size);
  16250. const snake = (start, end, diag) => {
  16251. return {
  16252. start,
  16253. end,
  16254. diag
  16255. };
  16256. };
  16257. const buildScript = (start1, end1, start2, end2, script) => {
  16258. const middle = getMiddleSnake(start1, end1, start2, end2);
  16259. if (middle === null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) {
  16260. let i = start1;
  16261. let j = start2;
  16262. while (i < end1 || j < end2) {
  16263. if (i < end1 && j < end2 && left[i] === right[j]) {
  16264. script.push([
  16265. KEEP,
  16266. left[i]
  16267. ]);
  16268. ++i;
  16269. ++j;
  16270. } else {
  16271. if (end1 - start1 > end2 - start2) {
  16272. script.push([
  16273. DELETE,
  16274. left[i]
  16275. ]);
  16276. ++i;
  16277. } else {
  16278. script.push([
  16279. INSERT,
  16280. right[j]
  16281. ]);
  16282. ++j;
  16283. }
  16284. }
  16285. }
  16286. } else {
  16287. buildScript(start1, middle.start, start2, middle.start - middle.diag, script);
  16288. for (let i2 = middle.start; i2 < middle.end; ++i2) {
  16289. script.push([
  16290. KEEP,
  16291. left[i2]
  16292. ]);
  16293. }
  16294. buildScript(middle.end, end1, middle.end - middle.diag, end2, script);
  16295. }
  16296. };
  16297. const buildSnake = (start, diag, end1, end2) => {
  16298. let end = start;
  16299. while (end - diag < end2 && end < end1 && left[end] === right[end - diag]) {
  16300. ++end;
  16301. }
  16302. return snake(start, end, diag);
  16303. };
  16304. const getMiddleSnake = (start1, end1, start2, end2) => {
  16305. const m = end1 - start1;
  16306. const n = end2 - start2;
  16307. if (m === 0 || n === 0) {
  16308. return null;
  16309. }
  16310. const delta = m - n;
  16311. const sum = n + m;
  16312. const offset = (sum % 2 === 0 ? sum : sum + 1) / 2;
  16313. vDown[1 + offset] = start1;
  16314. vUp[1 + offset] = end1 + 1;
  16315. let d, k, i, x, y;
  16316. for (d = 0; d <= offset; ++d) {
  16317. for (k = -d; k <= d; k += 2) {
  16318. i = k + offset;
  16319. if (k === -d || k !== d && vDown[i - 1] < vDown[i + 1]) {
  16320. vDown[i] = vDown[i + 1];
  16321. } else {
  16322. vDown[i] = vDown[i - 1] + 1;
  16323. }
  16324. x = vDown[i];
  16325. y = x - start1 + start2 - k;
  16326. while (x < end1 && y < end2 && left[x] === right[y]) {
  16327. vDown[i] = ++x;
  16328. ++y;
  16329. }
  16330. if (delta % 2 !== 0 && delta - d <= k && k <= delta + d) {
  16331. if (vUp[i - delta] <= vDown[i]) {
  16332. return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2);
  16333. }
  16334. }
  16335. }
  16336. for (k = delta - d; k <= delta + d; k += 2) {
  16337. i = k + offset - delta;
  16338. if (k === delta - d || k !== delta + d && vUp[i + 1] <= vUp[i - 1]) {
  16339. vUp[i] = vUp[i + 1] - 1;
  16340. } else {
  16341. vUp[i] = vUp[i - 1];
  16342. }
  16343. x = vUp[i] - 1;
  16344. y = x - start1 + start2 - k;
  16345. while (x >= start1 && y >= start2 && left[x] === right[y]) {
  16346. vUp[i] = x--;
  16347. y--;
  16348. }
  16349. if (delta % 2 === 0 && -d <= k && k <= d) {
  16350. if (vUp[i] <= vDown[i + delta]) {
  16351. return buildSnake(vUp[i], k + start1 - start2, end1, end2);
  16352. }
  16353. }
  16354. }
  16355. }
  16356. };
  16357. const script = [];
  16358. buildScript(0, left.length, 0, right.length, script);
  16359. return script;
  16360. };
  16361. const getOuterHtml = elm => {
  16362. if (isElement$6(elm)) {
  16363. return elm.outerHTML;
  16364. } else if (isText$8(elm)) {
  16365. return Entities.encodeRaw(elm.data, false);
  16366. } else if (isComment(elm)) {
  16367. return '<!--' + elm.data + '-->';
  16368. }
  16369. return '';
  16370. };
  16371. const createFragment = html => {
  16372. let node;
  16373. const container = document.createElement('div');
  16374. const frag = document.createDocumentFragment();
  16375. if (html) {
  16376. container.innerHTML = html;
  16377. }
  16378. while (node = container.firstChild) {
  16379. frag.appendChild(node);
  16380. }
  16381. return frag;
  16382. };
  16383. const insertAt = (elm, html, index) => {
  16384. const fragment = createFragment(html);
  16385. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  16386. const target = elm.childNodes[index];
  16387. target.parentNode.insertBefore(fragment, target);
  16388. } else {
  16389. elm.appendChild(fragment);
  16390. }
  16391. };
  16392. const removeAt = (elm, index) => {
  16393. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  16394. const target = elm.childNodes[index];
  16395. target.parentNode.removeChild(target);
  16396. }
  16397. };
  16398. const applyDiff = (diff, elm) => {
  16399. let index = 0;
  16400. each$g(diff, action => {
  16401. if (action[0] === KEEP) {
  16402. index++;
  16403. } else if (action[0] === INSERT) {
  16404. insertAt(elm, action[1], index);
  16405. index++;
  16406. } else if (action[0] === DELETE) {
  16407. removeAt(elm, index);
  16408. }
  16409. });
  16410. };
  16411. const read$2 = elm => {
  16412. return filter$6(map$3(from(elm.childNodes), getOuterHtml), item => {
  16413. return item.length > 0;
  16414. });
  16415. };
  16416. const write = (fragments, elm) => {
  16417. const currentFragments = map$3(from(elm.childNodes), getOuterHtml);
  16418. applyDiff(diff(currentFragments, fragments), elm);
  16419. return elm;
  16420. };
  16421. const lazyTempDocument = cached(() => document.implementation.createHTMLDocument('undo'));
  16422. const hasIframes = html => {
  16423. return html.indexOf('</iframe>') !== -1;
  16424. };
  16425. const createFragmentedLevel = fragments => {
  16426. return {
  16427. type: 'fragmented',
  16428. fragments,
  16429. content: '',
  16430. bookmark: null,
  16431. beforeBookmark: null
  16432. };
  16433. };
  16434. const createCompleteLevel = content => {
  16435. return {
  16436. type: 'complete',
  16437. fragments: null,
  16438. content,
  16439. bookmark: null,
  16440. beforeBookmark: null
  16441. };
  16442. };
  16443. const createFromEditor = editor => {
  16444. const fragments = read$2(editor.getBody());
  16445. const trimmedFragments = bind$3(fragments, html => {
  16446. const trimmed = trimInternal(editor.serializer, html);
  16447. return trimmed.length > 0 ? [trimmed] : [];
  16448. });
  16449. const content = trimmedFragments.join('');
  16450. return hasIframes(content) ? createFragmentedLevel(trimmedFragments) : createCompleteLevel(content);
  16451. };
  16452. const applyToEditor = (editor, level, before) => {
  16453. const bookmark = before ? level.beforeBookmark : level.bookmark;
  16454. if (level.type === 'fragmented') {
  16455. write(level.fragments, editor.getBody());
  16456. } else {
  16457. editor.setContent(level.content, {
  16458. format: 'raw',
  16459. no_selection: isNonNullable(bookmark) && isPathBookmark(bookmark) ? !bookmark.isFakeCaret : true
  16460. });
  16461. }
  16462. editor.selection.moveToBookmark(bookmark);
  16463. };
  16464. const getLevelContent = level => {
  16465. return level.type === 'fragmented' ? level.fragments.join('') : level.content;
  16466. };
  16467. const getCleanLevelContent = level => {
  16468. const elm = SugarElement.fromTag('body', lazyTempDocument());
  16469. set(elm, getLevelContent(level));
  16470. each$g(descendants(elm, '*[data-mce-bogus]'), unwrap);
  16471. return get$6(elm);
  16472. };
  16473. const hasEqualContent = (level1, level2) => getLevelContent(level1) === getLevelContent(level2);
  16474. const hasEqualCleanedContent = (level1, level2) => getCleanLevelContent(level1) === getCleanLevelContent(level2);
  16475. const isEq$1 = (level1, level2) => {
  16476. if (!level1 || !level2) {
  16477. return false;
  16478. } else if (hasEqualContent(level1, level2)) {
  16479. return true;
  16480. } else {
  16481. return hasEqualCleanedContent(level1, level2);
  16482. }
  16483. };
  16484. const isUnlocked = locks => locks.get() === 0;
  16485. const setTyping = (undoManager, typing, locks) => {
  16486. if (isUnlocked(locks)) {
  16487. undoManager.typing = typing;
  16488. }
  16489. };
  16490. const endTyping = (undoManager, locks) => {
  16491. if (undoManager.typing) {
  16492. setTyping(undoManager, false, locks);
  16493. undoManager.add();
  16494. }
  16495. };
  16496. const endTypingLevelIgnoreLocks = undoManager => {
  16497. if (undoManager.typing) {
  16498. undoManager.typing = false;
  16499. undoManager.add();
  16500. }
  16501. };
  16502. const beforeChange$1 = (editor, locks, beforeBookmark) => {
  16503. if (isUnlocked(locks)) {
  16504. beforeBookmark.set(getUndoBookmark(editor.selection));
  16505. }
  16506. };
  16507. const addUndoLevel$1 = (editor, undoManager, index, locks, beforeBookmark, level, event) => {
  16508. const currentLevel = createFromEditor(editor);
  16509. level = level || {};
  16510. level = Tools.extend(level, currentLevel);
  16511. if (isUnlocked(locks) === false || editor.removed) {
  16512. return null;
  16513. }
  16514. const lastLevel = undoManager.data[index.get()];
  16515. if (editor.dispatch('BeforeAddUndo', {
  16516. level,
  16517. lastLevel,
  16518. originalEvent: event
  16519. }).isDefaultPrevented()) {
  16520. return null;
  16521. }
  16522. if (lastLevel && isEq$1(lastLevel, level)) {
  16523. return null;
  16524. }
  16525. if (undoManager.data[index.get()]) {
  16526. beforeBookmark.get().each(bm => {
  16527. undoManager.data[index.get()].beforeBookmark = bm;
  16528. });
  16529. }
  16530. const customUndoRedoLevels = getCustomUndoRedoLevels(editor);
  16531. if (customUndoRedoLevels) {
  16532. if (undoManager.data.length > customUndoRedoLevels) {
  16533. for (let i = 0; i < undoManager.data.length - 1; i++) {
  16534. undoManager.data[i] = undoManager.data[i + 1];
  16535. }
  16536. undoManager.data.length--;
  16537. index.set(undoManager.data.length);
  16538. }
  16539. }
  16540. level.bookmark = getUndoBookmark(editor.selection);
  16541. if (index.get() < undoManager.data.length - 1) {
  16542. undoManager.data.length = index.get() + 1;
  16543. }
  16544. undoManager.data.push(level);
  16545. index.set(undoManager.data.length - 1);
  16546. const args = {
  16547. level,
  16548. lastLevel,
  16549. originalEvent: event
  16550. };
  16551. if (index.get() > 0) {
  16552. editor.setDirty(true);
  16553. editor.dispatch('AddUndo', args);
  16554. editor.dispatch('change', args);
  16555. } else {
  16556. editor.dispatch('AddUndo', args);
  16557. }
  16558. return level;
  16559. };
  16560. const clear$1 = (editor, undoManager, index) => {
  16561. undoManager.data = [];
  16562. index.set(0);
  16563. undoManager.typing = false;
  16564. editor.dispatch('ClearUndos');
  16565. };
  16566. const extra$1 = (editor, undoManager, index, callback1, callback2) => {
  16567. if (undoManager.transact(callback1)) {
  16568. const bookmark = undoManager.data[index.get()].bookmark;
  16569. const lastLevel = undoManager.data[index.get() - 1];
  16570. applyToEditor(editor, lastLevel, true);
  16571. if (undoManager.transact(callback2)) {
  16572. undoManager.data[index.get() - 1].beforeBookmark = bookmark;
  16573. }
  16574. }
  16575. };
  16576. const redo$1 = (editor, index, data) => {
  16577. let level;
  16578. if (index.get() < data.length - 1) {
  16579. index.set(index.get() + 1);
  16580. level = data[index.get()];
  16581. applyToEditor(editor, level, false);
  16582. editor.setDirty(true);
  16583. editor.dispatch('Redo', { level });
  16584. }
  16585. return level;
  16586. };
  16587. const undo$1 = (editor, undoManager, locks, index) => {
  16588. let level;
  16589. if (undoManager.typing) {
  16590. undoManager.add();
  16591. undoManager.typing = false;
  16592. setTyping(undoManager, false, locks);
  16593. }
  16594. if (index.get() > 0) {
  16595. index.set(index.get() - 1);
  16596. level = undoManager.data[index.get()];
  16597. applyToEditor(editor, level, true);
  16598. editor.setDirty(true);
  16599. editor.dispatch('Undo', { level });
  16600. }
  16601. return level;
  16602. };
  16603. const reset$1 = undoManager => {
  16604. undoManager.clear();
  16605. undoManager.add();
  16606. };
  16607. const hasUndo$1 = (editor, undoManager, index) => index.get() > 0 || undoManager.typing && undoManager.data[0] && !isEq$1(createFromEditor(editor), undoManager.data[0]);
  16608. const hasRedo$1 = (undoManager, index) => index.get() < undoManager.data.length - 1 && !undoManager.typing;
  16609. const transact$1 = (undoManager, locks, callback) => {
  16610. endTyping(undoManager, locks);
  16611. undoManager.beforeChange();
  16612. undoManager.ignore(callback);
  16613. return undoManager.add();
  16614. };
  16615. const ignore$1 = (locks, callback) => {
  16616. try {
  16617. locks.set(locks.get() + 1);
  16618. callback();
  16619. } finally {
  16620. locks.set(locks.get() - 1);
  16621. }
  16622. };
  16623. const addVisualInternal = (editor, elm) => {
  16624. const dom = editor.dom;
  16625. const scope = isNonNullable(elm) ? elm : editor.getBody();
  16626. if (isUndefined(editor.hasVisual)) {
  16627. editor.hasVisual = isVisualAidsEnabled(editor);
  16628. }
  16629. each$g(dom.select('table,a', scope), matchedElm => {
  16630. switch (matchedElm.nodeName) {
  16631. case 'TABLE':
  16632. const cls = getVisualAidsTableClass(editor);
  16633. const value = dom.getAttrib(matchedElm, 'border');
  16634. if ((!value || value === '0') && editor.hasVisual) {
  16635. dom.addClass(matchedElm, cls);
  16636. } else {
  16637. dom.removeClass(matchedElm, cls);
  16638. }
  16639. break;
  16640. case 'A':
  16641. if (!dom.getAttrib(matchedElm, 'href')) {
  16642. const value = dom.getAttrib(matchedElm, 'name') || matchedElm.id;
  16643. const cls = getVisualAidsAnchorClass(editor);
  16644. if (value && editor.hasVisual) {
  16645. dom.addClass(matchedElm, cls);
  16646. } else {
  16647. dom.removeClass(matchedElm, cls);
  16648. }
  16649. }
  16650. break;
  16651. }
  16652. });
  16653. editor.dispatch('VisualAid', {
  16654. element: elm,
  16655. hasVisual: editor.hasVisual
  16656. });
  16657. };
  16658. const makePlainAdaptor = editor => ({
  16659. init: { bindEvents: noop },
  16660. undoManager: {
  16661. beforeChange: (locks, beforeBookmark) => beforeChange$1(editor, locks, beforeBookmark),
  16662. add: (undoManager, index, locks, beforeBookmark, level, event) => addUndoLevel$1(editor, undoManager, index, locks, beforeBookmark, level, event),
  16663. undo: (undoManager, locks, index) => undo$1(editor, undoManager, locks, index),
  16664. redo: (index, data) => redo$1(editor, index, data),
  16665. clear: (undoManager, index) => clear$1(editor, undoManager, index),
  16666. reset: undoManager => reset$1(undoManager),
  16667. hasUndo: (undoManager, index) => hasUndo$1(editor, undoManager, index),
  16668. hasRedo: (undoManager, index) => hasRedo$1(undoManager, index),
  16669. transact: (undoManager, locks, callback) => transact$1(undoManager, locks, callback),
  16670. ignore: (locks, callback) => ignore$1(locks, callback),
  16671. extra: (undoManager, index, callback1, callback2) => extra$1(editor, undoManager, index, callback1, callback2)
  16672. },
  16673. formatter: {
  16674. match: (name, vars, node, similar) => match$2(editor, name, vars, node, similar),
  16675. matchAll: (names, vars) => matchAll(editor, names, vars),
  16676. matchNode: (node, name, vars, similar) => matchNode(editor, node, name, vars, similar),
  16677. canApply: name => canApply(editor, name),
  16678. closest: names => closest$1(editor, names),
  16679. apply: (name, vars, node) => applyFormat$1(editor, name, vars, node),
  16680. remove: (name, vars, node, similar) => remove$2(editor, name, vars, node, similar),
  16681. toggle: (name, vars, node) => toggle(editor, name, vars, node),
  16682. formatChanged: (registeredFormatListeners, formats, callback, similar, vars) => formatChangedInternal(editor, registeredFormatListeners, formats, callback, similar, vars)
  16683. },
  16684. editor: {
  16685. getContent: args => getContentInternal(editor, args),
  16686. setContent: (content, args) => setContentInternal(editor, content, args),
  16687. insertContent: (value, details) => insertHtmlAtCaret(editor, value, details),
  16688. addVisual: elm => addVisualInternal(editor, elm)
  16689. },
  16690. selection: { getContent: (format, args) => getSelectedContentInternal(editor, format, args) },
  16691. autocompleter: {
  16692. addDecoration: range => create$8(editor, range),
  16693. removeDecoration: () => remove$3(editor, SugarElement.fromDom(editor.getBody()))
  16694. },
  16695. raw: { getModel: () => Optional.none() }
  16696. });
  16697. const makeRtcAdaptor = rtcEditor => {
  16698. const defaultVars = vars => isObject(vars) ? vars : {};
  16699. const {init, undoManager, formatter, editor, selection, autocompleter, raw} = rtcEditor;
  16700. return {
  16701. init: { bindEvents: init.bindEvents },
  16702. undoManager: {
  16703. beforeChange: undoManager.beforeChange,
  16704. add: undoManager.add,
  16705. undo: undoManager.undo,
  16706. redo: undoManager.redo,
  16707. clear: undoManager.clear,
  16708. reset: undoManager.reset,
  16709. hasUndo: undoManager.hasUndo,
  16710. hasRedo: undoManager.hasRedo,
  16711. transact: (_undoManager, _locks, fn) => undoManager.transact(fn),
  16712. ignore: (_locks, callback) => undoManager.ignore(callback),
  16713. extra: (_undoManager, _index, callback1, callback2) => undoManager.extra(callback1, callback2)
  16714. },
  16715. formatter: {
  16716. match: (name, vars, _node, similar) => formatter.match(name, defaultVars(vars), similar),
  16717. matchAll: formatter.matchAll,
  16718. matchNode: formatter.matchNode,
  16719. canApply: name => formatter.canApply(name),
  16720. closest: names => formatter.closest(names),
  16721. apply: (name, vars, _node) => formatter.apply(name, defaultVars(vars)),
  16722. remove: (name, vars, _node, _similar) => formatter.remove(name, defaultVars(vars)),
  16723. toggle: (name, vars, _node) => formatter.toggle(name, defaultVars(vars)),
  16724. formatChanged: (_rfl, formats, callback, similar, vars) => formatter.formatChanged(formats, callback, similar, vars)
  16725. },
  16726. editor: {
  16727. getContent: args => editor.getContent(args),
  16728. setContent: (content, args) => {
  16729. return {
  16730. content: editor.setContent(content, args),
  16731. html: ''
  16732. };
  16733. },
  16734. insertContent: (content, _details) => {
  16735. editor.insertContent(content);
  16736. return '';
  16737. },
  16738. addVisual: editor.addVisual
  16739. },
  16740. selection: { getContent: (_format, args) => selection.getContent(args) },
  16741. autocompleter: {
  16742. addDecoration: autocompleter.addDecoration,
  16743. removeDecoration: autocompleter.removeDecoration
  16744. },
  16745. raw: { getModel: () => Optional.some(raw.getRawModel()) }
  16746. };
  16747. };
  16748. const makeNoopAdaptor = () => {
  16749. const nul = constant(null);
  16750. const empty = constant('');
  16751. return {
  16752. init: { bindEvents: noop },
  16753. undoManager: {
  16754. beforeChange: noop,
  16755. add: nul,
  16756. undo: nul,
  16757. redo: nul,
  16758. clear: noop,
  16759. reset: noop,
  16760. hasUndo: never,
  16761. hasRedo: never,
  16762. transact: nul,
  16763. ignore: noop,
  16764. extra: noop
  16765. },
  16766. formatter: {
  16767. match: never,
  16768. matchAll: constant([]),
  16769. matchNode: constant(undefined),
  16770. canApply: never,
  16771. closest: empty,
  16772. apply: noop,
  16773. remove: noop,
  16774. toggle: noop,
  16775. formatChanged: constant({ unbind: noop })
  16776. },
  16777. editor: {
  16778. getContent: empty,
  16779. setContent: constant({
  16780. content: '',
  16781. html: ''
  16782. }),
  16783. insertContent: constant(''),
  16784. addVisual: noop
  16785. },
  16786. selection: { getContent: empty },
  16787. autocompleter: {
  16788. addDecoration: noop,
  16789. removeDecoration: noop
  16790. },
  16791. raw: { getModel: constant(Optional.none()) }
  16792. };
  16793. };
  16794. const isRtc = editor => has$2(editor.plugins, 'rtc');
  16795. const getRtcSetup = editor => get$a(editor.plugins, 'rtc').bind(rtcPlugin => Optional.from(rtcPlugin.setup));
  16796. const setup$s = editor => {
  16797. const editorCast = editor;
  16798. return getRtcSetup(editor).fold(() => {
  16799. editorCast.rtcInstance = makePlainAdaptor(editor);
  16800. return Optional.none();
  16801. }, setup => {
  16802. editorCast.rtcInstance = makeNoopAdaptor();
  16803. return Optional.some(() => setup().then(rtcEditor => {
  16804. editorCast.rtcInstance = makeRtcAdaptor(rtcEditor);
  16805. return rtcEditor.rtc.isRemote;
  16806. }));
  16807. });
  16808. };
  16809. const getRtcInstanceWithFallback = editor => editor.rtcInstance ? editor.rtcInstance : makePlainAdaptor(editor);
  16810. const getRtcInstanceWithError = editor => {
  16811. const rtcInstance = editor.rtcInstance;
  16812. if (!rtcInstance) {
  16813. throw new Error('Failed to get RTC instance not yet initialized.');
  16814. } else {
  16815. return rtcInstance;
  16816. }
  16817. };
  16818. const beforeChange = (editor, locks, beforeBookmark) => {
  16819. getRtcInstanceWithError(editor).undoManager.beforeChange(locks, beforeBookmark);
  16820. };
  16821. const addUndoLevel = (editor, undoManager, index, locks, beforeBookmark, level, event) => getRtcInstanceWithError(editor).undoManager.add(undoManager, index, locks, beforeBookmark, level, event);
  16822. const undo = (editor, undoManager, locks, index) => getRtcInstanceWithError(editor).undoManager.undo(undoManager, locks, index);
  16823. const redo = (editor, index, data) => getRtcInstanceWithError(editor).undoManager.redo(index, data);
  16824. const clear = (editor, undoManager, index) => {
  16825. getRtcInstanceWithError(editor).undoManager.clear(undoManager, index);
  16826. };
  16827. const reset = (editor, undoManager) => {
  16828. getRtcInstanceWithError(editor).undoManager.reset(undoManager);
  16829. };
  16830. const hasUndo = (editor, undoManager, index) => getRtcInstanceWithError(editor).undoManager.hasUndo(undoManager, index);
  16831. const hasRedo = (editor, undoManager, index) => getRtcInstanceWithError(editor).undoManager.hasRedo(undoManager, index);
  16832. const transact = (editor, undoManager, locks, callback) => getRtcInstanceWithError(editor).undoManager.transact(undoManager, locks, callback);
  16833. const ignore = (editor, locks, callback) => {
  16834. getRtcInstanceWithError(editor).undoManager.ignore(locks, callback);
  16835. };
  16836. const extra = (editor, undoManager, index, callback1, callback2) => {
  16837. getRtcInstanceWithError(editor).undoManager.extra(undoManager, index, callback1, callback2);
  16838. };
  16839. const matchFormat = (editor, name, vars, node, similar) => getRtcInstanceWithError(editor).formatter.match(name, vars, node, similar);
  16840. const matchAllFormats = (editor, names, vars) => getRtcInstanceWithError(editor).formatter.matchAll(names, vars);
  16841. const matchNodeFormat = (editor, node, name, vars, similar) => getRtcInstanceWithError(editor).formatter.matchNode(node, name, vars, similar);
  16842. const canApplyFormat = (editor, name) => getRtcInstanceWithError(editor).formatter.canApply(name);
  16843. const closestFormat = (editor, names) => getRtcInstanceWithError(editor).formatter.closest(names);
  16844. const applyFormat = (editor, name, vars, node) => {
  16845. getRtcInstanceWithError(editor).formatter.apply(name, vars, node);
  16846. };
  16847. const removeFormat = (editor, name, vars, node, similar) => {
  16848. getRtcInstanceWithError(editor).formatter.remove(name, vars, node, similar);
  16849. };
  16850. const toggleFormat = (editor, name, vars, node) => {
  16851. getRtcInstanceWithError(editor).formatter.toggle(name, vars, node);
  16852. };
  16853. const formatChanged = (editor, registeredFormatListeners, formats, callback, similar, vars) => getRtcInstanceWithError(editor).formatter.formatChanged(registeredFormatListeners, formats, callback, similar, vars);
  16854. const getContent$2 = (editor, args) => getRtcInstanceWithFallback(editor).editor.getContent(args);
  16855. const setContent$2 = (editor, content, args) => getRtcInstanceWithFallback(editor).editor.setContent(content, args);
  16856. const insertContent$1 = (editor, value, details) => getRtcInstanceWithFallback(editor).editor.insertContent(value, details);
  16857. const getSelectedContent = (editor, format, args) => getRtcInstanceWithError(editor).selection.getContent(format, args);
  16858. const addVisual$1 = (editor, elm) => getRtcInstanceWithError(editor).editor.addVisual(elm);
  16859. const bindEvents = editor => getRtcInstanceWithError(editor).init.bindEvents();
  16860. const addAutocompleterDecoration = (editor, range) => getRtcInstanceWithError(editor).autocompleter.addDecoration(range);
  16861. const removeAutocompleterDecoration = editor => getRtcInstanceWithError(editor).autocompleter.removeDecoration();
  16862. const getContent$1 = (editor, args = {}) => {
  16863. const format = args.format ? args.format : 'html';
  16864. return getSelectedContent(editor, format, args);
  16865. };
  16866. const removeEmpty = text => {
  16867. if (text.dom.length === 0) {
  16868. remove$5(text);
  16869. return Optional.none();
  16870. } else {
  16871. return Optional.some(text);
  16872. }
  16873. };
  16874. const walkPastBookmark = (node, start) => node.filter(elm => BookmarkManager.isBookmarkNode(elm.dom)).bind(start ? nextSibling : prevSibling);
  16875. const merge$1 = (outer, inner, rng, start) => {
  16876. const outerElm = outer.dom;
  16877. const innerElm = inner.dom;
  16878. const oldLength = start ? outerElm.length : innerElm.length;
  16879. if (start) {
  16880. mergeTextNodes(outerElm, innerElm, false, !start);
  16881. rng.setStart(innerElm, oldLength);
  16882. } else {
  16883. mergeTextNodes(innerElm, outerElm, false, !start);
  16884. rng.setEnd(innerElm, oldLength);
  16885. }
  16886. };
  16887. const normalizeTextIfRequired = (inner, start) => {
  16888. parent(inner).each(root => {
  16889. const text = inner.dom;
  16890. if (start && needsToBeNbspLeft(root, CaretPosition(text, 0))) {
  16891. normalizeWhitespaceAfter(text, 0);
  16892. } else if (!start && needsToBeNbspRight(root, CaretPosition(text, text.length))) {
  16893. normalizeWhitespaceBefore(text, text.length);
  16894. }
  16895. });
  16896. };
  16897. const mergeAndNormalizeText = (outerNode, innerNode, rng, start) => {
  16898. outerNode.bind(outer => {
  16899. const normalizer = start ? normalizeWhitespaceBefore : normalizeWhitespaceAfter;
  16900. normalizer(outer.dom, start ? outer.dom.length : 0);
  16901. return innerNode.filter(isText$9).map(inner => merge$1(outer, inner, rng, start));
  16902. }).orThunk(() => {
  16903. const innerTextNode = walkPastBookmark(innerNode, start).or(innerNode).filter(isText$9);
  16904. return innerTextNode.map(inner => normalizeTextIfRequired(inner, start));
  16905. });
  16906. };
  16907. const rngSetContent = (rng, fragment) => {
  16908. const firstChild = Optional.from(fragment.firstChild).map(SugarElement.fromDom);
  16909. const lastChild = Optional.from(fragment.lastChild).map(SugarElement.fromDom);
  16910. rng.deleteContents();
  16911. rng.insertNode(fragment);
  16912. const prevText = firstChild.bind(prevSibling).filter(isText$9).bind(removeEmpty);
  16913. const nextText = lastChild.bind(nextSibling).filter(isText$9).bind(removeEmpty);
  16914. mergeAndNormalizeText(prevText, firstChild, rng, true);
  16915. mergeAndNormalizeText(nextText, lastChild, rng, false);
  16916. rng.collapse(false);
  16917. };
  16918. const setupArgs$2 = (args, content) => ({
  16919. format: 'html',
  16920. ...args,
  16921. set: true,
  16922. selection: true,
  16923. content
  16924. });
  16925. const cleanContent = (editor, args) => {
  16926. if (args.format !== 'raw') {
  16927. const rng = editor.selection.getRng();
  16928. const contextBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
  16929. const contextArgs = contextBlock ? { context: contextBlock.nodeName.toLowerCase() } : {};
  16930. const node = editor.parser.parse(args.content, {
  16931. forced_root_block: false,
  16932. ...contextArgs,
  16933. ...args
  16934. });
  16935. return HtmlSerializer({ validate: false }, editor.schema).serialize(node);
  16936. } else {
  16937. return args.content;
  16938. }
  16939. };
  16940. const setContent$1 = (editor, content, args = {}) => {
  16941. const defaultedArgs = setupArgs$2(args, content);
  16942. preProcessSetContent(editor, defaultedArgs).each(updatedArgs => {
  16943. const cleanedContent = cleanContent(editor, updatedArgs);
  16944. const rng = editor.selection.getRng();
  16945. rngSetContent(rng, rng.createContextualFragment(cleanedContent));
  16946. editor.selection.setRng(rng);
  16947. scrollRangeIntoView(editor, rng);
  16948. postProcessSetContent(editor, cleanedContent, updatedArgs);
  16949. });
  16950. };
  16951. const deleteFromCallbackMap = (callbackMap, selector, callback) => {
  16952. if (callbackMap && has$2(callbackMap, selector)) {
  16953. const newCallbacks = filter$6(callbackMap[selector], cb => cb !== callback);
  16954. if (newCallbacks.length === 0) {
  16955. delete callbackMap[selector];
  16956. } else {
  16957. callbackMap[selector] = newCallbacks;
  16958. }
  16959. }
  16960. };
  16961. var SelectorChanged = (dom, editor) => {
  16962. let selectorChangedData;
  16963. let currentSelectors;
  16964. const findMatchingNode = (selector, nodes) => find$2(nodes, node => dom.is(node, selector));
  16965. const getParents = elem => dom.getParents(elem, null, dom.getRoot());
  16966. return {
  16967. selectorChangedWithUnbind: (selector, callback) => {
  16968. if (!selectorChangedData) {
  16969. selectorChangedData = {};
  16970. currentSelectors = {};
  16971. editor.on('NodeChange', e => {
  16972. const node = e.element;
  16973. const parents = getParents(node);
  16974. const matchedSelectors = {};
  16975. Tools.each(selectorChangedData, (callbacks, selector) => {
  16976. findMatchingNode(selector, parents).each(node => {
  16977. if (!currentSelectors[selector]) {
  16978. each$g(callbacks, callback => {
  16979. callback(true, {
  16980. node,
  16981. selector,
  16982. parents
  16983. });
  16984. });
  16985. currentSelectors[selector] = callbacks;
  16986. }
  16987. matchedSelectors[selector] = callbacks;
  16988. });
  16989. });
  16990. Tools.each(currentSelectors, (callbacks, selector) => {
  16991. if (!matchedSelectors[selector]) {
  16992. delete currentSelectors[selector];
  16993. Tools.each(callbacks, callback => {
  16994. callback(false, {
  16995. node,
  16996. selector,
  16997. parents
  16998. });
  16999. });
  17000. }
  17001. });
  17002. });
  17003. }
  17004. if (!selectorChangedData[selector]) {
  17005. selectorChangedData[selector] = [];
  17006. }
  17007. selectorChangedData[selector].push(callback);
  17008. findMatchingNode(selector, getParents(editor.selection.getStart())).each(() => {
  17009. currentSelectors[selector] = selectorChangedData[selector];
  17010. });
  17011. return {
  17012. unbind: () => {
  17013. deleteFromCallbackMap(selectorChangedData, selector, callback);
  17014. deleteFromCallbackMap(currentSelectors, selector, callback);
  17015. }
  17016. };
  17017. }
  17018. };
  17019. };
  17020. const isAttachedToDom = node => {
  17021. return !!(node && node.ownerDocument) && contains(SugarElement.fromDom(node.ownerDocument), SugarElement.fromDom(node));
  17022. };
  17023. const isValidRange = rng => {
  17024. if (!rng) {
  17025. return false;
  17026. } else {
  17027. return isAttachedToDom(rng.startContainer) && isAttachedToDom(rng.endContainer);
  17028. }
  17029. };
  17030. const EditorSelection = (dom, win, serializer, editor) => {
  17031. let selectedRange;
  17032. let explicitRange;
  17033. const {selectorChangedWithUnbind} = SelectorChanged(dom, editor);
  17034. const setCursorLocation = (node, offset) => {
  17035. const rng = dom.createRng();
  17036. if (isNonNullable(node) && isNonNullable(offset)) {
  17037. rng.setStart(node, offset);
  17038. rng.setEnd(node, offset);
  17039. setRng(rng);
  17040. collapse(false);
  17041. } else {
  17042. moveEndPoint(dom, rng, editor.getBody(), true);
  17043. setRng(rng);
  17044. }
  17045. };
  17046. const getContent = args => getContent$1(editor, args);
  17047. const setContent = (content, args) => setContent$1(editor, content, args);
  17048. const getStart$1 = real => getStart(editor.getBody(), getRng$1(), real);
  17049. const getEnd = real => getEnd$1(editor.getBody(), getRng$1(), real);
  17050. const getBookmark = (type, normalized) => bookmarkManager.getBookmark(type, normalized);
  17051. const moveToBookmark = bookmark => bookmarkManager.moveToBookmark(bookmark);
  17052. const select$1 = (node, content) => {
  17053. select(dom, node, content).each(setRng);
  17054. return node;
  17055. };
  17056. const isCollapsed = () => {
  17057. const rng = getRng$1(), sel = getSel();
  17058. if (!rng || rng.item) {
  17059. return false;
  17060. }
  17061. if (rng.compareEndPoints) {
  17062. return rng.compareEndPoints('StartToEnd', rng) === 0;
  17063. }
  17064. return !sel || rng.collapsed;
  17065. };
  17066. const collapse = toStart => {
  17067. const rng = getRng$1();
  17068. rng.collapse(!!toStart);
  17069. setRng(rng);
  17070. };
  17071. const getSel = () => win.getSelection ? win.getSelection() : win.document.selection;
  17072. const getRng$1 = () => {
  17073. let selection, rng, elm;
  17074. const tryCompareBoundaryPoints = (how, sourceRange, destinationRange) => {
  17075. try {
  17076. return sourceRange.compareBoundaryPoints(how, destinationRange);
  17077. } catch (ex) {
  17078. return -1;
  17079. }
  17080. };
  17081. const doc = win.document;
  17082. if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  17083. const bookmark = getRng(editor);
  17084. if (bookmark.isSome()) {
  17085. return bookmark.map(r => processRanges(editor, [r])[0]).getOr(doc.createRange());
  17086. }
  17087. }
  17088. try {
  17089. if ((selection = getSel()) && !isRestrictedNode(selection.anchorNode)) {
  17090. if (selection.rangeCount > 0) {
  17091. rng = selection.getRangeAt(0);
  17092. } else {
  17093. rng = selection.createRange ? selection.createRange() : doc.createRange();
  17094. }
  17095. rng = processRanges(editor, [rng])[0];
  17096. }
  17097. } catch (ex) {
  17098. }
  17099. if (!rng) {
  17100. rng = doc.createRange();
  17101. }
  17102. if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
  17103. elm = dom.getRoot();
  17104. rng.setStart(elm, 0);
  17105. rng.setEnd(elm, 0);
  17106. }
  17107. if (selectedRange && explicitRange) {
  17108. if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 && tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
  17109. rng = explicitRange;
  17110. } else {
  17111. selectedRange = null;
  17112. explicitRange = null;
  17113. }
  17114. }
  17115. return rng;
  17116. };
  17117. const setRng = (rng, forward) => {
  17118. let node;
  17119. if (!isValidRange(rng)) {
  17120. return;
  17121. }
  17122. const sel = getSel();
  17123. const evt = editor.dispatch('SetSelectionRange', {
  17124. range: rng,
  17125. forward
  17126. });
  17127. rng = evt.range;
  17128. if (sel) {
  17129. explicitRange = rng;
  17130. try {
  17131. sel.removeAllRanges();
  17132. sel.addRange(rng);
  17133. } catch (ex) {
  17134. }
  17135. if (forward === false && sel.extend) {
  17136. sel.collapse(rng.endContainer, rng.endOffset);
  17137. sel.extend(rng.startContainer, rng.startOffset);
  17138. }
  17139. selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
  17140. }
  17141. if (!rng.collapsed && rng.startContainer === rng.endContainer && sel.setBaseAndExtent) {
  17142. if (rng.endOffset - rng.startOffset < 2) {
  17143. if (rng.startContainer.hasChildNodes()) {
  17144. node = rng.startContainer.childNodes[rng.startOffset];
  17145. if (node && node.tagName === 'IMG') {
  17146. sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
  17147. if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
  17148. sel.setBaseAndExtent(node, 0, node, 1);
  17149. }
  17150. }
  17151. }
  17152. }
  17153. }
  17154. editor.dispatch('AfterSetSelectionRange', {
  17155. range: rng,
  17156. forward
  17157. });
  17158. };
  17159. const setNode = elm => {
  17160. setContent(dom.getOuterHTML(elm));
  17161. return elm;
  17162. };
  17163. const getNode$1 = () => getNode(editor.getBody(), getRng$1());
  17164. const getSelectedBlocks$1 = (startElm, endElm) => getSelectedBlocks(dom, getRng$1(), startElm, endElm);
  17165. const isForward = () => {
  17166. const sel = getSel();
  17167. const anchorNode = sel === null || sel === void 0 ? void 0 : sel.anchorNode;
  17168. const focusNode = sel === null || sel === void 0 ? void 0 : sel.focusNode;
  17169. if (!sel || !anchorNode || !focusNode || isRestrictedNode(anchorNode) || isRestrictedNode(focusNode)) {
  17170. return true;
  17171. }
  17172. const anchorRange = dom.createRng();
  17173. anchorRange.setStart(anchorNode, sel.anchorOffset);
  17174. anchorRange.collapse(true);
  17175. const focusRange = dom.createRng();
  17176. focusRange.setStart(focusNode, sel.focusOffset);
  17177. focusRange.collapse(true);
  17178. return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
  17179. };
  17180. const normalize = () => {
  17181. const rng = getRng$1();
  17182. const sel = getSel();
  17183. if (!hasMultipleRanges(sel) && hasAnyRanges(editor)) {
  17184. const normRng = normalize$2(dom, rng);
  17185. normRng.each(normRng => {
  17186. setRng(normRng, isForward());
  17187. });
  17188. return normRng.getOr(rng);
  17189. }
  17190. return rng;
  17191. };
  17192. const selectorChanged = (selector, callback) => {
  17193. selectorChangedWithUnbind(selector, callback);
  17194. return exports;
  17195. };
  17196. const getScrollContainer = () => {
  17197. let scrollContainer;
  17198. let node = dom.getRoot();
  17199. while (node && node.nodeName !== 'BODY') {
  17200. if (node.scrollHeight > node.clientHeight) {
  17201. scrollContainer = node;
  17202. break;
  17203. }
  17204. node = node.parentNode;
  17205. }
  17206. return scrollContainer;
  17207. };
  17208. const scrollIntoView = (elm, alignToTop) => {
  17209. if (isNonNullable(elm)) {
  17210. scrollElementIntoView(editor, elm, alignToTop);
  17211. } else {
  17212. scrollRangeIntoView(editor, getRng$1(), alignToTop);
  17213. }
  17214. };
  17215. const placeCaretAt = (clientX, clientY) => setRng(fromPoint(clientX, clientY, editor.getDoc()));
  17216. const getBoundingClientRect = () => {
  17217. const rng = getRng$1();
  17218. return rng.collapsed ? CaretPosition.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
  17219. };
  17220. const destroy = () => {
  17221. win = selectedRange = explicitRange = null;
  17222. controlSelection.destroy();
  17223. };
  17224. const exports = {
  17225. bookmarkManager: null,
  17226. controlSelection: null,
  17227. dom,
  17228. win,
  17229. serializer,
  17230. editor,
  17231. collapse,
  17232. setCursorLocation,
  17233. getContent,
  17234. setContent,
  17235. getBookmark,
  17236. moveToBookmark,
  17237. select: select$1,
  17238. isCollapsed,
  17239. isForward,
  17240. setNode,
  17241. getNode: getNode$1,
  17242. getSel,
  17243. setRng,
  17244. getRng: getRng$1,
  17245. getStart: getStart$1,
  17246. getEnd,
  17247. getSelectedBlocks: getSelectedBlocks$1,
  17248. normalize,
  17249. selectorChanged,
  17250. selectorChangedWithUnbind,
  17251. getScrollContainer,
  17252. scrollIntoView,
  17253. placeCaretAt,
  17254. getBoundingClientRect,
  17255. destroy
  17256. };
  17257. const bookmarkManager = BookmarkManager(exports);
  17258. const controlSelection = ControlSelection(exports, editor);
  17259. exports.bookmarkManager = bookmarkManager;
  17260. exports.controlSelection = controlSelection;
  17261. return exports;
  17262. };
  17263. const register$3 = (htmlParser, settings, dom) => {
  17264. htmlParser.addAttributeFilter('data-mce-tabindex', (nodes, name) => {
  17265. let i = nodes.length;
  17266. while (i--) {
  17267. const node = nodes[i];
  17268. node.attr('tabindex', node.attr('data-mce-tabindex'));
  17269. node.attr(name, null);
  17270. }
  17271. });
  17272. htmlParser.addAttributeFilter('src,href,style', (nodes, name) => {
  17273. const internalName = 'data-mce-' + name;
  17274. const urlConverter = settings.url_converter;
  17275. const urlConverterScope = settings.url_converter_scope;
  17276. let i = nodes.length;
  17277. while (i--) {
  17278. const node = nodes[i];
  17279. let value = node.attr(internalName);
  17280. if (value !== undefined) {
  17281. node.attr(name, value.length > 0 ? value : null);
  17282. node.attr(internalName, null);
  17283. } else {
  17284. value = node.attr(name);
  17285. if (name === 'style') {
  17286. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  17287. } else if (urlConverter) {
  17288. value = urlConverter.call(urlConverterScope, value, name, node.name);
  17289. }
  17290. node.attr(name, value.length > 0 ? value : null);
  17291. }
  17292. }
  17293. });
  17294. htmlParser.addAttributeFilter('class', nodes => {
  17295. let i = nodes.length;
  17296. while (i--) {
  17297. const node = nodes[i];
  17298. let value = node.attr('class');
  17299. if (value) {
  17300. value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
  17301. node.attr('class', value.length > 0 ? value : null);
  17302. }
  17303. }
  17304. });
  17305. htmlParser.addAttributeFilter('data-mce-type', (nodes, name, args) => {
  17306. let i = nodes.length;
  17307. while (i--) {
  17308. const node = nodes[i];
  17309. if (node.attr('data-mce-type') === 'bookmark' && !args.cleanup) {
  17310. const hasChildren = Optional.from(node.firstChild).exists(firstChild => !isZwsp(firstChild.value));
  17311. if (hasChildren) {
  17312. node.unwrap();
  17313. } else {
  17314. node.remove();
  17315. }
  17316. }
  17317. }
  17318. });
  17319. htmlParser.addNodeFilter('noscript', nodes => {
  17320. let i = nodes.length;
  17321. while (i--) {
  17322. const node = nodes[i].firstChild;
  17323. if (node) {
  17324. node.value = Entities.decode(node.value);
  17325. }
  17326. }
  17327. });
  17328. htmlParser.addNodeFilter('script,style', (nodes, name) => {
  17329. const trim = value => {
  17330. 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, '');
  17331. };
  17332. let i = nodes.length;
  17333. while (i--) {
  17334. const node = nodes[i];
  17335. const value = node.firstChild ? node.firstChild.value : '';
  17336. if (name === 'script') {
  17337. const type = node.attr('type');
  17338. if (type) {
  17339. node.attr('type', type === 'mce-no/type' ? null : type.replace(/^mce\-/, ''));
  17340. }
  17341. if (settings.element_format === 'xhtml' && value.length > 0) {
  17342. node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
  17343. }
  17344. } else {
  17345. if (settings.element_format === 'xhtml' && value.length > 0) {
  17346. node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
  17347. }
  17348. }
  17349. }
  17350. });
  17351. htmlParser.addNodeFilter('#comment', nodes => {
  17352. let i = nodes.length;
  17353. while (i--) {
  17354. const node = nodes[i];
  17355. if (settings.preserve_cdata && node.value.indexOf('[CDATA[') === 0) {
  17356. node.name = '#cdata';
  17357. node.type = 4;
  17358. node.value = dom.decode(node.value.replace(/^\[CDATA\[|\]\]$/g, ''));
  17359. } else if (node.value.indexOf('mce:protected ') === 0) {
  17360. node.name = '#text';
  17361. node.type = 3;
  17362. node.raw = true;
  17363. node.value = unescape(node.value).substr(14);
  17364. }
  17365. }
  17366. });
  17367. htmlParser.addNodeFilter('xml:namespace,input', (nodes, name) => {
  17368. let i = nodes.length;
  17369. while (i--) {
  17370. const node = nodes[i];
  17371. if (node.type === 7) {
  17372. node.remove();
  17373. } else if (node.type === 1) {
  17374. if (name === 'input' && !node.attr('type')) {
  17375. node.attr('type', 'text');
  17376. }
  17377. }
  17378. }
  17379. });
  17380. htmlParser.addAttributeFilter('data-mce-type', nodes => {
  17381. each$g(nodes, node => {
  17382. if (node.attr('data-mce-type') === 'format-caret') {
  17383. if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
  17384. node.remove();
  17385. } else {
  17386. node.unwrap();
  17387. }
  17388. }
  17389. });
  17390. });
  17391. 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', (nodes, name) => {
  17392. let i = nodes.length;
  17393. while (i--) {
  17394. nodes[i].attr(name, null);
  17395. }
  17396. });
  17397. };
  17398. const trimTrailingBr = rootNode => {
  17399. const isBr = node => {
  17400. return node && node.name === 'br';
  17401. };
  17402. const brNode1 = rootNode.lastChild;
  17403. if (isBr(brNode1)) {
  17404. const brNode2 = brNode1.prev;
  17405. if (isBr(brNode2)) {
  17406. brNode1.remove();
  17407. brNode2.remove();
  17408. }
  17409. }
  17410. };
  17411. const preProcess$1 = (editor, node, args) => {
  17412. let oldDoc;
  17413. const dom = editor.dom;
  17414. let clonedNode = node.cloneNode(true);
  17415. const impl = document.implementation;
  17416. if (impl.createHTMLDocument) {
  17417. const doc = impl.createHTMLDocument('');
  17418. Tools.each(clonedNode.nodeName === 'BODY' ? clonedNode.childNodes : [clonedNode], node => {
  17419. doc.body.appendChild(doc.importNode(node, true));
  17420. });
  17421. if (clonedNode.nodeName !== 'BODY') {
  17422. clonedNode = doc.body.firstChild;
  17423. } else {
  17424. clonedNode = doc.body;
  17425. }
  17426. oldDoc = dom.doc;
  17427. dom.doc = doc;
  17428. }
  17429. firePreProcess(editor, {
  17430. ...args,
  17431. node: clonedNode
  17432. });
  17433. if (oldDoc) {
  17434. dom.doc = oldDoc;
  17435. }
  17436. return clonedNode;
  17437. };
  17438. const shouldFireEvent = (editor, args) => {
  17439. return editor && editor.hasEventListeners('PreProcess') && !args.no_events;
  17440. };
  17441. const process$1 = (editor, node, args) => {
  17442. return shouldFireEvent(editor, args) ? preProcess$1(editor, node, args) : node;
  17443. };
  17444. const addTempAttr = (htmlParser, tempAttrs, name) => {
  17445. if (Tools.inArray(tempAttrs, name) === -1) {
  17446. htmlParser.addAttributeFilter(name, (nodes, name) => {
  17447. let i = nodes.length;
  17448. while (i--) {
  17449. nodes[i].attr(name, null);
  17450. }
  17451. });
  17452. tempAttrs.push(name);
  17453. }
  17454. };
  17455. const postProcess = (editor, args, content) => {
  17456. if (!args.no_events && editor) {
  17457. const outArgs = firePostProcess(editor, {
  17458. ...args,
  17459. content
  17460. });
  17461. return outArgs.content;
  17462. } else {
  17463. return content;
  17464. }
  17465. };
  17466. const getHtmlFromNode = (dom, node, args) => {
  17467. const html = trim$1(args.getInner ? node.innerHTML : dom.getOuterHTML(node));
  17468. return args.selection || isWsPreserveElement(SugarElement.fromDom(node)) ? html : Tools.trim(html);
  17469. };
  17470. const parseHtml = (htmlParser, html, args) => {
  17471. const parserArgs = args.selection ? {
  17472. forced_root_block: false,
  17473. ...args
  17474. } : args;
  17475. const rootNode = htmlParser.parse(html, parserArgs);
  17476. trimTrailingBr(rootNode);
  17477. return rootNode;
  17478. };
  17479. const serializeNode = (settings, schema, node) => {
  17480. const htmlSerializer = HtmlSerializer(settings, schema);
  17481. return htmlSerializer.serialize(node);
  17482. };
  17483. const toHtml = (editor, settings, schema, rootNode, args) => {
  17484. const content = serializeNode(settings, schema, rootNode);
  17485. return postProcess(editor, args, content);
  17486. };
  17487. const DomSerializerImpl = (settings, editor) => {
  17488. const tempAttrs = ['data-mce-selected'];
  17489. const dom = editor && editor.dom ? editor.dom : DOMUtils.DOM;
  17490. const schema = editor && editor.schema ? editor.schema : Schema(settings);
  17491. settings.entity_encoding = settings.entity_encoding || 'named';
  17492. settings.remove_trailing_brs = 'remove_trailing_brs' in settings ? settings.remove_trailing_brs : true;
  17493. const htmlParser = DomParser(settings, schema);
  17494. register$3(htmlParser, settings, dom);
  17495. const serialize = (node, parserArgs = {}) => {
  17496. const args = {
  17497. format: 'html',
  17498. ...parserArgs
  17499. };
  17500. const targetNode = process$1(editor, node, args);
  17501. const html = getHtmlFromNode(dom, targetNode, args);
  17502. const rootNode = parseHtml(htmlParser, html, args);
  17503. return args.format === 'tree' ? rootNode : toHtml(editor, settings, schema, rootNode, args);
  17504. };
  17505. return {
  17506. schema,
  17507. addNodeFilter: htmlParser.addNodeFilter,
  17508. addAttributeFilter: htmlParser.addAttributeFilter,
  17509. serialize: serialize,
  17510. addRules: schema.addValidElements,
  17511. setRules: schema.setValidElements,
  17512. addTempAttr: curry(addTempAttr, htmlParser, tempAttrs),
  17513. getTempAttrs: constant(tempAttrs),
  17514. getNodeFilters: htmlParser.getNodeFilters,
  17515. getAttributeFilters: htmlParser.getAttributeFilters
  17516. };
  17517. };
  17518. const DomSerializer = (settings, editor) => {
  17519. const domSerializer = DomSerializerImpl(settings, editor);
  17520. return {
  17521. schema: domSerializer.schema,
  17522. addNodeFilter: domSerializer.addNodeFilter,
  17523. addAttributeFilter: domSerializer.addAttributeFilter,
  17524. serialize: domSerializer.serialize,
  17525. addRules: domSerializer.addRules,
  17526. setRules: domSerializer.setRules,
  17527. addTempAttr: domSerializer.addTempAttr,
  17528. getTempAttrs: domSerializer.getTempAttrs,
  17529. getNodeFilters: domSerializer.getNodeFilters,
  17530. getAttributeFilters: domSerializer.getAttributeFilters
  17531. };
  17532. };
  17533. const defaultFormat$1 = 'html';
  17534. const setupArgs$1 = (args, format) => ({
  17535. ...args,
  17536. format,
  17537. get: true,
  17538. getInner: true
  17539. });
  17540. const getContent = (editor, args = {}) => {
  17541. const format = args.format ? args.format : defaultFormat$1;
  17542. const defaultedArgs = setupArgs$1(args, format);
  17543. return preProcessGetContent(editor, defaultedArgs).fold(identity, updatedArgs => {
  17544. const content = getContent$2(editor, updatedArgs);
  17545. return postProcessGetContent(editor, content, updatedArgs);
  17546. });
  17547. };
  17548. const defaultFormat = 'html';
  17549. const setupArgs = (args, content) => ({
  17550. format: defaultFormat,
  17551. ...args,
  17552. set: true,
  17553. content
  17554. });
  17555. const setContent = (editor, content, args = {}) => {
  17556. const defaultedArgs = setupArgs(args, content);
  17557. return preProcessSetContent(editor, defaultedArgs).map(updatedArgs => {
  17558. const result = setContent$2(editor, updatedArgs.content, updatedArgs);
  17559. postProcessSetContent(editor, result.html, updatedArgs);
  17560. return result.content;
  17561. }).getOr(content);
  17562. };
  17563. const removedOptions = ('autoresize_on_init,content_editable_state,padd_empty_with_br,block_elements,' + 'boolean_attributes,editor_deselector,editor_selector,elements,file_browser_callback_types,filepicker_validator_handler,' + 'force_hex_style_colors,force_p_newlines,gecko_spellcheck,images_dataimg_filter,media_scripts,mode,move_caret_before_on_enter_elements,' + 'non_empty_elements,self_closing_elements,short_ended_elements,special,spellchecker_select_languages,spellchecker_whitelist,' + 'tab_focus,tabfocus_elements,table_responsive_width,text_block_elements,text_inline_elements,toolbar_drawer,types,validate,whitespace_elements,' + 'paste_enable_default_filters,paste_filter_drop,paste_word_valid_elements,paste_retain_style_properties,paste_convert_word_fake_lists').split(',');
  17564. const removedPlugins = 'bbcode,colorpicker,contextmenu,fullpage,legacyoutput,spellchecker,textcolor'.split(',');
  17565. const getRemovedOptions = options => {
  17566. const settingNames = filter$6(removedOptions, setting => has$2(options, setting));
  17567. const forcedRootBlock = options.forced_root_block;
  17568. if (forcedRootBlock === false || forcedRootBlock === '') {
  17569. settingNames.push('forced_root_block (false only)');
  17570. }
  17571. return sort(settingNames);
  17572. };
  17573. const getRemovedPlugins = options => {
  17574. const plugins = Tools.makeMap(options.plugins, ' ');
  17575. const hasPlugin = plugin => has$2(plugins, plugin);
  17576. const pluginNames = filter$6(removedPlugins, hasPlugin);
  17577. return sort(pluginNames);
  17578. };
  17579. const logRemovedWarnings = (rawOptions, normalizedOptions) => {
  17580. const removedOptions = getRemovedOptions(rawOptions);
  17581. const removedPlugins = getRemovedPlugins(normalizedOptions);
  17582. const hasRemovedPlugins = removedPlugins.length > 0;
  17583. const hasRemovedOptions = removedOptions.length > 0;
  17584. const isLegacyMobileTheme = normalizedOptions.theme === 'mobile';
  17585. if (hasRemovedPlugins || hasRemovedOptions || isLegacyMobileTheme) {
  17586. const listJoiner = '\n- ';
  17587. const themesMessage = isLegacyMobileTheme ? `\n\nThemes:${ listJoiner }mobile` : '';
  17588. const pluginsMessage = hasRemovedPlugins ? `\n\nPlugins:${ listJoiner }${ removedPlugins.join(listJoiner) }` : '';
  17589. const optionsMessage = hasRemovedOptions ? `\n\nOptions:${ listJoiner }${ removedOptions.join(listJoiner) }` : '';
  17590. console.warn('The following deprecated features are currently enabled and have been removed in TinyMCE 6.0. These features will no longer work and should be removed from the TinyMCE configuration. ' + 'See https://www.tiny.cloud/docs/tinymce/6/migration-from-5x/ for more information.' + themesMessage + pluginsMessage + optionsMessage);
  17591. }
  17592. };
  17593. const logWarnings = (rawOptions, normalizedOptions) => {
  17594. logRemovedWarnings(rawOptions, normalizedOptions);
  17595. };
  17596. const DOM$8 = DOMUtils.DOM;
  17597. const restoreOriginalStyles = editor => {
  17598. DOM$8.setStyle(editor.id, 'display', editor.orgDisplay);
  17599. };
  17600. const safeDestroy = x => Optional.from(x).each(x => x.destroy());
  17601. const clearDomReferences = editor => {
  17602. editor.contentAreaContainer = editor.formElement = editor.container = editor.editorContainer = null;
  17603. editor.bodyElement = editor.contentDocument = editor.contentWindow = null;
  17604. editor.iframeElement = editor.targetElm = null;
  17605. if (editor.selection) {
  17606. editor.selection = editor.selection.win = editor.selection.dom = editor.selection.dom.doc = null;
  17607. }
  17608. };
  17609. const restoreForm = editor => {
  17610. const form = editor.formElement;
  17611. if (form) {
  17612. if (form._mceOldSubmit) {
  17613. form.submit = form._mceOldSubmit;
  17614. form._mceOldSubmit = null;
  17615. }
  17616. DOM$8.unbind(form, 'submit reset', editor.formEventDelegate);
  17617. }
  17618. };
  17619. const remove$1 = editor => {
  17620. if (!editor.removed) {
  17621. const {_selectionOverrides, editorUpload} = editor;
  17622. const body = editor.getBody();
  17623. const element = editor.getElement();
  17624. if (body) {
  17625. editor.save({ is_removing: true });
  17626. }
  17627. editor.removed = true;
  17628. editor.unbindAllNativeEvents();
  17629. if (editor.hasHiddenInput && element) {
  17630. DOM$8.remove(element.nextSibling);
  17631. }
  17632. fireRemove(editor);
  17633. editor.editorManager.remove(editor);
  17634. if (!editor.inline && body) {
  17635. restoreOriginalStyles(editor);
  17636. }
  17637. fireDetach(editor);
  17638. DOM$8.remove(editor.getContainer());
  17639. safeDestroy(_selectionOverrides);
  17640. safeDestroy(editorUpload);
  17641. editor.destroy();
  17642. }
  17643. };
  17644. const destroy = (editor, automatic) => {
  17645. const {selection, dom} = editor;
  17646. if (editor.destroyed) {
  17647. return;
  17648. }
  17649. if (!automatic && !editor.removed) {
  17650. editor.remove();
  17651. return;
  17652. }
  17653. if (!automatic) {
  17654. editor.editorManager.off('beforeunload', editor._beforeUnload);
  17655. if (editor.theme && editor.theme.destroy) {
  17656. editor.theme.destroy();
  17657. }
  17658. safeDestroy(selection);
  17659. safeDestroy(dom);
  17660. }
  17661. restoreForm(editor);
  17662. clearDomReferences(editor);
  17663. editor.destroyed = true;
  17664. };
  17665. const CreateIconManager = () => {
  17666. const lookup = {};
  17667. const add = (id, iconPack) => {
  17668. lookup[id] = iconPack;
  17669. };
  17670. const get = id => {
  17671. if (lookup[id]) {
  17672. return lookup[id];
  17673. }
  17674. return { icons: {} };
  17675. };
  17676. const has = id => has$2(lookup, id);
  17677. return {
  17678. add,
  17679. get,
  17680. has
  17681. };
  17682. };
  17683. const IconManager = CreateIconManager();
  17684. const ModelManager = AddOnManager.ModelManager;
  17685. const getProp = (propName, elm) => {
  17686. const rawElm = elm.dom;
  17687. return rawElm[propName];
  17688. };
  17689. const getComputedSizeProp = (propName, elm) => parseInt(get$7(elm, propName), 10);
  17690. const getClientWidth = curry(getProp, 'clientWidth');
  17691. const getClientHeight = curry(getProp, 'clientHeight');
  17692. const getMarginTop = curry(getComputedSizeProp, 'margin-top');
  17693. const getMarginLeft = curry(getComputedSizeProp, 'margin-left');
  17694. const getBoundingClientRect = elm => elm.dom.getBoundingClientRect();
  17695. const isInsideElementContentArea = (bodyElm, clientX, clientY) => {
  17696. const clientWidth = getClientWidth(bodyElm);
  17697. const clientHeight = getClientHeight(bodyElm);
  17698. return clientX >= 0 && clientY >= 0 && clientX <= clientWidth && clientY <= clientHeight;
  17699. };
  17700. const transpose = (inline, elm, clientX, clientY) => {
  17701. const clientRect = getBoundingClientRect(elm);
  17702. const deltaX = inline ? clientRect.left + elm.dom.clientLeft + getMarginLeft(elm) : 0;
  17703. const deltaY = inline ? clientRect.top + elm.dom.clientTop + getMarginTop(elm) : 0;
  17704. const x = clientX - deltaX;
  17705. const y = clientY - deltaY;
  17706. return {
  17707. x,
  17708. y
  17709. };
  17710. };
  17711. const isXYInContentArea = (editor, clientX, clientY) => {
  17712. const bodyElm = SugarElement.fromDom(editor.getBody());
  17713. const targetElm = editor.inline ? bodyElm : documentElement(bodyElm);
  17714. const transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
  17715. return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
  17716. };
  17717. const fromDomSafe = node => Optional.from(node).map(SugarElement.fromDom);
  17718. const isEditorAttachedToDom = editor => {
  17719. const rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
  17720. return fromDomSafe(rawContainer).map(inBody).getOr(false);
  17721. };
  17722. const NotificationManagerImpl = () => {
  17723. const unimplemented = () => {
  17724. throw new Error('Theme did not provide a NotificationManager implementation.');
  17725. };
  17726. return {
  17727. open: unimplemented,
  17728. close: unimplemented,
  17729. getArgs: unimplemented
  17730. };
  17731. };
  17732. const NotificationManager = editor => {
  17733. const notifications = [];
  17734. const getImplementation = () => {
  17735. const theme = editor.theme;
  17736. return theme && theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
  17737. };
  17738. const getTopNotification = () => {
  17739. return Optional.from(notifications[0]);
  17740. };
  17741. const isEqual = (a, b) => {
  17742. return a.type === b.type && a.text === b.text && !a.progressBar && !a.timeout && !b.progressBar && !b.timeout;
  17743. };
  17744. const reposition = () => {
  17745. each$g(notifications, notification => {
  17746. notification.reposition();
  17747. });
  17748. };
  17749. const addNotification = notification => {
  17750. notifications.push(notification);
  17751. };
  17752. const closeNotification = notification => {
  17753. findIndex$2(notifications, otherNotification => {
  17754. return otherNotification === notification;
  17755. }).each(index => {
  17756. notifications.splice(index, 1);
  17757. });
  17758. };
  17759. const open = (spec, fireEvent = true) => {
  17760. if (editor.removed || !isEditorAttachedToDom(editor)) {
  17761. return;
  17762. }
  17763. if (fireEvent) {
  17764. editor.dispatch('BeforeOpenNotification', { notification: spec });
  17765. }
  17766. return find$2(notifications, notification => {
  17767. return isEqual(getImplementation().getArgs(notification), spec);
  17768. }).getOrThunk(() => {
  17769. editor.editorManager.setActive(editor);
  17770. const notification = getImplementation().open(spec, () => {
  17771. closeNotification(notification);
  17772. reposition();
  17773. getTopNotification().fold(() => editor.focus(), top => focus$1(SugarElement.fromDom(top.getEl())));
  17774. });
  17775. addNotification(notification);
  17776. reposition();
  17777. editor.dispatch('OpenNotification', { notification: { ...notification } });
  17778. return notification;
  17779. });
  17780. };
  17781. const close = () => {
  17782. getTopNotification().each(notification => {
  17783. getImplementation().close(notification);
  17784. closeNotification(notification);
  17785. reposition();
  17786. });
  17787. };
  17788. const getNotifications = constant(notifications);
  17789. const registerEvents = editor => {
  17790. editor.on('SkinLoaded', () => {
  17791. const serviceMessage = getServiceMessage(editor);
  17792. if (serviceMessage) {
  17793. open({
  17794. text: serviceMessage,
  17795. type: 'warning',
  17796. timeout: 0
  17797. }, false);
  17798. }
  17799. reposition();
  17800. });
  17801. editor.on('show ResizeEditor ResizeWindow NodeChange', () => {
  17802. requestAnimationFrame(reposition);
  17803. });
  17804. editor.on('remove', () => {
  17805. each$g(notifications.slice(), notification => {
  17806. getImplementation().close(notification);
  17807. });
  17808. });
  17809. };
  17810. registerEvents(editor);
  17811. return {
  17812. open,
  17813. close,
  17814. getNotifications
  17815. };
  17816. };
  17817. const PluginManager = AddOnManager.PluginManager;
  17818. const ThemeManager = AddOnManager.ThemeManager;
  17819. var WindowManagerImpl = () => {
  17820. const unimplemented = () => {
  17821. throw new Error('Theme did not provide a WindowManager implementation.');
  17822. };
  17823. return {
  17824. open: unimplemented,
  17825. openUrl: unimplemented,
  17826. alert: unimplemented,
  17827. confirm: unimplemented,
  17828. close: unimplemented,
  17829. getParams: unimplemented,
  17830. setParams: unimplemented
  17831. };
  17832. };
  17833. const WindowManager = editor => {
  17834. let dialogs = [];
  17835. const getImplementation = () => {
  17836. const theme = editor.theme;
  17837. return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
  17838. };
  17839. const funcBind = (scope, f) => {
  17840. return (...args) => {
  17841. return f ? f.apply(scope, args) : undefined;
  17842. };
  17843. };
  17844. const fireOpenEvent = dialog => {
  17845. editor.dispatch('OpenWindow', { dialog });
  17846. };
  17847. const fireCloseEvent = dialog => {
  17848. editor.dispatch('CloseWindow', { dialog });
  17849. };
  17850. const addDialog = dialog => {
  17851. dialogs.push(dialog);
  17852. fireOpenEvent(dialog);
  17853. };
  17854. const closeDialog = dialog => {
  17855. fireCloseEvent(dialog);
  17856. dialogs = filter$6(dialogs, otherDialog => {
  17857. return otherDialog !== dialog;
  17858. });
  17859. if (dialogs.length === 0) {
  17860. editor.focus();
  17861. }
  17862. };
  17863. const getTopDialog = () => {
  17864. return Optional.from(dialogs[dialogs.length - 1]);
  17865. };
  17866. const storeSelectionAndOpenDialog = openDialog => {
  17867. editor.editorManager.setActive(editor);
  17868. store(editor);
  17869. editor.ui.show();
  17870. const dialog = openDialog();
  17871. addDialog(dialog);
  17872. return dialog;
  17873. };
  17874. const open = (args, params) => {
  17875. return storeSelectionAndOpenDialog(() => getImplementation().open(args, params, closeDialog));
  17876. };
  17877. const openUrl = args => {
  17878. return storeSelectionAndOpenDialog(() => getImplementation().openUrl(args, closeDialog));
  17879. };
  17880. const alert = (message, callback, scope) => {
  17881. const windowManagerImpl = getImplementation();
  17882. windowManagerImpl.alert(message, funcBind(scope ? scope : windowManagerImpl, callback));
  17883. };
  17884. const confirm = (message, callback, scope) => {
  17885. const windowManagerImpl = getImplementation();
  17886. windowManagerImpl.confirm(message, funcBind(scope ? scope : windowManagerImpl, callback));
  17887. };
  17888. const close = () => {
  17889. getTopDialog().each(dialog => {
  17890. getImplementation().close(dialog);
  17891. closeDialog(dialog);
  17892. });
  17893. };
  17894. editor.on('remove', () => {
  17895. each$g(dialogs, dialog => {
  17896. getImplementation().close(dialog);
  17897. });
  17898. });
  17899. return {
  17900. open,
  17901. openUrl,
  17902. alert,
  17903. confirm,
  17904. close
  17905. };
  17906. };
  17907. const displayNotification = (editor, message) => {
  17908. editor.notificationManager.open({
  17909. type: 'error',
  17910. text: message
  17911. });
  17912. };
  17913. const displayError = (editor, message) => {
  17914. if (editor._skinLoaded) {
  17915. displayNotification(editor, message);
  17916. } else {
  17917. editor.on('SkinLoaded', () => {
  17918. displayNotification(editor, message);
  17919. });
  17920. }
  17921. };
  17922. const uploadError = (editor, message) => {
  17923. displayError(editor, I18n.translate([
  17924. 'Failed to upload image: {0}',
  17925. message
  17926. ]));
  17927. };
  17928. const logError = (editor, errorType, msg) => {
  17929. fireError(editor, errorType, { message: msg });
  17930. console.error(msg);
  17931. };
  17932. const createLoadError = (type, url, name) => name ? `Failed to load ${ type }: ${ name } from url ${ url }` : `Failed to load ${ type } url: ${ url }`;
  17933. const pluginLoadError = (editor, url, name) => {
  17934. logError(editor, 'PluginLoadError', createLoadError('plugin', url, name));
  17935. };
  17936. const iconsLoadError = (editor, url, name) => {
  17937. logError(editor, 'IconsLoadError', createLoadError('icons', url, name));
  17938. };
  17939. const languageLoadError = (editor, url, name) => {
  17940. logError(editor, 'LanguageLoadError', createLoadError('language', url, name));
  17941. };
  17942. const themeLoadError = (editor, url, name) => {
  17943. logError(editor, 'ThemeLoadError', createLoadError('theme', url, name));
  17944. };
  17945. const modelLoadError = (editor, url, name) => {
  17946. logError(editor, 'ModelLoadError', createLoadError('model', url, name));
  17947. };
  17948. const pluginInitError = (editor, name, err) => {
  17949. const message = I18n.translate([
  17950. 'Failed to initialize plugin: {0}',
  17951. name
  17952. ]);
  17953. fireError(editor, 'PluginLoadError', { message });
  17954. initError(message, err);
  17955. displayError(editor, message);
  17956. };
  17957. const initError = (message, ...x) => {
  17958. const console = window.console;
  17959. if (console) {
  17960. if (console.error) {
  17961. console.error(message, ...x);
  17962. } else {
  17963. console.log(message, ...x);
  17964. }
  17965. }
  17966. };
  17967. const isContentCssSkinName = url => /^[a-z0-9\-]+$/i.test(url);
  17968. const getContentCssUrls = editor => {
  17969. return transformToUrls(editor, getContentCss(editor));
  17970. };
  17971. const getFontCssUrls = editor => {
  17972. return transformToUrls(editor, getFontCss(editor));
  17973. };
  17974. const transformToUrls = (editor, cssLinks) => {
  17975. const skinUrl = editor.editorManager.baseURL + '/skins/content';
  17976. const suffix = editor.editorManager.suffix;
  17977. const contentCssFile = `content${ suffix }.css`;
  17978. const inline = editor.inline === true;
  17979. return map$3(cssLinks, url => {
  17980. if (isContentCssSkinName(url) && !inline) {
  17981. return `${ skinUrl }/${ url }/${ contentCssFile }`;
  17982. } else {
  17983. return editor.documentBaseURI.toAbsolute(url);
  17984. }
  17985. });
  17986. };
  17987. const appendContentCssFromSettings = editor => {
  17988. editor.contentCSS = editor.contentCSS.concat(getContentCssUrls(editor), getFontCssUrls(editor));
  17989. };
  17990. const filter$1 = always;
  17991. const bind$1 = (element, event, handler) => bind$2(element, event, filter$1, handler);
  17992. const UploadStatus = () => {
  17993. const PENDING = 1, UPLOADED = 2;
  17994. let blobUriStatuses = {};
  17995. const createStatus = (status, resultUri) => {
  17996. return {
  17997. status,
  17998. resultUri
  17999. };
  18000. };
  18001. const hasBlobUri = blobUri => {
  18002. return blobUri in blobUriStatuses;
  18003. };
  18004. const getResultUri = blobUri => {
  18005. const result = blobUriStatuses[blobUri];
  18006. return result ? result.resultUri : null;
  18007. };
  18008. const isPending = blobUri => {
  18009. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
  18010. };
  18011. const isUploaded = blobUri => {
  18012. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
  18013. };
  18014. const markPending = blobUri => {
  18015. blobUriStatuses[blobUri] = createStatus(PENDING, null);
  18016. };
  18017. const markUploaded = (blobUri, resultUri) => {
  18018. blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
  18019. };
  18020. const removeFailed = blobUri => {
  18021. delete blobUriStatuses[blobUri];
  18022. };
  18023. const destroy = () => {
  18024. blobUriStatuses = {};
  18025. };
  18026. return {
  18027. hasBlobUri,
  18028. getResultUri,
  18029. isPending,
  18030. isUploaded,
  18031. markPending,
  18032. markUploaded,
  18033. removeFailed,
  18034. destroy
  18035. };
  18036. };
  18037. let count = 0;
  18038. const seed = () => {
  18039. const rnd = () => {
  18040. return Math.round(Math.random() * 4294967295).toString(36);
  18041. };
  18042. const now = new Date().getTime();
  18043. return 's' + now.toString(36) + rnd() + rnd() + rnd();
  18044. };
  18045. const uuid = prefix => {
  18046. return prefix + count++ + seed();
  18047. };
  18048. const BlobCache = () => {
  18049. let cache = [];
  18050. const mimeToExt = mime => {
  18051. const mimes = {
  18052. 'image/jpeg': 'jpg',
  18053. 'image/jpg': 'jpg',
  18054. 'image/gif': 'gif',
  18055. 'image/png': 'png',
  18056. 'image/apng': 'apng',
  18057. 'image/avif': 'avif',
  18058. 'image/svg+xml': 'svg',
  18059. 'image/webp': 'webp',
  18060. 'image/bmp': 'bmp',
  18061. 'image/tiff': 'tiff'
  18062. };
  18063. return mimes[mime.toLowerCase()] || 'dat';
  18064. };
  18065. const create = (o, blob, base64, name, filename) => {
  18066. if (isString(o)) {
  18067. const id = o;
  18068. return toBlobInfo({
  18069. id,
  18070. name,
  18071. filename,
  18072. blob,
  18073. base64
  18074. });
  18075. } else if (isObject(o)) {
  18076. return toBlobInfo(o);
  18077. } else {
  18078. throw new Error('Unknown input type');
  18079. }
  18080. };
  18081. const toBlobInfo = o => {
  18082. if (!o.blob || !o.base64) {
  18083. throw new Error('blob and base64 representations of the image are required for BlobInfo to be created');
  18084. }
  18085. const id = o.id || uuid('blobid');
  18086. const name = o.name || id;
  18087. const blob = o.blob;
  18088. return {
  18089. id: constant(id),
  18090. name: constant(name),
  18091. filename: constant(o.filename || name + '.' + mimeToExt(blob.type)),
  18092. blob: constant(blob),
  18093. base64: constant(o.base64),
  18094. blobUri: constant(o.blobUri || URL.createObjectURL(blob)),
  18095. uri: constant(o.uri)
  18096. };
  18097. };
  18098. const add = blobInfo => {
  18099. if (!get(blobInfo.id())) {
  18100. cache.push(blobInfo);
  18101. }
  18102. };
  18103. const findFirst = predicate => find$2(cache, predicate).getOrUndefined();
  18104. const get = id => findFirst(cachedBlobInfo => cachedBlobInfo.id() === id);
  18105. const getByUri = blobUri => findFirst(blobInfo => blobInfo.blobUri() === blobUri);
  18106. const getByData = (base64, type) => findFirst(blobInfo => blobInfo.base64() === base64 && blobInfo.blob().type === type);
  18107. const removeByUri = blobUri => {
  18108. cache = filter$6(cache, blobInfo => {
  18109. if (blobInfo.blobUri() === blobUri) {
  18110. URL.revokeObjectURL(blobInfo.blobUri());
  18111. return false;
  18112. }
  18113. return true;
  18114. });
  18115. };
  18116. const destroy = () => {
  18117. each$g(cache, cachedBlobInfo => {
  18118. URL.revokeObjectURL(cachedBlobInfo.blobUri());
  18119. });
  18120. cache = [];
  18121. };
  18122. return {
  18123. create,
  18124. add,
  18125. get,
  18126. getByUri,
  18127. getByData,
  18128. findFirst,
  18129. removeByUri,
  18130. destroy
  18131. };
  18132. };
  18133. const Uploader = (uploadStatus, settings) => {
  18134. const pendingPromises = {};
  18135. const pathJoin = (path1, path2) => {
  18136. if (path1) {
  18137. return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
  18138. }
  18139. return path2;
  18140. };
  18141. const defaultHandler = (blobInfo, progress) => new Promise((success, failure) => {
  18142. const xhr = new XMLHttpRequest();
  18143. xhr.open('POST', settings.url);
  18144. xhr.withCredentials = settings.credentials;
  18145. xhr.upload.onprogress = e => {
  18146. progress(e.loaded / e.total * 100);
  18147. };
  18148. xhr.onerror = () => {
  18149. failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  18150. };
  18151. xhr.onload = () => {
  18152. if (xhr.status < 200 || xhr.status >= 300) {
  18153. failure('HTTP Error: ' + xhr.status);
  18154. return;
  18155. }
  18156. const json = JSON.parse(xhr.responseText);
  18157. if (!json || !isString(json.location)) {
  18158. failure('Invalid JSON: ' + xhr.responseText);
  18159. return;
  18160. }
  18161. success(pathJoin(settings.basePath, json.location));
  18162. };
  18163. const formData = new FormData();
  18164. formData.append('file', blobInfo.blob(), blobInfo.filename());
  18165. xhr.send(formData);
  18166. });
  18167. const noUpload = () => new Promise(resolve => {
  18168. resolve([]);
  18169. });
  18170. const handlerSuccess = (blobInfo, url) => ({
  18171. url,
  18172. blobInfo,
  18173. status: true
  18174. });
  18175. const handlerFailure = (blobInfo, error) => ({
  18176. url: '',
  18177. blobInfo,
  18178. status: false,
  18179. error
  18180. });
  18181. const resolvePending = (blobUri, result) => {
  18182. Tools.each(pendingPromises[blobUri], resolve => {
  18183. resolve(result);
  18184. });
  18185. delete pendingPromises[blobUri];
  18186. };
  18187. const uploadBlobInfo = (blobInfo, handler, openNotification) => {
  18188. uploadStatus.markPending(blobInfo.blobUri());
  18189. return new Promise(resolve => {
  18190. let notification;
  18191. let progress;
  18192. try {
  18193. const closeNotification = () => {
  18194. if (notification) {
  18195. notification.close();
  18196. progress = noop;
  18197. }
  18198. };
  18199. const success = url => {
  18200. closeNotification();
  18201. uploadStatus.markUploaded(blobInfo.blobUri(), url);
  18202. resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
  18203. resolve(handlerSuccess(blobInfo, url));
  18204. };
  18205. const failure = error => {
  18206. closeNotification();
  18207. uploadStatus.removeFailed(blobInfo.blobUri());
  18208. resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error));
  18209. resolve(handlerFailure(blobInfo, error));
  18210. };
  18211. progress = percent => {
  18212. if (percent < 0 || percent > 100) {
  18213. return;
  18214. }
  18215. Optional.from(notification).orThunk(() => Optional.from(openNotification).map(apply$1)).each(n => {
  18216. notification = n;
  18217. n.progressBar.value(percent);
  18218. });
  18219. };
  18220. handler(blobInfo, progress).then(success, err => {
  18221. failure(isString(err) ? { message: err } : err);
  18222. });
  18223. } catch (ex) {
  18224. resolve(handlerFailure(blobInfo, ex));
  18225. }
  18226. });
  18227. };
  18228. const isDefaultHandler = handler => handler === defaultHandler;
  18229. const pendingUploadBlobInfo = blobInfo => {
  18230. const blobUri = blobInfo.blobUri();
  18231. return new Promise(resolve => {
  18232. pendingPromises[blobUri] = pendingPromises[blobUri] || [];
  18233. pendingPromises[blobUri].push(resolve);
  18234. });
  18235. };
  18236. const uploadBlobs = (blobInfos, openNotification) => {
  18237. blobInfos = Tools.grep(blobInfos, blobInfo => !uploadStatus.isUploaded(blobInfo.blobUri()));
  18238. return Promise.all(Tools.map(blobInfos, blobInfo => uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification)));
  18239. };
  18240. const upload = (blobInfos, openNotification) => !settings.url && isDefaultHandler(settings.handler) ? noUpload() : uploadBlobs(blobInfos, openNotification);
  18241. if (isFunction(settings.handler) === false) {
  18242. settings.handler = defaultHandler;
  18243. }
  18244. return { upload };
  18245. };
  18246. const openNotification = editor => () => editor.notificationManager.open({
  18247. text: editor.translate('Image uploading...'),
  18248. type: 'info',
  18249. timeout: -1,
  18250. progressBar: true
  18251. });
  18252. const createUploader = (editor, uploadStatus) => Uploader(uploadStatus, {
  18253. url: getImageUploadUrl(editor),
  18254. basePath: getImageUploadBasePath(editor),
  18255. credentials: getImagesUploadCredentials(editor),
  18256. handler: getImagesUploadHandler(editor)
  18257. });
  18258. const ImageUploader = editor => {
  18259. const uploadStatus = UploadStatus();
  18260. const uploader = createUploader(editor, uploadStatus);
  18261. return { upload: (blobInfos, showNotification = true) => uploader.upload(blobInfos, showNotification ? openNotification(editor) : undefined) };
  18262. };
  18263. const UploadChangeHandler = editor => {
  18264. const lastChangedLevel = Cell(null);
  18265. editor.on('change AddUndo', e => {
  18266. lastChangedLevel.set({ ...e.level });
  18267. });
  18268. const fireIfChanged = () => {
  18269. const data = editor.undoManager.data;
  18270. last$3(data).filter(level => {
  18271. return !isEq$1(lastChangedLevel.get(), level);
  18272. }).each(level => {
  18273. editor.setDirty(true);
  18274. editor.dispatch('change', {
  18275. level,
  18276. lastLevel: get$b(data, data.length - 2).getOrNull()
  18277. });
  18278. });
  18279. };
  18280. return { fireIfChanged };
  18281. };
  18282. const EditorUpload = editor => {
  18283. const blobCache = BlobCache();
  18284. let uploader, imageScanner;
  18285. const uploadStatus = UploadStatus();
  18286. const urlFilters = [];
  18287. const changeHandler = UploadChangeHandler(editor);
  18288. const aliveGuard = callback => {
  18289. return result => {
  18290. if (editor.selection) {
  18291. return callback(result);
  18292. }
  18293. return [];
  18294. };
  18295. };
  18296. const cacheInvalidator = url => url + (url.indexOf('?') === -1 ? '?' : '&') + new Date().getTime();
  18297. const replaceString = (content, search, replace) => {
  18298. let index = 0;
  18299. do {
  18300. index = content.indexOf(search, index);
  18301. if (index !== -1) {
  18302. content = content.substring(0, index) + replace + content.substr(index + search.length);
  18303. index += replace.length - search.length + 1;
  18304. }
  18305. } while (index !== -1);
  18306. return content;
  18307. };
  18308. const replaceImageUrl = (content, targetUrl, replacementUrl) => {
  18309. const replacementString = `src="${ replacementUrl }"${ replacementUrl === Env.transparentSrc ? ' data-mce-placeholder="1"' : '' }`;
  18310. content = replaceString(content, `src="${ targetUrl }"`, replacementString);
  18311. content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
  18312. return content;
  18313. };
  18314. const replaceUrlInUndoStack = (targetUrl, replacementUrl) => {
  18315. each$g(editor.undoManager.data, level => {
  18316. if (level.type === 'fragmented') {
  18317. level.fragments = map$3(level.fragments, fragment => replaceImageUrl(fragment, targetUrl, replacementUrl));
  18318. } else {
  18319. level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
  18320. }
  18321. });
  18322. };
  18323. const replaceImageUriInView = (image, resultUri) => {
  18324. const src = editor.convertURL(resultUri, 'src');
  18325. replaceUrlInUndoStack(image.src, resultUri);
  18326. setAll$1(SugarElement.fromDom(image), {
  18327. 'src': shouldReuseFileName(editor) ? cacheInvalidator(resultUri) : resultUri,
  18328. 'data-mce-src': src
  18329. });
  18330. };
  18331. const uploadImages = () => {
  18332. if (!uploader) {
  18333. uploader = createUploader(editor, uploadStatus);
  18334. }
  18335. return scanForImages().then(aliveGuard(imageInfos => {
  18336. const blobInfos = map$3(imageInfos, imageInfo => imageInfo.blobInfo);
  18337. return uploader.upload(blobInfos, openNotification(editor)).then(aliveGuard(result => {
  18338. const imagesToRemove = [];
  18339. const filteredResult = map$3(result, (uploadInfo, index) => {
  18340. const blobInfo = imageInfos[index].blobInfo;
  18341. const image = imageInfos[index].image;
  18342. let removed = false;
  18343. if (uploadInfo.status && shouldReplaceBlobUris(editor)) {
  18344. blobCache.removeByUri(image.src);
  18345. if (isRtc(editor)) ; else {
  18346. replaceImageUriInView(image, uploadInfo.url);
  18347. }
  18348. } else if (uploadInfo.error) {
  18349. if (uploadInfo.error.remove) {
  18350. replaceUrlInUndoStack(image.getAttribute('src'), Env.transparentSrc);
  18351. imagesToRemove.push(image);
  18352. removed = true;
  18353. }
  18354. uploadError(editor, uploadInfo.error.message);
  18355. }
  18356. return {
  18357. element: image,
  18358. status: uploadInfo.status,
  18359. uploadUri: uploadInfo.url,
  18360. blobInfo,
  18361. removed
  18362. };
  18363. });
  18364. if (filteredResult.length > 0) {
  18365. changeHandler.fireIfChanged();
  18366. }
  18367. if (imagesToRemove.length > 0 && !isRtc(editor)) {
  18368. editor.undoManager.transact(() => {
  18369. each$g(imagesToRemove, element => {
  18370. editor.dom.remove(element);
  18371. blobCache.removeByUri(element.src);
  18372. });
  18373. });
  18374. }
  18375. return filteredResult;
  18376. }));
  18377. }));
  18378. };
  18379. const uploadImagesAuto = () => isAutomaticUploadsEnabled(editor) ? uploadImages() : Promise.resolve([]);
  18380. const isValidDataUriImage = imgElm => forall(urlFilters, filter => filter(imgElm));
  18381. const addFilter = filter => {
  18382. urlFilters.push(filter);
  18383. };
  18384. const scanForImages = () => {
  18385. if (!imageScanner) {
  18386. imageScanner = ImageScanner(uploadStatus, blobCache);
  18387. }
  18388. return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(result => {
  18389. result = filter$6(result, resultItem => {
  18390. if (typeof resultItem === 'string') {
  18391. displayError(editor, resultItem);
  18392. return false;
  18393. }
  18394. return true;
  18395. });
  18396. if (isRtc(editor)) ; else {
  18397. each$g(result, resultItem => {
  18398. replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
  18399. resultItem.image.src = resultItem.blobInfo.blobUri();
  18400. resultItem.image.removeAttribute('data-mce-src');
  18401. });
  18402. }
  18403. return result;
  18404. }));
  18405. };
  18406. const destroy = () => {
  18407. blobCache.destroy();
  18408. uploadStatus.destroy();
  18409. imageScanner = uploader = null;
  18410. };
  18411. const replaceBlobUris = content => {
  18412. return content.replace(/src="(blob:[^"]+)"/g, (match, blobUri) => {
  18413. const resultUri = uploadStatus.getResultUri(blobUri);
  18414. if (resultUri) {
  18415. return 'src="' + resultUri + '"';
  18416. }
  18417. let blobInfo = blobCache.getByUri(blobUri);
  18418. if (!blobInfo) {
  18419. blobInfo = foldl(editor.editorManager.get(), (result, editor) => {
  18420. return result || editor.editorUpload && editor.editorUpload.blobCache.getByUri(blobUri);
  18421. }, null);
  18422. }
  18423. if (blobInfo) {
  18424. const blob = blobInfo.blob();
  18425. return 'src="data:' + blob.type + ';base64,' + blobInfo.base64() + '"';
  18426. }
  18427. return match;
  18428. });
  18429. };
  18430. editor.on('SetContent', () => {
  18431. if (isAutomaticUploadsEnabled(editor)) {
  18432. uploadImagesAuto();
  18433. } else {
  18434. scanForImages();
  18435. }
  18436. });
  18437. editor.on('RawSaveContent', e => {
  18438. e.content = replaceBlobUris(e.content);
  18439. });
  18440. editor.on('GetContent', e => {
  18441. if (e.source_view || e.format === 'raw' || e.format === 'tree') {
  18442. return;
  18443. }
  18444. e.content = replaceBlobUris(e.content);
  18445. });
  18446. editor.on('PostRender', () => {
  18447. editor.parser.addNodeFilter('img', images => {
  18448. each$g(images, img => {
  18449. const src = img.attr('src');
  18450. if (blobCache.getByUri(src)) {
  18451. return;
  18452. }
  18453. const resultUri = uploadStatus.getResultUri(src);
  18454. if (resultUri) {
  18455. img.attr('src', resultUri);
  18456. }
  18457. });
  18458. });
  18459. });
  18460. return {
  18461. blobCache,
  18462. addFilter,
  18463. uploadImages,
  18464. uploadImagesAuto,
  18465. scanForImages,
  18466. destroy
  18467. };
  18468. };
  18469. const get$1 = editor => {
  18470. const dom = editor.dom;
  18471. const schemaType = editor.schema.type;
  18472. const formats = {
  18473. valigntop: [{
  18474. selector: 'td,th',
  18475. styles: { verticalAlign: 'top' }
  18476. }],
  18477. valignmiddle: [{
  18478. selector: 'td,th',
  18479. styles: { verticalAlign: 'middle' }
  18480. }],
  18481. valignbottom: [{
  18482. selector: 'td,th',
  18483. styles: { verticalAlign: 'bottom' }
  18484. }],
  18485. alignleft: [
  18486. {
  18487. selector: 'figure.image',
  18488. collapsed: false,
  18489. classes: 'align-left',
  18490. ceFalseOverride: true,
  18491. preview: 'font-family font-size'
  18492. },
  18493. {
  18494. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  18495. styles: { textAlign: 'left' },
  18496. inherit: false,
  18497. preview: false
  18498. },
  18499. {
  18500. selector: 'img,audio,video',
  18501. collapsed: false,
  18502. styles: { float: 'left' },
  18503. preview: 'font-family font-size'
  18504. },
  18505. {
  18506. selector: 'table',
  18507. collapsed: false,
  18508. styles: {
  18509. marginLeft: '0px',
  18510. marginRight: 'auto'
  18511. },
  18512. onformat: table => {
  18513. dom.setStyle(table, 'float', null);
  18514. },
  18515. preview: 'font-family font-size'
  18516. }
  18517. ],
  18518. aligncenter: [
  18519. {
  18520. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  18521. styles: { textAlign: 'center' },
  18522. inherit: false,
  18523. preview: 'font-family font-size'
  18524. },
  18525. {
  18526. selector: 'figure.image',
  18527. collapsed: false,
  18528. classes: 'align-center',
  18529. ceFalseOverride: true,
  18530. preview: 'font-family font-size'
  18531. },
  18532. {
  18533. selector: 'img,audio,video',
  18534. collapsed: false,
  18535. styles: {
  18536. display: 'block',
  18537. marginLeft: 'auto',
  18538. marginRight: 'auto'
  18539. },
  18540. preview: false
  18541. },
  18542. {
  18543. selector: 'table',
  18544. collapsed: false,
  18545. styles: {
  18546. marginLeft: 'auto',
  18547. marginRight: 'auto'
  18548. },
  18549. preview: 'font-family font-size'
  18550. }
  18551. ],
  18552. alignright: [
  18553. {
  18554. selector: 'figure.image',
  18555. collapsed: false,
  18556. classes: 'align-right',
  18557. ceFalseOverride: true,
  18558. preview: 'font-family font-size'
  18559. },
  18560. {
  18561. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  18562. styles: { textAlign: 'right' },
  18563. inherit: false,
  18564. preview: 'font-family font-size'
  18565. },
  18566. {
  18567. selector: 'img,audio,video',
  18568. collapsed: false,
  18569. styles: { float: 'right' },
  18570. preview: 'font-family font-size'
  18571. },
  18572. {
  18573. selector: 'table',
  18574. collapsed: false,
  18575. styles: {
  18576. marginRight: '0px',
  18577. marginLeft: 'auto'
  18578. },
  18579. onformat: table => {
  18580. dom.setStyle(table, 'float', null);
  18581. },
  18582. preview: 'font-family font-size'
  18583. }
  18584. ],
  18585. alignjustify: [{
  18586. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  18587. styles: { textAlign: 'justify' },
  18588. inherit: false,
  18589. preview: 'font-family font-size'
  18590. }],
  18591. bold: [
  18592. {
  18593. inline: 'strong',
  18594. remove: 'all',
  18595. preserve_attributes: [
  18596. 'class',
  18597. 'style'
  18598. ]
  18599. },
  18600. {
  18601. inline: 'span',
  18602. styles: { fontWeight: 'bold' }
  18603. },
  18604. {
  18605. inline: 'b',
  18606. remove: 'all',
  18607. preserve_attributes: [
  18608. 'class',
  18609. 'style'
  18610. ]
  18611. }
  18612. ],
  18613. italic: [
  18614. {
  18615. inline: 'em',
  18616. remove: 'all',
  18617. preserve_attributes: [
  18618. 'class',
  18619. 'style'
  18620. ]
  18621. },
  18622. {
  18623. inline: 'span',
  18624. styles: { fontStyle: 'italic' }
  18625. },
  18626. {
  18627. inline: 'i',
  18628. remove: 'all',
  18629. preserve_attributes: [
  18630. 'class',
  18631. 'style'
  18632. ]
  18633. }
  18634. ],
  18635. underline: [
  18636. {
  18637. inline: 'span',
  18638. styles: { textDecoration: 'underline' },
  18639. exact: true
  18640. },
  18641. {
  18642. inline: 'u',
  18643. remove: 'all',
  18644. preserve_attributes: [
  18645. 'class',
  18646. 'style'
  18647. ]
  18648. }
  18649. ],
  18650. strikethrough: (() => {
  18651. const span = {
  18652. inline: 'span',
  18653. styles: { textDecoration: 'line-through' },
  18654. exact: true
  18655. };
  18656. const strike = {
  18657. inline: 'strike',
  18658. remove: 'all',
  18659. preserve_attributes: [
  18660. 'class',
  18661. 'style'
  18662. ]
  18663. };
  18664. const s = {
  18665. inline: 's',
  18666. remove: 'all',
  18667. preserve_attributes: [
  18668. 'class',
  18669. 'style'
  18670. ]
  18671. };
  18672. return schemaType !== 'html4' ? [
  18673. s,
  18674. span,
  18675. strike
  18676. ] : [
  18677. span,
  18678. s,
  18679. strike
  18680. ];
  18681. })(),
  18682. forecolor: {
  18683. inline: 'span',
  18684. styles: { color: '%value' },
  18685. links: true,
  18686. remove_similar: true,
  18687. clear_child_styles: true
  18688. },
  18689. hilitecolor: {
  18690. inline: 'span',
  18691. styles: { backgroundColor: '%value' },
  18692. links: true,
  18693. remove_similar: true,
  18694. clear_child_styles: true
  18695. },
  18696. fontname: {
  18697. inline: 'span',
  18698. toggle: false,
  18699. styles: { fontFamily: '%value' },
  18700. clear_child_styles: true
  18701. },
  18702. fontsize: {
  18703. inline: 'span',
  18704. toggle: false,
  18705. styles: { fontSize: '%value' },
  18706. clear_child_styles: true
  18707. },
  18708. lineheight: {
  18709. selector: 'h1,h2,h3,h4,h5,h6,p,li,td,th,div',
  18710. styles: { lineHeight: '%value' }
  18711. },
  18712. fontsize_class: {
  18713. inline: 'span',
  18714. attributes: { class: '%value' }
  18715. },
  18716. blockquote: {
  18717. block: 'blockquote',
  18718. wrapper: true,
  18719. remove: 'all'
  18720. },
  18721. subscript: { inline: 'sub' },
  18722. superscript: { inline: 'sup' },
  18723. code: { inline: 'code' },
  18724. link: {
  18725. inline: 'a',
  18726. selector: 'a',
  18727. remove: 'all',
  18728. split: true,
  18729. deep: true,
  18730. onmatch: (node, _fmt, _itemName) => {
  18731. return isElement$6(node) && node.hasAttribute('href');
  18732. },
  18733. onformat: (elm, _fmt, vars) => {
  18734. Tools.each(vars, (value, key) => {
  18735. dom.setAttrib(elm, key, value);
  18736. });
  18737. }
  18738. },
  18739. lang: {
  18740. inline: 'span',
  18741. clear_child_styles: true,
  18742. remove_similar: true,
  18743. attributes: {
  18744. 'lang': '%value',
  18745. 'data-mce-lang': vars => {
  18746. var _a;
  18747. return (_a = vars === null || vars === void 0 ? void 0 : vars.customValue) !== null && _a !== void 0 ? _a : null;
  18748. }
  18749. }
  18750. },
  18751. removeformat: [
  18752. {
  18753. selector: 'b,strong,em,i,font,u,strike,s,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins,small',
  18754. remove: 'all',
  18755. split: true,
  18756. expand: false,
  18757. block_expand: true,
  18758. deep: true
  18759. },
  18760. {
  18761. selector: 'span',
  18762. attributes: [
  18763. 'style',
  18764. 'class'
  18765. ],
  18766. remove: 'empty',
  18767. split: true,
  18768. expand: false,
  18769. deep: true
  18770. },
  18771. {
  18772. selector: '*',
  18773. attributes: [
  18774. 'style',
  18775. 'class'
  18776. ],
  18777. split: false,
  18778. expand: false,
  18779. deep: true
  18780. }
  18781. ]
  18782. };
  18783. Tools.each('p h1 h2 h3 h4 h5 h6 div address pre dt dd samp'.split(/\s/), name => {
  18784. formats[name] = {
  18785. block: name,
  18786. remove: 'all'
  18787. };
  18788. });
  18789. return formats;
  18790. };
  18791. const genericBase = {
  18792. remove_similar: true,
  18793. inherit: false
  18794. };
  18795. const cellBase = {
  18796. selector: 'td,th',
  18797. ...genericBase
  18798. };
  18799. const cellFormats = {
  18800. tablecellbackgroundcolor: {
  18801. styles: { backgroundColor: '%value' },
  18802. ...cellBase
  18803. },
  18804. tablecellverticalalign: {
  18805. styles: { 'vertical-align': '%value' },
  18806. ...cellBase
  18807. },
  18808. tablecellbordercolor: {
  18809. styles: { borderColor: '%value' },
  18810. ...cellBase
  18811. },
  18812. tablecellclass: {
  18813. classes: ['%value'],
  18814. ...cellBase
  18815. },
  18816. tableclass: {
  18817. selector: 'table',
  18818. classes: ['%value'],
  18819. ...genericBase
  18820. },
  18821. tablecellborderstyle: {
  18822. styles: { borderStyle: '%value' },
  18823. ...cellBase
  18824. },
  18825. tablecellborderwidth: {
  18826. styles: { borderWidth: '%value' },
  18827. ...cellBase
  18828. }
  18829. };
  18830. const get = constant(cellFormats);
  18831. const FormatRegistry = editor => {
  18832. const formats = {};
  18833. const get$2 = name => isNonNullable(name) ? formats[name] : formats;
  18834. const has = name => has$2(formats, name);
  18835. const register = (name, format) => {
  18836. if (name) {
  18837. if (!isString(name)) {
  18838. each$f(name, (format, name) => {
  18839. register(name, format);
  18840. });
  18841. } else {
  18842. if (!isArray$1(format)) {
  18843. format = [format];
  18844. }
  18845. each$g(format, format => {
  18846. if (isUndefined(format.deep)) {
  18847. format.deep = !isSelectorFormat(format);
  18848. }
  18849. if (isUndefined(format.split)) {
  18850. format.split = !isSelectorFormat(format) || isInlineFormat(format);
  18851. }
  18852. if (isUndefined(format.remove) && isSelectorFormat(format) && !isInlineFormat(format)) {
  18853. format.remove = 'none';
  18854. }
  18855. if (isSelectorFormat(format) && isInlineFormat(format)) {
  18856. format.mixed = true;
  18857. format.block_expand = true;
  18858. }
  18859. if (isString(format.classes)) {
  18860. format.classes = format.classes.split(/\s+/);
  18861. }
  18862. });
  18863. formats[name] = format;
  18864. }
  18865. }
  18866. };
  18867. const unregister = name => {
  18868. if (name && formats[name]) {
  18869. delete formats[name];
  18870. }
  18871. return formats;
  18872. };
  18873. register(get$1(editor));
  18874. register(get());
  18875. register(getFormats(editor));
  18876. return {
  18877. get: get$2,
  18878. has,
  18879. register,
  18880. unregister
  18881. };
  18882. };
  18883. const each$3 = Tools.each;
  18884. const dom = DOMUtils.DOM;
  18885. const parsedSelectorToHtml = (ancestry, editor) => {
  18886. let elm, item, fragment;
  18887. const schema = editor && editor.schema || Schema({});
  18888. const decorate = (elm, item) => {
  18889. if (item.classes.length) {
  18890. dom.addClass(elm, item.classes.join(' '));
  18891. }
  18892. dom.setAttribs(elm, item.attrs);
  18893. };
  18894. const createElement = sItem => {
  18895. item = typeof sItem === 'string' ? {
  18896. name: sItem,
  18897. classes: [],
  18898. attrs: {}
  18899. } : sItem;
  18900. const elm = dom.create(item.name);
  18901. decorate(elm, item);
  18902. return elm;
  18903. };
  18904. const getRequiredParent = (elm, candidate) => {
  18905. const name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm;
  18906. const elmRule = schema.getElementRule(name);
  18907. const parentsRequired = elmRule && elmRule.parentsRequired;
  18908. if (parentsRequired && parentsRequired.length) {
  18909. return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
  18910. } else {
  18911. return false;
  18912. }
  18913. };
  18914. const wrapInHtml = (elm, ancestry, siblings) => {
  18915. let parent, parentCandidate;
  18916. const ancestor = ancestry.length > 0 && ancestry[0];
  18917. const ancestorName = ancestor && ancestor.name;
  18918. const parentRequired = getRequiredParent(elm, ancestorName);
  18919. if (parentRequired) {
  18920. if (ancestorName === parentRequired) {
  18921. parentCandidate = ancestry[0];
  18922. ancestry = ancestry.slice(1);
  18923. } else {
  18924. parentCandidate = parentRequired;
  18925. }
  18926. } else if (ancestor) {
  18927. parentCandidate = ancestry[0];
  18928. ancestry = ancestry.slice(1);
  18929. } else if (!siblings) {
  18930. return elm;
  18931. }
  18932. if (parentCandidate) {
  18933. parent = createElement(parentCandidate);
  18934. parent.appendChild(elm);
  18935. }
  18936. if (siblings) {
  18937. if (!parent) {
  18938. parent = dom.create('div');
  18939. parent.appendChild(elm);
  18940. }
  18941. Tools.each(siblings, sibling => {
  18942. const siblingElm = createElement(sibling);
  18943. parent.insertBefore(siblingElm, elm);
  18944. });
  18945. }
  18946. return wrapInHtml(parent, ancestry, parentCandidate && parentCandidate.siblings);
  18947. };
  18948. if (ancestry && ancestry.length) {
  18949. item = ancestry[0];
  18950. elm = createElement(item);
  18951. fragment = dom.create('div');
  18952. fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
  18953. return fragment;
  18954. } else {
  18955. return '';
  18956. }
  18957. };
  18958. const parseSelectorItem = item => {
  18959. let tagName;
  18960. const obj = {
  18961. classes: [],
  18962. attrs: {}
  18963. };
  18964. item = obj.selector = Tools.trim(item);
  18965. if (item !== '*') {
  18966. tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, ($0, $1, $2, $3, $4) => {
  18967. switch ($1) {
  18968. case '#':
  18969. obj.attrs.id = $2;
  18970. break;
  18971. case '.':
  18972. obj.classes.push($2);
  18973. break;
  18974. case ':':
  18975. if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
  18976. obj.attrs[$2] = $2;
  18977. }
  18978. break;
  18979. }
  18980. if ($3 === '[') {
  18981. const m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
  18982. if (m) {
  18983. obj.attrs[m[1]] = m[2];
  18984. }
  18985. }
  18986. return '';
  18987. });
  18988. }
  18989. obj.name = tagName || 'div';
  18990. return obj;
  18991. };
  18992. const parseSelector = selector => {
  18993. if (!selector || typeof selector !== 'string') {
  18994. return [];
  18995. }
  18996. selector = selector.split(/\s*,\s*/)[0];
  18997. selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1');
  18998. return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), item => {
  18999. const siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
  19000. const obj = siblings.pop();
  19001. if (siblings.length) {
  19002. obj.siblings = siblings;
  19003. }
  19004. return obj;
  19005. }).reverse();
  19006. };
  19007. const getCssText = (editor, format) => {
  19008. let name, previewFrag;
  19009. let previewCss = '', parentFontSize;
  19010. let previewStyles = getPreviewStyles(editor);
  19011. if (previewStyles === '') {
  19012. return '';
  19013. }
  19014. const removeVars = val => {
  19015. return val.replace(/%(\w+)/g, '');
  19016. };
  19017. if (typeof format === 'string') {
  19018. format = editor.formatter.get(format);
  19019. if (!format) {
  19020. return;
  19021. }
  19022. format = format[0];
  19023. }
  19024. if ('preview' in format) {
  19025. const previewOpt = get$a(format, 'preview');
  19026. if (is$2(previewOpt, false)) {
  19027. return '';
  19028. } else {
  19029. previewStyles = previewOpt.getOr(previewStyles);
  19030. }
  19031. }
  19032. name = format.block || format.inline || 'span';
  19033. const items = parseSelector(format.selector);
  19034. if (items.length) {
  19035. if (!items[0].name) {
  19036. items[0].name = name;
  19037. }
  19038. name = format.selector;
  19039. previewFrag = parsedSelectorToHtml(items, editor);
  19040. } else {
  19041. previewFrag = parsedSelectorToHtml([name], editor);
  19042. }
  19043. const previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;
  19044. each$3(format.styles, (value, name) => {
  19045. const newValue = removeVars(value);
  19046. if (newValue) {
  19047. dom.setStyle(previewElm, name, newValue);
  19048. }
  19049. });
  19050. each$3(format.attributes, (value, name) => {
  19051. const newValue = removeVars(value);
  19052. if (newValue) {
  19053. dom.setAttrib(previewElm, name, newValue);
  19054. }
  19055. });
  19056. each$3(format.classes, value => {
  19057. const newValue = removeVars(value);
  19058. if (!dom.hasClass(previewElm, newValue)) {
  19059. dom.addClass(previewElm, newValue);
  19060. }
  19061. });
  19062. editor.dispatch('PreviewFormats');
  19063. dom.setStyles(previewFrag, {
  19064. position: 'absolute',
  19065. left: -65535
  19066. });
  19067. editor.getBody().appendChild(previewFrag);
  19068. parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
  19069. parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
  19070. each$3(previewStyles.split(' '), name => {
  19071. let value = dom.getStyle(previewElm, name, true);
  19072. if (name === 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
  19073. value = dom.getStyle(editor.getBody(), name, true);
  19074. if (rgbaToHexString(value).toLowerCase() === '#ffffff') {
  19075. return;
  19076. }
  19077. }
  19078. if (name === 'color') {
  19079. if (rgbaToHexString(value).toLowerCase() === '#000000') {
  19080. return;
  19081. }
  19082. }
  19083. if (name === 'font-size') {
  19084. if (/em|%$/.test(value)) {
  19085. if (parentFontSize === 0) {
  19086. return;
  19087. }
  19088. const numValue = parseFloat(value) / (/%$/.test(value) ? 100 : 1);
  19089. value = numValue * parentFontSize + 'px';
  19090. }
  19091. }
  19092. if (name === 'border' && value) {
  19093. previewCss += 'padding:0 2px;';
  19094. }
  19095. previewCss += name + ':' + value + ';';
  19096. });
  19097. editor.dispatch('AfterPreviewFormats');
  19098. dom.remove(previewFrag);
  19099. return previewCss;
  19100. };
  19101. const setup$r = editor => {
  19102. editor.addShortcut('meta+b', '', 'Bold');
  19103. editor.addShortcut('meta+i', '', 'Italic');
  19104. editor.addShortcut('meta+u', '', 'Underline');
  19105. for (let i = 1; i <= 6; i++) {
  19106. editor.addShortcut('access+' + i, '', [
  19107. 'FormatBlock',
  19108. false,
  19109. 'h' + i
  19110. ]);
  19111. }
  19112. editor.addShortcut('access+7', '', [
  19113. 'FormatBlock',
  19114. false,
  19115. 'p'
  19116. ]);
  19117. editor.addShortcut('access+8', '', [
  19118. 'FormatBlock',
  19119. false,
  19120. 'div'
  19121. ]);
  19122. editor.addShortcut('access+9', '', [
  19123. 'FormatBlock',
  19124. false,
  19125. 'address'
  19126. ]);
  19127. };
  19128. const Formatter = editor => {
  19129. const formats = FormatRegistry(editor);
  19130. const formatChangeState = Cell(null);
  19131. setup$r(editor);
  19132. setup$u(editor);
  19133. return {
  19134. get: formats.get,
  19135. has: formats.has,
  19136. register: formats.register,
  19137. unregister: formats.unregister,
  19138. apply: (name, vars, node) => {
  19139. applyFormat(editor, name, vars, node);
  19140. },
  19141. remove: (name, vars, node, similar) => {
  19142. removeFormat(editor, name, vars, node, similar);
  19143. },
  19144. toggle: (name, vars, node) => {
  19145. toggleFormat(editor, name, vars, node);
  19146. },
  19147. match: (name, vars, node, similar) => matchFormat(editor, name, vars, node, similar),
  19148. closest: names => closestFormat(editor, names),
  19149. matchAll: (names, vars) => matchAllFormats(editor, names, vars),
  19150. matchNode: (node, name, vars, similar) => matchNodeFormat(editor, node, name, vars, similar),
  19151. canApply: name => canApplyFormat(editor, name),
  19152. formatChanged: (formats, callback, similar, vars) => formatChanged(editor, formatChangeState, formats, callback, similar, vars),
  19153. getCssText: curry(getCssText, editor)
  19154. };
  19155. };
  19156. const shouldIgnoreCommand = cmd => {
  19157. switch (cmd.toLowerCase()) {
  19158. case 'undo':
  19159. case 'redo':
  19160. case 'mcefocus':
  19161. return true;
  19162. default:
  19163. return false;
  19164. }
  19165. };
  19166. const registerEvents = (editor, undoManager, locks) => {
  19167. const isFirstTypedCharacter = Cell(false);
  19168. const addNonTypingUndoLevel = e => {
  19169. setTyping(undoManager, false, locks);
  19170. undoManager.add({}, e);
  19171. };
  19172. editor.on('init', () => {
  19173. undoManager.add();
  19174. });
  19175. editor.on('BeforeExecCommand', e => {
  19176. const cmd = e.command;
  19177. if (!shouldIgnoreCommand(cmd)) {
  19178. endTyping(undoManager, locks);
  19179. undoManager.beforeChange();
  19180. }
  19181. });
  19182. editor.on('ExecCommand', e => {
  19183. const cmd = e.command;
  19184. if (!shouldIgnoreCommand(cmd)) {
  19185. addNonTypingUndoLevel(e);
  19186. }
  19187. });
  19188. editor.on('ObjectResizeStart cut', () => {
  19189. undoManager.beforeChange();
  19190. });
  19191. editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
  19192. editor.on('dragend', addNonTypingUndoLevel);
  19193. editor.on('keyup', e => {
  19194. const keyCode = e.keyCode;
  19195. if (e.isDefaultPrevented()) {
  19196. return;
  19197. }
  19198. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45 || e.ctrlKey) {
  19199. addNonTypingUndoLevel();
  19200. editor.nodeChanged();
  19201. }
  19202. if (keyCode === 46 || keyCode === 8) {
  19203. editor.nodeChanged();
  19204. }
  19205. if (isFirstTypedCharacter.get() && undoManager.typing && isEq$1(createFromEditor(editor), undoManager.data[0]) === false) {
  19206. if (editor.isDirty() === false) {
  19207. editor.setDirty(true);
  19208. }
  19209. editor.dispatch('TypingUndo');
  19210. isFirstTypedCharacter.set(false);
  19211. editor.nodeChanged();
  19212. }
  19213. });
  19214. editor.on('keydown', e => {
  19215. const keyCode = e.keyCode;
  19216. if (e.isDefaultPrevented()) {
  19217. return;
  19218. }
  19219. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45) {
  19220. if (undoManager.typing) {
  19221. addNonTypingUndoLevel(e);
  19222. }
  19223. return;
  19224. }
  19225. const modKey = e.ctrlKey && !e.altKey || e.metaKey;
  19226. if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !undoManager.typing && !modKey) {
  19227. undoManager.beforeChange();
  19228. setTyping(undoManager, true, locks);
  19229. undoManager.add({}, e);
  19230. isFirstTypedCharacter.set(true);
  19231. }
  19232. });
  19233. editor.on('mousedown', e => {
  19234. if (undoManager.typing) {
  19235. addNonTypingUndoLevel(e);
  19236. }
  19237. });
  19238. const isInsertReplacementText = event => event.inputType === 'insertReplacementText';
  19239. const isInsertTextDataNull = event => event.inputType === 'insertText' && event.data === null;
  19240. const isInsertFromPasteOrDrop = event => event.inputType === 'insertFromPaste' || event.inputType === 'insertFromDrop';
  19241. editor.on('input', e => {
  19242. if (e.inputType && (isInsertReplacementText(e) || isInsertTextDataNull(e) || isInsertFromPasteOrDrop(e))) {
  19243. addNonTypingUndoLevel(e);
  19244. }
  19245. });
  19246. editor.on('AddUndo Undo Redo ClearUndos', e => {
  19247. if (!e.isDefaultPrevented()) {
  19248. editor.nodeChanged();
  19249. }
  19250. });
  19251. };
  19252. const addKeyboardShortcuts = editor => {
  19253. editor.addShortcut('meta+z', '', 'Undo');
  19254. editor.addShortcut('meta+y,meta+shift+z', '', 'Redo');
  19255. };
  19256. const UndoManager = editor => {
  19257. const beforeBookmark = value$2();
  19258. const locks = Cell(0);
  19259. const index = Cell(0);
  19260. const undoManager = {
  19261. data: [],
  19262. typing: false,
  19263. beforeChange: () => {
  19264. beforeChange(editor, locks, beforeBookmark);
  19265. },
  19266. add: (level, event) => {
  19267. return addUndoLevel(editor, undoManager, index, locks, beforeBookmark, level, event);
  19268. },
  19269. undo: () => {
  19270. return undo(editor, undoManager, locks, index);
  19271. },
  19272. redo: () => {
  19273. return redo(editor, index, undoManager.data);
  19274. },
  19275. clear: () => {
  19276. clear(editor, undoManager, index);
  19277. },
  19278. reset: () => {
  19279. reset(editor, undoManager);
  19280. },
  19281. hasUndo: () => {
  19282. return hasUndo(editor, undoManager, index);
  19283. },
  19284. hasRedo: () => {
  19285. return hasRedo(editor, undoManager, index);
  19286. },
  19287. transact: callback => {
  19288. return transact(editor, undoManager, locks, callback);
  19289. },
  19290. ignore: callback => {
  19291. ignore(editor, locks, callback);
  19292. },
  19293. extra: (callback1, callback2) => {
  19294. extra(editor, undoManager, index, callback1, callback2);
  19295. }
  19296. };
  19297. if (!isRtc(editor)) {
  19298. registerEvents(editor, undoManager, locks);
  19299. }
  19300. addKeyboardShortcuts(editor);
  19301. return undoManager;
  19302. };
  19303. const nonTypingKeycodes = [
  19304. 9,
  19305. 27,
  19306. VK.HOME,
  19307. VK.END,
  19308. 19,
  19309. 20,
  19310. 44,
  19311. 144,
  19312. 145,
  19313. 33,
  19314. 34,
  19315. 45,
  19316. 16,
  19317. 17,
  19318. 18,
  19319. 91,
  19320. 92,
  19321. 93,
  19322. VK.DOWN,
  19323. VK.UP,
  19324. VK.LEFT,
  19325. VK.RIGHT
  19326. ].concat(Env.browser.isFirefox() ? [224] : []);
  19327. const placeholderAttr = 'data-mce-placeholder';
  19328. const isKeyboardEvent = e => e.type === 'keydown' || e.type === 'keyup';
  19329. const isDeleteEvent = e => {
  19330. const keyCode = e.keyCode;
  19331. return keyCode === VK.BACKSPACE || keyCode === VK.DELETE;
  19332. };
  19333. const isNonTypingKeyboardEvent = e => {
  19334. if (isKeyboardEvent(e)) {
  19335. const keyCode = e.keyCode;
  19336. return !isDeleteEvent(e) && (VK.metaKeyPressed(e) || e.altKey || keyCode >= 112 && keyCode <= 123 || contains$2(nonTypingKeycodes, keyCode));
  19337. } else {
  19338. return false;
  19339. }
  19340. };
  19341. const isTypingKeyboardEvent = e => isKeyboardEvent(e) && !(isDeleteEvent(e) || e.type === 'keyup' && e.keyCode === 229);
  19342. const isVisuallyEmpty = (dom, rootElm, forcedRootBlock) => {
  19343. if (isEmpty$2(SugarElement.fromDom(rootElm), false)) {
  19344. const firstElement = rootElm.firstElementChild;
  19345. if (!firstElement) {
  19346. return true;
  19347. } else if (dom.getStyle(rootElm.firstElementChild, 'padding-left') || dom.getStyle(rootElm.firstElementChild, 'padding-right')) {
  19348. return false;
  19349. } else {
  19350. return forcedRootBlock === firstElement.nodeName.toLowerCase();
  19351. }
  19352. } else {
  19353. return false;
  19354. }
  19355. };
  19356. const setup$q = editor => {
  19357. const dom = editor.dom;
  19358. const rootBlock = getForcedRootBlock(editor);
  19359. const placeholder = getPlaceholder(editor);
  19360. const updatePlaceholder = (e, initial) => {
  19361. if (isNonTypingKeyboardEvent(e)) {
  19362. return;
  19363. }
  19364. const body = editor.getBody();
  19365. const showPlaceholder = isTypingKeyboardEvent(e) ? false : isVisuallyEmpty(dom, body, rootBlock);
  19366. const isPlaceholderShown = dom.getAttrib(body, placeholderAttr) !== '';
  19367. if (isPlaceholderShown !== showPlaceholder || initial) {
  19368. dom.setAttrib(body, placeholderAttr, showPlaceholder ? placeholder : null);
  19369. dom.setAttrib(body, 'aria-placeholder', showPlaceholder ? placeholder : null);
  19370. firePlaceholderToggle(editor, showPlaceholder);
  19371. editor.on(showPlaceholder ? 'keydown' : 'keyup', updatePlaceholder);
  19372. editor.off(showPlaceholder ? 'keyup' : 'keydown', updatePlaceholder);
  19373. }
  19374. };
  19375. if (placeholder) {
  19376. editor.on('init', e => {
  19377. updatePlaceholder(e, true);
  19378. editor.on('change SetContent ExecCommand', updatePlaceholder);
  19379. editor.on('paste', e => Delay.setEditorTimeout(editor, () => updatePlaceholder(e)));
  19380. });
  19381. }
  19382. };
  19383. const strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
  19384. const hasStrongRtl = text => strongRtl.test(text);
  19385. const isInlineTarget = (editor, elm) => is$1(SugarElement.fromDom(elm), getInlineBoundarySelector(editor));
  19386. const isRtl = element => DOMUtils.DOM.getStyle(element, 'direction', true) === 'rtl' || hasStrongRtl(element.textContent);
  19387. const findInlineParents = (isInlineTarget, rootNode, pos) => filter$6(DOMUtils.DOM.getParents(pos.container(), '*', rootNode), isInlineTarget);
  19388. const findRootInline = (isInlineTarget, rootNode, pos) => {
  19389. const parents = findInlineParents(isInlineTarget, rootNode, pos);
  19390. return Optional.from(parents[parents.length - 1]);
  19391. };
  19392. const hasSameParentBlock = (rootNode, node1, node2) => {
  19393. const block1 = getParentBlock$3(node1, rootNode);
  19394. const block2 = getParentBlock$3(node2, rootNode);
  19395. return block1 && block1 === block2;
  19396. };
  19397. const isAtZwsp = pos => isBeforeInline(pos) || isAfterInline(pos);
  19398. const normalizePosition = (forward, pos) => {
  19399. if (!pos) {
  19400. return pos;
  19401. }
  19402. const container = pos.container(), offset = pos.offset();
  19403. if (forward) {
  19404. if (isCaretContainerInline(container)) {
  19405. if (isText$8(container.nextSibling)) {
  19406. return CaretPosition(container.nextSibling, 0);
  19407. } else {
  19408. return CaretPosition.after(container);
  19409. }
  19410. } else {
  19411. return isBeforeInline(pos) ? CaretPosition(container, offset + 1) : pos;
  19412. }
  19413. } else {
  19414. if (isCaretContainerInline(container)) {
  19415. if (isText$8(container.previousSibling)) {
  19416. return CaretPosition(container.previousSibling, container.previousSibling.data.length);
  19417. } else {
  19418. return CaretPosition.before(container);
  19419. }
  19420. } else {
  19421. return isAfterInline(pos) ? CaretPosition(container, offset - 1) : pos;
  19422. }
  19423. }
  19424. };
  19425. const normalizeForwards = curry(normalizePosition, true);
  19426. const normalizeBackwards = curry(normalizePosition, false);
  19427. const execCommandIgnoreInputEvents = (editor, command) => {
  19428. const inputBlocker = e => e.stopImmediatePropagation();
  19429. editor.on('beforeinput input', inputBlocker, true);
  19430. editor.getDoc().execCommand(command);
  19431. editor.off('beforeinput input', inputBlocker);
  19432. };
  19433. const execDeleteCommand = editor => execCommandIgnoreInputEvents(editor, 'Delete');
  19434. const execForwardDeleteCommand = editor => execCommandIgnoreInputEvents(editor, 'ForwardDelete');
  19435. const isBeforeRoot = rootNode => elm => eq(rootNode, SugarElement.fromDom(elm.dom.parentNode));
  19436. const isTextBlockOrListItem = element => isTextBlock$2(element) || isListItem(element);
  19437. const getParentBlock$2 = (rootNode, elm) => {
  19438. if (contains(rootNode, elm)) {
  19439. return closest$4(elm, isTextBlockOrListItem, isBeforeRoot(rootNode));
  19440. } else {
  19441. return Optional.none();
  19442. }
  19443. };
  19444. const placeCaretInEmptyBody = editor => {
  19445. const body = editor.getBody();
  19446. const node = body.firstChild && editor.dom.isBlock(body.firstChild) ? body.firstChild : body;
  19447. editor.selection.setCursorLocation(node, 0);
  19448. };
  19449. const paddEmptyBody = editor => {
  19450. if (editor.dom.isEmpty(editor.getBody())) {
  19451. editor.setContent('');
  19452. placeCaretInEmptyBody(editor);
  19453. }
  19454. };
  19455. const willDeleteLastPositionInElement = (forward, fromPos, elm) => lift2(firstPositionIn(elm), lastPositionIn(elm), (firstPos, lastPos) => {
  19456. const normalizedFirstPos = normalizePosition(true, firstPos);
  19457. const normalizedLastPos = normalizePosition(false, lastPos);
  19458. const normalizedFromPos = normalizePosition(false, fromPos);
  19459. if (forward) {
  19460. return nextPosition(elm, normalizedFromPos).exists(nextPos => nextPos.isEqual(normalizedLastPos) && fromPos.isEqual(normalizedFirstPos));
  19461. } else {
  19462. return prevPosition(elm, normalizedFromPos).exists(prevPos => prevPos.isEqual(normalizedFirstPos) && fromPos.isEqual(normalizedLastPos));
  19463. }
  19464. }).getOr(true);
  19465. const blockPosition = (block, position) => ({
  19466. block,
  19467. position
  19468. });
  19469. const blockBoundary = (from, to) => ({
  19470. from,
  19471. to
  19472. });
  19473. const getBlockPosition = (rootNode, pos) => {
  19474. const rootElm = SugarElement.fromDom(rootNode);
  19475. const containerElm = SugarElement.fromDom(pos.container());
  19476. return getParentBlock$2(rootElm, containerElm).map(block => blockPosition(block, pos));
  19477. };
  19478. const isDifferentBlocks = blockBoundary => eq(blockBoundary.from.block, blockBoundary.to.block) === false;
  19479. const hasSameParent = blockBoundary => parent(blockBoundary.from.block).bind(parent1 => parent(blockBoundary.to.block).filter(parent2 => eq(parent1, parent2))).isSome();
  19480. const isEditable$2 = blockBoundary => isContentEditableFalse$a(blockBoundary.from.block.dom) === false && isContentEditableFalse$a(blockBoundary.to.block.dom) === false;
  19481. const skipLastBr = (rootNode, forward, blockPosition) => {
  19482. if (isBr$5(blockPosition.position.getNode()) && isEmpty$2(blockPosition.block) === false) {
  19483. return positionIn(false, blockPosition.block.dom).bind(lastPositionInBlock => {
  19484. if (lastPositionInBlock.isEqual(blockPosition.position)) {
  19485. return fromPosition(forward, rootNode, lastPositionInBlock).bind(to => getBlockPosition(rootNode, to));
  19486. } else {
  19487. return Optional.some(blockPosition);
  19488. }
  19489. }).getOr(blockPosition);
  19490. } else {
  19491. return blockPosition;
  19492. }
  19493. };
  19494. const readFromRange = (rootNode, forward, rng) => {
  19495. const fromBlockPos = getBlockPosition(rootNode, CaretPosition.fromRangeStart(rng));
  19496. const toBlockPos = fromBlockPos.bind(blockPos => fromPosition(forward, rootNode, blockPos.position).bind(to => getBlockPosition(rootNode, to).map(blockPos => skipLastBr(rootNode, forward, blockPos))));
  19497. return lift2(fromBlockPos, toBlockPos, blockBoundary).filter(blockBoundary => isDifferentBlocks(blockBoundary) && hasSameParent(blockBoundary) && isEditable$2(blockBoundary));
  19498. };
  19499. const read$1 = (rootNode, forward, rng) => rng.collapsed ? readFromRange(rootNode, forward, rng) : Optional.none();
  19500. const getChildrenUntilBlockBoundary = block => {
  19501. const children$1 = children(block);
  19502. return findIndex$2(children$1, isBlock$2).fold(constant(children$1), index => children$1.slice(0, index));
  19503. };
  19504. const extractChildren = block => {
  19505. const children = getChildrenUntilBlockBoundary(block);
  19506. each$g(children, remove$5);
  19507. return children;
  19508. };
  19509. const removeEmptyRoot = (rootNode, block) => {
  19510. const parents = parentsAndSelf(block, rootNode);
  19511. return find$2(parents.reverse(), element => isEmpty$2(element)).each(remove$5);
  19512. };
  19513. const isEmptyBefore = el => filter$6(prevSiblings(el), el => !isEmpty$2(el)).length === 0;
  19514. const nestedBlockMerge = (rootNode, fromBlock, toBlock, insertionPoint) => {
  19515. if (isEmpty$2(toBlock)) {
  19516. fillWithPaddingBr(toBlock);
  19517. return firstPositionIn(toBlock.dom);
  19518. }
  19519. if (isEmptyBefore(insertionPoint) && isEmpty$2(fromBlock)) {
  19520. before$3(insertionPoint, SugarElement.fromTag('br'));
  19521. }
  19522. const position = prevPosition(toBlock.dom, CaretPosition.before(insertionPoint.dom));
  19523. each$g(extractChildren(fromBlock), child => {
  19524. before$3(insertionPoint, child);
  19525. });
  19526. removeEmptyRoot(rootNode, fromBlock);
  19527. return position;
  19528. };
  19529. const sidelongBlockMerge = (rootNode, fromBlock, toBlock) => {
  19530. if (isEmpty$2(toBlock)) {
  19531. remove$5(toBlock);
  19532. if (isEmpty$2(fromBlock)) {
  19533. fillWithPaddingBr(fromBlock);
  19534. }
  19535. return firstPositionIn(fromBlock.dom);
  19536. }
  19537. const position = lastPositionIn(toBlock.dom);
  19538. each$g(extractChildren(fromBlock), child => {
  19539. append$1(toBlock, child);
  19540. });
  19541. removeEmptyRoot(rootNode, fromBlock);
  19542. return position;
  19543. };
  19544. const findInsertionPoint = (toBlock, block) => {
  19545. const parentsAndSelf$1 = parentsAndSelf(block, toBlock);
  19546. return Optional.from(parentsAndSelf$1[parentsAndSelf$1.length - 1]);
  19547. };
  19548. const getInsertionPoint = (fromBlock, toBlock) => contains(toBlock, fromBlock) ? findInsertionPoint(toBlock, fromBlock) : Optional.none();
  19549. const trimBr = (first, block) => {
  19550. positionIn(first, block.dom).map(position => position.getNode()).map(SugarElement.fromDom).filter(isBr$4).each(remove$5);
  19551. };
  19552. const mergeBlockInto = (rootNode, fromBlock, toBlock) => {
  19553. trimBr(true, fromBlock);
  19554. trimBr(false, toBlock);
  19555. return getInsertionPoint(fromBlock, toBlock).fold(curry(sidelongBlockMerge, rootNode, fromBlock, toBlock), curry(nestedBlockMerge, rootNode, fromBlock, toBlock));
  19556. };
  19557. const mergeBlocks = (rootNode, forward, block1, block2) => forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
  19558. const backspaceDelete$8 = (editor, forward) => {
  19559. const rootNode = SugarElement.fromDom(editor.getBody());
  19560. const position = read$1(rootNode.dom, forward, editor.selection.getRng()).map(blockBoundary => () => {
  19561. mergeBlocks(rootNode, forward, blockBoundary.from.block, blockBoundary.to.block).each(pos => {
  19562. editor.selection.setRng(pos.toRange());
  19563. });
  19564. });
  19565. return position;
  19566. };
  19567. const deleteRangeMergeBlocks = (rootNode, selection) => {
  19568. const rng = selection.getRng();
  19569. return lift2(getParentBlock$2(rootNode, SugarElement.fromDom(rng.startContainer)), getParentBlock$2(rootNode, SugarElement.fromDom(rng.endContainer)), (block1, block2) => {
  19570. if (eq(block1, block2) === false) {
  19571. return Optional.some(() => {
  19572. rng.deleteContents();
  19573. mergeBlocks(rootNode, true, block1, block2).each(pos => {
  19574. selection.setRng(pos.toRange());
  19575. });
  19576. });
  19577. } else {
  19578. return Optional.none();
  19579. }
  19580. }).getOr(Optional.none());
  19581. };
  19582. const isRawNodeInTable = (root, rawNode) => {
  19583. const node = SugarElement.fromDom(rawNode);
  19584. const isRoot = curry(eq, root);
  19585. return ancestor$3(node, isTableCell$4, isRoot).isSome();
  19586. };
  19587. const isSelectionInTable = (root, rng) => isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
  19588. const isEverythingSelected = (root, rng) => {
  19589. const noPrevious = prevPosition(root.dom, CaretPosition.fromRangeStart(rng)).isNone();
  19590. const noNext = nextPosition(root.dom, CaretPosition.fromRangeEnd(rng)).isNone();
  19591. return !isSelectionInTable(root, rng) && noPrevious && noNext;
  19592. };
  19593. const emptyEditor = editor => {
  19594. return Optional.some(() => {
  19595. editor.setContent('');
  19596. editor.selection.setCursorLocation();
  19597. });
  19598. };
  19599. const deleteRange$1 = editor => {
  19600. const rootNode = SugarElement.fromDom(editor.getBody());
  19601. const rng = editor.selection.getRng();
  19602. return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
  19603. };
  19604. const backspaceDelete$7 = (editor, _forward) => editor.selection.isCollapsed() ? Optional.none() : deleteRange$1(editor);
  19605. const isContentEditableTrue$1 = isContentEditableTrue$4;
  19606. const isContentEditableFalse$4 = isContentEditableFalse$a;
  19607. const showCaret = (direction, editor, node, before, scrollIntoView) => Optional.from(editor._selectionOverrides.showCaret(direction, node, before, scrollIntoView));
  19608. const getNodeRange = node => {
  19609. const rng = node.ownerDocument.createRange();
  19610. rng.selectNode(node);
  19611. return rng;
  19612. };
  19613. const selectNode = (editor, node) => {
  19614. const e = editor.dispatch('BeforeObjectSelected', { target: node });
  19615. if (e.isDefaultPrevented()) {
  19616. return Optional.none();
  19617. }
  19618. return Optional.some(getNodeRange(node));
  19619. };
  19620. const renderCaretAtRange = (editor, range, scrollIntoView) => {
  19621. const normalizedRange = normalizeRange(1, editor.getBody(), range);
  19622. const caretPosition = CaretPosition.fromRangeStart(normalizedRange);
  19623. const caretPositionNode = caretPosition.getNode();
  19624. if (isInlineFakeCaretTarget(caretPositionNode)) {
  19625. return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
  19626. }
  19627. const caretPositionBeforeNode = caretPosition.getNode(true);
  19628. if (isInlineFakeCaretTarget(caretPositionBeforeNode)) {
  19629. return showCaret(1, editor, caretPositionBeforeNode, false, false);
  19630. }
  19631. const ceRoot = editor.dom.getParent(caretPosition.getNode(), node => isContentEditableFalse$4(node) || isContentEditableTrue$1(node));
  19632. if (isInlineFakeCaretTarget(ceRoot)) {
  19633. return showCaret(1, editor, ceRoot, false, scrollIntoView);
  19634. }
  19635. return Optional.none();
  19636. };
  19637. const renderRangeCaret = (editor, range, scrollIntoView) => range.collapsed ? renderCaretAtRange(editor, range, scrollIntoView).getOr(range) : range;
  19638. const isBeforeBoundary = pos => isBeforeContentEditableFalse(pos) || isBeforeMedia(pos);
  19639. const isAfterBoundary = pos => isAfterContentEditableFalse(pos) || isAfterMedia(pos);
  19640. const trimEmptyTextNode = (dom, node) => {
  19641. if (isText$8(node) && node.data.length === 0) {
  19642. dom.remove(node);
  19643. }
  19644. };
  19645. const deleteContentAndShowCaret = (editor, range, node, direction, forward, peekCaretPosition) => {
  19646. showCaret(direction, editor, peekCaretPosition.getNode(!forward), forward, true).each(caretRange => {
  19647. if (range.collapsed) {
  19648. const deleteRange = range.cloneRange();
  19649. if (forward) {
  19650. deleteRange.setEnd(caretRange.startContainer, caretRange.startOffset);
  19651. } else {
  19652. deleteRange.setStart(caretRange.endContainer, caretRange.endOffset);
  19653. }
  19654. deleteRange.deleteContents();
  19655. } else {
  19656. range.deleteContents();
  19657. }
  19658. editor.selection.setRng(caretRange);
  19659. });
  19660. trimEmptyTextNode(editor.dom, node);
  19661. };
  19662. const deleteBoundaryText = (editor, forward) => {
  19663. const range = editor.selection.getRng();
  19664. if (!isText$8(range.commonAncestorContainer)) {
  19665. return Optional.none();
  19666. }
  19667. const direction = forward ? HDirection.Forwards : HDirection.Backwards;
  19668. const caretWalker = CaretWalker(editor.getBody());
  19669. const getNextPosFn = curry(getVisualCaretPosition, forward ? caretWalker.next : caretWalker.prev);
  19670. const isBeforeFn = forward ? isBeforeBoundary : isAfterBoundary;
  19671. const caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  19672. const nextCaretPosition = normalizePosition(forward, getNextPosFn(caretPosition));
  19673. if (!nextCaretPosition || !isMoveInsideSameBlock(caretPosition, nextCaretPosition)) {
  19674. return Optional.none();
  19675. } else if (isBeforeFn(nextCaretPosition)) {
  19676. return Optional.some(() => deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, nextCaretPosition));
  19677. }
  19678. const peekCaretPosition = getNextPosFn(nextCaretPosition);
  19679. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  19680. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  19681. return Optional.some(() => deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, peekCaretPosition));
  19682. }
  19683. }
  19684. return Optional.none();
  19685. };
  19686. const backspaceDelete$6 = (editor, forward) => deleteBoundaryText(editor, forward);
  19687. const isCompoundElement = node => isTableCell$4(SugarElement.fromDom(node)) || isListItem(SugarElement.fromDom(node));
  19688. const DeleteAction = Adt.generate([
  19689. { remove: ['element'] },
  19690. { moveToElement: ['element'] },
  19691. { moveToPosition: ['position'] }
  19692. ]);
  19693. const isAtContentEditableBlockCaret = (forward, from) => {
  19694. const elm = from.getNode(forward === false);
  19695. const caretLocation = forward ? 'after' : 'before';
  19696. return isElement$6(elm) && elm.getAttribute('data-mce-caret') === caretLocation;
  19697. };
  19698. const isDeleteFromCefDifferentBlocks = (root, forward, from, to) => {
  19699. const inSameBlock = elm => isInline$1(SugarElement.fromDom(elm)) && !isInSameBlock(from, to, root);
  19700. return getRelativeCefElm(!forward, from).fold(() => getRelativeCefElm(forward, to).fold(never, inSameBlock), inSameBlock);
  19701. };
  19702. const deleteEmptyBlockOrMoveToCef = (root, forward, from, to) => {
  19703. const toCefElm = to.getNode(forward === false);
  19704. return getParentBlock$2(SugarElement.fromDom(root), SugarElement.fromDom(from.getNode())).map(blockElm => isEmpty$2(blockElm) ? DeleteAction.remove(blockElm.dom) : DeleteAction.moveToElement(toCefElm)).orThunk(() => Optional.some(DeleteAction.moveToElement(toCefElm)));
  19705. };
  19706. const findCefPosition = (root, forward, from) => fromPosition(forward, root, from).bind(to => {
  19707. if (isCompoundElement(to.getNode())) {
  19708. return Optional.none();
  19709. } else if (isDeleteFromCefDifferentBlocks(root, forward, from, to)) {
  19710. return Optional.none();
  19711. } else if (forward && isContentEditableFalse$a(to.getNode())) {
  19712. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  19713. } else if (forward === false && isContentEditableFalse$a(to.getNode(true))) {
  19714. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  19715. } else if (forward && isAfterContentEditableFalse(from)) {
  19716. return Optional.some(DeleteAction.moveToPosition(to));
  19717. } else if (forward === false && isBeforeContentEditableFalse(from)) {
  19718. return Optional.some(DeleteAction.moveToPosition(to));
  19719. } else {
  19720. return Optional.none();
  19721. }
  19722. });
  19723. const getContentEditableBlockAction = (forward, elm) => {
  19724. if (forward && isContentEditableFalse$a(elm.nextSibling)) {
  19725. return Optional.some(DeleteAction.moveToElement(elm.nextSibling));
  19726. } else if (forward === false && isContentEditableFalse$a(elm.previousSibling)) {
  19727. return Optional.some(DeleteAction.moveToElement(elm.previousSibling));
  19728. } else {
  19729. return Optional.none();
  19730. }
  19731. };
  19732. const skipMoveToActionFromInlineCefToContent = (root, from, deleteAction) => deleteAction.fold(elm => Optional.some(DeleteAction.remove(elm)), elm => Optional.some(DeleteAction.moveToElement(elm)), to => {
  19733. if (isInSameBlock(from, to, root)) {
  19734. return Optional.none();
  19735. } else {
  19736. return Optional.some(DeleteAction.moveToPosition(to));
  19737. }
  19738. });
  19739. const getContentEditableAction = (root, forward, from) => {
  19740. if (isAtContentEditableBlockCaret(forward, from)) {
  19741. return getContentEditableBlockAction(forward, from.getNode(forward === false)).fold(() => findCefPosition(root, forward, from), Optional.some);
  19742. } else {
  19743. return findCefPosition(root, forward, from).bind(deleteAction => skipMoveToActionFromInlineCefToContent(root, from, deleteAction));
  19744. }
  19745. };
  19746. const read = (root, forward, rng) => {
  19747. const normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
  19748. const from = CaretPosition.fromRangeStart(normalizedRange);
  19749. const rootElement = SugarElement.fromDom(root);
  19750. if (forward === false && isAfterContentEditableFalse(from)) {
  19751. return Optional.some(DeleteAction.remove(from.getNode(true)));
  19752. } else if (forward && isBeforeContentEditableFalse(from)) {
  19753. return Optional.some(DeleteAction.remove(from.getNode()));
  19754. } else if (forward === false && isBeforeContentEditableFalse(from) && isAfterBr(rootElement, from)) {
  19755. return findPreviousBr(rootElement, from).map(br => DeleteAction.remove(br.getNode()));
  19756. } else if (forward && isAfterContentEditableFalse(from) && isBeforeBr$1(rootElement, from)) {
  19757. return findNextBr(rootElement, from).map(br => DeleteAction.remove(br.getNode()));
  19758. } else {
  19759. return getContentEditableAction(root, forward, from);
  19760. }
  19761. };
  19762. const deleteElement$1 = (editor, forward) => element => {
  19763. editor._selectionOverrides.hideFakeCaret();
  19764. deleteElement$2(editor, forward, SugarElement.fromDom(element));
  19765. return true;
  19766. };
  19767. const moveToElement = (editor, forward) => element => {
  19768. const pos = forward ? CaretPosition.before(element) : CaretPosition.after(element);
  19769. editor.selection.setRng(pos.toRange());
  19770. return true;
  19771. };
  19772. const moveToPosition = editor => pos => {
  19773. editor.selection.setRng(pos.toRange());
  19774. return true;
  19775. };
  19776. const getAncestorCe = (editor, node) => Optional.from(getContentEditableRoot$1(editor.getBody(), node));
  19777. const backspaceDeleteCaret = (editor, forward) => {
  19778. const selectedNode = editor.selection.getNode();
  19779. return getAncestorCe(editor, selectedNode).filter(isContentEditableFalse$a).fold(() => read(editor.getBody(), forward, editor.selection.getRng()).map(deleteAction => () => deleteAction.fold(deleteElement$1(editor, forward), moveToElement(editor, forward), moveToPosition(editor))), () => Optional.some(noop));
  19780. };
  19781. const deleteOffscreenSelection = rootElement => {
  19782. each$g(descendants(rootElement, '.mce-offscreen-selection'), remove$5);
  19783. };
  19784. const backspaceDeleteRange = (editor, forward) => {
  19785. const selectedNode = editor.selection.getNode();
  19786. if (isContentEditableFalse$a(selectedNode) && !isTableCell$5(selectedNode)) {
  19787. const hasCefAncestor = getAncestorCe(editor, selectedNode.parentNode).filter(isContentEditableFalse$a);
  19788. return hasCefAncestor.fold(() => Optional.some(() => {
  19789. deleteOffscreenSelection(SugarElement.fromDom(editor.getBody()));
  19790. deleteElement$2(editor, forward, SugarElement.fromDom(editor.selection.getNode()));
  19791. paddEmptyBody(editor);
  19792. }), () => Optional.some(noop));
  19793. }
  19794. return Optional.none();
  19795. };
  19796. const paddEmptyElement = editor => {
  19797. const dom = editor.dom, selection = editor.selection;
  19798. const ceRoot = getContentEditableRoot$1(editor.getBody(), selection.getNode());
  19799. if (isContentEditableTrue$4(ceRoot) && dom.isBlock(ceRoot) && dom.isEmpty(ceRoot)) {
  19800. const br = dom.create('br', { 'data-mce-bogus': '1' });
  19801. dom.setHTML(ceRoot, '');
  19802. ceRoot.appendChild(br);
  19803. selection.setRng(CaretPosition.before(br).toRange());
  19804. }
  19805. return true;
  19806. };
  19807. const backspaceDelete$5 = (editor, forward) => {
  19808. if (editor.selection.isCollapsed()) {
  19809. return backspaceDeleteCaret(editor, forward);
  19810. } else {
  19811. return backspaceDeleteRange(editor, forward);
  19812. }
  19813. };
  19814. const deleteCaret$2 = (editor, forward) => {
  19815. const fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  19816. return fromPosition(forward, editor.getBody(), fromPos).filter(pos => forward ? isBeforeImageBlock(pos) : isAfterImageBlock(pos)).bind(pos => Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, pos))).map(elm => () => editor.selection.select(elm));
  19817. };
  19818. const backspaceDelete$4 = (editor, forward) => editor.selection.isCollapsed() ? deleteCaret$2(editor, forward) : Optional.none();
  19819. const isText$1 = isText$8;
  19820. const startsWithCaretContainer = node => isText$1(node) && node.data[0] === ZWSP$1;
  19821. const endsWithCaretContainer = node => isText$1(node) && node.data[node.data.length - 1] === ZWSP$1;
  19822. const createZwsp = node => node.ownerDocument.createTextNode(ZWSP$1);
  19823. const insertBefore = node => {
  19824. if (isText$1(node.previousSibling)) {
  19825. if (endsWithCaretContainer(node.previousSibling)) {
  19826. return node.previousSibling;
  19827. } else {
  19828. node.previousSibling.appendData(ZWSP$1);
  19829. return node.previousSibling;
  19830. }
  19831. } else if (isText$1(node)) {
  19832. if (startsWithCaretContainer(node)) {
  19833. return node;
  19834. } else {
  19835. node.insertData(0, ZWSP$1);
  19836. return node;
  19837. }
  19838. } else {
  19839. const newNode = createZwsp(node);
  19840. node.parentNode.insertBefore(newNode, node);
  19841. return newNode;
  19842. }
  19843. };
  19844. const insertAfter = node => {
  19845. if (isText$1(node.nextSibling)) {
  19846. if (startsWithCaretContainer(node.nextSibling)) {
  19847. return node.nextSibling;
  19848. } else {
  19849. node.nextSibling.insertData(0, ZWSP$1);
  19850. return node.nextSibling;
  19851. }
  19852. } else if (isText$1(node)) {
  19853. if (endsWithCaretContainer(node)) {
  19854. return node;
  19855. } else {
  19856. node.appendData(ZWSP$1);
  19857. return node;
  19858. }
  19859. } else {
  19860. const newNode = createZwsp(node);
  19861. if (node.nextSibling) {
  19862. node.parentNode.insertBefore(newNode, node.nextSibling);
  19863. } else {
  19864. node.parentNode.appendChild(newNode);
  19865. }
  19866. return newNode;
  19867. }
  19868. };
  19869. const insertInline = (before, node) => before ? insertBefore(node) : insertAfter(node);
  19870. const insertInlineBefore = curry(insertInline, true);
  19871. const insertInlineAfter = curry(insertInline, false);
  19872. const insertInlinePos = (pos, before) => {
  19873. if (isText$8(pos.container())) {
  19874. return insertInline(before, pos.container());
  19875. } else {
  19876. return insertInline(before, pos.getNode());
  19877. }
  19878. };
  19879. const isPosCaretContainer = (pos, caret) => {
  19880. const caretNode = caret.get();
  19881. return caretNode && pos.container() === caretNode && isCaretContainerInline(caretNode);
  19882. };
  19883. const renderCaret = (caret, location) => location.fold(element => {
  19884. remove$4(caret.get());
  19885. const text = insertInlineBefore(element);
  19886. caret.set(text);
  19887. return Optional.some(CaretPosition(text, text.length - 1));
  19888. }, element => firstPositionIn(element).map(pos => {
  19889. if (!isPosCaretContainer(pos, caret)) {
  19890. remove$4(caret.get());
  19891. const text = insertInlinePos(pos, true);
  19892. caret.set(text);
  19893. return CaretPosition(text, 1);
  19894. } else {
  19895. return CaretPosition(caret.get(), 1);
  19896. }
  19897. }), element => lastPositionIn(element).map(pos => {
  19898. if (!isPosCaretContainer(pos, caret)) {
  19899. remove$4(caret.get());
  19900. const text = insertInlinePos(pos, false);
  19901. caret.set(text);
  19902. return CaretPosition(text, text.length - 1);
  19903. } else {
  19904. return CaretPosition(caret.get(), caret.get().length - 1);
  19905. }
  19906. }), element => {
  19907. remove$4(caret.get());
  19908. const text = insertInlineAfter(element);
  19909. caret.set(text);
  19910. return Optional.some(CaretPosition(text, 1));
  19911. });
  19912. const evaluateUntil = (fns, args) => {
  19913. for (let i = 0; i < fns.length; i++) {
  19914. const result = fns[i].apply(null, args);
  19915. if (result.isSome()) {
  19916. return result;
  19917. }
  19918. }
  19919. return Optional.none();
  19920. };
  19921. const Location = Adt.generate([
  19922. { before: ['element'] },
  19923. { start: ['element'] },
  19924. { end: ['element'] },
  19925. { after: ['element'] }
  19926. ]);
  19927. const rescope$1 = (rootNode, node) => {
  19928. const parentBlock = getParentBlock$3(node, rootNode);
  19929. return parentBlock ? parentBlock : rootNode;
  19930. };
  19931. const before = (isInlineTarget, rootNode, pos) => {
  19932. const nPos = normalizeForwards(pos);
  19933. const scope = rescope$1(rootNode, nPos.container());
  19934. return findRootInline(isInlineTarget, scope, nPos).fold(() => nextPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(inline => Location.before(inline)), Optional.none);
  19935. };
  19936. const isNotInsideFormatCaretContainer = (rootNode, elm) => getParentCaretContainer(rootNode, elm) === null;
  19937. const findInsideRootInline = (isInlineTarget, rootNode, pos) => findRootInline(isInlineTarget, rootNode, pos).filter(curry(isNotInsideFormatCaretContainer, rootNode));
  19938. const start$1 = (isInlineTarget, rootNode, pos) => {
  19939. const nPos = normalizeBackwards(pos);
  19940. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(inline => {
  19941. const prevPos = prevPosition(inline, nPos);
  19942. return prevPos.isNone() ? Optional.some(Location.start(inline)) : Optional.none();
  19943. });
  19944. };
  19945. const end = (isInlineTarget, rootNode, pos) => {
  19946. const nPos = normalizeForwards(pos);
  19947. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(inline => {
  19948. const nextPos = nextPosition(inline, nPos);
  19949. return nextPos.isNone() ? Optional.some(Location.end(inline)) : Optional.none();
  19950. });
  19951. };
  19952. const after = (isInlineTarget, rootNode, pos) => {
  19953. const nPos = normalizeBackwards(pos);
  19954. const scope = rescope$1(rootNode, nPos.container());
  19955. return findRootInline(isInlineTarget, scope, nPos).fold(() => prevPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(inline => Location.after(inline)), Optional.none);
  19956. };
  19957. const isValidLocation = location => isRtl(getElement(location)) === false;
  19958. const readLocation = (isInlineTarget, rootNode, pos) => {
  19959. const location = evaluateUntil([
  19960. before,
  19961. start$1,
  19962. end,
  19963. after
  19964. ], [
  19965. isInlineTarget,
  19966. rootNode,
  19967. pos
  19968. ]);
  19969. return location.filter(isValidLocation);
  19970. };
  19971. const getElement = location => location.fold(identity, identity, identity, identity);
  19972. const getName = location => location.fold(constant('before'), constant('start'), constant('end'), constant('after'));
  19973. const outside = location => location.fold(Location.before, Location.before, Location.after, Location.after);
  19974. const inside = location => location.fold(Location.start, Location.start, Location.end, Location.end);
  19975. const isEq = (location1, location2) => getName(location1) === getName(location2) && getElement(location1) === getElement(location2);
  19976. const betweenInlines = (forward, isInlineTarget, rootNode, from, to, location) => lift2(findRootInline(isInlineTarget, rootNode, from), findRootInline(isInlineTarget, rootNode, to), (fromInline, toInline) => {
  19977. if (fromInline !== toInline && hasSameParentBlock(rootNode, fromInline, toInline)) {
  19978. return Location.after(forward ? fromInline : toInline);
  19979. } else {
  19980. return location;
  19981. }
  19982. }).getOr(location);
  19983. const skipNoMovement = (fromLocation, toLocation) => fromLocation.fold(always, fromLocation => !isEq(fromLocation, toLocation));
  19984. const findLocationTraverse = (forward, isInlineTarget, rootNode, fromLocation, pos) => {
  19985. const from = normalizePosition(forward, pos);
  19986. const to = fromPosition(forward, rootNode, from).map(curry(normalizePosition, forward));
  19987. const location = to.fold(() => fromLocation.map(outside), to => readLocation(isInlineTarget, rootNode, to).map(curry(betweenInlines, forward, isInlineTarget, rootNode, from, to)).filter(curry(skipNoMovement, fromLocation)));
  19988. return location.filter(isValidLocation);
  19989. };
  19990. const findLocationSimple = (forward, location) => {
  19991. if (forward) {
  19992. return location.fold(compose(Optional.some, Location.start), Optional.none, compose(Optional.some, Location.after), Optional.none);
  19993. } else {
  19994. return location.fold(Optional.none, compose(Optional.some, Location.before), Optional.none, compose(Optional.some, Location.end));
  19995. }
  19996. };
  19997. const findLocation$1 = (forward, isInlineTarget, rootNode, pos) => {
  19998. const from = normalizePosition(forward, pos);
  19999. const fromLocation = readLocation(isInlineTarget, rootNode, from);
  20000. return readLocation(isInlineTarget, rootNode, from).bind(curry(findLocationSimple, forward)).orThunk(() => findLocationTraverse(forward, isInlineTarget, rootNode, fromLocation, pos));
  20001. };
  20002. const hasSelectionModifyApi = editor => {
  20003. return isFunction(editor.selection.getSel().modify);
  20004. };
  20005. const moveRel = (forward, selection, pos) => {
  20006. const delta = forward ? 1 : -1;
  20007. selection.setRng(CaretPosition(pos.container(), pos.offset() + delta).toRange());
  20008. selection.getSel().modify('move', forward ? 'forward' : 'backward', 'word');
  20009. return true;
  20010. };
  20011. const moveByWord = (forward, editor) => {
  20012. const rng = editor.selection.getRng();
  20013. const pos = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  20014. if (!hasSelectionModifyApi(editor)) {
  20015. return false;
  20016. } else if (forward && isBeforeInline(pos)) {
  20017. return moveRel(true, editor.selection, pos);
  20018. } else if (!forward && isAfterInline(pos)) {
  20019. return moveRel(false, editor.selection, pos);
  20020. } else {
  20021. return false;
  20022. }
  20023. };
  20024. var BreakType;
  20025. (function (BreakType) {
  20026. BreakType[BreakType['Br'] = 0] = 'Br';
  20027. BreakType[BreakType['Block'] = 1] = 'Block';
  20028. BreakType[BreakType['Wrap'] = 2] = 'Wrap';
  20029. BreakType[BreakType['Eol'] = 3] = 'Eol';
  20030. }(BreakType || (BreakType = {})));
  20031. const flip = (direction, positions) => direction === HDirection.Backwards ? reverse(positions) : positions;
  20032. const walk$1 = (direction, caretWalker, pos) => direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
  20033. const getBreakType = (scope, direction, currentPos, nextPos) => {
  20034. if (isBr$5(nextPos.getNode(direction === HDirection.Forwards))) {
  20035. return BreakType.Br;
  20036. } else if (isInSameBlock(currentPos, nextPos) === false) {
  20037. return BreakType.Block;
  20038. } else {
  20039. return BreakType.Wrap;
  20040. }
  20041. };
  20042. const getPositionsUntil = (predicate, direction, scope, start) => {
  20043. const caretWalker = CaretWalker(scope);
  20044. let currentPos = start;
  20045. const positions = [];
  20046. while (currentPos) {
  20047. const nextPos = walk$1(direction, caretWalker, currentPos);
  20048. if (!nextPos) {
  20049. break;
  20050. }
  20051. if (isBr$5(nextPos.getNode(false))) {
  20052. if (direction === HDirection.Forwards) {
  20053. return {
  20054. positions: flip(direction, positions).concat([nextPos]),
  20055. breakType: BreakType.Br,
  20056. breakAt: Optional.some(nextPos)
  20057. };
  20058. } else {
  20059. return {
  20060. positions: flip(direction, positions),
  20061. breakType: BreakType.Br,
  20062. breakAt: Optional.some(nextPos)
  20063. };
  20064. }
  20065. }
  20066. if (!nextPos.isVisible()) {
  20067. currentPos = nextPos;
  20068. continue;
  20069. }
  20070. if (predicate(currentPos, nextPos)) {
  20071. const breakType = getBreakType(scope, direction, currentPos, nextPos);
  20072. return {
  20073. positions: flip(direction, positions),
  20074. breakType,
  20075. breakAt: Optional.some(nextPos)
  20076. };
  20077. }
  20078. positions.push(nextPos);
  20079. currentPos = nextPos;
  20080. }
  20081. return {
  20082. positions: flip(direction, positions),
  20083. breakType: BreakType.Eol,
  20084. breakAt: Optional.none()
  20085. };
  20086. };
  20087. const getAdjacentLinePositions = (direction, getPositionsUntilBreak, scope, start) => getPositionsUntilBreak(scope, start).breakAt.map(pos => {
  20088. const positions = getPositionsUntilBreak(scope, pos).positions;
  20089. return direction === HDirection.Backwards ? positions.concat(pos) : [pos].concat(positions);
  20090. }).getOr([]);
  20091. const findClosestHorizontalPositionFromPoint = (positions, x) => foldl(positions, (acc, newPos) => acc.fold(() => Optional.some(newPos), lastPos => lift2(head(lastPos.getClientRects()), head(newPos.getClientRects()), (lastRect, newRect) => {
  20092. const lastDist = Math.abs(x - lastRect.left);
  20093. const newDist = Math.abs(x - newRect.left);
  20094. return newDist <= lastDist ? newPos : lastPos;
  20095. }).or(acc)), Optional.none());
  20096. const findClosestHorizontalPosition = (positions, pos) => head(pos.getClientRects()).bind(targetRect => findClosestHorizontalPositionFromPoint(positions, targetRect.left));
  20097. const getPositionsUntilPreviousLine = curry(getPositionsUntil, CaretPosition.isAbove, -1);
  20098. const getPositionsUntilNextLine = curry(getPositionsUntil, CaretPosition.isBelow, 1);
  20099. const getPositionsAbove = curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
  20100. const getPositionsBelow = curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
  20101. const isAtFirstLine = (scope, pos) => getPositionsUntilPreviousLine(scope, pos).breakAt.isNone();
  20102. const isAtLastLine = (scope, pos) => getPositionsUntilNextLine(scope, pos).breakAt.isNone();
  20103. const getFirstLinePositions = scope => firstPositionIn(scope).map(pos => [pos].concat(getPositionsUntilNextLine(scope, pos).positions)).getOr([]);
  20104. const getLastLinePositions = scope => lastPositionIn(scope).map(pos => getPositionsUntilPreviousLine(scope, pos).positions.concat(pos)).getOr([]);
  20105. const isContentEditableFalse$3 = isContentEditableFalse$a;
  20106. const distanceToRectLeft$1 = (clientRect, clientX) => Math.abs(clientRect.left - clientX);
  20107. const distanceToRectRight$1 = (clientRect, clientX) => Math.abs(clientRect.right - clientX);
  20108. const isNodeClientRect = rect => hasNonNullableKey(rect, 'node');
  20109. const findClosestClientRect = (clientRects, clientX) => reduce(clientRects, (oldClientRect, clientRect) => {
  20110. const oldDistance = Math.min(distanceToRectLeft$1(oldClientRect, clientX), distanceToRectRight$1(oldClientRect, clientX));
  20111. const newDistance = Math.min(distanceToRectLeft$1(clientRect, clientX), distanceToRectRight$1(clientRect, clientX));
  20112. if (newDistance === oldDistance && isNodeClientRect(clientRect) && isContentEditableFalse$3(clientRect.node)) {
  20113. return clientRect;
  20114. }
  20115. if (newDistance < oldDistance) {
  20116. return clientRect;
  20117. }
  20118. return oldClientRect;
  20119. });
  20120. const getNodeClientRects = node => {
  20121. const toArrayWithNode = clientRects => {
  20122. return map$3(clientRects, rect => {
  20123. const clientRect = clone$1(rect);
  20124. clientRect.node = node;
  20125. return clientRect;
  20126. });
  20127. };
  20128. if (isElement$6(node)) {
  20129. return toArrayWithNode(node.getClientRects());
  20130. } else if (isText$8(node)) {
  20131. const rng = node.ownerDocument.createRange();
  20132. rng.setStart(node, 0);
  20133. rng.setEnd(node, node.data.length);
  20134. return toArrayWithNode(rng.getClientRects());
  20135. } else {
  20136. return [];
  20137. }
  20138. };
  20139. const getClientRects = nodes => bind$3(nodes, getNodeClientRects);
  20140. var VDirection;
  20141. (function (VDirection) {
  20142. VDirection[VDirection['Up'] = -1] = 'Up';
  20143. VDirection[VDirection['Down'] = 1] = 'Down';
  20144. }(VDirection || (VDirection = {})));
  20145. const findUntil = (direction, root, predicateFn, node) => {
  20146. while (node = findNode(node, direction, isEditableCaretCandidate$1, root)) {
  20147. if (predicateFn(node)) {
  20148. return;
  20149. }
  20150. }
  20151. };
  20152. const walkUntil = (direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) => {
  20153. let line = 0;
  20154. const result = [];
  20155. const add = node => {
  20156. let clientRects = getClientRects([node]);
  20157. if (direction === -1) {
  20158. clientRects = clientRects.reverse();
  20159. }
  20160. for (let i = 0; i < clientRects.length; i++) {
  20161. const clientRect = clientRects[i];
  20162. if (isBeflowFn(clientRect, targetClientRect)) {
  20163. continue;
  20164. }
  20165. if (result.length > 0 && isAboveFn(clientRect, last$2(result))) {
  20166. line++;
  20167. }
  20168. clientRect.line = line;
  20169. if (predicateFn(clientRect)) {
  20170. return true;
  20171. }
  20172. result.push(clientRect);
  20173. }
  20174. };
  20175. const targetClientRect = last$2(caretPosition.getClientRects());
  20176. if (!targetClientRect) {
  20177. return result;
  20178. }
  20179. const node = caretPosition.getNode();
  20180. add(node);
  20181. findUntil(direction, root, add, node);
  20182. return result;
  20183. };
  20184. const aboveLineNumber = (lineNumber, clientRect) => clientRect.line > lineNumber;
  20185. const isLineNumber = (lineNumber, clientRect) => clientRect.line === lineNumber;
  20186. const upUntil = curry(walkUntil, VDirection.Up, isAbove$1, isBelow$1);
  20187. const downUntil = curry(walkUntil, VDirection.Down, isBelow$1, isAbove$1);
  20188. const positionsUntil = (direction, root, predicateFn, node) => {
  20189. const caretWalker = CaretWalker(root);
  20190. let walkFn;
  20191. let isBelowFn;
  20192. let isAboveFn;
  20193. let caretPosition;
  20194. const result = [];
  20195. let line = 0;
  20196. const getClientRect = caretPosition => {
  20197. if (direction === 1) {
  20198. return last$2(caretPosition.getClientRects());
  20199. }
  20200. return last$2(caretPosition.getClientRects());
  20201. };
  20202. if (direction === 1) {
  20203. walkFn = caretWalker.next;
  20204. isBelowFn = isBelow$1;
  20205. isAboveFn = isAbove$1;
  20206. caretPosition = CaretPosition.after(node);
  20207. } else {
  20208. walkFn = caretWalker.prev;
  20209. isBelowFn = isAbove$1;
  20210. isAboveFn = isBelow$1;
  20211. caretPosition = CaretPosition.before(node);
  20212. }
  20213. const targetClientRect = getClientRect(caretPosition);
  20214. do {
  20215. if (!caretPosition.isVisible()) {
  20216. continue;
  20217. }
  20218. const rect = getClientRect(caretPosition);
  20219. if (isAboveFn(rect, targetClientRect)) {
  20220. continue;
  20221. }
  20222. if (result.length > 0 && isBelowFn(rect, last$2(result))) {
  20223. line++;
  20224. }
  20225. const clientRect = clone$1(rect);
  20226. clientRect.position = caretPosition;
  20227. clientRect.line = line;
  20228. if (predicateFn(clientRect)) {
  20229. return result;
  20230. }
  20231. result.push(clientRect);
  20232. } while (caretPosition = walkFn(caretPosition));
  20233. return result;
  20234. };
  20235. const isAboveLine = lineNumber => clientRect => aboveLineNumber(lineNumber, clientRect);
  20236. const isLine = lineNumber => clientRect => isLineNumber(lineNumber, clientRect);
  20237. const moveToRange = (editor, rng) => {
  20238. editor.selection.setRng(rng);
  20239. scrollRangeIntoView(editor, editor.selection.getRng());
  20240. };
  20241. const renderRangeCaretOpt = (editor, range, scrollIntoView) => Optional.some(renderRangeCaret(editor, range, scrollIntoView));
  20242. const moveHorizontally = (editor, direction, range, isBefore, isAfter, isElement) => {
  20243. const forwards = direction === HDirection.Forwards;
  20244. const caretWalker = CaretWalker(editor.getBody());
  20245. const getNextPosFn = curry(getVisualCaretPosition, forwards ? caretWalker.next : caretWalker.prev);
  20246. const isBeforeFn = forwards ? isBefore : isAfter;
  20247. if (!range.collapsed) {
  20248. const node = getSelectedNode(range);
  20249. if (isElement(node)) {
  20250. return showCaret(direction, editor, node, direction === HDirection.Backwards, false);
  20251. }
  20252. }
  20253. const caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  20254. if (isBeforeFn(caretPosition)) {
  20255. return selectNode(editor, caretPosition.getNode(!forwards));
  20256. }
  20257. const nextCaretPosition = normalizePosition(forwards, getNextPosFn(caretPosition));
  20258. const rangeIsInContainerBlock = isRangeInCaretContainerBlock(range);
  20259. if (!nextCaretPosition) {
  20260. return rangeIsInContainerBlock ? Optional.some(range) : Optional.none();
  20261. }
  20262. if (isBeforeFn(nextCaretPosition)) {
  20263. return showCaret(direction, editor, nextCaretPosition.getNode(!forwards), forwards, false);
  20264. }
  20265. const peekCaretPosition = getNextPosFn(nextCaretPosition);
  20266. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  20267. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  20268. return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, false);
  20269. }
  20270. }
  20271. if (rangeIsInContainerBlock) {
  20272. return renderRangeCaretOpt(editor, nextCaretPosition.toRange(), false);
  20273. }
  20274. return Optional.none();
  20275. };
  20276. const moveVertically = (editor, direction, range, isBefore, isAfter, isElement) => {
  20277. const caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  20278. const caretClientRect = last$2(caretPosition.getClientRects());
  20279. const forwards = direction === VDirection.Down;
  20280. if (!caretClientRect) {
  20281. return Optional.none();
  20282. }
  20283. const walkerFn = forwards ? downUntil : upUntil;
  20284. const linePositions = walkerFn(editor.getBody(), isAboveLine(1), caretPosition);
  20285. const nextLinePositions = filter$6(linePositions, isLine(1));
  20286. const clientX = caretClientRect.left;
  20287. const nextLineRect = findClosestClientRect(nextLinePositions, clientX);
  20288. if (nextLineRect && isElement(nextLineRect.node)) {
  20289. const dist1 = Math.abs(clientX - nextLineRect.left);
  20290. const dist2 = Math.abs(clientX - nextLineRect.right);
  20291. return showCaret(direction, editor, nextLineRect.node, dist1 < dist2, false);
  20292. }
  20293. let currentNode;
  20294. if (isBefore(caretPosition)) {
  20295. currentNode = caretPosition.getNode();
  20296. } else if (isAfter(caretPosition)) {
  20297. currentNode = caretPosition.getNode(true);
  20298. } else {
  20299. currentNode = getSelectedNode(range);
  20300. }
  20301. if (currentNode) {
  20302. const caretPositions = positionsUntil(direction, editor.getBody(), isAboveLine(1), currentNode);
  20303. let closestNextLineRect = findClosestClientRect(filter$6(caretPositions, isLine(1)), clientX);
  20304. if (closestNextLineRect) {
  20305. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  20306. }
  20307. closestNextLineRect = last$2(filter$6(caretPositions, isLine(0)));
  20308. if (closestNextLineRect) {
  20309. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  20310. }
  20311. }
  20312. if (nextLinePositions.length === 0) {
  20313. return getLineEndPoint(editor, forwards).filter(forwards ? isAfter : isBefore).map(pos => renderRangeCaret(editor, pos.toRange(), false));
  20314. }
  20315. return Optional.none();
  20316. };
  20317. const getLineEndPoint = (editor, forward) => {
  20318. const rng = editor.selection.getRng();
  20319. const from = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  20320. const host = getEditingHost(from.container(), editor.getBody());
  20321. if (forward) {
  20322. const lineInfo = getPositionsUntilNextLine(host, from);
  20323. return last$3(lineInfo.positions);
  20324. } else {
  20325. const lineInfo = getPositionsUntilPreviousLine(host, from);
  20326. return head(lineInfo.positions);
  20327. }
  20328. };
  20329. const moveToLineEndPoint$3 = (editor, forward, isElementPosition) => getLineEndPoint(editor, forward).filter(isElementPosition).exists(pos => {
  20330. editor.selection.setRng(pos.toRange());
  20331. return true;
  20332. });
  20333. const setCaretPosition = (editor, pos) => {
  20334. const rng = editor.dom.createRng();
  20335. rng.setStart(pos.container(), pos.offset());
  20336. rng.setEnd(pos.container(), pos.offset());
  20337. editor.selection.setRng(rng);
  20338. };
  20339. const setSelected = (state, elm) => {
  20340. if (state) {
  20341. elm.setAttribute('data-mce-selected', 'inline-boundary');
  20342. } else {
  20343. elm.removeAttribute('data-mce-selected');
  20344. }
  20345. };
  20346. const renderCaretLocation = (editor, caret, location) => renderCaret(caret, location).map(pos => {
  20347. setCaretPosition(editor, pos);
  20348. return location;
  20349. });
  20350. const findLocation = (editor, caret, forward) => {
  20351. const rootNode = editor.getBody();
  20352. const from = CaretPosition.fromRangeStart(editor.selection.getRng());
  20353. const isInlineTarget$1 = curry(isInlineTarget, editor);
  20354. const location = findLocation$1(forward, isInlineTarget$1, rootNode, from);
  20355. return location.bind(location => renderCaretLocation(editor, caret, location));
  20356. };
  20357. const toggleInlines = (isInlineTarget, dom, elms) => {
  20358. const inlineBoundaries = map$3(descendants(SugarElement.fromDom(dom.getRoot()), '*[data-mce-selected="inline-boundary"]'), e => e.dom);
  20359. const selectedInlines = filter$6(inlineBoundaries, isInlineTarget);
  20360. const targetInlines = filter$6(elms, isInlineTarget);
  20361. each$g(difference(selectedInlines, targetInlines), curry(setSelected, false));
  20362. each$g(difference(targetInlines, selectedInlines), curry(setSelected, true));
  20363. };
  20364. const safeRemoveCaretContainer = (editor, caret) => {
  20365. if (editor.selection.isCollapsed() && editor.composing !== true && caret.get()) {
  20366. const pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  20367. if (CaretPosition.isTextPosition(pos) && isAtZwsp(pos) === false) {
  20368. setCaretPosition(editor, removeAndReposition(caret.get(), pos));
  20369. caret.set(null);
  20370. }
  20371. }
  20372. };
  20373. const renderInsideInlineCaret = (isInlineTarget, editor, caret, elms) => {
  20374. if (editor.selection.isCollapsed()) {
  20375. const inlines = filter$6(elms, isInlineTarget);
  20376. each$g(inlines, _inline => {
  20377. const pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  20378. readLocation(isInlineTarget, editor.getBody(), pos).bind(location => renderCaretLocation(editor, caret, location));
  20379. });
  20380. }
  20381. };
  20382. const move$2 = (editor, caret, forward) => isInlineBoundariesEnabled(editor) ? findLocation(editor, caret, forward).isSome() : false;
  20383. const moveWord = (forward, editor, _caret) => isInlineBoundariesEnabled(editor) ? moveByWord(forward, editor) : false;
  20384. const setupSelectedState = editor => {
  20385. const caret = Cell(null);
  20386. const isInlineTarget$1 = curry(isInlineTarget, editor);
  20387. editor.on('NodeChange', e => {
  20388. if (isInlineBoundariesEnabled(editor)) {
  20389. toggleInlines(isInlineTarget$1, editor.dom, e.parents);
  20390. safeRemoveCaretContainer(editor, caret);
  20391. renderInsideInlineCaret(isInlineTarget$1, editor, caret, e.parents);
  20392. }
  20393. });
  20394. return caret;
  20395. };
  20396. const moveNextWord = curry(moveWord, true);
  20397. const movePrevWord = curry(moveWord, false);
  20398. const moveToLineEndPoint$2 = (editor, forward, caret) => {
  20399. if (isInlineBoundariesEnabled(editor)) {
  20400. const linePoint = getLineEndPoint(editor, forward).getOrThunk(() => {
  20401. const rng = editor.selection.getRng();
  20402. return forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  20403. });
  20404. return readLocation(curry(isInlineTarget, editor), editor.getBody(), linePoint).exists(loc => {
  20405. const outsideLoc = outside(loc);
  20406. return renderCaret(caret, outsideLoc).exists(pos => {
  20407. setCaretPosition(editor, pos);
  20408. return true;
  20409. });
  20410. });
  20411. } else {
  20412. return false;
  20413. }
  20414. };
  20415. const rangeFromPositions = (from, to) => {
  20416. const range = document.createRange();
  20417. range.setStart(from.container(), from.offset());
  20418. range.setEnd(to.container(), to.offset());
  20419. return range;
  20420. };
  20421. const hasOnlyTwoOrLessPositionsLeft = elm => lift2(firstPositionIn(elm), lastPositionIn(elm), (firstPos, lastPos) => {
  20422. const normalizedFirstPos = normalizePosition(true, firstPos);
  20423. const normalizedLastPos = normalizePosition(false, lastPos);
  20424. return nextPosition(elm, normalizedFirstPos).forall(pos => pos.isEqual(normalizedLastPos));
  20425. }).getOr(true);
  20426. const setCaretLocation = (editor, caret) => location => renderCaret(caret, location).map(pos => () => setCaretPosition(editor, pos));
  20427. const deleteFromTo = (editor, caret, from, to) => {
  20428. const rootNode = editor.getBody();
  20429. const isInlineTarget$1 = curry(isInlineTarget, editor);
  20430. editor.undoManager.ignore(() => {
  20431. editor.selection.setRng(rangeFromPositions(from, to));
  20432. execDeleteCommand(editor);
  20433. readLocation(isInlineTarget$1, rootNode, CaretPosition.fromRangeStart(editor.selection.getRng())).map(inside).bind(setCaretLocation(editor, caret)).each(call);
  20434. });
  20435. editor.nodeChanged();
  20436. };
  20437. const rescope = (rootNode, node) => {
  20438. const parentBlock = getParentBlock$3(node, rootNode);
  20439. return parentBlock ? parentBlock : rootNode;
  20440. };
  20441. const backspaceDeleteCollapsed = (editor, caret, forward, from) => {
  20442. const rootNode = rescope(editor.getBody(), from.container());
  20443. const isInlineTarget$1 = curry(isInlineTarget, editor);
  20444. const fromLocation = readLocation(isInlineTarget$1, rootNode, from);
  20445. const location = fromLocation.bind(location => {
  20446. if (forward) {
  20447. return location.fold(constant(Optional.some(inside(location))), Optional.none, constant(Optional.some(outside(location))), Optional.none);
  20448. } else {
  20449. return location.fold(Optional.none, constant(Optional.some(outside(location))), Optional.none, constant(Optional.some(inside(location))));
  20450. }
  20451. });
  20452. return location.map(setCaretLocation(editor, caret)).getOrThunk(() => {
  20453. const toPosition = navigate(forward, rootNode, from);
  20454. const toLocation = toPosition.bind(pos => readLocation(isInlineTarget$1, rootNode, pos));
  20455. return lift2(fromLocation, toLocation, () => findRootInline(isInlineTarget$1, rootNode, from).bind(elm => {
  20456. if (hasOnlyTwoOrLessPositionsLeft(elm)) {
  20457. return Optional.some(() => {
  20458. deleteElement$2(editor, forward, SugarElement.fromDom(elm));
  20459. });
  20460. } else {
  20461. return Optional.none();
  20462. }
  20463. })).getOrThunk(() => toLocation.bind(() => toPosition.map(to => {
  20464. return () => {
  20465. if (forward) {
  20466. deleteFromTo(editor, caret, from, to);
  20467. } else {
  20468. deleteFromTo(editor, caret, to, from);
  20469. }
  20470. };
  20471. })));
  20472. });
  20473. };
  20474. const backspaceDelete$3 = (editor, caret, forward) => {
  20475. if (editor.selection.isCollapsed() && isInlineBoundariesEnabled(editor)) {
  20476. const from = CaretPosition.fromRangeStart(editor.selection.getRng());
  20477. return backspaceDeleteCollapsed(editor, caret, forward, from);
  20478. }
  20479. return Optional.none();
  20480. };
  20481. const getParentInlines = (rootElm, startElm) => {
  20482. const parents = parentsAndSelf(startElm, rootElm);
  20483. return findIndex$2(parents, isBlock$2).fold(constant(parents), index => parents.slice(0, index));
  20484. };
  20485. const hasOnlyOneChild = elm => childNodesCount(elm) === 1;
  20486. const deleteLastPosition = (forward, editor, target, parentInlines) => {
  20487. const isFormatElement$1 = curry(isFormatElement, editor);
  20488. const formatNodes = map$3(filter$6(parentInlines, isFormatElement$1), elm => elm.dom);
  20489. if (formatNodes.length === 0) {
  20490. deleteElement$2(editor, forward, target);
  20491. } else {
  20492. const pos = replaceWithCaretFormat(target.dom, formatNodes);
  20493. editor.selection.setRng(pos.toRange());
  20494. }
  20495. };
  20496. const deleteCaret$1 = (editor, forward) => {
  20497. const rootElm = SugarElement.fromDom(editor.getBody());
  20498. const startElm = SugarElement.fromDom(editor.selection.getStart());
  20499. const parentInlines = filter$6(getParentInlines(rootElm, startElm), hasOnlyOneChild);
  20500. return last$3(parentInlines).bind(target => {
  20501. const fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  20502. if (willDeleteLastPositionInElement(forward, fromPos, target.dom) && !isEmptyCaretFormatElement(target)) {
  20503. return Optional.some(() => deleteLastPosition(forward, editor, target, parentInlines));
  20504. } else {
  20505. return Optional.none();
  20506. }
  20507. });
  20508. };
  20509. const backspaceDelete$2 = (editor, forward) => editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : Optional.none();
  20510. const deleteElement = (editor, forward, element) => {
  20511. return Optional.some(() => {
  20512. editor._selectionOverrides.hideFakeCaret();
  20513. deleteElement$2(editor, forward, SugarElement.fromDom(element));
  20514. });
  20515. };
  20516. const deleteCaret = (editor, forward) => {
  20517. const isNearMedia = forward ? isBeforeMedia : isAfterMedia;
  20518. const direction = forward ? HDirection.Forwards : HDirection.Backwards;
  20519. const fromPos = getNormalizedRangeEndPoint(direction, editor.getBody(), editor.selection.getRng());
  20520. if (isNearMedia(fromPos)) {
  20521. return deleteElement(editor, forward, fromPos.getNode(!forward));
  20522. } else {
  20523. return Optional.from(normalizePosition(forward, fromPos)).filter(pos => isNearMedia(pos) && isMoveInsideSameBlock(fromPos, pos)).map(pos => () => deleteElement(editor, forward, pos.getNode(!forward)));
  20524. }
  20525. };
  20526. const deleteRange = (editor, forward) => {
  20527. const selectedNode = editor.selection.getNode();
  20528. return isMedia$2(selectedNode) ? deleteElement(editor, forward, selectedNode) : Optional.none();
  20529. };
  20530. const backspaceDelete$1 = (editor, forward) => editor.selection.isCollapsed() ? deleteCaret(editor, forward) : deleteRange(editor, forward);
  20531. const isEditable$1 = target => closest$4(target, elm => isContentEditableTrue$4(elm.dom) || isContentEditableFalse$a(elm.dom)).exists(elm => isContentEditableTrue$4(elm.dom));
  20532. const parseIndentValue = value => {
  20533. const number = parseInt(value, 10);
  20534. return isNaN(number) ? 0 : number;
  20535. };
  20536. const getIndentStyleName = (useMargin, element) => {
  20537. const indentStyleName = useMargin || isTable$2(element) ? 'margin' : 'padding';
  20538. const suffix = get$7(element, 'direction') === 'rtl' ? '-right' : '-left';
  20539. return indentStyleName + suffix;
  20540. };
  20541. const indentElement = (dom, command, useMargin, value, unit, element) => {
  20542. const indentStyleName = getIndentStyleName(useMargin, SugarElement.fromDom(element));
  20543. if (command === 'outdent') {
  20544. const styleValue = Math.max(0, parseIndentValue(element.style[indentStyleName]) - value);
  20545. dom.setStyle(element, indentStyleName, styleValue ? styleValue + unit : '');
  20546. } else {
  20547. const styleValue = parseIndentValue(element.style[indentStyleName]) + value + unit;
  20548. dom.setStyle(element, indentStyleName, styleValue);
  20549. }
  20550. };
  20551. const validateBlocks = (editor, blocks) => forall(blocks, block => {
  20552. const indentStyleName = getIndentStyleName(shouldIndentUseMargin(editor), block);
  20553. const intentValue = getRaw$1(block, indentStyleName).map(parseIndentValue).getOr(0);
  20554. const contentEditable = editor.dom.getContentEditable(block.dom);
  20555. return contentEditable !== 'false' && intentValue > 0;
  20556. });
  20557. const canOutdent = editor => {
  20558. const blocks = getBlocksToIndent(editor);
  20559. return !editor.mode.isReadOnly() && (blocks.length > 1 || validateBlocks(editor, blocks));
  20560. };
  20561. const isListComponent = el => isList(el) || isListItem(el);
  20562. const parentIsListComponent = el => parent(el).exists(isListComponent);
  20563. const getBlocksToIndent = editor => filter$6(fromDom$1(editor.selection.getSelectedBlocks()), el => !isListComponent(el) && !parentIsListComponent(el) && isEditable$1(el));
  20564. const handle = (editor, command) => {
  20565. const {dom} = editor;
  20566. const indentation = getIndentation(editor);
  20567. const indentUnit = /[a-z%]+$/i.exec(indentation)[0];
  20568. const indentValue = parseInt(indentation, 10);
  20569. const useMargin = shouldIndentUseMargin(editor);
  20570. each$g(getBlocksToIndent(editor), block => {
  20571. indentElement(dom, command, useMargin, indentValue, indentUnit, block.dom);
  20572. });
  20573. };
  20574. const indent = editor => handle(editor, 'indent');
  20575. const outdent = editor => handle(editor, 'outdent');
  20576. const backspaceDelete = editor => {
  20577. if (editor.selection.isCollapsed() && canOutdent(editor)) {
  20578. const dom = editor.dom;
  20579. const rng = editor.selection.getRng();
  20580. const pos = CaretPosition.fromRangeStart(rng);
  20581. const block = dom.getParent(rng.startContainer, dom.isBlock);
  20582. if (block !== null && isAtStartOfBlock(SugarElement.fromDom(block), pos)) {
  20583. return Optional.some(() => outdent(editor));
  20584. }
  20585. }
  20586. return Optional.none();
  20587. };
  20588. const findAction = (editor, caret, forward) => findMap([
  20589. backspaceDelete,
  20590. backspaceDelete$5,
  20591. backspaceDelete$6,
  20592. (editor, forward) => backspaceDelete$3(editor, caret, forward),
  20593. backspaceDelete$8,
  20594. backspaceDelete$9,
  20595. backspaceDelete$4,
  20596. backspaceDelete$1,
  20597. backspaceDelete$7,
  20598. backspaceDelete$2
  20599. ], item => item(editor, forward));
  20600. const deleteCommand = (editor, caret) => {
  20601. const result = findAction(editor, caret, false);
  20602. result.fold(() => {
  20603. execDeleteCommand(editor);
  20604. paddEmptyBody(editor);
  20605. }, call);
  20606. };
  20607. const forwardDeleteCommand = (editor, caret) => {
  20608. const result = findAction(editor, caret, true);
  20609. result.fold(() => execForwardDeleteCommand(editor), call);
  20610. };
  20611. const setup$p = (editor, caret) => {
  20612. editor.addCommand('delete', () => {
  20613. deleteCommand(editor, caret);
  20614. });
  20615. editor.addCommand('forwardDelete', () => {
  20616. forwardDeleteCommand(editor, caret);
  20617. });
  20618. };
  20619. const SIGNIFICANT_MOVE = 5;
  20620. const LONGPRESS_DELAY = 400;
  20621. const getTouch = event => {
  20622. if (event.touches === undefined || event.touches.length !== 1) {
  20623. return Optional.none();
  20624. }
  20625. return Optional.some(event.touches[0]);
  20626. };
  20627. const isFarEnough = (touch, data) => {
  20628. const distX = Math.abs(touch.clientX - data.x);
  20629. const distY = Math.abs(touch.clientY - data.y);
  20630. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  20631. };
  20632. const setup$o = editor => {
  20633. const startData = value$2();
  20634. const longpressFired = Cell(false);
  20635. const debounceLongpress = last$1(e => {
  20636. editor.dispatch('longpress', {
  20637. ...e,
  20638. type: 'longpress'
  20639. });
  20640. longpressFired.set(true);
  20641. }, LONGPRESS_DELAY);
  20642. editor.on('touchstart', e => {
  20643. getTouch(e).each(touch => {
  20644. debounceLongpress.cancel();
  20645. const data = {
  20646. x: touch.clientX,
  20647. y: touch.clientY,
  20648. target: e.target
  20649. };
  20650. debounceLongpress.throttle(e);
  20651. longpressFired.set(false);
  20652. startData.set(data);
  20653. });
  20654. }, true);
  20655. editor.on('touchmove', e => {
  20656. debounceLongpress.cancel();
  20657. getTouch(e).each(touch => {
  20658. startData.on(data => {
  20659. if (isFarEnough(touch, data)) {
  20660. startData.clear();
  20661. longpressFired.set(false);
  20662. editor.dispatch('longpresscancel');
  20663. }
  20664. });
  20665. });
  20666. }, true);
  20667. editor.on('touchend touchcancel', e => {
  20668. debounceLongpress.cancel();
  20669. if (e.type === 'touchcancel') {
  20670. return;
  20671. }
  20672. startData.get().filter(data => data.target.isEqualNode(e.target)).each(() => {
  20673. if (longpressFired.get()) {
  20674. e.preventDefault();
  20675. } else {
  20676. editor.dispatch('tap', {
  20677. ...e,
  20678. type: 'tap'
  20679. });
  20680. }
  20681. });
  20682. }, true);
  20683. };
  20684. const isBlockElement = (blockElements, node) => has$2(blockElements, node.nodeName);
  20685. const isValidTarget = (blockElements, node) => {
  20686. if (isText$8(node)) {
  20687. return true;
  20688. } else if (isElement$6(node)) {
  20689. return !isBlockElement(blockElements, node) && !isBookmarkNode$1(node);
  20690. } else {
  20691. return false;
  20692. }
  20693. };
  20694. const hasBlockParent = (blockElements, root, node) => {
  20695. return exists(parents(SugarElement.fromDom(node), SugarElement.fromDom(root)), elm => {
  20696. return isBlockElement(blockElements, elm.dom);
  20697. });
  20698. };
  20699. const shouldRemoveTextNode = (blockElements, node) => {
  20700. if (isText$8(node)) {
  20701. if (node.nodeValue.length === 0) {
  20702. return true;
  20703. } else if (/^\s+$/.test(node.nodeValue) && (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
  20704. return true;
  20705. }
  20706. }
  20707. return false;
  20708. };
  20709. const addRootBlocks = editor => {
  20710. const dom = editor.dom, selection = editor.selection;
  20711. const schema = editor.schema, blockElements = schema.getBlockElements();
  20712. let node = selection.getStart();
  20713. const rootNode = editor.getBody();
  20714. let rootBlockNode, tempNode, wrapped;
  20715. const forcedRootBlock = getForcedRootBlock(editor);
  20716. if (!node || !isElement$6(node)) {
  20717. return;
  20718. }
  20719. const rootNodeName = rootNode.nodeName.toLowerCase();
  20720. if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, node)) {
  20721. return;
  20722. }
  20723. const rng = selection.getRng();
  20724. const startContainer = rng.startContainer;
  20725. const startOffset = rng.startOffset;
  20726. const endContainer = rng.endContainer;
  20727. const endOffset = rng.endOffset;
  20728. const restoreSelection = hasFocus(editor);
  20729. node = rootNode.firstChild;
  20730. while (node) {
  20731. if (isValidTarget(blockElements, node)) {
  20732. if (shouldRemoveTextNode(blockElements, node)) {
  20733. tempNode = node;
  20734. node = node.nextSibling;
  20735. dom.remove(tempNode);
  20736. continue;
  20737. }
  20738. if (!rootBlockNode) {
  20739. rootBlockNode = dom.create(forcedRootBlock, getForcedRootBlockAttrs(editor));
  20740. node.parentNode.insertBefore(rootBlockNode, node);
  20741. wrapped = true;
  20742. }
  20743. tempNode = node;
  20744. node = node.nextSibling;
  20745. rootBlockNode.appendChild(tempNode);
  20746. } else {
  20747. rootBlockNode = null;
  20748. node = node.nextSibling;
  20749. }
  20750. }
  20751. if (wrapped && restoreSelection) {
  20752. rng.setStart(startContainer, startOffset);
  20753. rng.setEnd(endContainer, endOffset);
  20754. selection.setRng(rng);
  20755. editor.nodeChanged();
  20756. }
  20757. };
  20758. const setup$n = editor => {
  20759. editor.on('NodeChange', curry(addRootBlocks, editor));
  20760. };
  20761. const hasClass = checkClassName => node => (' ' + node.attr('class') + ' ').indexOf(checkClassName) !== -1;
  20762. const replaceMatchWithSpan = (editor, content, cls) => {
  20763. return function (match) {
  20764. const args = arguments, index = args[args.length - 2];
  20765. const prevChar = index > 0 ? content.charAt(index - 1) : '';
  20766. if (prevChar === '"') {
  20767. return match;
  20768. }
  20769. if (prevChar === '>') {
  20770. const findStartTagIndex = content.lastIndexOf('<', index);
  20771. if (findStartTagIndex !== -1) {
  20772. const tagHtml = content.substring(findStartTagIndex, index);
  20773. if (tagHtml.indexOf('contenteditable="false"') !== -1) {
  20774. return match;
  20775. }
  20776. }
  20777. }
  20778. return '<span class="' + cls + '" data-mce-content="' + editor.dom.encode(args[0]) + '">' + editor.dom.encode(typeof args[1] === 'string' ? args[1] : args[0]) + '</span>';
  20779. };
  20780. };
  20781. const convertRegExpsToNonEditable = (editor, nonEditableRegExps, e) => {
  20782. let i = nonEditableRegExps.length, content = e.content;
  20783. if (e.format === 'raw') {
  20784. return;
  20785. }
  20786. while (i--) {
  20787. content = content.replace(nonEditableRegExps[i], replaceMatchWithSpan(editor, content, getNonEditableClass(editor)));
  20788. }
  20789. e.content = content;
  20790. };
  20791. const setup$m = editor => {
  20792. const contentEditableAttrName = 'contenteditable';
  20793. const editClass = ' ' + Tools.trim(getEditableClass(editor)) + ' ';
  20794. const nonEditClass = ' ' + Tools.trim(getNonEditableClass(editor)) + ' ';
  20795. const hasEditClass = hasClass(editClass);
  20796. const hasNonEditClass = hasClass(nonEditClass);
  20797. const nonEditableRegExps = getNonEditableRegExps(editor);
  20798. if (nonEditableRegExps.length > 0) {
  20799. editor.on('BeforeSetContent', e => {
  20800. convertRegExpsToNonEditable(editor, nonEditableRegExps, e);
  20801. });
  20802. }
  20803. editor.parser.addAttributeFilter('class', nodes => {
  20804. let i = nodes.length;
  20805. while (i--) {
  20806. const node = nodes[i];
  20807. if (hasEditClass(node)) {
  20808. node.attr(contentEditableAttrName, 'true');
  20809. } else if (hasNonEditClass(node)) {
  20810. node.attr(contentEditableAttrName, 'false');
  20811. }
  20812. }
  20813. });
  20814. editor.serializer.addAttributeFilter(contentEditableAttrName, nodes => {
  20815. let i = nodes.length;
  20816. while (i--) {
  20817. const node = nodes[i];
  20818. if (!hasEditClass(node) && !hasNonEditClass(node)) {
  20819. continue;
  20820. }
  20821. if (nonEditableRegExps.length > 0 && node.attr('data-mce-content')) {
  20822. node.name = '#text';
  20823. node.type = 3;
  20824. node.raw = true;
  20825. node.value = node.attr('data-mce-content');
  20826. } else {
  20827. node.attr(contentEditableAttrName, null);
  20828. }
  20829. }
  20830. });
  20831. };
  20832. const findBlockCaretContainer = editor => descendant(SugarElement.fromDom(editor.getBody()), '*[data-mce-caret]').map(elm => elm.dom).getOrNull();
  20833. const showBlockCaretContainer = (editor, blockCaretContainer) => {
  20834. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  20835. showCaretContainerBlock(blockCaretContainer);
  20836. editor.selection.setRng(editor.selection.getRng());
  20837. editor.selection.scrollIntoView(blockCaretContainer);
  20838. }
  20839. };
  20840. const handleBlockContainer = (editor, e) => {
  20841. const blockCaretContainer = findBlockCaretContainer(editor);
  20842. if (!blockCaretContainer) {
  20843. return;
  20844. }
  20845. if (e.type === 'compositionstart') {
  20846. e.preventDefault();
  20847. e.stopPropagation();
  20848. showBlockCaretContainer(editor, blockCaretContainer);
  20849. return;
  20850. }
  20851. if (hasContent(blockCaretContainer)) {
  20852. showBlockCaretContainer(editor, blockCaretContainer);
  20853. editor.undoManager.add();
  20854. }
  20855. };
  20856. const setup$l = editor => {
  20857. editor.on('keyup compositionstart', curry(handleBlockContainer, editor));
  20858. };
  20859. const isContentEditableFalse$2 = isContentEditableFalse$a;
  20860. const moveToCeFalseHorizontally = (direction, editor, range) => moveHorizontally(editor, direction, range, isBeforeContentEditableFalse, isAfterContentEditableFalse, isContentEditableFalse$2);
  20861. const moveToCeFalseVertically = (direction, editor, range) => {
  20862. const isBefore = caretPosition => isBeforeContentEditableFalse(caretPosition) || isBeforeTable(caretPosition);
  20863. const isAfter = caretPosition => isAfterContentEditableFalse(caretPosition) || isAfterTable(caretPosition);
  20864. return moveVertically(editor, direction, range, isBefore, isAfter, isContentEditableFalse$2);
  20865. };
  20866. const createTextBlock = editor => {
  20867. const textBlock = editor.dom.create(getForcedRootBlock(editor));
  20868. textBlock.innerHTML = '<br data-mce-bogus="1">';
  20869. return textBlock;
  20870. };
  20871. const exitPreBlock = (editor, direction, range) => {
  20872. const caretWalker = CaretWalker(editor.getBody());
  20873. const getVisualCaretPosition$1 = curry(getVisualCaretPosition, direction === 1 ? caretWalker.next : caretWalker.prev);
  20874. if (range.collapsed) {
  20875. const pre = editor.dom.getParent(range.startContainer, 'PRE');
  20876. if (!pre) {
  20877. return;
  20878. }
  20879. const caretPos = getVisualCaretPosition$1(CaretPosition.fromRangeStart(range));
  20880. if (!caretPos) {
  20881. const newBlock = SugarElement.fromDom(createTextBlock(editor));
  20882. if (direction === 1) {
  20883. after$4(SugarElement.fromDom(pre), newBlock);
  20884. } else {
  20885. before$3(SugarElement.fromDom(pre), newBlock);
  20886. }
  20887. editor.selection.select(newBlock.dom, true);
  20888. editor.selection.collapse();
  20889. }
  20890. }
  20891. };
  20892. const getHorizontalRange = (editor, forward) => {
  20893. const direction = forward ? HDirection.Forwards : HDirection.Backwards;
  20894. const range = editor.selection.getRng();
  20895. return moveToCeFalseHorizontally(direction, editor, range).orThunk(() => {
  20896. exitPreBlock(editor, direction, range);
  20897. return Optional.none();
  20898. });
  20899. };
  20900. const getVerticalRange = (editor, down) => {
  20901. const direction = down ? 1 : -1;
  20902. const range = editor.selection.getRng();
  20903. return moveToCeFalseVertically(direction, editor, range).orThunk(() => {
  20904. exitPreBlock(editor, direction, range);
  20905. return Optional.none();
  20906. });
  20907. };
  20908. const moveH$2 = (editor, forward) => getHorizontalRange(editor, forward).exists(newRange => {
  20909. moveToRange(editor, newRange);
  20910. return true;
  20911. });
  20912. const moveV$3 = (editor, down) => getVerticalRange(editor, down).exists(newRange => {
  20913. moveToRange(editor, newRange);
  20914. return true;
  20915. });
  20916. const moveToLineEndPoint$1 = (editor, forward) => {
  20917. const isCefPosition = forward ? isAfterContentEditableFalse : isBeforeContentEditableFalse;
  20918. return moveToLineEndPoint$3(editor, forward, isCefPosition);
  20919. };
  20920. const isTarget = node => contains$2(['figcaption'], name(node));
  20921. const rangeBefore = target => {
  20922. const rng = document.createRange();
  20923. rng.setStartBefore(target.dom);
  20924. rng.setEndBefore(target.dom);
  20925. return rng;
  20926. };
  20927. const insertElement = (root, elm, forward) => {
  20928. if (forward) {
  20929. append$1(root, elm);
  20930. } else {
  20931. prepend(root, elm);
  20932. }
  20933. };
  20934. const insertEmptyLine = (root, forward, blockName, attrs) => {
  20935. const block = SugarElement.fromTag(blockName);
  20936. const br = SugarElement.fromTag('br');
  20937. setAll$1(block, attrs);
  20938. append$1(block, br);
  20939. insertElement(root, block, forward);
  20940. return rangeBefore(br);
  20941. };
  20942. const getClosestTargetBlock = (pos, root) => {
  20943. const isRoot = curry(eq, root);
  20944. return closest$4(SugarElement.fromDom(pos.container()), isBlock$2, isRoot).filter(isTarget);
  20945. };
  20946. const isAtFirstOrLastLine = (root, forward, pos) => forward ? isAtLastLine(root.dom, pos) : isAtFirstLine(root.dom, pos);
  20947. const moveCaretToNewEmptyLine = (editor, forward) => {
  20948. const root = SugarElement.fromDom(editor.getBody());
  20949. const pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  20950. const rootBlock = getForcedRootBlock(editor);
  20951. const rootBlockAttrs = getForcedRootBlockAttrs(editor);
  20952. return getClosestTargetBlock(pos, root).exists(() => {
  20953. if (isAtFirstOrLastLine(root, forward, pos)) {
  20954. const rng = insertEmptyLine(root, forward, rootBlock, rootBlockAttrs);
  20955. editor.selection.setRng(rng);
  20956. return true;
  20957. } else {
  20958. return false;
  20959. }
  20960. });
  20961. };
  20962. const moveV$2 = (editor, forward) => {
  20963. if (editor.selection.isCollapsed()) {
  20964. return moveCaretToNewEmptyLine(editor, forward);
  20965. } else {
  20966. return false;
  20967. }
  20968. };
  20969. const baseKeyPattern = {
  20970. shiftKey: false,
  20971. altKey: false,
  20972. ctrlKey: false,
  20973. metaKey: false,
  20974. keyCode: 0
  20975. };
  20976. const defaultPatterns = patterns => map$3(patterns, pattern => ({
  20977. ...baseKeyPattern,
  20978. action: noop,
  20979. ...pattern
  20980. }));
  20981. const defaultDelayedPatterns = patterns => map$3(patterns, pattern => ({
  20982. ...baseKeyPattern,
  20983. action: () => Optional.none(),
  20984. ...pattern
  20985. }));
  20986. const matchesEvent = (pattern, evt) => evt.keyCode === pattern.keyCode && evt.shiftKey === pattern.shiftKey && evt.altKey === pattern.altKey && evt.ctrlKey === pattern.ctrlKey && evt.metaKey === pattern.metaKey;
  20987. const match$1 = (patterns, evt) => bind$3(defaultPatterns(patterns), pattern => matchesEvent(pattern, evt) ? [pattern] : []);
  20988. const matchDelayed = (patterns, evt) => bind$3(defaultDelayedPatterns(patterns), pattern => matchesEvent(pattern, evt) ? [pattern] : []);
  20989. const action = (f, ...x) => () => f.apply(null, x);
  20990. const execute = (patterns, evt) => find$2(match$1(patterns, evt), pattern => pattern.action());
  20991. const executeWithDelayedAction = (patterns, evt) => findMap(matchDelayed(patterns, evt), pattern => pattern.action());
  20992. const moveH$1 = (editor, forward) => {
  20993. const direction = forward ? HDirection.Forwards : HDirection.Backwards;
  20994. const range = editor.selection.getRng();
  20995. return moveHorizontally(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(newRange => {
  20996. moveToRange(editor, newRange);
  20997. return true;
  20998. });
  20999. };
  21000. const moveV$1 = (editor, down) => {
  21001. const direction = down ? 1 : -1;
  21002. const range = editor.selection.getRng();
  21003. return moveVertically(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(newRange => {
  21004. moveToRange(editor, newRange);
  21005. return true;
  21006. });
  21007. };
  21008. const moveToLineEndPoint = (editor, forward) => {
  21009. const isNearMedia = forward ? isAfterMedia : isBeforeMedia;
  21010. return moveToLineEndPoint$3(editor, forward, isNearMedia);
  21011. };
  21012. const adt = Adt.generate([
  21013. { none: ['current'] },
  21014. { first: ['current'] },
  21015. {
  21016. middle: [
  21017. 'current',
  21018. 'target'
  21019. ]
  21020. },
  21021. { last: ['current'] }
  21022. ]);
  21023. const none = current => adt.none(current);
  21024. const CellLocation = {
  21025. ...adt,
  21026. none
  21027. };
  21028. const firstLayer = (scope, selector) => {
  21029. return filterFirstLayer(scope, selector, always);
  21030. };
  21031. const filterFirstLayer = (scope, selector, predicate) => {
  21032. return bind$3(children(scope), x => {
  21033. if (is$1(x, selector)) {
  21034. return predicate(x) ? [x] : [];
  21035. } else {
  21036. return filterFirstLayer(x, selector, predicate);
  21037. }
  21038. });
  21039. };
  21040. const lookup$1 = (tags, element, isRoot = never) => {
  21041. if (isRoot(element)) {
  21042. return Optional.none();
  21043. }
  21044. if (contains$2(tags, name(element))) {
  21045. return Optional.some(element);
  21046. }
  21047. const isRootOrUpperTable = elm => is$1(elm, 'table') || isRoot(elm);
  21048. return ancestor$2(element, tags.join(','), isRootOrUpperTable);
  21049. };
  21050. const cell = (element, isRoot) => lookup$1([
  21051. 'td',
  21052. 'th'
  21053. ], element, isRoot);
  21054. const cells = ancestor => firstLayer(ancestor, 'th,td');
  21055. const table = (element, isRoot) => closest$3(element, 'table', isRoot);
  21056. const walk = (all, current, index, direction, isEligible = always) => {
  21057. const forwards = direction === 1;
  21058. if (!forwards && index <= 0) {
  21059. return CellLocation.first(all[0]);
  21060. } else if (forwards && index >= all.length - 1) {
  21061. return CellLocation.last(all[all.length - 1]);
  21062. } else {
  21063. const newIndex = index + direction;
  21064. const elem = all[newIndex];
  21065. return isEligible(elem) ? CellLocation.middle(current, elem) : walk(all, current, newIndex, direction, isEligible);
  21066. }
  21067. };
  21068. const detect = (current, isRoot) => {
  21069. return table(current, isRoot).bind(table => {
  21070. const all = cells(table);
  21071. const index = findIndex$2(all, x => eq(current, x));
  21072. return index.map(index => ({
  21073. index,
  21074. all
  21075. }));
  21076. });
  21077. };
  21078. const next = (current, isEligible, isRoot) => {
  21079. const detection = detect(current, isRoot);
  21080. return detection.fold(() => {
  21081. return CellLocation.none(current);
  21082. }, info => {
  21083. return walk(info.all, current, info.index, 1, isEligible);
  21084. });
  21085. };
  21086. const prev = (current, isEligible, isRoot) => {
  21087. const detection = detect(current, isRoot);
  21088. return detection.fold(() => {
  21089. return CellLocation.none();
  21090. }, info => {
  21091. return walk(info.all, current, info.index, -1, isEligible);
  21092. });
  21093. };
  21094. const closest = target => closest$3(target, '[contenteditable]');
  21095. const isEditable = (element, assumeEditable = false) => {
  21096. if (inBody(element)) {
  21097. return element.dom.isContentEditable;
  21098. } else {
  21099. return closest(element).fold(constant(assumeEditable), editable => getRaw(editable) === 'true');
  21100. }
  21101. };
  21102. const getRaw = element => element.dom.contentEditable;
  21103. const deflate = (rect, delta) => ({
  21104. left: rect.left - delta,
  21105. top: rect.top - delta,
  21106. right: rect.right + delta * 2,
  21107. bottom: rect.bottom + delta * 2,
  21108. width: rect.width + delta,
  21109. height: rect.height + delta
  21110. });
  21111. const getCorners = (getYAxisValue, tds) => bind$3(tds, td => {
  21112. const rect = deflate(clone$1(td.getBoundingClientRect()), -1);
  21113. return [
  21114. {
  21115. x: rect.left,
  21116. y: getYAxisValue(rect),
  21117. cell: td
  21118. },
  21119. {
  21120. x: rect.right,
  21121. y: getYAxisValue(rect),
  21122. cell: td
  21123. }
  21124. ];
  21125. });
  21126. const findClosestCorner = (corners, x, y) => foldl(corners, (acc, newCorner) => acc.fold(() => Optional.some(newCorner), oldCorner => {
  21127. const oldDist = Math.sqrt(Math.abs(oldCorner.x - x) + Math.abs(oldCorner.y - y));
  21128. const newDist = Math.sqrt(Math.abs(newCorner.x - x) + Math.abs(newCorner.y - y));
  21129. return Optional.some(newDist < oldDist ? newCorner : oldCorner);
  21130. }), Optional.none());
  21131. const getClosestCell = (getYAxisValue, isTargetCorner, table, x, y) => {
  21132. const cells = descendants(SugarElement.fromDom(table), 'td,th,caption').map(e => e.dom);
  21133. const corners = filter$6(getCorners(getYAxisValue, cells), corner => isTargetCorner(corner, y));
  21134. return findClosestCorner(corners, x, y).map(corner => corner.cell);
  21135. };
  21136. const getBottomValue = rect => rect.bottom;
  21137. const getTopValue = rect => rect.top;
  21138. const isAbove = (corner, y) => corner.y < y;
  21139. const isBelow = (corner, y) => corner.y > y;
  21140. const getClosestCellAbove = curry(getClosestCell, getBottomValue, isAbove);
  21141. const getClosestCellBelow = curry(getClosestCell, getTopValue, isBelow);
  21142. const findClosestPositionInAboveCell = (table, pos) => head(pos.getClientRects()).bind(rect => getClosestCellAbove(table, rect.left, rect.top)).bind(cell => findClosestHorizontalPosition(getLastLinePositions(cell), pos));
  21143. const findClosestPositionInBelowCell = (table, pos) => last$3(pos.getClientRects()).bind(rect => getClosestCellBelow(table, rect.left, rect.top)).bind(cell => findClosestHorizontalPosition(getFirstLinePositions(cell), pos));
  21144. const hasNextBreak = (getPositionsUntil, scope, lineInfo) => lineInfo.breakAt.exists(breakPos => getPositionsUntil(scope, breakPos).breakAt.isSome());
  21145. const startsWithWrapBreak = lineInfo => lineInfo.breakType === BreakType.Wrap && lineInfo.positions.length === 0;
  21146. const startsWithBrBreak = lineInfo => lineInfo.breakType === BreakType.Br && lineInfo.positions.length === 1;
  21147. const isAtTableCellLine = (getPositionsUntil, scope, pos) => {
  21148. const lineInfo = getPositionsUntil(scope, pos);
  21149. if (startsWithWrapBreak(lineInfo) || !isBr$5(pos.getNode()) && startsWithBrBreak(lineInfo)) {
  21150. return !hasNextBreak(getPositionsUntil, scope, lineInfo);
  21151. } else {
  21152. return lineInfo.breakAt.isNone();
  21153. }
  21154. };
  21155. const isAtFirstTableCellLine = curry(isAtTableCellLine, getPositionsUntilPreviousLine);
  21156. const isAtLastTableCellLine = curry(isAtTableCellLine, getPositionsUntilNextLine);
  21157. const isCaretAtStartOrEndOfTable = (forward, rng, table) => {
  21158. const caretPos = CaretPosition.fromRangeStart(rng);
  21159. return positionIn(!forward, table).exists(pos => pos.isEqual(caretPos));
  21160. };
  21161. const navigateHorizontally = (editor, forward, table, _td) => {
  21162. const rng = editor.selection.getRng();
  21163. const direction = forward ? 1 : -1;
  21164. if (isFakeCaretTableBrowser() && isCaretAtStartOrEndOfTable(forward, rng, table)) {
  21165. showCaret(direction, editor, table, !forward, false).each(newRng => {
  21166. moveToRange(editor, newRng);
  21167. });
  21168. return true;
  21169. }
  21170. return false;
  21171. };
  21172. const getClosestAbovePosition = (root, table, start) => findClosestPositionInAboveCell(table, start).orThunk(() => head(start.getClientRects()).bind(rect => findClosestHorizontalPositionFromPoint(getPositionsAbove(root, CaretPosition.before(table)), rect.left))).getOr(CaretPosition.before(table));
  21173. const getClosestBelowPosition = (root, table, start) => findClosestPositionInBelowCell(table, start).orThunk(() => head(start.getClientRects()).bind(rect => findClosestHorizontalPositionFromPoint(getPositionsBelow(root, CaretPosition.after(table)), rect.left))).getOr(CaretPosition.after(table));
  21174. const getTable = (previous, pos) => {
  21175. const node = pos.getNode(previous);
  21176. return isElement$6(node) && node.nodeName === 'TABLE' ? Optional.some(node) : Optional.none();
  21177. };
  21178. const renderBlock = (down, editor, table) => {
  21179. const forcedRootBlock = getForcedRootBlock(editor);
  21180. editor.undoManager.transact(() => {
  21181. const element = SugarElement.fromTag(forcedRootBlock);
  21182. setAll$1(element, getForcedRootBlockAttrs(editor));
  21183. append$1(element, SugarElement.fromTag('br'));
  21184. if (down) {
  21185. after$4(SugarElement.fromDom(table), element);
  21186. } else {
  21187. before$3(SugarElement.fromDom(table), element);
  21188. }
  21189. const rng = editor.dom.createRng();
  21190. rng.setStart(element.dom, 0);
  21191. rng.setEnd(element.dom, 0);
  21192. moveToRange(editor, rng);
  21193. });
  21194. };
  21195. const moveCaret = (editor, down, pos) => {
  21196. const table = down ? getTable(true, pos) : getTable(false, pos);
  21197. const last = down === false;
  21198. table.fold(() => moveToRange(editor, pos.toRange()), table => positionIn(last, editor.getBody()).filter(lastPos => lastPos.isEqual(pos)).fold(() => moveToRange(editor, pos.toRange()), _ => renderBlock(down, editor, table)));
  21199. };
  21200. const navigateVertically = (editor, down, table, td) => {
  21201. const rng = editor.selection.getRng();
  21202. const pos = CaretPosition.fromRangeStart(rng);
  21203. const root = editor.getBody();
  21204. if (!down && isAtFirstTableCellLine(td, pos)) {
  21205. const newPos = getClosestAbovePosition(root, table, pos);
  21206. moveCaret(editor, down, newPos);
  21207. return true;
  21208. } else if (down && isAtLastTableCellLine(td, pos)) {
  21209. const newPos = getClosestBelowPosition(root, table, pos);
  21210. moveCaret(editor, down, newPos);
  21211. return true;
  21212. } else {
  21213. return false;
  21214. }
  21215. };
  21216. const move$1 = (editor, forward, mover) => Optional.from(editor.dom.getParent(editor.selection.getNode(), 'td,th')).bind(td => Optional.from(editor.dom.getParent(td, 'table')).map(table => mover(editor, forward, table, td))).getOr(false);
  21217. const moveH = (editor, forward) => move$1(editor, forward, navigateHorizontally);
  21218. const moveV = (editor, forward) => move$1(editor, forward, navigateVertically);
  21219. const getCellFirstCursorPosition = cell => {
  21220. const selection = SimSelection.exact(cell, 0, cell, 0);
  21221. return toNative(selection);
  21222. };
  21223. const tabGo = (editor, isRoot, cell) => {
  21224. return cell.fold(Optional.none, Optional.none, (_current, next) => {
  21225. return first(next).map(cell => {
  21226. return getCellFirstCursorPosition(cell);
  21227. });
  21228. }, current => {
  21229. editor.execCommand('mceTableInsertRowAfter');
  21230. return tabForward(editor, isRoot, current);
  21231. });
  21232. };
  21233. const tabForward = (editor, isRoot, cell) => tabGo(editor, isRoot, next(cell, isEditable));
  21234. const tabBackward = (editor, isRoot, cell) => tabGo(editor, isRoot, prev(cell, isEditable));
  21235. const handleTab = (editor, forward) => {
  21236. const rootElements = [
  21237. 'table',
  21238. 'li',
  21239. 'dl'
  21240. ];
  21241. const body = SugarElement.fromDom(editor.getBody());
  21242. const isRoot = element => {
  21243. const name$1 = name(element);
  21244. return eq(element, body) || contains$2(rootElements, name$1);
  21245. };
  21246. const rng = editor.selection.getRng();
  21247. const container = SugarElement.fromDom(!forward ? rng.startContainer : rng.endContainer);
  21248. return cell(container, isRoot).map(cell => {
  21249. table(cell, isRoot).each(table => {
  21250. editor.model.table.clearSelectedCells(table.dom);
  21251. });
  21252. editor.selection.collapse(!forward);
  21253. const navigation = !forward ? tabBackward : tabForward;
  21254. const rng = navigation(editor, isRoot, cell);
  21255. rng.each(range => {
  21256. editor.selection.setRng(range);
  21257. });
  21258. return true;
  21259. }).getOr(false);
  21260. };
  21261. const executeKeydownOverride$4 = (editor, caret, evt) => {
  21262. const os = detect$2().os;
  21263. execute([
  21264. {
  21265. keyCode: VK.RIGHT,
  21266. action: action(moveH$2, editor, true)
  21267. },
  21268. {
  21269. keyCode: VK.LEFT,
  21270. action: action(moveH$2, editor, false)
  21271. },
  21272. {
  21273. keyCode: VK.UP,
  21274. action: action(moveV$3, editor, false)
  21275. },
  21276. {
  21277. keyCode: VK.DOWN,
  21278. action: action(moveV$3, editor, true)
  21279. },
  21280. {
  21281. keyCode: VK.RIGHT,
  21282. action: action(moveH, editor, true)
  21283. },
  21284. {
  21285. keyCode: VK.LEFT,
  21286. action: action(moveH, editor, false)
  21287. },
  21288. {
  21289. keyCode: VK.UP,
  21290. action: action(moveV, editor, false)
  21291. },
  21292. {
  21293. keyCode: VK.DOWN,
  21294. action: action(moveV, editor, true)
  21295. },
  21296. {
  21297. keyCode: VK.RIGHT,
  21298. action: action(moveH$1, editor, true)
  21299. },
  21300. {
  21301. keyCode: VK.LEFT,
  21302. action: action(moveH$1, editor, false)
  21303. },
  21304. {
  21305. keyCode: VK.UP,
  21306. action: action(moveV$1, editor, false)
  21307. },
  21308. {
  21309. keyCode: VK.DOWN,
  21310. action: action(moveV$1, editor, true)
  21311. },
  21312. {
  21313. keyCode: VK.RIGHT,
  21314. action: action(move$2, editor, caret, true)
  21315. },
  21316. {
  21317. keyCode: VK.LEFT,
  21318. action: action(move$2, editor, caret, false)
  21319. },
  21320. {
  21321. keyCode: VK.RIGHT,
  21322. ctrlKey: !os.isMacOS(),
  21323. altKey: os.isMacOS(),
  21324. action: action(moveNextWord, editor, caret)
  21325. },
  21326. {
  21327. keyCode: VK.LEFT,
  21328. ctrlKey: !os.isMacOS(),
  21329. altKey: os.isMacOS(),
  21330. action: action(movePrevWord, editor, caret)
  21331. },
  21332. {
  21333. keyCode: VK.UP,
  21334. action: action(moveV$2, editor, false)
  21335. },
  21336. {
  21337. keyCode: VK.DOWN,
  21338. action: action(moveV$2, editor, true)
  21339. }
  21340. ], evt).each(_ => {
  21341. evt.preventDefault();
  21342. });
  21343. };
  21344. const setup$k = (editor, caret) => {
  21345. editor.on('keydown', evt => {
  21346. if (evt.isDefaultPrevented() === false) {
  21347. executeKeydownOverride$4(editor, caret, evt);
  21348. }
  21349. });
  21350. };
  21351. const point = (container, offset) => ({
  21352. container,
  21353. offset
  21354. });
  21355. const DOM$7 = DOMUtils.DOM;
  21356. const alwaysNext = startNode => node => startNode === node ? -1 : 0;
  21357. const isBoundary = dom => node => dom.isBlock(node) || contains$2([
  21358. 'BR',
  21359. 'IMG',
  21360. 'HR',
  21361. 'INPUT'
  21362. ], node.nodeName) || dom.getContentEditable(node) === 'false';
  21363. const textBefore = (node, offset, rootNode) => {
  21364. if (isText$8(node) && offset >= 0) {
  21365. return Optional.some(point(node, offset));
  21366. } else {
  21367. const textSeeker = TextSeeker(DOM$7);
  21368. return Optional.from(textSeeker.backwards(node, offset, alwaysNext(node), rootNode)).map(prev => point(prev.container, prev.container.data.length));
  21369. }
  21370. };
  21371. const textAfter = (node, offset, rootNode) => {
  21372. if (isText$8(node) && offset >= node.length) {
  21373. return Optional.some(point(node, offset));
  21374. } else {
  21375. const textSeeker = TextSeeker(DOM$7);
  21376. return Optional.from(textSeeker.forwards(node, offset, alwaysNext(node), rootNode)).map(prev => point(prev.container, 0));
  21377. }
  21378. };
  21379. const scanLeft = (node, offset, rootNode) => {
  21380. if (!isText$8(node)) {
  21381. return Optional.none();
  21382. }
  21383. const text = node.textContent;
  21384. if (offset >= 0 && offset <= text.length) {
  21385. return Optional.some(point(node, offset));
  21386. } else {
  21387. const textSeeker = TextSeeker(DOM$7);
  21388. return Optional.from(textSeeker.backwards(node, offset, alwaysNext(node), rootNode)).bind(prev => {
  21389. const prevText = prev.container.data;
  21390. return scanLeft(prev.container, offset + prevText.length, rootNode);
  21391. });
  21392. }
  21393. };
  21394. const scanRight = (node, offset, rootNode) => {
  21395. if (!isText$8(node)) {
  21396. return Optional.none();
  21397. }
  21398. const text = node.textContent;
  21399. if (offset <= text.length) {
  21400. return Optional.some(point(node, offset));
  21401. } else {
  21402. const textSeeker = TextSeeker(DOM$7);
  21403. return Optional.from(textSeeker.forwards(node, offset, alwaysNext(node), rootNode)).bind(next => scanRight(next.container, offset - text.length, rootNode));
  21404. }
  21405. };
  21406. const repeatLeft = (dom, node, offset, process, rootNode) => {
  21407. const search = TextSeeker(dom, isBoundary(dom));
  21408. return Optional.from(search.backwards(node, offset, process, rootNode));
  21409. };
  21410. const isValidTextRange = rng => rng.collapsed && rng.startContainer.nodeType === 3;
  21411. const getText = rng => rng.toString().replace(/\u00A0/g, ' ').replace(/\uFEFF/g, '');
  21412. const isWhitespace = chr => chr !== '' && ' \xA0\f\n\r\t\x0B'.indexOf(chr) !== -1;
  21413. const stripTriggerChar = (text, triggerCh) => text.substring(triggerCh.length);
  21414. const findChar = (text, index, ch) => {
  21415. let i;
  21416. for (i = index - 1; i >= 0; i--) {
  21417. const char = text.charAt(i);
  21418. if (isWhitespace(char)) {
  21419. return Optional.none();
  21420. }
  21421. if (char === ch) {
  21422. break;
  21423. }
  21424. }
  21425. return Optional.some(i);
  21426. };
  21427. const findStart = (dom, initRange, ch, minChars = 0) => {
  21428. if (!isValidTextRange(initRange)) {
  21429. return Optional.none();
  21430. }
  21431. const findTriggerChIndex = (element, offset, text) => findChar(text, offset, ch).getOr(offset);
  21432. const root = dom.getParent(initRange.startContainer, dom.isBlock) || dom.getRoot();
  21433. return repeatLeft(dom, initRange.startContainer, initRange.startOffset, findTriggerChIndex, root).bind(spot => {
  21434. const range = initRange.cloneRange();
  21435. range.setStart(spot.container, spot.offset);
  21436. range.setEnd(initRange.endContainer, initRange.endOffset);
  21437. if (range.collapsed) {
  21438. return Optional.none();
  21439. }
  21440. const text = getText(range);
  21441. const triggerCharIndex = text.lastIndexOf(ch);
  21442. if (triggerCharIndex !== 0 || stripTriggerChar(text, ch).length < minChars) {
  21443. return Optional.none();
  21444. } else {
  21445. return Optional.some({
  21446. text: stripTriggerChar(text, ch),
  21447. range,
  21448. triggerChar: ch
  21449. });
  21450. }
  21451. });
  21452. };
  21453. const getContext = (dom, initRange, ch, minChars = 0) => detect$1(SugarElement.fromDom(initRange.startContainer)).fold(() => findStart(dom, initRange, ch, minChars), elm => {
  21454. const range = dom.createRng();
  21455. range.selectNode(elm.dom);
  21456. const text = getText(range);
  21457. return Optional.some({
  21458. range,
  21459. text: stripTriggerChar(text, ch),
  21460. triggerChar: ch
  21461. });
  21462. });
  21463. const isText = node => node.nodeType === TEXT;
  21464. const isElement = node => node.nodeType === ELEMENT;
  21465. const toLast = node => {
  21466. if (isText(node)) {
  21467. return point(node, node.data.length);
  21468. } else {
  21469. const children = node.childNodes;
  21470. return children.length > 0 ? toLast(children[children.length - 1]) : point(node, children.length);
  21471. }
  21472. };
  21473. const toLeaf = (node, offset) => {
  21474. const children = node.childNodes;
  21475. if (children.length > 0 && offset < children.length) {
  21476. return toLeaf(children[offset], 0);
  21477. } else if (children.length > 0 && isElement(node) && children.length === offset) {
  21478. return toLast(children[children.length - 1]);
  21479. } else {
  21480. return point(node, offset);
  21481. }
  21482. };
  21483. const isPreviousCharContent = (dom, leaf) => repeatLeft(dom, leaf.container, leaf.offset, (element, offset) => offset === 0 ? -1 : offset, dom.getRoot()).filter(spot => {
  21484. const char = spot.container.data.charAt(spot.offset - 1);
  21485. return !isWhitespace(char);
  21486. }).isSome();
  21487. const isStartOfWord = dom => rng => {
  21488. const leaf = toLeaf(rng.startContainer, rng.startOffset);
  21489. return !isPreviousCharContent(dom, leaf);
  21490. };
  21491. const getTriggerContext = (dom, initRange, database) => findMap(database.triggerChars, ch => getContext(dom, initRange, ch));
  21492. const lookup = (editor, getDatabase) => {
  21493. const database = getDatabase();
  21494. const rng = editor.selection.getRng();
  21495. return getTriggerContext(editor.dom, rng, database).bind(context => lookupWithContext(editor, getDatabase, context));
  21496. };
  21497. const lookupWithContext = (editor, getDatabase, context, fetchOptions = {}) => {
  21498. const database = getDatabase();
  21499. const rng = editor.selection.getRng();
  21500. const startText = rng.startContainer.nodeValue;
  21501. const autocompleters = filter$6(database.lookupByChar(context.triggerChar), autocompleter => context.text.length >= autocompleter.minChars && autocompleter.matches.getOrThunk(() => isStartOfWord(editor.dom))(context.range, startText, context.text));
  21502. if (autocompleters.length === 0) {
  21503. return Optional.none();
  21504. }
  21505. const lookupData = Promise.all(map$3(autocompleters, ac => {
  21506. const fetchResult = ac.fetch(context.text, ac.maxResults, fetchOptions);
  21507. return fetchResult.then(results => ({
  21508. matchText: context.text,
  21509. items: results,
  21510. columns: ac.columns,
  21511. onAction: ac.onAction,
  21512. highlightOn: ac.highlightOn
  21513. }));
  21514. }));
  21515. return Optional.some({
  21516. lookupData,
  21517. context
  21518. });
  21519. };
  21520. var SimpleResultType;
  21521. (function (SimpleResultType) {
  21522. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  21523. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  21524. }(SimpleResultType || (SimpleResultType = {})));
  21525. const fold$1 = (res, onError, onValue) => res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  21526. const partition = results => {
  21527. const values = [];
  21528. const errors = [];
  21529. each$g(results, obj => {
  21530. fold$1(obj, err => errors.push(err), val => values.push(val));
  21531. });
  21532. return {
  21533. values,
  21534. errors
  21535. };
  21536. };
  21537. const mapError = (res, f) => {
  21538. if (res.stype === SimpleResultType.Error) {
  21539. return {
  21540. stype: SimpleResultType.Error,
  21541. serror: f(res.serror)
  21542. };
  21543. } else {
  21544. return res;
  21545. }
  21546. };
  21547. const map = (res, f) => {
  21548. if (res.stype === SimpleResultType.Value) {
  21549. return {
  21550. stype: SimpleResultType.Value,
  21551. svalue: f(res.svalue)
  21552. };
  21553. } else {
  21554. return res;
  21555. }
  21556. };
  21557. const bind = (res, f) => {
  21558. if (res.stype === SimpleResultType.Value) {
  21559. return f(res.svalue);
  21560. } else {
  21561. return res;
  21562. }
  21563. };
  21564. const bindError = (res, f) => {
  21565. if (res.stype === SimpleResultType.Error) {
  21566. return f(res.serror);
  21567. } else {
  21568. return res;
  21569. }
  21570. };
  21571. const svalue = v => ({
  21572. stype: SimpleResultType.Value,
  21573. svalue: v
  21574. });
  21575. const serror = e => ({
  21576. stype: SimpleResultType.Error,
  21577. serror: e
  21578. });
  21579. const toResult = res => fold$1(res, Result.error, Result.value);
  21580. const fromResult = res => res.fold(serror, svalue);
  21581. const SimpleResult = {
  21582. fromResult,
  21583. toResult,
  21584. svalue,
  21585. partition,
  21586. serror,
  21587. bind,
  21588. bindError,
  21589. map,
  21590. mapError,
  21591. fold: fold$1
  21592. };
  21593. const formatObj = input => {
  21594. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  21595. };
  21596. const formatErrors = errors => {
  21597. const es = errors.length > 10 ? errors.slice(0, 10).concat([{
  21598. path: [],
  21599. getErrorInfo: constant('... (only showing first ten failures)')
  21600. }]) : errors;
  21601. return map$3(es, e => {
  21602. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  21603. });
  21604. };
  21605. const nu = (path, getErrorInfo) => {
  21606. return SimpleResult.serror([{
  21607. path,
  21608. getErrorInfo
  21609. }]);
  21610. };
  21611. const missingRequired = (path, key, obj) => nu(path, () => 'Could not find valid *required* value for "' + key + '" in ' + formatObj(obj));
  21612. const missingKey = (path, key) => nu(path, () => 'Choice schema did not contain choice key: "' + key + '"');
  21613. const missingBranch = (path, branches, branch) => nu(path, () => 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches));
  21614. const custom = (path, err) => nu(path, constant(err));
  21615. const chooseFrom = (path, input, branches, ch) => {
  21616. const fields = get$a(branches, ch);
  21617. return fields.fold(() => missingBranch(path, branches, ch), vp => vp.extract(path.concat(['branch: ' + ch]), input));
  21618. };
  21619. const choose$1 = (key, branches) => {
  21620. const extract = (path, input) => {
  21621. const choice = get$a(input, key);
  21622. return choice.fold(() => missingKey(path, key), chosen => chooseFrom(path, input, branches, chosen));
  21623. };
  21624. const toString = () => 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  21625. return {
  21626. extract,
  21627. toString
  21628. };
  21629. };
  21630. const shallow = (old, nu) => {
  21631. return nu;
  21632. };
  21633. const deep = (old, nu) => {
  21634. const bothObjects = isPlainObject(old) && isPlainObject(nu);
  21635. return bothObjects ? deepMerge(old, nu) : nu;
  21636. };
  21637. const baseMerge = merger => {
  21638. return (...objects) => {
  21639. if (objects.length === 0) {
  21640. throw new Error(`Can't merge zero objects`);
  21641. }
  21642. const ret = {};
  21643. for (let j = 0; j < objects.length; j++) {
  21644. const curObject = objects[j];
  21645. for (const key in curObject) {
  21646. if (has$2(curObject, key)) {
  21647. ret[key] = merger(ret[key], curObject[key]);
  21648. }
  21649. }
  21650. }
  21651. return ret;
  21652. };
  21653. };
  21654. const deepMerge = baseMerge(deep);
  21655. const merge = baseMerge(shallow);
  21656. const required = () => ({
  21657. tag: 'required',
  21658. process: {}
  21659. });
  21660. const defaultedThunk = fallbackThunk => ({
  21661. tag: 'defaultedThunk',
  21662. process: fallbackThunk
  21663. });
  21664. const defaulted$1 = fallback => defaultedThunk(constant(fallback));
  21665. const asOption = () => ({
  21666. tag: 'option',
  21667. process: {}
  21668. });
  21669. const mergeValues = (values, base) => values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge.apply(undefined, values))) : SimpleResult.svalue(base);
  21670. const mergeErrors = errors => compose(SimpleResult.serror, flatten)(errors);
  21671. const consolidateObj = (objects, base) => {
  21672. const partition = SimpleResult.partition(objects);
  21673. return partition.errors.length > 0 ? mergeErrors(partition.errors) : mergeValues(partition.values, base);
  21674. };
  21675. const consolidateArr = objects => {
  21676. const partitions = SimpleResult.partition(objects);
  21677. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : SimpleResult.svalue(partitions.values);
  21678. };
  21679. const ResultCombine = {
  21680. consolidateObj,
  21681. consolidateArr
  21682. };
  21683. const field$1 = (key, newKey, presence, prop) => ({
  21684. tag: 'field',
  21685. key,
  21686. newKey,
  21687. presence,
  21688. prop
  21689. });
  21690. const customField$1 = (newKey, instantiator) => ({
  21691. tag: 'custom',
  21692. newKey,
  21693. instantiator
  21694. });
  21695. const fold = (value, ifField, ifCustom) => {
  21696. switch (value.tag) {
  21697. case 'field':
  21698. return ifField(value.key, value.newKey, value.presence, value.prop);
  21699. case 'custom':
  21700. return ifCustom(value.newKey, value.instantiator);
  21701. }
  21702. };
  21703. const value = validator => {
  21704. const extract = (path, val) => {
  21705. return SimpleResult.bindError(validator(val), err => custom(path, err));
  21706. };
  21707. const toString = constant('val');
  21708. return {
  21709. extract,
  21710. toString
  21711. };
  21712. };
  21713. const anyValue$1 = value(SimpleResult.svalue);
  21714. const requiredAccess = (path, obj, key, bundle) => get$a(obj, key).fold(() => missingRequired(path, key, obj), bundle);
  21715. const fallbackAccess = (obj, key, fallback, bundle) => {
  21716. const v = get$a(obj, key).getOrThunk(() => fallback(obj));
  21717. return bundle(v);
  21718. };
  21719. const optionAccess = (obj, key, bundle) => bundle(get$a(obj, key));
  21720. const optionDefaultedAccess = (obj, key, fallback, bundle) => {
  21721. const opt = get$a(obj, key).map(val => val === true ? fallback(obj) : val);
  21722. return bundle(opt);
  21723. };
  21724. const extractField = (field, path, obj, key, prop) => {
  21725. const bundle = av => prop.extract(path.concat([key]), av);
  21726. const bundleAsOption = optValue => optValue.fold(() => SimpleResult.svalue(Optional.none()), ov => {
  21727. const result = prop.extract(path.concat([key]), ov);
  21728. return SimpleResult.map(result, Optional.some);
  21729. });
  21730. switch (field.tag) {
  21731. case 'required':
  21732. return requiredAccess(path, obj, key, bundle);
  21733. case 'defaultedThunk':
  21734. return fallbackAccess(obj, key, field.process, bundle);
  21735. case 'option':
  21736. return optionAccess(obj, key, bundleAsOption);
  21737. case 'defaultedOptionThunk':
  21738. return optionDefaultedAccess(obj, key, field.process, bundleAsOption);
  21739. case 'mergeWithThunk': {
  21740. return fallbackAccess(obj, key, constant({}), v => {
  21741. const result = deepMerge(field.process(obj), v);
  21742. return bundle(result);
  21743. });
  21744. }
  21745. }
  21746. };
  21747. const extractFields = (path, obj, fields) => {
  21748. const success = {};
  21749. const errors = [];
  21750. for (const field of fields) {
  21751. fold(field, (key, newKey, presence, prop) => {
  21752. const result = extractField(presence, path, obj, key, prop);
  21753. SimpleResult.fold(result, err => {
  21754. errors.push(...err);
  21755. }, res => {
  21756. success[newKey] = res;
  21757. });
  21758. }, (newKey, instantiator) => {
  21759. success[newKey] = instantiator(obj);
  21760. });
  21761. }
  21762. return errors.length > 0 ? SimpleResult.serror(errors) : SimpleResult.svalue(success);
  21763. };
  21764. const objOf = values => {
  21765. const extract = (path, o) => extractFields(path, o, values);
  21766. const toString = () => {
  21767. const fieldStrings = map$3(values, value => fold(value, (key, _okey, _presence, prop) => key + ' -> ' + prop.toString(), (newKey, _instantiator) => 'state(' + newKey + ')'));
  21768. return 'obj{\n' + fieldStrings.join('\n') + '}';
  21769. };
  21770. return {
  21771. extract,
  21772. toString
  21773. };
  21774. };
  21775. const arrOf = prop => {
  21776. const extract = (path, array) => {
  21777. const results = map$3(array, (a, i) => prop.extract(path.concat(['[' + i + ']']), a));
  21778. return ResultCombine.consolidateArr(results);
  21779. };
  21780. const toString = () => 'array(' + prop.toString() + ')';
  21781. return {
  21782. extract,
  21783. toString
  21784. };
  21785. };
  21786. const valueOf = validator => value(v => validator(v).fold(SimpleResult.serror, SimpleResult.svalue));
  21787. const extractValue = (label, prop, obj) => {
  21788. const res = prop.extract([label], obj);
  21789. return SimpleResult.mapError(res, errs => ({
  21790. input: obj,
  21791. errors: errs
  21792. }));
  21793. };
  21794. const asRaw = (label, prop, obj) => SimpleResult.toResult(extractValue(label, prop, obj));
  21795. const formatError = errInfo => {
  21796. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  21797. };
  21798. const choose = (key, branches) => choose$1(key, map$2(branches, objOf));
  21799. const anyValue = constant(anyValue$1);
  21800. const typedValue = (validator, expectedType) => value(a => {
  21801. const actualType = typeof a;
  21802. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror(`Expected type: ${ expectedType } but got: ${ actualType }`);
  21803. });
  21804. const number = typedValue(isNumber, 'number');
  21805. const string = typedValue(isString, 'string');
  21806. const boolean = typedValue(isBoolean, 'boolean');
  21807. const functionProcessor = typedValue(isFunction, 'function');
  21808. const field = field$1;
  21809. const customField = customField$1;
  21810. const validateEnum = values => valueOf(value => contains$2(values, value) ? Result.value(value) : Result.error(`Unsupported value: "${ value }", choose one of "${ values.join(', ') }".`));
  21811. const requiredOf = (key, schema) => field(key, key, required(), schema);
  21812. const requiredString = key => requiredOf(key, string);
  21813. const requiredFunction = key => requiredOf(key, functionProcessor);
  21814. const requiredArrayOf = (key, schema) => field(key, key, required(), arrOf(schema));
  21815. const optionOf = (key, schema) => field(key, key, asOption(), schema);
  21816. const optionString = key => optionOf(key, string);
  21817. const optionFunction = key => optionOf(key, functionProcessor);
  21818. const defaulted = (key, fallback) => field(key, key, defaulted$1(fallback), anyValue());
  21819. const defaultedOf = (key, fallback, schema) => field(key, key, defaulted$1(fallback), schema);
  21820. const defaultedNumber = (key, fallback) => defaultedOf(key, fallback, number);
  21821. const defaultedString = (key, fallback) => defaultedOf(key, fallback, string);
  21822. const defaultedStringEnum = (key, fallback, values) => defaultedOf(key, fallback, validateEnum(values));
  21823. const defaultedBoolean = (key, fallback) => defaultedOf(key, fallback, boolean);
  21824. const defaultedFunction = (key, fallback) => defaultedOf(key, fallback, functionProcessor);
  21825. const defaultedArrayOf = (key, fallback, schema) => defaultedOf(key, fallback, arrOf(schema));
  21826. const type = requiredString('type');
  21827. const fetch = requiredFunction('fetch');
  21828. const onAction = requiredFunction('onAction');
  21829. const onSetup = defaultedFunction('onSetup', () => noop);
  21830. const optionalText = optionString('text');
  21831. const optionalIcon = optionString('icon');
  21832. const optionalTooltip = optionString('tooltip');
  21833. const optionalLabel = optionString('label');
  21834. const active = defaultedBoolean('active', false);
  21835. const enabled = defaultedBoolean('enabled', true);
  21836. const primary = defaultedBoolean('primary', false);
  21837. const defaultedColumns = num => defaulted('columns', num);
  21838. const defaultedType = type => defaultedString('type', type);
  21839. const autocompleterSchema = objOf([
  21840. type,
  21841. requiredString('ch'),
  21842. defaultedNumber('minChars', 1),
  21843. defaultedColumns(1),
  21844. defaultedNumber('maxResults', 10),
  21845. optionFunction('matches'),
  21846. fetch,
  21847. onAction,
  21848. defaultedArrayOf('highlightOn', [], string)
  21849. ]);
  21850. const createAutocompleter = spec => asRaw('Autocompleter', autocompleterSchema, spec);
  21851. const baseToolbarButtonFields = [
  21852. enabled,
  21853. optionalTooltip,
  21854. optionalIcon,
  21855. optionalText,
  21856. onSetup
  21857. ];
  21858. const baseToolbarToggleButtonFields = [active].concat(baseToolbarButtonFields);
  21859. const contextBarFields = [
  21860. defaultedFunction('predicate', never),
  21861. defaultedStringEnum('scope', 'node', [
  21862. 'node',
  21863. 'editor'
  21864. ]),
  21865. defaultedStringEnum('position', 'selection', [
  21866. 'node',
  21867. 'selection',
  21868. 'line'
  21869. ])
  21870. ];
  21871. const contextButtonFields = baseToolbarButtonFields.concat([
  21872. defaultedType('contextformbutton'),
  21873. primary,
  21874. onAction,
  21875. customField('original', identity)
  21876. ]);
  21877. const contextToggleButtonFields = baseToolbarToggleButtonFields.concat([
  21878. defaultedType('contextformbutton'),
  21879. primary,
  21880. onAction,
  21881. customField('original', identity)
  21882. ]);
  21883. const launchButtonFields = baseToolbarButtonFields.concat([defaultedType('contextformbutton')]);
  21884. const launchToggleButtonFields = baseToolbarToggleButtonFields.concat([defaultedType('contextformtogglebutton')]);
  21885. const toggleOrNormal = choose('type', {
  21886. contextformbutton: contextButtonFields,
  21887. contextformtogglebutton: contextToggleButtonFields
  21888. });
  21889. objOf([
  21890. defaultedType('contextform'),
  21891. defaultedFunction('initValue', constant('')),
  21892. optionalLabel,
  21893. requiredArrayOf('commands', toggleOrNormal),
  21894. optionOf('launch', choose('type', {
  21895. contextformbutton: launchButtonFields,
  21896. contextformtogglebutton: launchToggleButtonFields
  21897. }))
  21898. ].concat(contextBarFields));
  21899. const register$2 = editor => {
  21900. const popups = editor.ui.registry.getAll().popups;
  21901. const dataset = map$2(popups, popup => createAutocompleter(popup).fold(err => {
  21902. throw new Error(formatError(err));
  21903. }, identity));
  21904. const triggerChars = stringArray(mapToArray(dataset, v => v.ch));
  21905. const datasetValues = values(dataset);
  21906. const lookupByChar = ch => filter$6(datasetValues, dv => dv.ch === ch);
  21907. return {
  21908. dataset,
  21909. triggerChars,
  21910. lookupByChar
  21911. };
  21912. };
  21913. const setupEditorInput = (editor, api) => {
  21914. const update = last$1(api.load, 50);
  21915. editor.on('keypress compositionend', e => {
  21916. if (e.which === 27) {
  21917. return;
  21918. }
  21919. update.throttle();
  21920. });
  21921. editor.on('keydown', e => {
  21922. const keyCode = e.which;
  21923. if (keyCode === 8) {
  21924. update.throttle();
  21925. } else if (keyCode === 27) {
  21926. api.cancelIfNecessary();
  21927. }
  21928. });
  21929. editor.on('remove', update.cancel);
  21930. };
  21931. const setup$j = editor => {
  21932. const activeAutocompleter = value$2();
  21933. const uiActive = Cell(false);
  21934. const isActive = activeAutocompleter.isSet;
  21935. const cancelIfNecessary = () => {
  21936. if (isActive()) {
  21937. removeAutocompleterDecoration(editor);
  21938. fireAutocompleterEnd(editor);
  21939. uiActive.set(false);
  21940. activeAutocompleter.clear();
  21941. }
  21942. };
  21943. const commenceIfNecessary = context => {
  21944. if (!isActive()) {
  21945. addAutocompleterDecoration(editor, context.range);
  21946. activeAutocompleter.set({
  21947. triggerChar: context.triggerChar,
  21948. matchLength: context.text.length
  21949. });
  21950. }
  21951. };
  21952. const getAutocompleters = cached(() => register$2(editor));
  21953. const doLookup = fetchOptions => activeAutocompleter.get().map(ac => getContext(editor.dom, editor.selection.getRng(), ac.triggerChar).bind(newContext => lookupWithContext(editor, getAutocompleters, newContext, fetchOptions))).getOrThunk(() => lookup(editor, getAutocompleters));
  21954. const load = fetchOptions => {
  21955. doLookup(fetchOptions).fold(cancelIfNecessary, lookupInfo => {
  21956. commenceIfNecessary(lookupInfo.context);
  21957. lookupInfo.lookupData.then(lookupData => {
  21958. activeAutocompleter.get().map(ac => {
  21959. const context = lookupInfo.context;
  21960. if (ac.triggerChar === context.triggerChar) {
  21961. if (context.text.length - ac.matchLength >= 10) {
  21962. cancelIfNecessary();
  21963. } else {
  21964. activeAutocompleter.set({
  21965. ...ac,
  21966. matchLength: context.text.length
  21967. });
  21968. if (uiActive.get()) {
  21969. fireAutocompleterUpdate(editor, { lookupData });
  21970. } else {
  21971. uiActive.set(true);
  21972. fireAutocompleterStart(editor, { lookupData });
  21973. }
  21974. }
  21975. }
  21976. });
  21977. });
  21978. });
  21979. };
  21980. editor.addCommand('mceAutocompleterReload', (_ui, value) => {
  21981. const fetchOptions = isObject(value) ? value.fetchOptions : {};
  21982. load(fetchOptions);
  21983. });
  21984. editor.addCommand('mceAutocompleterClose', cancelIfNecessary);
  21985. setupEditorInput(editor, {
  21986. cancelIfNecessary,
  21987. load
  21988. });
  21989. };
  21990. const createAndFireInputEvent = eventType => (editor, inputType, specifics = {}) => {
  21991. const target = editor.getBody();
  21992. const overrides = {
  21993. bubbles: true,
  21994. composed: true,
  21995. data: null,
  21996. isComposing: false,
  21997. detail: 0,
  21998. view: null,
  21999. target,
  22000. currentTarget: target,
  22001. eventPhase: Event.AT_TARGET,
  22002. originalTarget: target,
  22003. explicitOriginalTarget: target,
  22004. isTrusted: false,
  22005. srcElement: target,
  22006. cancelable: false,
  22007. preventDefault: noop,
  22008. inputType
  22009. };
  22010. const input = clone$3(new InputEvent(eventType));
  22011. return editor.dispatch(eventType, {
  22012. ...input,
  22013. ...overrides,
  22014. ...specifics
  22015. });
  22016. };
  22017. const fireFakeInputEvent = createAndFireInputEvent('input');
  22018. const fireFakeBeforeInputEvent = createAndFireInputEvent('beforeinput');
  22019. const executeKeydownOverride$3 = (editor, caret, evt) => {
  22020. const inputType = evt.keyCode === VK.BACKSPACE ? 'deleteContentBackward' : 'deleteContentForward';
  22021. executeWithDelayedAction([
  22022. {
  22023. keyCode: VK.BACKSPACE,
  22024. action: action(backspaceDelete, editor)
  22025. },
  22026. {
  22027. keyCode: VK.BACKSPACE,
  22028. action: action(backspaceDelete$5, editor, false)
  22029. },
  22030. {
  22031. keyCode: VK.DELETE,
  22032. action: action(backspaceDelete$5, editor, true)
  22033. },
  22034. {
  22035. keyCode: VK.BACKSPACE,
  22036. action: action(backspaceDelete$6, editor, false)
  22037. },
  22038. {
  22039. keyCode: VK.DELETE,
  22040. action: action(backspaceDelete$6, editor, true)
  22041. },
  22042. {
  22043. keyCode: VK.BACKSPACE,
  22044. action: action(backspaceDelete$3, editor, caret, false)
  22045. },
  22046. {
  22047. keyCode: VK.DELETE,
  22048. action: action(backspaceDelete$3, editor, caret, true)
  22049. },
  22050. {
  22051. keyCode: VK.BACKSPACE,
  22052. action: action(backspaceDelete$9, editor, false)
  22053. },
  22054. {
  22055. keyCode: VK.DELETE,
  22056. action: action(backspaceDelete$9, editor, true)
  22057. },
  22058. {
  22059. keyCode: VK.BACKSPACE,
  22060. action: action(backspaceDelete$4, editor, false)
  22061. },
  22062. {
  22063. keyCode: VK.DELETE,
  22064. action: action(backspaceDelete$4, editor, true)
  22065. },
  22066. {
  22067. keyCode: VK.BACKSPACE,
  22068. action: action(backspaceDelete$1, editor, false)
  22069. },
  22070. {
  22071. keyCode: VK.DELETE,
  22072. action: action(backspaceDelete$1, editor, true)
  22073. },
  22074. {
  22075. keyCode: VK.BACKSPACE,
  22076. action: action(backspaceDelete$7, editor, false)
  22077. },
  22078. {
  22079. keyCode: VK.DELETE,
  22080. action: action(backspaceDelete$7, editor, true)
  22081. },
  22082. {
  22083. keyCode: VK.BACKSPACE,
  22084. action: action(backspaceDelete$8, editor, false)
  22085. },
  22086. {
  22087. keyCode: VK.DELETE,
  22088. action: action(backspaceDelete$8, editor, true)
  22089. },
  22090. {
  22091. keyCode: VK.BACKSPACE,
  22092. action: action(backspaceDelete$2, editor, false)
  22093. },
  22094. {
  22095. keyCode: VK.DELETE,
  22096. action: action(backspaceDelete$2, editor, true)
  22097. }
  22098. ], evt).each(applyAction => {
  22099. evt.preventDefault();
  22100. const beforeInput = fireFakeBeforeInputEvent(editor, inputType);
  22101. if (!beforeInput.isDefaultPrevented()) {
  22102. applyAction();
  22103. fireFakeInputEvent(editor, inputType);
  22104. }
  22105. });
  22106. };
  22107. const executeKeyupOverride = (editor, evt) => {
  22108. execute([
  22109. {
  22110. keyCode: VK.BACKSPACE,
  22111. action: action(paddEmptyElement, editor)
  22112. },
  22113. {
  22114. keyCode: VK.DELETE,
  22115. action: action(paddEmptyElement, editor)
  22116. }
  22117. ], evt);
  22118. };
  22119. const setup$i = (editor, caret) => {
  22120. editor.on('keydown', evt => {
  22121. if (evt.isDefaultPrevented() === false) {
  22122. executeKeydownOverride$3(editor, caret, evt);
  22123. }
  22124. });
  22125. editor.on('keyup', evt => {
  22126. if (evt.isDefaultPrevented() === false) {
  22127. executeKeyupOverride(editor, evt);
  22128. }
  22129. });
  22130. };
  22131. const firstNonWhiteSpaceNodeSibling = node => {
  22132. while (node) {
  22133. if (node.nodeType === 1 || node.nodeType === 3 && node.data && /[\r\n\s]/.test(node.data)) {
  22134. return node;
  22135. }
  22136. node = node.nextSibling;
  22137. }
  22138. };
  22139. const moveToCaretPosition = (editor, root) => {
  22140. let node, lastNode = root;
  22141. const dom = editor.dom;
  22142. const moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
  22143. if (!root) {
  22144. return;
  22145. }
  22146. if (/^(LI|DT|DD)$/.test(root.nodeName)) {
  22147. const firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild);
  22148. if (firstChild && /^(UL|OL|DL)$/.test(firstChild.nodeName)) {
  22149. root.insertBefore(dom.doc.createTextNode(nbsp), root.firstChild);
  22150. }
  22151. }
  22152. const rng = dom.createRng();
  22153. root.normalize();
  22154. if (root.hasChildNodes()) {
  22155. const walker = new DomTreeWalker(root, root);
  22156. while (node = walker.current()) {
  22157. if (isText$8(node)) {
  22158. rng.setStart(node, 0);
  22159. rng.setEnd(node, 0);
  22160. break;
  22161. }
  22162. if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) {
  22163. rng.setStartBefore(node);
  22164. rng.setEndBefore(node);
  22165. break;
  22166. }
  22167. lastNode = node;
  22168. node = walker.next();
  22169. }
  22170. if (!node) {
  22171. rng.setStart(lastNode, 0);
  22172. rng.setEnd(lastNode, 0);
  22173. }
  22174. } else {
  22175. if (isBr$5(root)) {
  22176. if (root.nextSibling && dom.isBlock(root.nextSibling)) {
  22177. rng.setStartBefore(root);
  22178. rng.setEndBefore(root);
  22179. } else {
  22180. rng.setStartAfter(root);
  22181. rng.setEndAfter(root);
  22182. }
  22183. } else {
  22184. rng.setStart(root, 0);
  22185. rng.setEnd(root, 0);
  22186. }
  22187. }
  22188. editor.selection.setRng(rng);
  22189. scrollRangeIntoView(editor, rng);
  22190. };
  22191. const getEditableRoot$1 = (dom, node) => {
  22192. const root = dom.getRoot();
  22193. let parent, editableRoot;
  22194. parent = node;
  22195. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  22196. if (dom.getContentEditable(parent) === 'true') {
  22197. editableRoot = parent;
  22198. }
  22199. parent = parent.parentNode;
  22200. }
  22201. return parent !== root ? editableRoot : root;
  22202. };
  22203. const getParentBlock$1 = editor => {
  22204. return Optional.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
  22205. };
  22206. const getParentBlockName = editor => {
  22207. return getParentBlock$1(editor).fold(constant(''), parentBlock => {
  22208. return parentBlock.nodeName.toUpperCase();
  22209. });
  22210. };
  22211. const isListItemParentBlock = editor => {
  22212. return getParentBlock$1(editor).filter(elm => {
  22213. return isListItem(SugarElement.fromDom(elm));
  22214. }).isSome();
  22215. };
  22216. const hasFirstChild = (elm, name) => {
  22217. return elm.firstChild && elm.firstChild.nodeName === name;
  22218. };
  22219. const isFirstChild = elm => {
  22220. var _a;
  22221. return ((_a = elm.parentNode) === null || _a === void 0 ? void 0 : _a.firstChild) === elm;
  22222. };
  22223. const hasParent = (elm, parentName) => {
  22224. return elm && elm.parentNode && elm.parentNode.nodeName === parentName;
  22225. };
  22226. const isListBlock = elm => {
  22227. return elm && /^(OL|UL|LI)$/.test(elm.nodeName);
  22228. };
  22229. const isNestedList = elm => {
  22230. return isListBlock(elm) && isListBlock(elm.parentNode);
  22231. };
  22232. const getContainerBlock = containerBlock => {
  22233. const containerBlockParent = containerBlock.parentNode;
  22234. if (/^(LI|DT|DD)$/.test(containerBlockParent.nodeName)) {
  22235. return containerBlockParent;
  22236. }
  22237. return containerBlock;
  22238. };
  22239. const isFirstOrLastLi = (containerBlock, parentBlock, first) => {
  22240. let node = containerBlock[first ? 'firstChild' : 'lastChild'];
  22241. while (node) {
  22242. if (isElement$6(node)) {
  22243. break;
  22244. }
  22245. node = node[first ? 'nextSibling' : 'previousSibling'];
  22246. }
  22247. return node === parentBlock;
  22248. };
  22249. const insert$3 = (editor, createNewBlock, containerBlock, parentBlock, newBlockName) => {
  22250. const dom = editor.dom;
  22251. const rng = editor.selection.getRng();
  22252. if (containerBlock === editor.getBody()) {
  22253. return;
  22254. }
  22255. if (isNestedList(containerBlock)) {
  22256. newBlockName = 'LI';
  22257. }
  22258. let newBlock = createNewBlock(newBlockName);
  22259. if (isFirstOrLastLi(containerBlock, parentBlock, true) && isFirstOrLastLi(containerBlock, parentBlock, false)) {
  22260. if (hasParent(containerBlock, 'LI')) {
  22261. const containerBlockParent = getContainerBlock(containerBlock);
  22262. dom.insertAfter(newBlock, containerBlockParent);
  22263. if (isFirstChild(containerBlock)) {
  22264. dom.remove(containerBlockParent);
  22265. } else {
  22266. dom.remove(containerBlock);
  22267. }
  22268. } else {
  22269. dom.replace(newBlock, containerBlock);
  22270. }
  22271. } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
  22272. if (hasParent(containerBlock, 'LI')) {
  22273. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  22274. newBlock.appendChild(dom.doc.createTextNode(' '));
  22275. newBlock.appendChild(containerBlock);
  22276. } else {
  22277. containerBlock.parentNode.insertBefore(newBlock, containerBlock);
  22278. }
  22279. dom.remove(parentBlock);
  22280. } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
  22281. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  22282. dom.remove(parentBlock);
  22283. } else {
  22284. containerBlock = getContainerBlock(containerBlock);
  22285. const tmpRng = rng.cloneRange();
  22286. tmpRng.setStartAfter(parentBlock);
  22287. tmpRng.setEndAfter(containerBlock);
  22288. const fragment = tmpRng.extractContents();
  22289. if (newBlockName === 'LI' && hasFirstChild(fragment, 'LI')) {
  22290. newBlock = fragment.firstChild;
  22291. dom.insertAfter(fragment, containerBlock);
  22292. } else {
  22293. dom.insertAfter(fragment, containerBlock);
  22294. dom.insertAfter(newBlock, containerBlock);
  22295. }
  22296. dom.remove(parentBlock);
  22297. }
  22298. moveToCaretPosition(editor, newBlock);
  22299. };
  22300. const trimZwsp = fragment => {
  22301. each$g(descendants$1(SugarElement.fromDom(fragment), isText$9), text => {
  22302. const rawNode = text.dom;
  22303. rawNode.nodeValue = trim$1(rawNode.nodeValue);
  22304. });
  22305. };
  22306. const isEmptyAnchor = (dom, elm) => {
  22307. return elm && elm.nodeName === 'A' && dom.isEmpty(elm);
  22308. };
  22309. const isTableCell = node => {
  22310. return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  22311. };
  22312. const emptyBlock = elm => {
  22313. elm.innerHTML = '<br data-mce-bogus="1">';
  22314. };
  22315. const containerAndSiblingName = (container, nodeName) => {
  22316. return container.nodeName === nodeName || container.previousSibling && container.previousSibling.nodeName === nodeName;
  22317. };
  22318. const canSplitBlock = (dom, node) => {
  22319. return node && dom.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.getContentEditable(node) !== 'true';
  22320. };
  22321. const trimInlineElementsOnLeftSideOfBlock = (dom, nonEmptyElementsMap, block) => {
  22322. let node = block;
  22323. const firstChilds = [];
  22324. let i;
  22325. if (!node) {
  22326. return;
  22327. }
  22328. while (node = node.firstChild) {
  22329. if (dom.isBlock(node)) {
  22330. return;
  22331. }
  22332. if (isElement$6(node) && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  22333. firstChilds.push(node);
  22334. }
  22335. }
  22336. i = firstChilds.length;
  22337. while (i--) {
  22338. node = firstChilds[i];
  22339. if (!node.hasChildNodes() || node.firstChild === node.lastChild && node.firstChild.nodeValue === '') {
  22340. dom.remove(node);
  22341. } else {
  22342. if (isEmptyAnchor(dom, node)) {
  22343. dom.remove(node);
  22344. }
  22345. }
  22346. }
  22347. };
  22348. const normalizeZwspOffset = (start, container, offset) => {
  22349. if (isText$8(container) === false) {
  22350. return offset;
  22351. } else if (start) {
  22352. return offset === 1 && container.data.charAt(offset - 1) === ZWSP$1 ? 0 : offset;
  22353. } else {
  22354. return offset === container.data.length - 1 && container.data.charAt(offset) === ZWSP$1 ? container.data.length : offset;
  22355. }
  22356. };
  22357. const includeZwspInRange = rng => {
  22358. const newRng = rng.cloneRange();
  22359. newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
  22360. newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
  22361. return newRng;
  22362. };
  22363. const trimLeadingLineBreaks = node => {
  22364. do {
  22365. if (isText$8(node)) {
  22366. node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
  22367. }
  22368. node = node.firstChild;
  22369. } while (node);
  22370. };
  22371. const getEditableRoot = (dom, node) => {
  22372. const root = dom.getRoot();
  22373. let parent, editableRoot;
  22374. parent = node;
  22375. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  22376. if (dom.getContentEditable(parent) === 'true') {
  22377. editableRoot = parent;
  22378. }
  22379. parent = parent.parentNode;
  22380. }
  22381. return parent !== root ? editableRoot : root;
  22382. };
  22383. const applyAttributes = (editor, node, forcedRootBlockAttrs) => {
  22384. const dom = editor.dom;
  22385. Optional.from(forcedRootBlockAttrs.style).map(dom.parseStyle).each(attrStyles => {
  22386. const currentStyles = getAllRaw(SugarElement.fromDom(node));
  22387. const newStyles = {
  22388. ...currentStyles,
  22389. ...attrStyles
  22390. };
  22391. dom.setStyles(node, newStyles);
  22392. });
  22393. const attrClassesOpt = Optional.from(forcedRootBlockAttrs.class).map(attrClasses => attrClasses.split(/\s+/));
  22394. const currentClassesOpt = Optional.from(node.className).map(currentClasses => filter$6(currentClasses.split(/\s+/), clazz => clazz !== ''));
  22395. lift2(attrClassesOpt, currentClassesOpt, (attrClasses, currentClasses) => {
  22396. const filteredClasses = filter$6(currentClasses, clazz => !contains$2(attrClasses, clazz));
  22397. const newClasses = [
  22398. ...attrClasses,
  22399. ...filteredClasses
  22400. ];
  22401. dom.setAttrib(node, 'class', newClasses.join(' '));
  22402. });
  22403. const appliedAttrs = [
  22404. 'style',
  22405. 'class'
  22406. ];
  22407. const remainingAttrs = filter$5(forcedRootBlockAttrs, (_, attrs) => !contains$2(appliedAttrs, attrs));
  22408. dom.setAttribs(node, remainingAttrs);
  22409. };
  22410. const setForcedBlockAttrs = (editor, node) => {
  22411. const forcedRootBlockName = getForcedRootBlock(editor);
  22412. if (forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
  22413. const forcedRootBlockAttrs = getForcedRootBlockAttrs(editor);
  22414. applyAttributes(editor, node, forcedRootBlockAttrs);
  22415. }
  22416. };
  22417. const wrapSelfAndSiblingsInDefaultBlock = (editor, newBlockName, rng, container, offset) => {
  22418. let newBlock, parentBlock, startNode, node, next, rootBlockName;
  22419. const dom = editor.dom, editableRoot = getEditableRoot(dom, container);
  22420. parentBlock = dom.getParent(container, dom.isBlock);
  22421. if (!parentBlock || !canSplitBlock(dom, parentBlock)) {
  22422. parentBlock = parentBlock || editableRoot;
  22423. if (parentBlock === editor.getBody() || isTableCell(parentBlock)) {
  22424. rootBlockName = parentBlock.nodeName.toLowerCase();
  22425. } else {
  22426. rootBlockName = parentBlock.parentNode.nodeName.toLowerCase();
  22427. }
  22428. if (!parentBlock.hasChildNodes()) {
  22429. newBlock = dom.create(newBlockName);
  22430. setForcedBlockAttrs(editor, newBlock);
  22431. parentBlock.appendChild(newBlock);
  22432. rng.setStart(newBlock, 0);
  22433. rng.setEnd(newBlock, 0);
  22434. return newBlock;
  22435. }
  22436. node = container;
  22437. while (node.parentNode !== parentBlock) {
  22438. node = node.parentNode;
  22439. }
  22440. while (node && !dom.isBlock(node)) {
  22441. startNode = node;
  22442. node = node.previousSibling;
  22443. }
  22444. if (startNode && editor.schema.isValidChild(rootBlockName, newBlockName.toLowerCase())) {
  22445. newBlock = dom.create(newBlockName);
  22446. setForcedBlockAttrs(editor, newBlock);
  22447. startNode.parentNode.insertBefore(newBlock, startNode);
  22448. node = startNode;
  22449. while (node && !dom.isBlock(node)) {
  22450. next = node.nextSibling;
  22451. newBlock.appendChild(node);
  22452. node = next;
  22453. }
  22454. rng.setStart(container, offset);
  22455. rng.setEnd(container, offset);
  22456. }
  22457. }
  22458. return container;
  22459. };
  22460. const addBrToBlockIfNeeded = (dom, block) => {
  22461. block.normalize();
  22462. const lastChild = block.lastChild;
  22463. if (!lastChild || /^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true))) {
  22464. dom.add(block, 'br');
  22465. }
  22466. };
  22467. const insert$2 = (editor, evt) => {
  22468. let tmpRng, container, offset, parentBlock;
  22469. let newBlock, fragment, containerBlock, parentBlockName, isAfterLastNodeInContainer;
  22470. const dom = editor.dom;
  22471. const schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
  22472. const rng = editor.selection.getRng();
  22473. const newBlockName = getForcedRootBlock(editor);
  22474. const createNewBlock = name => {
  22475. let node = container, block, clonedNode, caretNode;
  22476. const textInlineElements = schema.getTextInlineElements();
  22477. if (name || parentBlockName === 'TABLE' || parentBlockName === 'HR') {
  22478. block = dom.create(name || newBlockName);
  22479. } else {
  22480. block = parentBlock.cloneNode(false);
  22481. }
  22482. caretNode = block;
  22483. if (shouldKeepStyles(editor) === false) {
  22484. dom.setAttrib(block, 'style', null);
  22485. dom.setAttrib(block, 'class', null);
  22486. } else {
  22487. do {
  22488. if (textInlineElements[node.nodeName]) {
  22489. if (isCaretNode(node) || isBookmarkNode$1(node)) {
  22490. continue;
  22491. }
  22492. clonedNode = node.cloneNode(false);
  22493. dom.setAttrib(clonedNode, 'id', '');
  22494. if (block.hasChildNodes()) {
  22495. clonedNode.appendChild(block.firstChild);
  22496. block.appendChild(clonedNode);
  22497. } else {
  22498. caretNode = clonedNode;
  22499. block.appendChild(clonedNode);
  22500. }
  22501. }
  22502. } while ((node = node.parentNode) && node !== editableRoot);
  22503. }
  22504. setForcedBlockAttrs(editor, block);
  22505. emptyBlock(caretNode);
  22506. return block;
  22507. };
  22508. const isCaretAtStartOrEndOfBlock = start => {
  22509. let node, name;
  22510. const normalizedOffset = normalizeZwspOffset(start, container, offset);
  22511. if (isText$8(container) && (start ? normalizedOffset > 0 : normalizedOffset < container.nodeValue.length)) {
  22512. return false;
  22513. }
  22514. if (container.parentNode === parentBlock && isAfterLastNodeInContainer && !start) {
  22515. return true;
  22516. }
  22517. if (start && isElement$6(container) && container === parentBlock.firstChild) {
  22518. return true;
  22519. }
  22520. if (containerAndSiblingName(container, 'TABLE') || containerAndSiblingName(container, 'HR')) {
  22521. return isAfterLastNodeInContainer && !start || !isAfterLastNodeInContainer && start;
  22522. }
  22523. const walker = new DomTreeWalker(container, parentBlock);
  22524. if (isText$8(container)) {
  22525. if (start && normalizedOffset === 0) {
  22526. walker.prev();
  22527. } else if (!start && normalizedOffset === container.nodeValue.length) {
  22528. walker.next();
  22529. }
  22530. }
  22531. while (node = walker.current()) {
  22532. if (isElement$6(node)) {
  22533. if (!node.getAttribute('data-mce-bogus')) {
  22534. name = node.nodeName.toLowerCase();
  22535. if (nonEmptyElementsMap[name] && name !== 'br') {
  22536. return false;
  22537. }
  22538. }
  22539. } else if (isText$8(node) && !isWhitespaceText(node.nodeValue)) {
  22540. return false;
  22541. }
  22542. if (start) {
  22543. walker.prev();
  22544. } else {
  22545. walker.next();
  22546. }
  22547. }
  22548. return true;
  22549. };
  22550. const insertNewBlockAfter = () => {
  22551. if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName !== 'HGROUP') {
  22552. newBlock = createNewBlock(newBlockName);
  22553. } else {
  22554. newBlock = createNewBlock();
  22555. }
  22556. if (shouldEndContainerOnEmptyBlock(editor) && canSplitBlock(dom, containerBlock) && dom.isEmpty(parentBlock)) {
  22557. newBlock = dom.split(containerBlock, parentBlock);
  22558. } else {
  22559. dom.insertAfter(newBlock, parentBlock);
  22560. }
  22561. moveToCaretPosition(editor, newBlock);
  22562. };
  22563. normalize$2(dom, rng).each(normRng => {
  22564. rng.setStart(normRng.startContainer, normRng.startOffset);
  22565. rng.setEnd(normRng.endContainer, normRng.endOffset);
  22566. });
  22567. container = rng.startContainer;
  22568. offset = rng.startOffset;
  22569. const shiftKey = !!(evt && evt.shiftKey);
  22570. const ctrlKey = !!(evt && evt.ctrlKey);
  22571. if (isElement$6(container) && container.hasChildNodes()) {
  22572. isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  22573. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  22574. if (isAfterLastNodeInContainer && isText$8(container)) {
  22575. offset = container.nodeValue.length;
  22576. } else {
  22577. offset = 0;
  22578. }
  22579. }
  22580. const editableRoot = getEditableRoot(dom, container);
  22581. if (!editableRoot) {
  22582. return;
  22583. }
  22584. if (!shiftKey) {
  22585. container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset);
  22586. }
  22587. parentBlock = dom.getParent(container, dom.isBlock);
  22588. containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  22589. parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : '';
  22590. const containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  22591. if (containerBlockName === 'LI' && !ctrlKey) {
  22592. parentBlock = containerBlock;
  22593. containerBlock = containerBlock.parentNode;
  22594. parentBlockName = containerBlockName;
  22595. }
  22596. if (/^(LI|DT|DD)$/.test(parentBlockName)) {
  22597. if (dom.isEmpty(parentBlock)) {
  22598. insert$3(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
  22599. return;
  22600. }
  22601. }
  22602. if (parentBlock === editor.getBody()) {
  22603. return;
  22604. }
  22605. if (isCaretContainerBlock$1(parentBlock)) {
  22606. newBlock = showCaretContainerBlock(parentBlock);
  22607. if (dom.isEmpty(parentBlock)) {
  22608. emptyBlock(parentBlock);
  22609. }
  22610. setForcedBlockAttrs(editor, newBlock);
  22611. moveToCaretPosition(editor, newBlock);
  22612. } else if (isCaretAtStartOrEndOfBlock()) {
  22613. insertNewBlockAfter();
  22614. } else if (isCaretAtStartOrEndOfBlock(true)) {
  22615. newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
  22616. moveToCaretPosition(editor, containerAndSiblingName(parentBlock, 'HR') ? newBlock : parentBlock);
  22617. } else {
  22618. tmpRng = includeZwspInRange(rng).cloneRange();
  22619. tmpRng.setEndAfter(parentBlock);
  22620. fragment = tmpRng.extractContents();
  22621. trimZwsp(fragment);
  22622. trimLeadingLineBreaks(fragment);
  22623. newBlock = fragment.firstChild;
  22624. dom.insertAfter(fragment, parentBlock);
  22625. trimInlineElementsOnLeftSideOfBlock(dom, nonEmptyElementsMap, newBlock);
  22626. addBrToBlockIfNeeded(dom, parentBlock);
  22627. if (dom.isEmpty(parentBlock)) {
  22628. emptyBlock(parentBlock);
  22629. }
  22630. newBlock.normalize();
  22631. if (dom.isEmpty(newBlock)) {
  22632. dom.remove(newBlock);
  22633. insertNewBlockAfter();
  22634. } else {
  22635. setForcedBlockAttrs(editor, newBlock);
  22636. moveToCaretPosition(editor, newBlock);
  22637. }
  22638. }
  22639. dom.setAttrib(newBlock, 'id', '');
  22640. editor.dispatch('NewBlock', { newBlock });
  22641. };
  22642. const hasRightSideContent = (schema, container, parentBlock) => {
  22643. const walker = new DomTreeWalker(container, parentBlock);
  22644. let node;
  22645. const nonEmptyElementsMap = schema.getNonEmptyElements();
  22646. while (node = walker.next()) {
  22647. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
  22648. return true;
  22649. }
  22650. }
  22651. };
  22652. const moveSelectionToBr = (editor, brElm, extraBr) => {
  22653. const rng = editor.dom.createRng();
  22654. if (!extraBr) {
  22655. rng.setStartAfter(brElm);
  22656. rng.setEndAfter(brElm);
  22657. } else {
  22658. rng.setStartBefore(brElm);
  22659. rng.setEndBefore(brElm);
  22660. }
  22661. editor.selection.setRng(rng);
  22662. scrollRangeIntoView(editor, rng);
  22663. };
  22664. const insertBrAtCaret = (editor, evt) => {
  22665. const selection = editor.selection;
  22666. const dom = editor.dom;
  22667. const rng = selection.getRng();
  22668. let brElm;
  22669. let extraBr;
  22670. normalize$2(dom, rng).each(normRng => {
  22671. rng.setStart(normRng.startContainer, normRng.startOffset);
  22672. rng.setEnd(normRng.endContainer, normRng.endOffset);
  22673. });
  22674. let offset = rng.startOffset;
  22675. let container = rng.startContainer;
  22676. if (container.nodeType === 1 && container.hasChildNodes()) {
  22677. const isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  22678. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  22679. if (isAfterLastNodeInContainer && container.nodeType === 3) {
  22680. offset = container.nodeValue.length;
  22681. } else {
  22682. offset = 0;
  22683. }
  22684. }
  22685. let parentBlock = dom.getParent(container, dom.isBlock);
  22686. const containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  22687. const containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  22688. const isControlKey = !!(evt && evt.ctrlKey);
  22689. if (containerBlockName === 'LI' && !isControlKey) {
  22690. parentBlock = containerBlock;
  22691. }
  22692. if (container && container.nodeType === 3 && offset >= container.nodeValue.length) {
  22693. if (!hasRightSideContent(editor.schema, container, parentBlock)) {
  22694. brElm = dom.create('br');
  22695. rng.insertNode(brElm);
  22696. rng.setStartAfter(brElm);
  22697. rng.setEndAfter(brElm);
  22698. extraBr = true;
  22699. }
  22700. }
  22701. brElm = dom.create('br');
  22702. rangeInsertNode(dom, rng, brElm);
  22703. moveSelectionToBr(editor, brElm, extraBr);
  22704. editor.undoManager.add();
  22705. };
  22706. const insertBrBefore = (editor, inline) => {
  22707. const br = SugarElement.fromTag('br');
  22708. before$3(SugarElement.fromDom(inline), br);
  22709. editor.undoManager.add();
  22710. };
  22711. const insertBrAfter = (editor, inline) => {
  22712. if (!hasBrAfter(editor.getBody(), inline)) {
  22713. after$4(SugarElement.fromDom(inline), SugarElement.fromTag('br'));
  22714. }
  22715. const br = SugarElement.fromTag('br');
  22716. after$4(SugarElement.fromDom(inline), br);
  22717. moveSelectionToBr(editor, br.dom, false);
  22718. editor.undoManager.add();
  22719. };
  22720. const isBeforeBr = pos => {
  22721. return isBr$5(pos.getNode());
  22722. };
  22723. const hasBrAfter = (rootNode, startNode) => {
  22724. if (isBeforeBr(CaretPosition.after(startNode))) {
  22725. return true;
  22726. } else {
  22727. return nextPosition(rootNode, CaretPosition.after(startNode)).map(pos => {
  22728. return isBr$5(pos.getNode());
  22729. }).getOr(false);
  22730. }
  22731. };
  22732. const isAnchorLink = elm => {
  22733. return elm && elm.nodeName === 'A' && 'href' in elm;
  22734. };
  22735. const isInsideAnchor = location => {
  22736. return location.fold(never, isAnchorLink, isAnchorLink, never);
  22737. };
  22738. const readInlineAnchorLocation = editor => {
  22739. const isInlineTarget$1 = curry(isInlineTarget, editor);
  22740. const position = CaretPosition.fromRangeStart(editor.selection.getRng());
  22741. return readLocation(isInlineTarget$1, editor.getBody(), position).filter(isInsideAnchor);
  22742. };
  22743. const insertBrOutsideAnchor = (editor, location) => {
  22744. location.fold(noop, curry(insertBrBefore, editor), curry(insertBrAfter, editor), noop);
  22745. };
  22746. const insert$1 = (editor, evt) => {
  22747. const anchorLocation = readInlineAnchorLocation(editor);
  22748. if (anchorLocation.isSome()) {
  22749. anchorLocation.each(curry(insertBrOutsideAnchor, editor));
  22750. } else {
  22751. insertBrAtCaret(editor, evt);
  22752. }
  22753. };
  22754. const matchesSelector = (editor, selector) => {
  22755. return getParentBlock$1(editor).filter(parentBlock => {
  22756. return selector.length > 0 && is$1(SugarElement.fromDom(parentBlock), selector);
  22757. }).isSome();
  22758. };
  22759. const shouldInsertBr = editor => {
  22760. return matchesSelector(editor, getBrNewLineSelector(editor));
  22761. };
  22762. const shouldBlockNewLine$1 = editor => {
  22763. return matchesSelector(editor, getNoNewLineSelector(editor));
  22764. };
  22765. const newLineAction = Adt.generate([
  22766. { br: [] },
  22767. { block: [] },
  22768. { none: [] }
  22769. ]);
  22770. const shouldBlockNewLine = (editor, _shiftKey) => {
  22771. return shouldBlockNewLine$1(editor);
  22772. };
  22773. const inListBlock = requiredState => {
  22774. return (editor, _shiftKey) => {
  22775. return isListItemParentBlock(editor) === requiredState;
  22776. };
  22777. };
  22778. const inBlock = (blockName, requiredState) => (editor, _shiftKey) => {
  22779. const state = getParentBlockName(editor) === blockName.toUpperCase();
  22780. return state === requiredState;
  22781. };
  22782. const inPreBlock = requiredState => inBlock('pre', requiredState);
  22783. const inSummaryBlock = () => inBlock('summary', true);
  22784. const shouldPutBrInPre = requiredState => {
  22785. return (editor, _shiftKey) => {
  22786. return shouldPutBrInPre$1(editor) === requiredState;
  22787. };
  22788. };
  22789. const inBrContext = (editor, _shiftKey) => {
  22790. return shouldInsertBr(editor);
  22791. };
  22792. const hasShiftKey = (_editor, shiftKey) => {
  22793. return shiftKey;
  22794. };
  22795. const canInsertIntoEditableRoot = editor => {
  22796. const forcedRootBlock = getForcedRootBlock(editor);
  22797. const rootEditable = getEditableRoot$1(editor.dom, editor.selection.getStart());
  22798. return rootEditable && editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock);
  22799. };
  22800. const match = (predicates, action) => {
  22801. return (editor, shiftKey) => {
  22802. const isMatch = foldl(predicates, (res, p) => {
  22803. return res && p(editor, shiftKey);
  22804. }, true);
  22805. return isMatch ? Optional.some(action) : Optional.none();
  22806. };
  22807. };
  22808. const getAction = (editor, evt) => {
  22809. return evaluateUntil([
  22810. match([shouldBlockNewLine], newLineAction.none()),
  22811. match([inSummaryBlock()], newLineAction.br()),
  22812. match([
  22813. inPreBlock(true),
  22814. shouldPutBrInPre(false),
  22815. hasShiftKey
  22816. ], newLineAction.br()),
  22817. match([
  22818. inPreBlock(true),
  22819. shouldPutBrInPre(false)
  22820. ], newLineAction.block()),
  22821. match([
  22822. inPreBlock(true),
  22823. shouldPutBrInPre(true),
  22824. hasShiftKey
  22825. ], newLineAction.block()),
  22826. match([
  22827. inPreBlock(true),
  22828. shouldPutBrInPre(true)
  22829. ], newLineAction.br()),
  22830. match([
  22831. inListBlock(true),
  22832. hasShiftKey
  22833. ], newLineAction.br()),
  22834. match([inListBlock(true)], newLineAction.block()),
  22835. match([inBrContext], newLineAction.br()),
  22836. match([hasShiftKey], newLineAction.br()),
  22837. match([canInsertIntoEditableRoot], newLineAction.block())
  22838. ], [
  22839. editor,
  22840. !!(evt && evt.shiftKey)
  22841. ]).getOr(newLineAction.none());
  22842. };
  22843. const insert = (editor, evt) => {
  22844. getAction(editor, evt).fold(() => {
  22845. if (isNonNullable(evt)) {
  22846. const event = fireFakeBeforeInputEvent(editor, 'insertLineBreak');
  22847. if (event.isDefaultPrevented()) {
  22848. return;
  22849. }
  22850. }
  22851. insert$1(editor, evt);
  22852. if (isNonNullable(evt)) {
  22853. fireFakeInputEvent(editor, 'insertLineBreak');
  22854. }
  22855. }, () => {
  22856. if (isNonNullable(evt)) {
  22857. const event = fireFakeBeforeInputEvent(editor, 'insertParagraph');
  22858. if (event.isDefaultPrevented()) {
  22859. return;
  22860. }
  22861. }
  22862. insert$2(editor, evt);
  22863. if (isNonNullable(evt)) {
  22864. fireFakeInputEvent(editor, 'insertParagraph');
  22865. }
  22866. }, noop);
  22867. };
  22868. const handleEnterKeyEvent = (editor, event) => {
  22869. if (event.isDefaultPrevented()) {
  22870. return;
  22871. }
  22872. event.preventDefault();
  22873. endTypingLevelIgnoreLocks(editor.undoManager);
  22874. editor.undoManager.transact(() => {
  22875. if (editor.selection.isCollapsed() === false) {
  22876. execDeleteCommand(editor);
  22877. }
  22878. insert(editor, event);
  22879. });
  22880. };
  22881. const setup$h = editor => {
  22882. editor.on('keydown', event => {
  22883. if (event.keyCode === VK.ENTER) {
  22884. handleEnterKeyEvent(editor, event);
  22885. }
  22886. });
  22887. };
  22888. const executeKeydownOverride$2 = (editor, caret, evt) => {
  22889. execute([
  22890. {
  22891. keyCode: VK.END,
  22892. action: action(moveToLineEndPoint$1, editor, true)
  22893. },
  22894. {
  22895. keyCode: VK.HOME,
  22896. action: action(moveToLineEndPoint$1, editor, false)
  22897. },
  22898. {
  22899. keyCode: VK.END,
  22900. action: action(moveToLineEndPoint, editor, true)
  22901. },
  22902. {
  22903. keyCode: VK.HOME,
  22904. action: action(moveToLineEndPoint, editor, false)
  22905. },
  22906. {
  22907. keyCode: VK.END,
  22908. action: action(moveToLineEndPoint$2, editor, true, caret)
  22909. },
  22910. {
  22911. keyCode: VK.HOME,
  22912. action: action(moveToLineEndPoint$2, editor, false, caret)
  22913. }
  22914. ], evt).each(_ => {
  22915. evt.preventDefault();
  22916. });
  22917. };
  22918. const setup$g = (editor, caret) => {
  22919. editor.on('keydown', evt => {
  22920. if (evt.isDefaultPrevented() === false) {
  22921. executeKeydownOverride$2(editor, caret, evt);
  22922. }
  22923. });
  22924. };
  22925. const setup$f = editor => {
  22926. editor.on('input', e => {
  22927. if (e.isComposing === false) {
  22928. normalizeNbspsInEditor(editor);
  22929. }
  22930. });
  22931. };
  22932. const platform = detect$2();
  22933. const executeKeyupAction = (editor, caret, evt) => {
  22934. execute([
  22935. {
  22936. keyCode: VK.PAGE_UP,
  22937. action: action(moveToLineEndPoint$2, editor, false, caret)
  22938. },
  22939. {
  22940. keyCode: VK.PAGE_DOWN,
  22941. action: action(moveToLineEndPoint$2, editor, true, caret)
  22942. }
  22943. ], evt);
  22944. };
  22945. const stopImmediatePropagation = e => e.stopImmediatePropagation();
  22946. const isPageUpDown = evt => evt.keyCode === VK.PAGE_UP || evt.keyCode === VK.PAGE_DOWN;
  22947. const setNodeChangeBlocker = (blocked, editor, block) => {
  22948. if (block && !blocked.get()) {
  22949. editor.on('NodeChange', stopImmediatePropagation, true);
  22950. } else if (!block && blocked.get()) {
  22951. editor.off('NodeChange', stopImmediatePropagation);
  22952. }
  22953. blocked.set(block);
  22954. };
  22955. const setup$e = (editor, caret) => {
  22956. if (platform.os.isMacOS()) {
  22957. return;
  22958. }
  22959. const blocked = Cell(false);
  22960. editor.on('keydown', evt => {
  22961. if (isPageUpDown(evt)) {
  22962. setNodeChangeBlocker(blocked, editor, true);
  22963. }
  22964. });
  22965. editor.on('keyup', evt => {
  22966. if (evt.isDefaultPrevented() === false) {
  22967. executeKeyupAction(editor, caret, evt);
  22968. }
  22969. if (isPageUpDown(evt) && blocked.get()) {
  22970. setNodeChangeBlocker(blocked, editor, false);
  22971. editor.nodeChanged();
  22972. }
  22973. });
  22974. };
  22975. const insertTextAtPosition = (text, pos) => {
  22976. const container = pos.container();
  22977. const offset = pos.offset();
  22978. if (isText$8(container)) {
  22979. container.insertData(offset, text);
  22980. return Optional.some(CaretPosition(container, offset + text.length));
  22981. } else {
  22982. return getElementFromPosition(pos).map(elm => {
  22983. const textNode = SugarElement.fromText(text);
  22984. if (pos.isAtEnd()) {
  22985. after$4(elm, textNode);
  22986. } else {
  22987. before$3(elm, textNode);
  22988. }
  22989. return CaretPosition(textNode.dom, text.length);
  22990. });
  22991. }
  22992. };
  22993. const insertNbspAtPosition = curry(insertTextAtPosition, nbsp);
  22994. const insertSpaceAtPosition = curry(insertTextAtPosition, ' ');
  22995. const locationToCaretPosition = root => location => location.fold(element => prevPosition(root.dom, CaretPosition.before(element)), element => firstPositionIn(element), element => lastPositionIn(element), element => nextPosition(root.dom, CaretPosition.after(element)));
  22996. const insertInlineBoundarySpaceOrNbsp = (root, pos) => checkPos => needsToHaveNbsp(root, checkPos) ? insertNbspAtPosition(pos) : insertSpaceAtPosition(pos);
  22997. const setSelection = editor => pos => {
  22998. editor.selection.setRng(pos.toRange());
  22999. editor.nodeChanged();
  23000. return true;
  23001. };
  23002. const insertSpaceOrNbspAtSelection = editor => {
  23003. const pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23004. const root = SugarElement.fromDom(editor.getBody());
  23005. if (editor.selection.isCollapsed()) {
  23006. const isInlineTarget$1 = curry(isInlineTarget, editor);
  23007. const caretPosition = CaretPosition.fromRangeStart(editor.selection.getRng());
  23008. return readLocation(isInlineTarget$1, editor.getBody(), caretPosition).bind(locationToCaretPosition(root)).map(checkPos => () => insertInlineBoundarySpaceOrNbsp(root, pos)(checkPos).each(setSelection(editor)));
  23009. } else {
  23010. return Optional.none();
  23011. }
  23012. };
  23013. const executeKeydownOverride$1 = (editor, evt) => {
  23014. executeWithDelayedAction([{
  23015. keyCode: VK.SPACEBAR,
  23016. action: action(insertSpaceOrNbspAtSelection, editor)
  23017. }], evt).each(applyAction => {
  23018. evt.preventDefault();
  23019. const event = fireFakeBeforeInputEvent(editor, 'insertText', { data: ' ' });
  23020. if (!event.isDefaultPrevented()) {
  23021. applyAction();
  23022. fireFakeInputEvent(editor, 'insertText', { data: ' ' });
  23023. }
  23024. });
  23025. };
  23026. const setup$d = editor => {
  23027. editor.on('keydown', evt => {
  23028. if (evt.isDefaultPrevented() === false) {
  23029. executeKeydownOverride$1(editor, evt);
  23030. }
  23031. });
  23032. };
  23033. const tableTabNavigation = editor => {
  23034. if (hasTableTabNavigation(editor)) {
  23035. return [
  23036. {
  23037. keyCode: VK.TAB,
  23038. action: action(handleTab, editor, true)
  23039. },
  23040. {
  23041. keyCode: VK.TAB,
  23042. shiftKey: true,
  23043. action: action(handleTab, editor, false)
  23044. }
  23045. ];
  23046. } else {
  23047. return [];
  23048. }
  23049. };
  23050. const executeKeydownOverride = (editor, evt) => {
  23051. execute([...tableTabNavigation(editor)], evt).each(_ => {
  23052. evt.preventDefault();
  23053. });
  23054. };
  23055. const setup$c = editor => {
  23056. editor.on('keydown', evt => {
  23057. if (evt.isDefaultPrevented() === false) {
  23058. executeKeydownOverride(editor, evt);
  23059. }
  23060. });
  23061. };
  23062. const setup$b = editor => {
  23063. editor.addShortcut('Meta+P', '', 'mcePrint');
  23064. setup$j(editor);
  23065. if (isRtc(editor)) {
  23066. return Cell(null);
  23067. } else {
  23068. const caret = setupSelectedState(editor);
  23069. setup$l(editor);
  23070. setup$k(editor, caret);
  23071. setup$i(editor, caret);
  23072. setup$h(editor);
  23073. setup$d(editor);
  23074. setup$f(editor);
  23075. setup$c(editor);
  23076. setup$g(editor, caret);
  23077. setup$e(editor, caret);
  23078. return caret;
  23079. }
  23080. };
  23081. class NodeChange {
  23082. constructor(editor) {
  23083. this.lastPath = [];
  23084. this.editor = editor;
  23085. let lastRng;
  23086. const self = this;
  23087. if (!('onselectionchange' in editor.getDoc())) {
  23088. editor.on('NodeChange click mouseup keyup focus', e => {
  23089. const nativeRng = editor.selection.getRng();
  23090. const fakeRng = {
  23091. startContainer: nativeRng.startContainer,
  23092. startOffset: nativeRng.startOffset,
  23093. endContainer: nativeRng.endContainer,
  23094. endOffset: nativeRng.endOffset
  23095. };
  23096. if (e.type === 'nodechange' || !isEq$4(fakeRng, lastRng)) {
  23097. editor.dispatch('SelectionChange');
  23098. }
  23099. lastRng = fakeRng;
  23100. });
  23101. }
  23102. editor.on('contextmenu', () => {
  23103. editor.dispatch('SelectionChange');
  23104. });
  23105. editor.on('SelectionChange', () => {
  23106. const startElm = editor.selection.getStart(true);
  23107. if (!startElm) {
  23108. return;
  23109. }
  23110. if (hasAnyRanges(editor) && !self.isSameElementPath(startElm) && editor.dom.isChildOf(startElm, editor.getBody())) {
  23111. editor.nodeChanged({ selectionChange: true });
  23112. }
  23113. });
  23114. editor.on('mouseup', e => {
  23115. if (!e.isDefaultPrevented() && hasAnyRanges(editor)) {
  23116. if (editor.selection.getNode().nodeName === 'IMG') {
  23117. Delay.setEditorTimeout(editor, () => {
  23118. editor.nodeChanged();
  23119. });
  23120. } else {
  23121. editor.nodeChanged();
  23122. }
  23123. }
  23124. });
  23125. }
  23126. nodeChanged(args) {
  23127. const selection = this.editor.selection;
  23128. let node, parents, root;
  23129. if (this.editor.initialized && selection && !shouldDisableNodeChange(this.editor) && !this.editor.mode.isReadOnly()) {
  23130. root = this.editor.getBody();
  23131. node = selection.getStart(true) || root;
  23132. if (node.ownerDocument !== this.editor.getDoc() || !this.editor.dom.isChildOf(node, root)) {
  23133. node = root;
  23134. }
  23135. parents = [];
  23136. this.editor.dom.getParent(node, node => {
  23137. if (node === root) {
  23138. return true;
  23139. }
  23140. parents.push(node);
  23141. });
  23142. args = args || {};
  23143. args.element = node;
  23144. args.parents = parents;
  23145. this.editor.dispatch('NodeChange', args);
  23146. }
  23147. }
  23148. isSameElementPath(startElm) {
  23149. let i;
  23150. const editor = this.editor;
  23151. const currentPath = reverse(editor.dom.getParents(startElm, always, editor.getBody()));
  23152. if (currentPath.length === this.lastPath.length) {
  23153. for (i = currentPath.length; i >= 0; i--) {
  23154. if (currentPath[i] !== this.lastPath[i]) {
  23155. break;
  23156. }
  23157. }
  23158. if (i === -1) {
  23159. this.lastPath = currentPath;
  23160. return true;
  23161. }
  23162. }
  23163. this.lastPath = currentPath;
  23164. return false;
  23165. }
  23166. }
  23167. const internalMimeType = 'x-tinymce/html';
  23168. const internalHtmlMime = constant(internalMimeType);
  23169. const internalMark = '<!-- ' + internalMimeType + ' -->';
  23170. const mark = html => internalMark + html;
  23171. const unmark = html => html.replace(internalMark, '');
  23172. const isMarked = html => html.indexOf(internalMark) !== -1;
  23173. const isPlainText = text => {
  23174. return !/<(?:\/?(?!(?:div|p|br|span)>)\w+|(?:(?!(?:span style="white-space:\s?pre;?">)|br\s?\/>))\w+\s[^>]+)>/i.test(text);
  23175. };
  23176. const openContainer = (rootTag, rootAttrs) => {
  23177. let tag = '<' + rootTag;
  23178. const attrs = mapToArray(rootAttrs, (value, key) => key + '="' + Entities.encodeAllRaw(value) + '"');
  23179. if (attrs.length) {
  23180. tag += ' ' + attrs.join(' ');
  23181. }
  23182. return tag + '>';
  23183. };
  23184. const toBlockElements = (text, rootTag, rootAttrs) => {
  23185. const blocks = text.split(/\n\n/);
  23186. const tagOpen = openContainer(rootTag, rootAttrs);
  23187. const tagClose = '</' + rootTag + '>';
  23188. const paragraphs = map$3(blocks, p => {
  23189. return p.split(/\n/).join('<br />');
  23190. });
  23191. const stitch = p => {
  23192. return tagOpen + p + tagClose;
  23193. };
  23194. return paragraphs.length === 1 ? paragraphs[0] : map$3(paragraphs, stitch).join('');
  23195. };
  23196. const pasteBinDefaultContent = '%MCEPASTEBIN%';
  23197. const create$6 = (editor, lastRngCell) => {
  23198. const {dom, selection} = editor;
  23199. const body = editor.getBody();
  23200. lastRngCell.set(selection.getRng());
  23201. const pasteBinElm = dom.add(editor.getBody(), 'div', {
  23202. 'id': 'mcepastebin',
  23203. 'class': 'mce-pastebin',
  23204. 'contentEditable': true,
  23205. 'data-mce-bogus': 'all',
  23206. 'style': 'position: fixed; top: 50%; width: 10px; height: 10px; overflow: hidden; opacity: 0'
  23207. }, pasteBinDefaultContent);
  23208. if (Env.browser.isFirefox()) {
  23209. dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) === 'rtl' ? 65535 : -65535);
  23210. }
  23211. dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', e => {
  23212. e.stopPropagation();
  23213. });
  23214. pasteBinElm.focus();
  23215. selection.select(pasteBinElm, true);
  23216. };
  23217. const remove = (editor, lastRngCell) => {
  23218. const dom = editor.dom;
  23219. if (getEl(editor)) {
  23220. let pasteBinClone;
  23221. const lastRng = lastRngCell.get();
  23222. while (pasteBinClone = getEl(editor)) {
  23223. dom.remove(pasteBinClone);
  23224. dom.unbind(pasteBinClone);
  23225. }
  23226. if (lastRng) {
  23227. editor.selection.setRng(lastRng);
  23228. }
  23229. }
  23230. lastRngCell.set(null);
  23231. };
  23232. const getEl = editor => editor.dom.get('mcepastebin');
  23233. const isPasteBin = elm => elm && elm.id === 'mcepastebin';
  23234. const getHtml = editor => {
  23235. const dom = editor.dom;
  23236. const copyAndRemove = (toElm, fromElm) => {
  23237. toElm.appendChild(fromElm);
  23238. dom.remove(fromElm, true);
  23239. };
  23240. const [pasteBinElm, ...pasteBinClones] = filter$6(editor.getBody().childNodes, isPasteBin);
  23241. each$g(pasteBinClones, pasteBinClone => {
  23242. copyAndRemove(pasteBinElm, pasteBinClone);
  23243. });
  23244. const dirtyWrappers = dom.select('div[id=mcepastebin]', pasteBinElm);
  23245. for (let i = dirtyWrappers.length - 1; i >= 0; i--) {
  23246. const cleanWrapper = dom.create('div');
  23247. pasteBinElm.insertBefore(cleanWrapper, dirtyWrappers[i]);
  23248. copyAndRemove(cleanWrapper, dirtyWrappers[i]);
  23249. }
  23250. return pasteBinElm ? pasteBinElm.innerHTML : '';
  23251. };
  23252. const isDefaultPasteBinContent = content => content === pasteBinDefaultContent;
  23253. const PasteBin = editor => {
  23254. const lastRng = Cell(null);
  23255. return {
  23256. create: () => create$6(editor, lastRng),
  23257. remove: () => remove(editor, lastRng),
  23258. getEl: () => getEl(editor),
  23259. getHtml: () => getHtml(editor),
  23260. getLastRng: lastRng.get
  23261. };
  23262. };
  23263. const filter = (content, items) => {
  23264. Tools.each(items, v => {
  23265. if (is$4(v, RegExp)) {
  23266. content = content.replace(v, '');
  23267. } else {
  23268. content = content.replace(v[0], v[1]);
  23269. }
  23270. });
  23271. return content;
  23272. };
  23273. const innerText = html => {
  23274. const schema = Schema();
  23275. const domParser = DomParser({}, schema);
  23276. let text = '';
  23277. const voidElements = schema.getVoidElements();
  23278. const ignoreElements = Tools.makeMap('script noscript style textarea video audio iframe object', ' ');
  23279. const blockElements = schema.getBlockElements();
  23280. const walk = node => {
  23281. const name = node.name, currentNode = node;
  23282. if (name === 'br') {
  23283. text += '\n';
  23284. return;
  23285. }
  23286. if (name === 'wbr') {
  23287. return;
  23288. }
  23289. if (voidElements[name]) {
  23290. text += ' ';
  23291. }
  23292. if (ignoreElements[name]) {
  23293. text += ' ';
  23294. return;
  23295. }
  23296. if (node.type === 3) {
  23297. text += node.value;
  23298. }
  23299. if (!(node.name in schema.getVoidElements())) {
  23300. if (node = node.firstChild) {
  23301. do {
  23302. walk(node);
  23303. } while (node = node.next);
  23304. }
  23305. }
  23306. if (blockElements[name] && currentNode.next) {
  23307. text += '\n';
  23308. if (name === 'p') {
  23309. text += '\n';
  23310. }
  23311. }
  23312. };
  23313. html = filter(html, [/<!\[[^\]]+\]>/g]);
  23314. walk(domParser.parse(html));
  23315. return text;
  23316. };
  23317. const trimHtml = html => {
  23318. const trimSpaces = (all, s1, s2) => {
  23319. if (!s1 && !s2) {
  23320. return ' ';
  23321. }
  23322. return nbsp;
  23323. };
  23324. html = filter(html, [
  23325. /^[\s\S]*<body[^>]*>\s*|\s*<\/body[^>]*>[\s\S]*$/ig,
  23326. /<!--StartFragment-->|<!--EndFragment-->/g,
  23327. [
  23328. /( ?)<span class="Apple-converted-space">\u00a0<\/span>( ?)/g,
  23329. trimSpaces
  23330. ],
  23331. /<br class="Apple-interchange-newline">/g,
  23332. /<br>$/i
  23333. ]);
  23334. return html;
  23335. };
  23336. const createIdGenerator = prefix => {
  23337. let count = 0;
  23338. return () => {
  23339. return prefix + count++;
  23340. };
  23341. };
  23342. const getImageMimeType = ext => {
  23343. const lowerExt = ext.toLowerCase();
  23344. const mimeOverrides = {
  23345. jpg: 'jpeg',
  23346. jpe: 'jpeg',
  23347. jfi: 'jpeg',
  23348. jif: 'jpeg',
  23349. jfif: 'jpeg',
  23350. pjpeg: 'jpeg',
  23351. pjp: 'jpeg',
  23352. svg: 'svg+xml'
  23353. };
  23354. return Tools.hasOwn(mimeOverrides, lowerExt) ? 'image/' + mimeOverrides[lowerExt] : 'image/' + lowerExt;
  23355. };
  23356. const preProcess = (editor, html) => {
  23357. const parser = DomParser({}, editor.schema);
  23358. parser.addNodeFilter('meta', nodes => {
  23359. Tools.each(nodes, node => {
  23360. node.remove();
  23361. });
  23362. });
  23363. const fragment = parser.parse(html, {
  23364. forced_root_block: false,
  23365. isRootContent: true
  23366. });
  23367. return HtmlSerializer({ validate: true }, editor.schema).serialize(fragment);
  23368. };
  23369. const processResult = (content, cancelled) => ({
  23370. content,
  23371. cancelled
  23372. });
  23373. const postProcessFilter = (editor, html, internal) => {
  23374. const tempBody = editor.dom.create('div', { style: 'display:none' }, html);
  23375. const postProcessArgs = firePastePostProcess(editor, tempBody, internal);
  23376. return processResult(postProcessArgs.node.innerHTML, postProcessArgs.isDefaultPrevented());
  23377. };
  23378. const filterContent = (editor, content, internal) => {
  23379. const preProcessArgs = firePastePreProcess(editor, content, internal);
  23380. const filteredContent = preProcess(editor, preProcessArgs.content);
  23381. if (editor.hasEventListeners('PastePostProcess') && !preProcessArgs.isDefaultPrevented()) {
  23382. return postProcessFilter(editor, filteredContent, internal);
  23383. } else {
  23384. return processResult(filteredContent, preProcessArgs.isDefaultPrevented());
  23385. }
  23386. };
  23387. const process = (editor, html, internal) => {
  23388. return filterContent(editor, html, internal);
  23389. };
  23390. const pasteHtml$1 = (editor, html) => {
  23391. editor.insertContent(html, {
  23392. merge: shouldPasteMergeFormats(editor),
  23393. paste: true
  23394. });
  23395. return true;
  23396. };
  23397. const isAbsoluteUrl = url => /^https?:\/\/[\w\?\-\/+=.&%@~#]+$/i.test(url);
  23398. const isImageUrl = (editor, url) => {
  23399. return isAbsoluteUrl(url) && exists(getAllowedImageFileTypes(editor), type => endsWith(url.toLowerCase(), `.${ type.toLowerCase() }`));
  23400. };
  23401. const createImage = (editor, url, pasteHtmlFn) => {
  23402. editor.undoManager.extra(() => {
  23403. pasteHtmlFn(editor, url);
  23404. }, () => {
  23405. editor.insertContent('<img src="' + url + '">');
  23406. });
  23407. return true;
  23408. };
  23409. const createLink = (editor, url, pasteHtmlFn) => {
  23410. editor.undoManager.extra(() => {
  23411. pasteHtmlFn(editor, url);
  23412. }, () => {
  23413. editor.execCommand('mceInsertLink', false, url);
  23414. });
  23415. return true;
  23416. };
  23417. const linkSelection = (editor, html, pasteHtmlFn) => !editor.selection.isCollapsed() && isAbsoluteUrl(html) ? createLink(editor, html, pasteHtmlFn) : false;
  23418. const insertImage = (editor, html, pasteHtmlFn) => isImageUrl(editor, html) ? createImage(editor, html, pasteHtmlFn) : false;
  23419. const smartInsertContent = (editor, html) => {
  23420. Tools.each([
  23421. linkSelection,
  23422. insertImage,
  23423. pasteHtml$1
  23424. ], action => {
  23425. return action(editor, html, pasteHtml$1) !== true;
  23426. });
  23427. };
  23428. const insertContent = (editor, html, pasteAsText) => {
  23429. if (pasteAsText || !isSmartPasteEnabled(editor)) {
  23430. pasteHtml$1(editor, html);
  23431. } else {
  23432. smartInsertContent(editor, html);
  23433. }
  23434. };
  23435. const uniqueId = createIdGenerator('mceclip');
  23436. const doPaste = (editor, content, internal, pasteAsText) => {
  23437. const args = process(editor, content, internal);
  23438. if (args.cancelled === false) {
  23439. insertContent(editor, args.content, pasteAsText);
  23440. }
  23441. };
  23442. const pasteHtml = (editor, html, internalFlag) => {
  23443. const internal = internalFlag ? internalFlag : isMarked(html);
  23444. doPaste(editor, unmark(html), internal, false);
  23445. };
  23446. const pasteText = (editor, text) => {
  23447. const encodedText = editor.dom.encode(text).replace(/\r\n/g, '\n');
  23448. const normalizedText = normalize$4(encodedText, getPasteTabSpaces(editor));
  23449. const html = toBlockElements(normalizedText, getForcedRootBlock(editor), getForcedRootBlockAttrs(editor));
  23450. doPaste(editor, html, false, true);
  23451. };
  23452. const getDataTransferItems = dataTransfer => {
  23453. const items = {};
  23454. if (dataTransfer && dataTransfer.types) {
  23455. for (let i = 0; i < dataTransfer.types.length; i++) {
  23456. const contentType = dataTransfer.types[i];
  23457. try {
  23458. items[contentType] = dataTransfer.getData(contentType);
  23459. } catch (ex) {
  23460. items[contentType] = '';
  23461. }
  23462. }
  23463. }
  23464. return items;
  23465. };
  23466. const hasContentType = (clipboardContent, mimeType) => mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
  23467. const hasHtmlOrText = content => hasContentType(content, 'text/html') || hasContentType(content, 'text/plain');
  23468. const extractFilename = (editor, str) => {
  23469. const m = str.match(/([\s\S]+?)(?:\.[a-z0-9.]+)$/i);
  23470. return isNonNullable(m) ? editor.dom.encode(m[1]) : null;
  23471. };
  23472. const createBlobInfo = (editor, blobCache, file, base64) => {
  23473. const id = uniqueId();
  23474. const useFileName = shouldReuseFileName(editor) && isNonNullable(file.name);
  23475. const name = useFileName ? extractFilename(editor, file.name) : id;
  23476. const filename = useFileName ? file.name : undefined;
  23477. const blobInfo = blobCache.create(id, file, base64, name, filename);
  23478. blobCache.add(blobInfo);
  23479. return blobInfo;
  23480. };
  23481. const pasteImage = (editor, imageItem) => {
  23482. const {
  23483. data: base64,
  23484. type
  23485. } = parseDataUri$1(imageItem.uri);
  23486. const file = imageItem.file;
  23487. const blobCache = editor.editorUpload.blobCache;
  23488. const existingBlobInfo = blobCache.getByData(base64, type);
  23489. const blobInfo = existingBlobInfo !== null && existingBlobInfo !== void 0 ? existingBlobInfo : createBlobInfo(editor, blobCache, file, base64);
  23490. pasteHtml(editor, `<img src="${ blobInfo.blobUri() }">`, false);
  23491. };
  23492. const isClipboardEvent = event => event.type === 'paste';
  23493. const readFilesAsDataUris = items => Promise.all(map$3(items, file => {
  23494. return blobToDataUri(file).then(uri => ({
  23495. file,
  23496. uri
  23497. }));
  23498. }));
  23499. const isImage = editor => {
  23500. const allowedExtensions = getAllowedImageFileTypes(editor);
  23501. return file => startsWith(file.type, 'image/') && exists(allowedExtensions, extension => {
  23502. return getImageMimeType(extension) === file.type;
  23503. });
  23504. };
  23505. const getImagesFromDataTransfer = (editor, dataTransfer) => {
  23506. const items = dataTransfer.items ? bind$3(from(dataTransfer.items), item => {
  23507. return item.kind === 'file' ? [item.getAsFile()] : [];
  23508. }) : [];
  23509. const files = dataTransfer.files ? from(dataTransfer.files) : [];
  23510. return filter$6(items.length > 0 ? items : files, isImage(editor));
  23511. };
  23512. const pasteImageData = (editor, e, rng) => {
  23513. const dataTransfer = isClipboardEvent(e) ? e.clipboardData : e.dataTransfer;
  23514. if (shouldPasteDataImages(editor) && dataTransfer) {
  23515. const images = getImagesFromDataTransfer(editor, dataTransfer);
  23516. if (images.length > 0) {
  23517. e.preventDefault();
  23518. readFilesAsDataUris(images).then(fileResults => {
  23519. if (rng) {
  23520. editor.selection.setRng(rng);
  23521. }
  23522. each$g(fileResults, result => {
  23523. pasteImage(editor, result);
  23524. });
  23525. });
  23526. return true;
  23527. }
  23528. }
  23529. return false;
  23530. };
  23531. const isBrokenAndroidClipboardEvent = e => {
  23532. var _a, _b;
  23533. return Env.os.isAndroid() && ((_b = (_a = e.clipboardData) === null || _a === void 0 ? void 0 : _a.items) === null || _b === void 0 ? void 0 : _b.length) === 0;
  23534. };
  23535. const isKeyboardPasteEvent = e => VK.metaKeyPressed(e) && e.keyCode === 86 || e.shiftKey && e.keyCode === 45;
  23536. const insertClipboardContent = (editor, clipboardContent, html, plainTextMode) => {
  23537. let content = trimHtml(html);
  23538. const isInternal = hasContentType(clipboardContent, internalHtmlMime()) || isMarked(html);
  23539. const isPlainTextHtml = !isInternal && isPlainText(content);
  23540. const isAbsoluteUrl$1 = isAbsoluteUrl(content);
  23541. if (isDefaultPasteBinContent(content) || !content.length || isPlainTextHtml && !isAbsoluteUrl$1) {
  23542. plainTextMode = true;
  23543. }
  23544. if (plainTextMode || isAbsoluteUrl$1) {
  23545. if (hasContentType(clipboardContent, 'text/plain') && isPlainTextHtml) {
  23546. content = clipboardContent['text/plain'];
  23547. } else {
  23548. content = innerText(content);
  23549. }
  23550. }
  23551. if (isDefaultPasteBinContent(content)) {
  23552. return;
  23553. }
  23554. if (plainTextMode) {
  23555. pasteText(editor, content);
  23556. } else {
  23557. pasteHtml(editor, content, isInternal);
  23558. }
  23559. };
  23560. const registerEventHandlers = (editor, pasteBin, pasteFormat) => {
  23561. let keyboardPastePlainTextState;
  23562. const getLastRng = () => pasteBin.getLastRng() || editor.selection.getRng();
  23563. editor.on('keydown', e => {
  23564. if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
  23565. keyboardPastePlainTextState = e.shiftKey && e.keyCode === 86;
  23566. }
  23567. });
  23568. editor.on('paste', e => {
  23569. if (e.isDefaultPrevented() || isBrokenAndroidClipboardEvent(e)) {
  23570. return;
  23571. }
  23572. const plainTextMode = pasteFormat.get() === 'text' || keyboardPastePlainTextState;
  23573. keyboardPastePlainTextState = false;
  23574. const clipboardContent = getDataTransferItems(e.clipboardData);
  23575. if (!hasHtmlOrText(clipboardContent) && pasteImageData(editor, e, getLastRng())) {
  23576. return;
  23577. }
  23578. if (hasContentType(clipboardContent, 'text/html')) {
  23579. e.preventDefault();
  23580. insertClipboardContent(editor, clipboardContent, clipboardContent['text/html'], plainTextMode);
  23581. } else {
  23582. pasteBin.create();
  23583. Delay.setEditorTimeout(editor, () => {
  23584. const html = pasteBin.getHtml();
  23585. pasteBin.remove();
  23586. insertClipboardContent(editor, clipboardContent, html, plainTextMode);
  23587. }, 0);
  23588. }
  23589. });
  23590. };
  23591. const registerDataImageFilter = editor => {
  23592. const isWebKitFakeUrl = src => startsWith(src, 'webkit-fake-url');
  23593. const isDataUri = src => startsWith(src, 'data:');
  23594. const isPasteInsert = args => {
  23595. var _a;
  23596. return ((_a = args.data) === null || _a === void 0 ? void 0 : _a.paste) === true;
  23597. };
  23598. editor.parser.addNodeFilter('img', (nodes, name, args) => {
  23599. if (!shouldPasteDataImages(editor) && isPasteInsert(args)) {
  23600. for (const node of nodes) {
  23601. const src = node.attr('src');
  23602. if (isString(src) && !node.attr('data-mce-object') && src !== Env.transparentSrc) {
  23603. if (isWebKitFakeUrl(src)) {
  23604. node.remove();
  23605. } else if (!shouldAllowHtmlDataUrls(editor) && isDataUri(src)) {
  23606. node.remove();
  23607. }
  23608. }
  23609. }
  23610. }
  23611. });
  23612. };
  23613. const registerEventsAndFilters = (editor, pasteBin, pasteFormat) => {
  23614. registerEventHandlers(editor, pasteBin, pasteFormat);
  23615. registerDataImageFilter(editor);
  23616. };
  23617. const togglePlainTextPaste = (editor, pasteFormat) => {
  23618. if (pasteFormat.get() === 'text') {
  23619. pasteFormat.set('html');
  23620. firePastePlainTextToggle(editor, false);
  23621. } else {
  23622. pasteFormat.set('text');
  23623. firePastePlainTextToggle(editor, true);
  23624. }
  23625. editor.focus();
  23626. };
  23627. const register$1 = (editor, pasteFormat) => {
  23628. editor.addCommand('mceTogglePlainTextPaste', () => {
  23629. togglePlainTextPaste(editor, pasteFormat);
  23630. });
  23631. editor.addCommand('mceInsertClipboardContent', (ui, value) => {
  23632. if (value.html) {
  23633. pasteHtml(editor, value.html, value.internal);
  23634. }
  23635. if (value.text) {
  23636. pasteText(editor, value.text);
  23637. }
  23638. });
  23639. };
  23640. const setHtml5Clipboard = (clipboardData, html, text) => {
  23641. try {
  23642. clipboardData.clearData();
  23643. clipboardData.setData('text/html', html);
  23644. clipboardData.setData('text/plain', text);
  23645. clipboardData.setData(internalHtmlMime(), html);
  23646. return true;
  23647. } catch (e) {
  23648. return false;
  23649. }
  23650. };
  23651. const setClipboardData = (evt, data, fallback, done) => {
  23652. if (setHtml5Clipboard(evt.clipboardData, data.html, data.text)) {
  23653. evt.preventDefault();
  23654. done();
  23655. } else {
  23656. fallback(data.html, done);
  23657. }
  23658. };
  23659. const fallback = editor => (html, done) => {
  23660. const {dom, selection} = editor;
  23661. const outer = dom.create('div', {
  23662. 'contenteditable': 'false',
  23663. 'data-mce-bogus': 'all'
  23664. });
  23665. const inner = dom.create('div', { contenteditable: 'true' }, html);
  23666. dom.setStyles(outer, {
  23667. position: 'fixed',
  23668. top: '0',
  23669. left: '-3000px',
  23670. width: '1000px',
  23671. overflow: 'hidden'
  23672. });
  23673. outer.appendChild(inner);
  23674. dom.add(editor.getBody(), outer);
  23675. const range = selection.getRng();
  23676. inner.focus();
  23677. const offscreenRange = dom.createRng();
  23678. offscreenRange.selectNodeContents(inner);
  23679. selection.setRng(offscreenRange);
  23680. Delay.setEditorTimeout(editor, () => {
  23681. selection.setRng(range);
  23682. dom.remove(outer);
  23683. done();
  23684. }, 0);
  23685. };
  23686. const getData = editor => ({
  23687. html: mark(editor.selection.getContent({ contextual: true })),
  23688. text: editor.selection.getContent({ format: 'text' })
  23689. });
  23690. const isTableSelection = editor => !!editor.dom.getParent(editor.selection.getStart(), 'td[data-mce-selected],th[data-mce-selected]', editor.getBody());
  23691. const hasSelectedContent = editor => !editor.selection.isCollapsed() || isTableSelection(editor);
  23692. const cut = editor => evt => {
  23693. if (!evt.isDefaultPrevented() && hasSelectedContent(editor)) {
  23694. setClipboardData(evt, getData(editor), fallback(editor), () => {
  23695. if (Env.browser.isChromium() || Env.browser.isFirefox()) {
  23696. const rng = editor.selection.getRng();
  23697. Delay.setEditorTimeout(editor, () => {
  23698. editor.selection.setRng(rng);
  23699. editor.execCommand('Delete');
  23700. }, 0);
  23701. } else {
  23702. editor.execCommand('Delete');
  23703. }
  23704. });
  23705. }
  23706. };
  23707. const copy = editor => evt => {
  23708. if (!evt.isDefaultPrevented() && hasSelectedContent(editor)) {
  23709. setClipboardData(evt, getData(editor), fallback(editor), noop);
  23710. }
  23711. };
  23712. const register = editor => {
  23713. editor.on('cut', cut(editor));
  23714. editor.on('copy', copy(editor));
  23715. };
  23716. const getCaretRangeFromEvent = (editor, e) => {
  23717. var _a, _b;
  23718. return RangeUtils.getCaretRangeFromPoint((_a = e.clientX) !== null && _a !== void 0 ? _a : 0, (_b = e.clientY) !== null && _b !== void 0 ? _b : 0, editor.getDoc());
  23719. };
  23720. const isPlainTextFileUrl = content => {
  23721. const plainTextContent = content['text/plain'];
  23722. return plainTextContent ? plainTextContent.indexOf('file://') === 0 : false;
  23723. };
  23724. const setFocusedRange = (editor, rng) => {
  23725. editor.focus();
  23726. if (rng) {
  23727. editor.selection.setRng(rng);
  23728. }
  23729. };
  23730. const hasImage = dataTransfer => exists(dataTransfer.files, file => /^image\//.test(file.type));
  23731. const setup$a = (editor, draggingInternallyState) => {
  23732. if (shouldPasteBlockDrop(editor)) {
  23733. editor.on('dragend dragover draggesture dragdrop drop drag', e => {
  23734. e.preventDefault();
  23735. e.stopPropagation();
  23736. });
  23737. }
  23738. if (!shouldPasteDataImages(editor)) {
  23739. editor.on('drop', e => {
  23740. const dataTransfer = e.dataTransfer;
  23741. if (dataTransfer && hasImage(dataTransfer)) {
  23742. e.preventDefault();
  23743. }
  23744. });
  23745. }
  23746. editor.on('drop', e => {
  23747. if (e.isDefaultPrevented() || draggingInternallyState.get()) {
  23748. return;
  23749. }
  23750. const rng = getCaretRangeFromEvent(editor, e);
  23751. if (isNullable(rng)) {
  23752. return;
  23753. }
  23754. const dropContent = getDataTransferItems(e.dataTransfer);
  23755. const internal = hasContentType(dropContent, internalHtmlMime());
  23756. if ((!hasHtmlOrText(dropContent) || isPlainTextFileUrl(dropContent)) && pasteImageData(editor, e, rng)) {
  23757. return;
  23758. }
  23759. const internalContent = dropContent[internalHtmlMime()];
  23760. const content = internalContent || dropContent['text/html'] || dropContent['text/plain'];
  23761. if (content) {
  23762. e.preventDefault();
  23763. Delay.setEditorTimeout(editor, () => {
  23764. editor.undoManager.transact(() => {
  23765. if (internalContent) {
  23766. editor.execCommand('Delete');
  23767. }
  23768. setFocusedRange(editor, rng);
  23769. const trimmedContent = trimHtml(content);
  23770. if (dropContent['text/html']) {
  23771. pasteHtml(editor, trimmedContent, internal);
  23772. } else {
  23773. pasteText(editor, trimmedContent);
  23774. }
  23775. });
  23776. });
  23777. }
  23778. });
  23779. editor.on('dragstart', _e => {
  23780. draggingInternallyState.set(true);
  23781. });
  23782. editor.on('dragover dragend', e => {
  23783. if (shouldPasteDataImages(editor) && draggingInternallyState.get() === false) {
  23784. e.preventDefault();
  23785. setFocusedRange(editor, getCaretRangeFromEvent(editor, e));
  23786. }
  23787. if (e.type === 'dragend') {
  23788. draggingInternallyState.set(false);
  23789. }
  23790. });
  23791. };
  23792. const setup$9 = editor => {
  23793. const processEvent = f => e => {
  23794. f(editor, e);
  23795. };
  23796. const preProcess = getPastePreProcess(editor);
  23797. if (isFunction(preProcess)) {
  23798. editor.on('PastePreProcess', processEvent(preProcess));
  23799. }
  23800. const postProcess = getPastePostProcess(editor);
  23801. if (isFunction(postProcess)) {
  23802. editor.on('PastePostProcess', processEvent(postProcess));
  23803. }
  23804. };
  23805. const addPreProcessFilter = (editor, filterFunc) => {
  23806. editor.on('PastePreProcess', e => {
  23807. e.content = filterFunc(editor, e.content, e.internal);
  23808. });
  23809. };
  23810. const rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
  23811. const rgbToHex = value => Tools.trim(value).replace(rgbRegExp, rgbaToHexString).toLowerCase();
  23812. const removeWebKitStyles = (editor, content, internal) => {
  23813. const webKitStylesOption = getPasteWebkitStyles(editor);
  23814. if (internal || webKitStylesOption === 'all' || !shouldPasteRemoveWebKitStyles(editor)) {
  23815. return content;
  23816. }
  23817. const webKitStyles = webKitStylesOption ? webKitStylesOption.split(/[, ]/) : [];
  23818. if (webKitStyles && webKitStylesOption !== 'none') {
  23819. const dom = editor.dom, node = editor.selection.getNode();
  23820. content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, (all, before, value, after) => {
  23821. const inputStyles = dom.parseStyle(dom.decode(value));
  23822. const outputStyles = {};
  23823. for (let i = 0; i < webKitStyles.length; i++) {
  23824. const inputValue = inputStyles[webKitStyles[i]];
  23825. let compareInput = inputValue;
  23826. let currentValue = dom.getStyle(node, webKitStyles[i], true);
  23827. if (/color/.test(webKitStyles[i])) {
  23828. compareInput = rgbToHex(compareInput);
  23829. currentValue = rgbToHex(currentValue);
  23830. }
  23831. if (currentValue !== compareInput) {
  23832. outputStyles[webKitStyles[i]] = inputValue;
  23833. }
  23834. }
  23835. const outputStyle = dom.serializeStyle(outputStyles, 'span');
  23836. if (outputStyle) {
  23837. return before + ' style="' + outputStyle + '"' + after;
  23838. }
  23839. return before + after;
  23840. });
  23841. } else {
  23842. content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, '$1$3');
  23843. }
  23844. content = content.replace(/(<[^>]+) data-mce-style="([^"]+)"([^>]*>)/gi, (all, before, value, after) => {
  23845. return before + ' style="' + value + '"' + after;
  23846. });
  23847. return content;
  23848. };
  23849. const setup$8 = editor => {
  23850. if (Env.browser.isChromium() || Env.browser.isSafari()) {
  23851. addPreProcessFilter(editor, removeWebKitStyles);
  23852. }
  23853. };
  23854. const setup$7 = editor => {
  23855. const draggingInternallyState = Cell(false);
  23856. const pasteFormat = Cell(isPasteAsTextEnabled(editor) ? 'text' : 'html');
  23857. const pasteBin = PasteBin(editor);
  23858. setup$8(editor);
  23859. register$1(editor, pasteFormat);
  23860. setup$9(editor);
  23861. editor.on('PreInit', () => {
  23862. register(editor);
  23863. setup$a(editor, draggingInternallyState);
  23864. registerEventsAndFilters(editor, pasteBin, pasteFormat);
  23865. });
  23866. };
  23867. const preventSummaryToggle = editor => {
  23868. editor.on('click', e => {
  23869. if (editor.dom.getParent(e.target, 'details')) {
  23870. e.preventDefault();
  23871. }
  23872. });
  23873. };
  23874. const filterDetails = editor => {
  23875. editor.parser.addNodeFilter('details', elms => {
  23876. each$g(elms, details => {
  23877. details.attr('data-mce-open', details.attr('open'));
  23878. details.attr('open', 'open');
  23879. });
  23880. });
  23881. editor.serializer.addNodeFilter('details', elms => {
  23882. each$g(elms, details => {
  23883. const open = details.attr('data-mce-open');
  23884. details.attr('open', isString(open) ? open : null);
  23885. details.attr('data-mce-open', null);
  23886. });
  23887. });
  23888. };
  23889. const setup$6 = editor => {
  23890. preventSummaryToggle(editor);
  23891. filterDetails(editor);
  23892. };
  23893. const isTextBlockNode = node => isElement$6(node) && isTextBlock$2(SugarElement.fromDom(node));
  23894. const normalizeSelection = editor => {
  23895. const rng = editor.selection.getRng();
  23896. const startPos = CaretPosition.fromRangeStart(rng);
  23897. const endPos = CaretPosition.fromRangeEnd(rng);
  23898. if (CaretPosition.isElementPosition(startPos)) {
  23899. const container = startPos.container();
  23900. if (isTextBlockNode(container)) {
  23901. firstPositionIn(container).each(pos => rng.setStart(pos.container(), pos.offset()));
  23902. }
  23903. }
  23904. if (CaretPosition.isElementPosition(endPos)) {
  23905. const container = startPos.container();
  23906. if (isTextBlockNode(container)) {
  23907. lastPositionIn(container).each(pos => rng.setEnd(pos.container(), pos.offset()));
  23908. }
  23909. }
  23910. editor.selection.setRng(normalize(rng));
  23911. };
  23912. const setup$5 = editor => {
  23913. editor.on('click', e => {
  23914. if (e.detail >= 3) {
  23915. normalizeSelection(editor);
  23916. }
  23917. });
  23918. };
  23919. var FakeCaretPosition;
  23920. (function (FakeCaretPosition) {
  23921. FakeCaretPosition['Before'] = 'before';
  23922. FakeCaretPosition['After'] = 'after';
  23923. }(FakeCaretPosition || (FakeCaretPosition = {})));
  23924. const distanceToRectLeft = (clientRect, clientX) => Math.abs(clientRect.left - clientX);
  23925. const distanceToRectRight = (clientRect, clientX) => Math.abs(clientRect.right - clientX);
  23926. const isInsideY = (clientY, clientRect) => clientY >= clientRect.top && clientY <= clientRect.bottom;
  23927. const collidesY = (r1, r2) => r1.top < r2.bottom && r1.bottom > r2.top;
  23928. const isOverlapping = (r1, r2) => {
  23929. const overlap = overlapY(r1, r2) / Math.min(r1.height, r2.height);
  23930. return collidesY(r1, r2) && overlap > 0.5;
  23931. };
  23932. const splitRectsPerAxis = (rects, y) => {
  23933. const intersectingRects = filter$6(rects, rect => isInsideY(y, rect));
  23934. return boundingClientRectFromRects(intersectingRects).fold(() => [
  23935. [],
  23936. rects
  23937. ], boundingRect => {
  23938. const {
  23939. pass: horizontal,
  23940. fail: vertical
  23941. } = partition$2(rects, rect => isOverlapping(rect, boundingRect));
  23942. return [
  23943. horizontal,
  23944. vertical
  23945. ];
  23946. });
  23947. };
  23948. const clientInfo = (rect, clientX) => {
  23949. return {
  23950. node: rect.node,
  23951. position: distanceToRectLeft(rect, clientX) < distanceToRectRight(rect, clientX) ? FakeCaretPosition.Before : FakeCaretPosition.After
  23952. };
  23953. };
  23954. const horizontalDistance = (rect, x, _y) => x > rect.left && x < rect.right ? 0 : Math.min(Math.abs(rect.left - x), Math.abs(rect.right - x));
  23955. const closestChildCaretCandidateNodeRect = (children, clientX, clientY) => {
  23956. const caretCandidateRect = rect => {
  23957. if (isCaretCandidate$3(rect.node)) {
  23958. return Optional.some(rect);
  23959. } else if (isElement$6(rect.node)) {
  23960. return closestChildCaretCandidateNodeRect(from(rect.node.childNodes), clientX, clientY);
  23961. } else {
  23962. return Optional.none();
  23963. }
  23964. };
  23965. const getClosestTextNode = (rects, distance) => {
  23966. if (rects.length >= 2) {
  23967. const r1 = caretCandidateRect(rects[0]).getOr(rects[0]);
  23968. const r2 = caretCandidateRect(rects[1]).getOr(rects[1]);
  23969. const deltaDistance = Math.abs(distance(r1, clientX, clientY) - distance(r2, clientX, clientY));
  23970. if (deltaDistance < 2) {
  23971. if (isText$8(r1.node)) {
  23972. return Optional.some(r1);
  23973. } else if (isText$8(r2.node)) {
  23974. return Optional.some(r2);
  23975. }
  23976. }
  23977. }
  23978. return Optional.none();
  23979. };
  23980. const findClosestCaretCandidateNodeRect = (rects, distance) => {
  23981. const sortedRects = sort(rects, (r1, r2) => distance(r1, clientX, clientY) - distance(r2, clientX, clientY));
  23982. return getClosestTextNode(sortedRects, distance).orThunk(() => findMap(sortedRects, caretCandidateRect));
  23983. };
  23984. const [horizontalRects, verticalRects] = splitRectsPerAxis(getClientRects(children), clientY);
  23985. const {
  23986. pass: above,
  23987. fail: below
  23988. } = partition$2(verticalRects, rect => rect.top < clientY);
  23989. return findClosestCaretCandidateNodeRect(horizontalRects, horizontalDistance).orThunk(() => findClosestCaretCandidateNodeRect(below, distanceToRectEdgeFromXY)).orThunk(() => findClosestCaretCandidateNodeRect(above, distanceToRectEdgeFromXY));
  23990. };
  23991. const traverseUp = (rootElm, scope, clientX, clientY) => {
  23992. const helper = (scope, prevScope) => {
  23993. return prevScope.fold(() => closestChildCaretCandidateNodeRect(from(scope.dom.childNodes), clientX, clientY), prevScope => {
  23994. const uncheckedChildren = filter$6(from(scope.dom.childNodes), node => node !== prevScope.dom);
  23995. return closestChildCaretCandidateNodeRect(uncheckedChildren, clientX, clientY);
  23996. }).orThunk(() => {
  23997. const parent = eq(scope, rootElm) ? Optional.none() : parentElement(scope);
  23998. return parent.bind(newScope => helper(newScope, Optional.some(scope)));
  23999. });
  24000. };
  24001. return helper(scope, Optional.none());
  24002. };
  24003. const closestCaretCandidateNodeRect = (root, clientX, clientY) => {
  24004. const rootElm = SugarElement.fromDom(root);
  24005. const ownerDoc = documentOrOwner(rootElm);
  24006. const elementAtPoint = SugarElement.fromPoint(ownerDoc, clientX, clientY).filter(elm => contains(rootElm, elm));
  24007. const element = elementAtPoint.getOr(rootElm);
  24008. return traverseUp(rootElm, element, clientX, clientY);
  24009. };
  24010. const closestFakeCaretCandidate = (root, clientX, clientY) => closestCaretCandidateNodeRect(root, clientX, clientY).filter(rect => isFakeCaretTarget(rect.node)).map(rect => clientInfo(rect, clientX));
  24011. const getAbsolutePosition = elm => {
  24012. const clientRect = elm.getBoundingClientRect();
  24013. const doc = elm.ownerDocument;
  24014. const docElem = doc.documentElement;
  24015. const win = doc.defaultView;
  24016. return {
  24017. top: clientRect.top + win.pageYOffset - docElem.clientTop,
  24018. left: clientRect.left + win.pageXOffset - docElem.clientLeft
  24019. };
  24020. };
  24021. const getBodyPosition = editor => editor.inline ? getAbsolutePosition(editor.getBody()) : {
  24022. left: 0,
  24023. top: 0
  24024. };
  24025. const getScrollPosition = editor => {
  24026. const body = editor.getBody();
  24027. return editor.inline ? {
  24028. left: body.scrollLeft,
  24029. top: body.scrollTop
  24030. } : {
  24031. left: 0,
  24032. top: 0
  24033. };
  24034. };
  24035. const getBodyScroll = editor => {
  24036. const body = editor.getBody(), docElm = editor.getDoc().documentElement;
  24037. const inlineScroll = {
  24038. left: body.scrollLeft,
  24039. top: body.scrollTop
  24040. };
  24041. const iframeScroll = {
  24042. left: body.scrollLeft || docElm.scrollLeft,
  24043. top: body.scrollTop || docElm.scrollTop
  24044. };
  24045. return editor.inline ? inlineScroll : iframeScroll;
  24046. };
  24047. const getMousePosition = (editor, event) => {
  24048. if (event.target.ownerDocument !== editor.getDoc()) {
  24049. const iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
  24050. const scrollPosition = getBodyScroll(editor);
  24051. return {
  24052. left: event.pageX - iframePosition.left + scrollPosition.left,
  24053. top: event.pageY - iframePosition.top + scrollPosition.top
  24054. };
  24055. }
  24056. return {
  24057. left: event.pageX,
  24058. top: event.pageY
  24059. };
  24060. };
  24061. const calculatePosition = (bodyPosition, scrollPosition, mousePosition) => ({
  24062. pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
  24063. pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
  24064. });
  24065. const calc = (editor, event) => calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
  24066. const isContentEditableFalse$1 = isContentEditableFalse$a, isContentEditableTrue = isContentEditableTrue$4;
  24067. const isDraggable = (rootElm, elm) => isContentEditableFalse$1(elm) && elm !== rootElm;
  24068. const isValidDropTarget = (editor, targetElement, dragElement) => {
  24069. if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
  24070. return false;
  24071. }
  24072. return !isContentEditableFalse$1(targetElement);
  24073. };
  24074. const cloneElement = elm => {
  24075. const cloneElm = elm.cloneNode(true);
  24076. cloneElm.removeAttribute('data-mce-selected');
  24077. return cloneElm;
  24078. };
  24079. const createGhost = (editor, elm, width, height) => {
  24080. const dom = editor.dom;
  24081. const clonedElm = elm.cloneNode(true);
  24082. dom.setStyles(clonedElm, {
  24083. width,
  24084. height
  24085. });
  24086. dom.setAttrib(clonedElm, 'data-mce-selected', null);
  24087. const ghostElm = dom.create('div', {
  24088. 'class': 'mce-drag-container',
  24089. 'data-mce-bogus': 'all',
  24090. 'unselectable': 'on',
  24091. 'contenteditable': 'false'
  24092. });
  24093. dom.setStyles(ghostElm, {
  24094. position: 'absolute',
  24095. opacity: 0.5,
  24096. overflow: 'hidden',
  24097. border: 0,
  24098. padding: 0,
  24099. margin: 0,
  24100. width,
  24101. height
  24102. });
  24103. dom.setStyles(clonedElm, {
  24104. margin: 0,
  24105. boxSizing: 'border-box'
  24106. });
  24107. ghostElm.appendChild(clonedElm);
  24108. return ghostElm;
  24109. };
  24110. const appendGhostToBody = (ghostElm, bodyElm) => {
  24111. if (ghostElm.parentNode !== bodyElm) {
  24112. bodyElm.appendChild(ghostElm);
  24113. }
  24114. };
  24115. const moveGhost = (ghostElm, position, width, height, maxX, maxY) => {
  24116. let overflowX = 0, overflowY = 0;
  24117. ghostElm.style.left = position.pageX + 'px';
  24118. ghostElm.style.top = position.pageY + 'px';
  24119. if (position.pageX + width > maxX) {
  24120. overflowX = position.pageX + width - maxX;
  24121. }
  24122. if (position.pageY + height > maxY) {
  24123. overflowY = position.pageY + height - maxY;
  24124. }
  24125. ghostElm.style.width = width - overflowX + 'px';
  24126. ghostElm.style.height = height - overflowY + 'px';
  24127. };
  24128. const removeElement = elm => {
  24129. if (elm && elm.parentNode) {
  24130. elm.parentNode.removeChild(elm);
  24131. }
  24132. };
  24133. const isLeftMouseButtonPressed = e => e.button === 0;
  24134. const applyRelPos = (state, position) => ({
  24135. pageX: position.pageX - state.relX,
  24136. pageY: position.pageY + 5
  24137. });
  24138. const start = (state, editor) => e => {
  24139. if (isLeftMouseButtonPressed(e)) {
  24140. const ceElm = find$2(editor.dom.getParents(e.target), or(isContentEditableFalse$1, isContentEditableTrue)).getOr(null);
  24141. if (isDraggable(editor.getBody(), ceElm)) {
  24142. const elmPos = editor.dom.getPos(ceElm);
  24143. const bodyElm = editor.getBody();
  24144. const docElm = editor.getDoc().documentElement;
  24145. state.set({
  24146. element: ceElm,
  24147. dragging: false,
  24148. screenX: e.screenX,
  24149. screenY: e.screenY,
  24150. maxX: (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2,
  24151. maxY: (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2,
  24152. relX: e.pageX - elmPos.x,
  24153. relY: e.pageY - elmPos.y,
  24154. width: ceElm.offsetWidth,
  24155. height: ceElm.offsetHeight,
  24156. ghost: createGhost(editor, ceElm, ceElm.offsetWidth, ceElm.offsetHeight)
  24157. });
  24158. }
  24159. }
  24160. };
  24161. const move = (state, editor) => {
  24162. const throttledPlaceCaretAt = first$1((clientX, clientY) => {
  24163. editor._selectionOverrides.hideFakeCaret();
  24164. editor.selection.placeCaretAt(clientX, clientY);
  24165. }, 0);
  24166. editor.on('remove', throttledPlaceCaretAt.cancel);
  24167. return e => state.on(state => {
  24168. const movement = Math.max(Math.abs(e.screenX - state.screenX), Math.abs(e.screenY - state.screenY));
  24169. if (!state.dragging && movement > 10) {
  24170. const args = editor.dispatch('dragstart', { target: state.element });
  24171. if (args.isDefaultPrevented()) {
  24172. return;
  24173. }
  24174. state.dragging = true;
  24175. editor.focus();
  24176. }
  24177. if (state.dragging) {
  24178. const targetPos = applyRelPos(state, calc(editor, e));
  24179. appendGhostToBody(state.ghost, editor.getBody());
  24180. moveGhost(state.ghost, targetPos, state.width, state.height, state.maxX, state.maxY);
  24181. throttledPlaceCaretAt.throttle(e.clientX, e.clientY);
  24182. }
  24183. });
  24184. };
  24185. const getRawTarget = selection => {
  24186. const rng = selection.getSel().getRangeAt(0);
  24187. const startContainer = rng.startContainer;
  24188. return startContainer.nodeType === 3 ? startContainer.parentNode : startContainer;
  24189. };
  24190. const drop = (state, editor) => e => {
  24191. state.on(state => {
  24192. if (state.dragging) {
  24193. if (isValidDropTarget(editor, getRawTarget(editor.selection), state.element)) {
  24194. const targetClone = cloneElement(state.element);
  24195. const args = editor.dispatch('drop', {
  24196. clientX: e.clientX,
  24197. clientY: e.clientY
  24198. });
  24199. if (!args.isDefaultPrevented()) {
  24200. editor.undoManager.transact(() => {
  24201. removeElement(state.element);
  24202. editor.insertContent(editor.dom.getOuterHTML(targetClone));
  24203. editor._selectionOverrides.hideFakeCaret();
  24204. });
  24205. }
  24206. }
  24207. editor.dispatch('dragend');
  24208. }
  24209. });
  24210. removeDragState(state);
  24211. };
  24212. const stop = (state, editor) => () => {
  24213. state.on(state => {
  24214. if (state.dragging) {
  24215. editor.dispatch('dragend');
  24216. }
  24217. });
  24218. removeDragState(state);
  24219. };
  24220. const removeDragState = state => {
  24221. state.on(state => {
  24222. removeElement(state.ghost);
  24223. });
  24224. state.clear();
  24225. };
  24226. const bindFakeDragEvents = editor => {
  24227. const state = value$2();
  24228. const pageDom = DOMUtils.DOM;
  24229. const rootDocument = document;
  24230. const dragStartHandler = start(state, editor);
  24231. const dragHandler = move(state, editor);
  24232. const dropHandler = drop(state, editor);
  24233. const dragEndHandler = stop(state, editor);
  24234. editor.on('mousedown', dragStartHandler);
  24235. editor.on('mousemove', dragHandler);
  24236. editor.on('mouseup', dropHandler);
  24237. pageDom.bind(rootDocument, 'mousemove', dragHandler);
  24238. pageDom.bind(rootDocument, 'mouseup', dragEndHandler);
  24239. editor.on('remove', () => {
  24240. pageDom.unbind(rootDocument, 'mousemove', dragHandler);
  24241. pageDom.unbind(rootDocument, 'mouseup', dragEndHandler);
  24242. });
  24243. editor.on('keydown', e => {
  24244. if (e.keyCode === VK.ESC) {
  24245. dragEndHandler();
  24246. }
  24247. });
  24248. };
  24249. const blockUnsupportedFileDrop = editor => {
  24250. const preventFileDrop = e => {
  24251. if (!e.isDefaultPrevented()) {
  24252. const dataTransfer = e.dataTransfer;
  24253. if (dataTransfer && (contains$2(dataTransfer.types, 'Files') || dataTransfer.files.length > 0)) {
  24254. e.preventDefault();
  24255. if (e.type === 'drop') {
  24256. displayError(editor, 'Dropped file type is not supported');
  24257. }
  24258. }
  24259. }
  24260. };
  24261. const preventFileDropIfUIElement = e => {
  24262. if (isUIElement(editor, e.target)) {
  24263. preventFileDrop(e);
  24264. }
  24265. };
  24266. const setup = () => {
  24267. const pageDom = DOMUtils.DOM;
  24268. const dom = editor.dom;
  24269. const doc = document;
  24270. const editorRoot = editor.inline ? editor.getBody() : editor.getDoc();
  24271. const eventNames = [
  24272. 'drop',
  24273. 'dragover'
  24274. ];
  24275. each$g(eventNames, name => {
  24276. pageDom.bind(doc, name, preventFileDropIfUIElement);
  24277. dom.bind(editorRoot, name, preventFileDrop);
  24278. });
  24279. editor.on('remove', () => {
  24280. each$g(eventNames, name => {
  24281. pageDom.unbind(doc, name, preventFileDropIfUIElement);
  24282. dom.unbind(editorRoot, name, preventFileDrop);
  24283. });
  24284. });
  24285. };
  24286. editor.on('init', () => {
  24287. Delay.setEditorTimeout(editor, setup, 0);
  24288. });
  24289. };
  24290. const init$2 = editor => {
  24291. bindFakeDragEvents(editor);
  24292. if (shouldBlockUnsupportedDrop(editor)) {
  24293. blockUnsupportedFileDrop(editor);
  24294. }
  24295. };
  24296. const setup$4 = editor => {
  24297. const renderFocusCaret = first$1(() => {
  24298. if (!editor.removed && editor.getBody().contains(document.activeElement)) {
  24299. const rng = editor.selection.getRng();
  24300. if (rng.collapsed) {
  24301. const caretRange = renderRangeCaret(editor, rng, false);
  24302. editor.selection.setRng(caretRange);
  24303. }
  24304. }
  24305. }, 0);
  24306. editor.on('focus', () => {
  24307. renderFocusCaret.throttle();
  24308. });
  24309. editor.on('blur', () => {
  24310. renderFocusCaret.cancel();
  24311. });
  24312. };
  24313. const setup$3 = editor => {
  24314. editor.on('init', () => {
  24315. editor.on('focusin', e => {
  24316. const target = e.target;
  24317. if (isMedia$2(target)) {
  24318. const ceRoot = getContentEditableRoot$1(editor.getBody(), target);
  24319. const node = isContentEditableFalse$a(ceRoot) ? ceRoot : target;
  24320. if (editor.selection.getNode() !== node) {
  24321. selectNode(editor, node).each(rng => editor.selection.setRng(rng));
  24322. }
  24323. }
  24324. });
  24325. });
  24326. };
  24327. const isContentEditableFalse = isContentEditableFalse$a;
  24328. const getContentEditableRoot = (editor, node) => getContentEditableRoot$1(editor.getBody(), node);
  24329. const SelectionOverrides = editor => {
  24330. const selection = editor.selection, dom = editor.dom;
  24331. const isBlock = dom.isBlock;
  24332. const rootNode = editor.getBody();
  24333. const fakeCaret = FakeCaret(editor, rootNode, isBlock, () => hasFocus(editor));
  24334. const realSelectionId = 'sel-' + dom.uniqueId();
  24335. const elementSelectionAttr = 'data-mce-selected';
  24336. let selectedElement;
  24337. const isFakeSelectionElement = node => dom.hasClass(node, 'mce-offscreen-selection');
  24338. const isFakeSelectionTargetElement = node => node !== rootNode && (isContentEditableFalse(node) || isMedia$2(node)) && dom.isChildOf(node, rootNode);
  24339. const setRange = range => {
  24340. if (range) {
  24341. selection.setRng(range);
  24342. }
  24343. };
  24344. const showCaret = (direction, node, before, scrollIntoView = true) => {
  24345. const e = editor.dispatch('ShowCaret', {
  24346. target: node,
  24347. direction,
  24348. before
  24349. });
  24350. if (e.isDefaultPrevented()) {
  24351. return null;
  24352. }
  24353. if (scrollIntoView) {
  24354. selection.scrollIntoView(node, direction === -1);
  24355. }
  24356. return fakeCaret.show(before, node);
  24357. };
  24358. const showBlockCaretContainer = blockCaretContainer => {
  24359. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  24360. showCaretContainerBlock(blockCaretContainer);
  24361. selection.scrollIntoView(blockCaretContainer);
  24362. }
  24363. };
  24364. const registerEvents = () => {
  24365. editor.on('click', e => {
  24366. const contentEditableRoot = getContentEditableRoot(editor, e.target);
  24367. if (contentEditableRoot) {
  24368. if (isContentEditableFalse(contentEditableRoot)) {
  24369. e.preventDefault();
  24370. editor.focus();
  24371. }
  24372. }
  24373. });
  24374. editor.on('blur NewBlock', removeElementSelection);
  24375. editor.on('ResizeWindow FullscreenStateChanged', fakeCaret.reposition);
  24376. editor.on('tap', e => {
  24377. const targetElm = e.target;
  24378. const contentEditableRoot = getContentEditableRoot(editor, targetElm);
  24379. if (isContentEditableFalse(contentEditableRoot)) {
  24380. e.preventDefault();
  24381. selectNode(editor, contentEditableRoot).each(setElementSelection);
  24382. } else if (isFakeSelectionTargetElement(targetElm)) {
  24383. selectNode(editor, targetElm).each(setElementSelection);
  24384. }
  24385. }, true);
  24386. editor.on('mousedown', e => {
  24387. const targetElm = e.target;
  24388. if (targetElm !== rootNode && targetElm.nodeName !== 'HTML' && !dom.isChildOf(targetElm, rootNode)) {
  24389. return;
  24390. }
  24391. if (isXYInContentArea(editor, e.clientX, e.clientY) === false) {
  24392. return;
  24393. }
  24394. removeElementSelection();
  24395. hideFakeCaret();
  24396. const closestContentEditable = getContentEditableRoot(editor, targetElm);
  24397. if (isContentEditableFalse(closestContentEditable)) {
  24398. e.preventDefault();
  24399. selectNode(editor, closestContentEditable).each(setElementSelection);
  24400. } else {
  24401. closestFakeCaretCandidate(rootNode, e.clientX, e.clientY).each(caretInfo => {
  24402. e.preventDefault();
  24403. const range = showCaret(1, caretInfo.node, caretInfo.position === FakeCaretPosition.Before, false);
  24404. setRange(range);
  24405. if (isElement$6(closestContentEditable)) {
  24406. closestContentEditable.focus();
  24407. } else {
  24408. editor.getBody().focus();
  24409. }
  24410. });
  24411. }
  24412. });
  24413. editor.on('keypress', e => {
  24414. if (VK.modifierPressed(e)) {
  24415. return;
  24416. }
  24417. if (isContentEditableFalse(selection.getNode())) {
  24418. e.preventDefault();
  24419. }
  24420. });
  24421. editor.on('GetSelectionRange', e => {
  24422. let rng = e.range;
  24423. if (selectedElement) {
  24424. if (!selectedElement.parentNode) {
  24425. selectedElement = null;
  24426. return;
  24427. }
  24428. rng = rng.cloneRange();
  24429. rng.selectNode(selectedElement);
  24430. e.range = rng;
  24431. }
  24432. });
  24433. editor.on('SetSelectionRange', e => {
  24434. e.range = normalizeVoidElementSelection(e.range);
  24435. const rng = setElementSelection(e.range, e.forward);
  24436. if (rng) {
  24437. e.range = rng;
  24438. }
  24439. });
  24440. const isPasteBin = node => node.id === 'mcepastebin';
  24441. editor.on('AfterSetSelectionRange', e => {
  24442. const rng = e.range;
  24443. const parentNode = rng.startContainer.parentNode;
  24444. if (!isRangeInCaretContainer(rng) && !isPasteBin(parentNode)) {
  24445. hideFakeCaret();
  24446. }
  24447. if (!isFakeSelectionElement(parentNode)) {
  24448. removeElementSelection();
  24449. }
  24450. });
  24451. init$2(editor);
  24452. setup$4(editor);
  24453. setup$3(editor);
  24454. };
  24455. const isWithinCaretContainer = node => isCaretContainer$2(node) || startsWithCaretContainer$1(node) || endsWithCaretContainer$1(node);
  24456. const isRangeInCaretContainer = rng => isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
  24457. const normalizeVoidElementSelection = rng => {
  24458. const voidElements = editor.schema.getVoidElements();
  24459. const newRng = dom.createRng();
  24460. const startContainer = rng.startContainer;
  24461. const startOffset = rng.startOffset;
  24462. const endContainer = rng.endContainer;
  24463. const endOffset = rng.endOffset;
  24464. if (has$2(voidElements, startContainer.nodeName.toLowerCase())) {
  24465. if (startOffset === 0) {
  24466. newRng.setStartBefore(startContainer);
  24467. } else {
  24468. newRng.setStartAfter(startContainer);
  24469. }
  24470. } else {
  24471. newRng.setStart(startContainer, startOffset);
  24472. }
  24473. if (has$2(voidElements, endContainer.nodeName.toLowerCase())) {
  24474. if (endOffset === 0) {
  24475. newRng.setEndBefore(endContainer);
  24476. } else {
  24477. newRng.setEndAfter(endContainer);
  24478. }
  24479. } else {
  24480. newRng.setEnd(endContainer, endOffset);
  24481. }
  24482. return newRng;
  24483. };
  24484. const setupOffscreenSelection = (node, targetClone) => {
  24485. const body = SugarElement.fromDom(editor.getBody());
  24486. const doc = editor.getDoc();
  24487. const realSelectionContainer = descendant(body, '#' + realSelectionId).getOrThunk(() => {
  24488. const newContainer = SugarElement.fromHtml('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>', doc);
  24489. set$2(newContainer, 'id', realSelectionId);
  24490. append$1(body, newContainer);
  24491. return newContainer;
  24492. });
  24493. const newRange = dom.createRng();
  24494. empty(realSelectionContainer);
  24495. append(realSelectionContainer, [
  24496. SugarElement.fromText(nbsp, doc),
  24497. SugarElement.fromDom(targetClone),
  24498. SugarElement.fromText(nbsp, doc)
  24499. ]);
  24500. newRange.setStart(realSelectionContainer.dom.firstChild, 1);
  24501. newRange.setEnd(realSelectionContainer.dom.lastChild, 0);
  24502. setAll(realSelectionContainer, { top: dom.getPos(node, editor.getBody()).y + 'px' });
  24503. focus$1(realSelectionContainer);
  24504. const sel = selection.getSel();
  24505. sel.removeAllRanges();
  24506. sel.addRange(newRange);
  24507. return newRange;
  24508. };
  24509. const selectElement = elm => {
  24510. const targetClone = elm.cloneNode(true);
  24511. const e = editor.dispatch('ObjectSelected', {
  24512. target: elm,
  24513. targetClone
  24514. });
  24515. if (e.isDefaultPrevented()) {
  24516. return null;
  24517. }
  24518. const range = setupOffscreenSelection(elm, e.targetClone);
  24519. const nodeElm = SugarElement.fromDom(elm);
  24520. each$g(descendants(SugarElement.fromDom(editor.getBody()), '*[data-mce-selected]'), elm => {
  24521. if (!eq(nodeElm, elm)) {
  24522. remove$a(elm, elementSelectionAttr);
  24523. }
  24524. });
  24525. if (!dom.getAttrib(elm, elementSelectionAttr)) {
  24526. elm.setAttribute(elementSelectionAttr, '1');
  24527. }
  24528. selectedElement = elm;
  24529. hideFakeCaret();
  24530. return range;
  24531. };
  24532. const setElementSelection = (range, forward) => {
  24533. if (!range) {
  24534. return null;
  24535. }
  24536. if (range.collapsed) {
  24537. if (!isRangeInCaretContainer(range)) {
  24538. const dir = forward ? 1 : -1;
  24539. const caretPosition = getNormalizedRangeEndPoint(dir, rootNode, range);
  24540. const beforeNode = caretPosition.getNode(!forward);
  24541. if (isFakeCaretTarget(beforeNode)) {
  24542. return showCaret(dir, beforeNode, forward ? !caretPosition.isAtEnd() : false, false);
  24543. }
  24544. const afterNode = caretPosition.getNode(forward);
  24545. if (isFakeCaretTarget(afterNode)) {
  24546. return showCaret(dir, afterNode, forward ? false : !caretPosition.isAtEnd(), false);
  24547. }
  24548. }
  24549. return null;
  24550. }
  24551. let startContainer = range.startContainer;
  24552. let startOffset = range.startOffset;
  24553. const endOffset = range.endOffset;
  24554. if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse(startContainer.parentNode)) {
  24555. startContainer = startContainer.parentNode;
  24556. startOffset = dom.nodeIndex(startContainer);
  24557. startContainer = startContainer.parentNode;
  24558. }
  24559. if (startContainer.nodeType !== 1) {
  24560. return null;
  24561. }
  24562. if (endOffset === startOffset + 1 && startContainer === range.endContainer) {
  24563. const node = startContainer.childNodes[startOffset];
  24564. if (isFakeSelectionTargetElement(node)) {
  24565. return selectElement(node);
  24566. }
  24567. }
  24568. return null;
  24569. };
  24570. const removeElementSelection = () => {
  24571. if (selectedElement) {
  24572. selectedElement.removeAttribute(elementSelectionAttr);
  24573. }
  24574. descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).each(remove$5);
  24575. selectedElement = null;
  24576. };
  24577. const destroy = () => {
  24578. fakeCaret.destroy();
  24579. selectedElement = null;
  24580. };
  24581. const hideFakeCaret = () => {
  24582. fakeCaret.hide();
  24583. };
  24584. if (!isRtc(editor)) {
  24585. registerEvents();
  24586. }
  24587. return {
  24588. showCaret,
  24589. showBlockCaretContainer,
  24590. hideFakeCaret,
  24591. destroy
  24592. };
  24593. };
  24594. const generatePath = (root, node, offset) => {
  24595. if (isText$8(node) && (offset < 0 || offset > node.data.length)) {
  24596. return [];
  24597. }
  24598. const p = [offset];
  24599. let current = node;
  24600. while (current !== root && current.parentNode) {
  24601. const parent = current.parentNode;
  24602. for (let i = 0; i < parent.childNodes.length; i++) {
  24603. if (parent.childNodes[i] === current) {
  24604. p.push(i);
  24605. break;
  24606. }
  24607. }
  24608. current = parent;
  24609. }
  24610. return current === root ? p.reverse() : [];
  24611. };
  24612. const generatePathRange = (root, startNode, startOffset, endNode, endOffset) => {
  24613. const start = generatePath(root, startNode, startOffset);
  24614. const end = generatePath(root, endNode, endOffset);
  24615. return {
  24616. start,
  24617. end
  24618. };
  24619. };
  24620. const resolvePath = (root, path) => {
  24621. const nodePath = path.slice();
  24622. const offset = nodePath.pop();
  24623. const resolvedNode = foldl(nodePath, (optNode, index) => optNode.bind(node => Optional.from(node.childNodes[index])), Optional.some(root));
  24624. return resolvedNode.bind(node => {
  24625. if (isText$8(node) && (offset < 0 || offset > node.data.length)) {
  24626. return Optional.none();
  24627. } else {
  24628. return Optional.some({
  24629. node,
  24630. offset
  24631. });
  24632. }
  24633. });
  24634. };
  24635. const resolvePathRange = (root, range) => resolvePath(root, range.start).bind(({
  24636. node: startNode,
  24637. offset: startOffset
  24638. }) => resolvePath(root, range.end).map(({
  24639. node: endNode,
  24640. offset: endOffset
  24641. }) => {
  24642. const rng = document.createRange();
  24643. rng.setStart(startNode, startOffset);
  24644. rng.setEnd(endNode, endOffset);
  24645. return rng;
  24646. }));
  24647. const generatePathRangeFromRange = (root, range) => generatePathRange(root, range.startContainer, range.startOffset, range.endContainer, range.endOffset);
  24648. const cleanEmptyNodes = (dom, node, isRoot) => {
  24649. if (node && dom.isEmpty(node) && !isRoot(node)) {
  24650. const parent = node.parentNode;
  24651. dom.remove(node);
  24652. cleanEmptyNodes(dom, parent, isRoot);
  24653. }
  24654. };
  24655. const deleteRng = (dom, rng, isRoot, clean = true) => {
  24656. const startParent = rng.startContainer.parentNode;
  24657. const endParent = rng.endContainer.parentNode;
  24658. rng.deleteContents();
  24659. if (clean && !isRoot(rng.startContainer)) {
  24660. if (isText$8(rng.startContainer) && rng.startContainer.data.length === 0) {
  24661. dom.remove(rng.startContainer);
  24662. }
  24663. if (isText$8(rng.endContainer) && rng.endContainer.data.length === 0) {
  24664. dom.remove(rng.endContainer);
  24665. }
  24666. cleanEmptyNodes(dom, startParent, isRoot);
  24667. if (startParent !== endParent) {
  24668. cleanEmptyNodes(dom, endParent, isRoot);
  24669. }
  24670. }
  24671. };
  24672. const getParentBlock = (editor, rng) => Optional.from(editor.dom.getParent(rng.startContainer, editor.dom.isBlock));
  24673. const stripPattern = (dom, block, pattern) => {
  24674. const firstTextNode = textAfter(block, 0, block);
  24675. firstTextNode.each(spot => {
  24676. const node = spot.container;
  24677. scanRight(node, pattern.start.length, block).each(end => {
  24678. const rng = dom.createRng();
  24679. rng.setStart(node, 0);
  24680. rng.setEnd(end.container, end.offset);
  24681. deleteRng(dom, rng, e => e === block);
  24682. });
  24683. });
  24684. };
  24685. const applyPattern$1 = (editor, match) => {
  24686. const dom = editor.dom;
  24687. const pattern = match.pattern;
  24688. const rng = resolvePathRange(dom.getRoot(), match.range).getOrDie('Unable to resolve path range');
  24689. const isBlockFormatName = (name, formatter) => {
  24690. const formatSet = formatter.get(name);
  24691. return isArray$1(formatSet) && head(formatSet).exists(format => has$2(format, 'block'));
  24692. };
  24693. getParentBlock(editor, rng).each(block => {
  24694. if (pattern.type === 'block-format') {
  24695. if (isBlockFormatName(pattern.format, editor.formatter)) {
  24696. editor.undoManager.transact(() => {
  24697. stripPattern(editor.dom, block, pattern);
  24698. editor.formatter.apply(pattern.format);
  24699. });
  24700. }
  24701. } else if (pattern.type === 'block-command') {
  24702. editor.undoManager.transact(() => {
  24703. stripPattern(editor.dom, block, pattern);
  24704. editor.execCommand(pattern.cmd, false, pattern.value);
  24705. });
  24706. }
  24707. });
  24708. return true;
  24709. };
  24710. const findPattern$1 = (patterns, text) => {
  24711. const nuText = text.replace(nbsp, ' ');
  24712. return find$2(patterns, pattern => text.indexOf(pattern.start) === 0 || nuText.indexOf(pattern.start) === 0);
  24713. };
  24714. const findPatterns$1 = (editor, patterns) => {
  24715. const dom = editor.dom;
  24716. const rng = editor.selection.getRng();
  24717. return getParentBlock(editor, rng).filter(block => {
  24718. const forcedRootBlock = getForcedRootBlock(editor);
  24719. const matchesForcedRootBlock = dom.is(block, forcedRootBlock);
  24720. return block !== null && matchesForcedRootBlock;
  24721. }).bind(block => {
  24722. const blockText = block.textContent;
  24723. const matchedPattern = findPattern$1(patterns, blockText);
  24724. return matchedPattern.map(pattern => {
  24725. if (Tools.trim(blockText).length === pattern.start.length) {
  24726. return [];
  24727. }
  24728. return [{
  24729. pattern,
  24730. range: generatePathRange(dom.getRoot(), block, 0, block, 0)
  24731. }];
  24732. });
  24733. }).getOr([]);
  24734. };
  24735. const applyMatches$1 = (editor, matches) => {
  24736. if (matches.length === 0) {
  24737. return;
  24738. }
  24739. const bookmark = editor.selection.getBookmark();
  24740. each$g(matches, match => applyPattern$1(editor, match));
  24741. editor.selection.moveToBookmark(bookmark);
  24742. };
  24743. const newMarker = (dom, id) => dom.create('span', {
  24744. 'data-mce-type': 'bookmark',
  24745. id
  24746. });
  24747. const rangeFromMarker = (dom, marker) => {
  24748. const rng = dom.createRng();
  24749. rng.setStartAfter(marker.start);
  24750. rng.setEndBefore(marker.end);
  24751. return rng;
  24752. };
  24753. const createMarker = (dom, markerPrefix, pathRange) => {
  24754. const rng = resolvePathRange(dom.getRoot(), pathRange).getOrDie('Unable to resolve path range');
  24755. const startNode = rng.startContainer;
  24756. const endNode = rng.endContainer;
  24757. const textEnd = rng.endOffset === 0 ? endNode : endNode.splitText(rng.endOffset);
  24758. const textStart = rng.startOffset === 0 ? startNode : startNode.splitText(rng.startOffset);
  24759. return {
  24760. prefix: markerPrefix,
  24761. end: textEnd.parentNode.insertBefore(newMarker(dom, markerPrefix + '-end'), textEnd),
  24762. start: textStart.parentNode.insertBefore(newMarker(dom, markerPrefix + '-start'), textStart)
  24763. };
  24764. };
  24765. const removeMarker = (dom, marker, isRoot) => {
  24766. cleanEmptyNodes(dom, dom.get(marker.prefix + '-end'), isRoot);
  24767. cleanEmptyNodes(dom, dom.get(marker.prefix + '-start'), isRoot);
  24768. };
  24769. const isReplacementPattern = pattern => pattern.start.length === 0;
  24770. const matchesPattern = patternContent => (element, offset) => {
  24771. const text = element.data;
  24772. const searchText = text.substring(0, offset);
  24773. const startEndIndex = searchText.lastIndexOf(patternContent.charAt(patternContent.length - 1));
  24774. const startIndex = searchText.lastIndexOf(patternContent);
  24775. if (startIndex !== -1) {
  24776. return startIndex + patternContent.length;
  24777. } else if (startEndIndex !== -1) {
  24778. return startEndIndex + 1;
  24779. } else {
  24780. return -1;
  24781. }
  24782. };
  24783. const findPatternStartFromSpot = (dom, pattern, block, spot) => {
  24784. const startPattern = pattern.start;
  24785. const startSpot = repeatLeft(dom, spot.container, spot.offset, matchesPattern(startPattern), block);
  24786. return startSpot.bind(spot => {
  24787. if (spot.offset >= startPattern.length) {
  24788. const rng = dom.createRng();
  24789. rng.setStart(spot.container, spot.offset - startPattern.length);
  24790. rng.setEnd(spot.container, spot.offset);
  24791. return Optional.some(rng);
  24792. } else {
  24793. const offset = spot.offset - startPattern.length;
  24794. return scanLeft(spot.container, offset, block).map(nextSpot => {
  24795. const rng = dom.createRng();
  24796. rng.setStart(nextSpot.container, nextSpot.offset);
  24797. rng.setEnd(spot.container, spot.offset);
  24798. return rng;
  24799. }).filter(rng => rng.toString() === startPattern).orThunk(() => findPatternStartFromSpot(dom, pattern, block, point(spot.container, 0)));
  24800. }
  24801. });
  24802. };
  24803. const findPatternStart = (dom, pattern, node, offset, block, requireGap = false) => {
  24804. if (pattern.start.length === 0 && !requireGap) {
  24805. const rng = dom.createRng();
  24806. rng.setStart(node, offset);
  24807. rng.setEnd(node, offset);
  24808. return Optional.some(rng);
  24809. }
  24810. return textBefore(node, offset, block).bind(spot => {
  24811. const start = findPatternStartFromSpot(dom, pattern, block, spot);
  24812. return start.bind(startRange => {
  24813. if (requireGap) {
  24814. if (startRange.endContainer === spot.container && startRange.endOffset === spot.offset) {
  24815. return Optional.none();
  24816. } else if (spot.offset === 0 && startRange.endContainer.textContent.length === startRange.endOffset) {
  24817. return Optional.none();
  24818. }
  24819. }
  24820. return Optional.some(startRange);
  24821. });
  24822. });
  24823. };
  24824. const findPattern = (editor, block, details) => {
  24825. const dom = editor.dom;
  24826. const root = dom.getRoot();
  24827. const pattern = details.pattern;
  24828. const endNode = details.position.container;
  24829. const endOffset = details.position.offset;
  24830. return scanLeft(endNode, endOffset - details.pattern.end.length, block).bind(spot => {
  24831. const endPathRng = generatePathRange(root, spot.container, spot.offset, endNode, endOffset);
  24832. if (isReplacementPattern(pattern)) {
  24833. return Optional.some({
  24834. matches: [{
  24835. pattern,
  24836. startRng: endPathRng,
  24837. endRng: endPathRng
  24838. }],
  24839. position: spot
  24840. });
  24841. } else {
  24842. const resultsOpt = findPatternsRec(editor, details.remainingPatterns, spot.container, spot.offset, block);
  24843. const results = resultsOpt.getOr({
  24844. matches: [],
  24845. position: spot
  24846. });
  24847. const pos = results.position;
  24848. const start = findPatternStart(dom, pattern, pos.container, pos.offset, block, resultsOpt.isNone());
  24849. return start.map(startRng => {
  24850. const startPathRng = generatePathRangeFromRange(root, startRng);
  24851. return {
  24852. matches: results.matches.concat([{
  24853. pattern,
  24854. startRng: startPathRng,
  24855. endRng: endPathRng
  24856. }]),
  24857. position: point(startRng.startContainer, startRng.startOffset)
  24858. };
  24859. });
  24860. }
  24861. });
  24862. };
  24863. const findPatternsRec = (editor, patterns, node, offset, block) => {
  24864. const dom = editor.dom;
  24865. return textBefore(node, offset, dom.getRoot()).bind(endSpot => {
  24866. const rng = dom.createRng();
  24867. rng.setStart(block, 0);
  24868. rng.setEnd(node, offset);
  24869. const text = rng.toString();
  24870. for (let i = 0; i < patterns.length; i++) {
  24871. const pattern = patterns[i];
  24872. if (!endsWith(text, pattern.end)) {
  24873. continue;
  24874. }
  24875. const patternsWithoutCurrent = patterns.slice();
  24876. patternsWithoutCurrent.splice(i, 1);
  24877. const result = findPattern(editor, block, {
  24878. pattern,
  24879. remainingPatterns: patternsWithoutCurrent,
  24880. position: endSpot
  24881. });
  24882. if (result.isSome()) {
  24883. return result;
  24884. }
  24885. }
  24886. return Optional.none();
  24887. });
  24888. };
  24889. const applyPattern = (editor, pattern, patternRange) => {
  24890. editor.selection.setRng(patternRange);
  24891. if (pattern.type === 'inline-format') {
  24892. each$g(pattern.format, format => {
  24893. editor.formatter.apply(format);
  24894. });
  24895. } else {
  24896. editor.execCommand(pattern.cmd, false, pattern.value);
  24897. }
  24898. };
  24899. const applyReplacementPattern = (editor, pattern, marker, isRoot) => {
  24900. const markerRange = rangeFromMarker(editor.dom, marker);
  24901. deleteRng(editor.dom, markerRange, isRoot);
  24902. applyPattern(editor, pattern, markerRange);
  24903. };
  24904. const applyPatternWithContent = (editor, pattern, startMarker, endMarker, isRoot) => {
  24905. const dom = editor.dom;
  24906. const markerEndRange = rangeFromMarker(dom, endMarker);
  24907. const markerStartRange = rangeFromMarker(dom, startMarker);
  24908. deleteRng(dom, markerStartRange, isRoot);
  24909. deleteRng(dom, markerEndRange, isRoot);
  24910. const patternMarker = {
  24911. prefix: startMarker.prefix,
  24912. start: startMarker.end,
  24913. end: endMarker.start
  24914. };
  24915. const patternRange = rangeFromMarker(dom, patternMarker);
  24916. applyPattern(editor, pattern, patternRange);
  24917. };
  24918. const addMarkers = (dom, matches) => {
  24919. const markerPrefix = generate$1('mce_textpattern');
  24920. const matchesWithEnds = foldr(matches, (acc, match) => {
  24921. const endMarker = createMarker(dom, markerPrefix + `_end${ acc.length }`, match.endRng);
  24922. return acc.concat([{
  24923. ...match,
  24924. endMarker
  24925. }]);
  24926. }, []);
  24927. return foldr(matchesWithEnds, (acc, match) => {
  24928. const idx = matchesWithEnds.length - acc.length - 1;
  24929. const startMarker = isReplacementPattern(match.pattern) ? match.endMarker : createMarker(dom, markerPrefix + `_start${ idx }`, match.startRng);
  24930. return acc.concat([{
  24931. ...match,
  24932. startMarker
  24933. }]);
  24934. }, []);
  24935. };
  24936. const findPatterns = (editor, patterns, space) => {
  24937. const rng = editor.selection.getRng();
  24938. if (rng.collapsed === false) {
  24939. return [];
  24940. }
  24941. return getParentBlock(editor, rng).bind(block => {
  24942. const offset = Math.max(0, rng.startOffset - (space ? 1 : 0));
  24943. return findPatternsRec(editor, patterns, rng.startContainer, offset, block);
  24944. }).fold(() => [], result => result.matches);
  24945. };
  24946. const applyMatches = (editor, matches) => {
  24947. if (matches.length === 0) {
  24948. return;
  24949. }
  24950. const dom = editor.dom;
  24951. const bookmark = editor.selection.getBookmark();
  24952. const matchesWithMarkers = addMarkers(dom, matches);
  24953. each$g(matchesWithMarkers, match => {
  24954. const block = dom.getParent(match.startMarker.start, dom.isBlock);
  24955. const isRoot = node => node === block;
  24956. if (isReplacementPattern(match.pattern)) {
  24957. applyReplacementPattern(editor, match.pattern, match.endMarker, isRoot);
  24958. } else {
  24959. applyPatternWithContent(editor, match.pattern, match.startMarker, match.endMarker, isRoot);
  24960. }
  24961. removeMarker(dom, match.endMarker, isRoot);
  24962. removeMarker(dom, match.startMarker, isRoot);
  24963. });
  24964. editor.selection.moveToBookmark(bookmark);
  24965. };
  24966. const hasPatterns = patternSet => patternSet.inlinePatterns.length > 0 || patternSet.blockPatterns.length > 0;
  24967. const handleEnter = (editor, patternSet) => {
  24968. if (!editor.selection.isCollapsed() || !hasPatterns(patternSet)) {
  24969. return false;
  24970. }
  24971. const inlineMatches = findPatterns(editor, patternSet.inlinePatterns, false);
  24972. const blockMatches = findPatterns$1(editor, patternSet.blockPatterns);
  24973. if (blockMatches.length > 0 || inlineMatches.length > 0) {
  24974. editor.undoManager.add();
  24975. editor.undoManager.extra(() => {
  24976. editor.execCommand('mceInsertNewLine');
  24977. }, () => {
  24978. editor.insertContent(zeroWidth);
  24979. applyMatches(editor, inlineMatches);
  24980. applyMatches$1(editor, blockMatches);
  24981. const range = editor.selection.getRng();
  24982. const spot = textBefore(range.startContainer, range.startOffset, editor.dom.getRoot());
  24983. editor.execCommand('mceInsertNewLine');
  24984. spot.each(s => {
  24985. const node = s.container;
  24986. if (node.data.charAt(s.offset - 1) === zeroWidth) {
  24987. node.deleteData(s.offset - 1, 1);
  24988. cleanEmptyNodes(editor.dom, node.parentNode, e => e === editor.dom.getRoot());
  24989. }
  24990. });
  24991. });
  24992. return true;
  24993. }
  24994. return false;
  24995. };
  24996. const handleInlineKey = (editor, inlinePatterns) => {
  24997. if (inlinePatterns.length > 0) {
  24998. const inlineMatches = findPatterns(editor, inlinePatterns, true);
  24999. if (inlineMatches.length > 0) {
  25000. editor.undoManager.transact(() => {
  25001. applyMatches(editor, inlineMatches);
  25002. });
  25003. }
  25004. }
  25005. };
  25006. const checkKeyEvent = (codes, event, predicate) => {
  25007. for (let i = 0; i < codes.length; i++) {
  25008. if (predicate(codes[i], event)) {
  25009. return true;
  25010. }
  25011. }
  25012. return false;
  25013. };
  25014. const checkKeyCode = (codes, event) => checkKeyEvent(codes, event, (code, event) => {
  25015. return code === event.keyCode && VK.modifierPressed(event) === false;
  25016. });
  25017. const checkCharCode = (chars, event) => checkKeyEvent(chars, event, (chr, event) => {
  25018. return chr.charCodeAt(0) === event.charCode;
  25019. });
  25020. const setup$2 = editor => {
  25021. const charCodes = [
  25022. ',',
  25023. '.',
  25024. ';',
  25025. ':',
  25026. '!',
  25027. '?'
  25028. ];
  25029. const keyCodes = [32];
  25030. const getPatternSet = () => createPatternSet(getTextPatterns(editor));
  25031. const getInlinePatterns$1 = () => getInlinePatterns(getTextPatterns(editor));
  25032. editor.on('keydown', e => {
  25033. if (e.keyCode === 13 && !VK.modifierPressed(e)) {
  25034. if (handleEnter(editor, getPatternSet())) {
  25035. e.preventDefault();
  25036. }
  25037. }
  25038. }, true);
  25039. editor.on('keyup', e => {
  25040. if (checkKeyCode(keyCodes, e)) {
  25041. handleInlineKey(editor, getInlinePatterns$1());
  25042. }
  25043. });
  25044. editor.on('keypress', e => {
  25045. if (checkCharCode(charCodes, e)) {
  25046. Delay.setEditorTimeout(editor, () => {
  25047. handleInlineKey(editor, getInlinePatterns$1());
  25048. });
  25049. }
  25050. });
  25051. };
  25052. const setup$1 = editor => {
  25053. setup$2(editor);
  25054. };
  25055. const Quirks = editor => {
  25056. const each = Tools.each;
  25057. const BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, parser = editor.parser;
  25058. const browser = Env.browser;
  25059. const isGecko = browser.isFirefox();
  25060. const isWebKit = browser.isChromium() || browser.isSafari();
  25061. const isiOS = Env.deviceType.isiPhone() || Env.deviceType.isiPad();
  25062. const isMac = Env.os.isMacOS() || Env.os.isiOS();
  25063. const setEditorCommandState = (cmd, state) => {
  25064. try {
  25065. editor.getDoc().execCommand(cmd, false, state);
  25066. } catch (ex) {
  25067. }
  25068. };
  25069. const isDefaultPrevented = e => {
  25070. return e.isDefaultPrevented();
  25071. };
  25072. const emptyEditorWhenDeleting = () => {
  25073. const serializeRng = rng => {
  25074. const body = dom.create('body');
  25075. const contents = rng.cloneContents();
  25076. body.appendChild(contents);
  25077. return selection.serializer.serialize(body, { format: 'html' });
  25078. };
  25079. const allContentsSelected = rng => {
  25080. const selection = serializeRng(rng);
  25081. const allRng = dom.createRng();
  25082. allRng.selectNode(editor.getBody());
  25083. const allSelection = serializeRng(allRng);
  25084. return selection === allSelection;
  25085. };
  25086. editor.on('keydown', e => {
  25087. const keyCode = e.keyCode;
  25088. let isCollapsed, body;
  25089. if (!isDefaultPrevented(e) && (keyCode === DELETE || keyCode === BACKSPACE)) {
  25090. isCollapsed = editor.selection.isCollapsed();
  25091. body = editor.getBody();
  25092. if (isCollapsed && !dom.isEmpty(body)) {
  25093. return;
  25094. }
  25095. if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
  25096. return;
  25097. }
  25098. e.preventDefault();
  25099. editor.setContent('');
  25100. if (body.firstChild && dom.isBlock(body.firstChild)) {
  25101. editor.selection.setCursorLocation(body.firstChild, 0);
  25102. } else {
  25103. editor.selection.setCursorLocation(body, 0);
  25104. }
  25105. editor.nodeChanged();
  25106. }
  25107. });
  25108. };
  25109. const selectAll = () => {
  25110. editor.shortcuts.add('meta+a', null, 'SelectAll');
  25111. };
  25112. const documentElementEditingFocus = () => {
  25113. if (!editor.inline) {
  25114. dom.bind(editor.getDoc(), 'mousedown mouseup', e => {
  25115. let rng;
  25116. if (e.target === editor.getDoc().documentElement) {
  25117. rng = selection.getRng();
  25118. editor.getBody().focus();
  25119. if (e.type === 'mousedown') {
  25120. if (isCaretContainer$2(rng.startContainer)) {
  25121. return;
  25122. }
  25123. selection.placeCaretAt(e.clientX, e.clientY);
  25124. } else {
  25125. selection.setRng(rng);
  25126. }
  25127. }
  25128. });
  25129. }
  25130. };
  25131. const removeHrOnBackspace = () => {
  25132. editor.on('keydown', e => {
  25133. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25134. if (!editor.getBody().getElementsByTagName('hr').length) {
  25135. return;
  25136. }
  25137. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25138. const node = selection.getNode();
  25139. const previousSibling = node.previousSibling;
  25140. if (node.nodeName === 'HR') {
  25141. dom.remove(node);
  25142. e.preventDefault();
  25143. return;
  25144. }
  25145. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'hr') {
  25146. dom.remove(previousSibling);
  25147. e.preventDefault();
  25148. }
  25149. }
  25150. }
  25151. });
  25152. };
  25153. const focusBody = () => {
  25154. if (!Range.prototype.getClientRects) {
  25155. editor.on('mousedown', e => {
  25156. if (!isDefaultPrevented(e) && e.target.nodeName === 'HTML') {
  25157. const body = editor.getBody();
  25158. body.blur();
  25159. Delay.setEditorTimeout(editor, () => {
  25160. body.focus();
  25161. });
  25162. }
  25163. });
  25164. }
  25165. };
  25166. const selectControlElements = () => {
  25167. const visualAidsAnchorClass = getVisualAidsAnchorClass(editor);
  25168. editor.on('click', e => {
  25169. const target = e.target;
  25170. if (/^(IMG|HR)$/.test(target.nodeName) && dom.getContentEditableParent(target) !== 'false') {
  25171. e.preventDefault();
  25172. editor.selection.select(target);
  25173. editor.nodeChanged();
  25174. }
  25175. if (target.nodeName === 'A' && dom.hasClass(target, visualAidsAnchorClass) && target.childNodes.length === 0) {
  25176. e.preventDefault();
  25177. selection.select(target);
  25178. }
  25179. });
  25180. };
  25181. const removeStylesWhenDeletingAcrossBlockElements = () => {
  25182. const getAttributeApplyFunction = () => {
  25183. const template = dom.getAttribs(selection.getStart().cloneNode(false));
  25184. return () => {
  25185. const target = selection.getStart();
  25186. if (target !== editor.getBody()) {
  25187. dom.setAttrib(target, 'style', null);
  25188. each(template, attr => {
  25189. target.setAttributeNode(attr.cloneNode(true));
  25190. });
  25191. }
  25192. };
  25193. };
  25194. const isSelectionAcrossElements = () => {
  25195. return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock);
  25196. };
  25197. editor.on('keypress', e => {
  25198. let applyAttributes;
  25199. if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) {
  25200. applyAttributes = getAttributeApplyFunction();
  25201. editor.getDoc().execCommand('delete', false, null);
  25202. applyAttributes();
  25203. e.preventDefault();
  25204. return false;
  25205. }
  25206. });
  25207. dom.bind(editor.getDoc(), 'cut', e => {
  25208. let applyAttributes;
  25209. if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
  25210. applyAttributes = getAttributeApplyFunction();
  25211. Delay.setEditorTimeout(editor, () => {
  25212. applyAttributes();
  25213. });
  25214. }
  25215. });
  25216. };
  25217. const disableBackspaceIntoATable = () => {
  25218. editor.on('keydown', e => {
  25219. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25220. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25221. const previousSibling = selection.getNode().previousSibling;
  25222. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'table') {
  25223. e.preventDefault();
  25224. return false;
  25225. }
  25226. }
  25227. }
  25228. });
  25229. };
  25230. const removeBlockQuoteOnBackSpace = () => {
  25231. editor.on('keydown', e => {
  25232. let rng, parent;
  25233. if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) {
  25234. return;
  25235. }
  25236. rng = selection.getRng();
  25237. const container = rng.startContainer;
  25238. const offset = rng.startOffset;
  25239. const root = dom.getRoot();
  25240. parent = container;
  25241. if (!rng.collapsed || offset !== 0) {
  25242. return;
  25243. }
  25244. while (parent && parent.parentNode && parent.parentNode.firstChild === parent && parent.parentNode !== root) {
  25245. parent = parent.parentNode;
  25246. }
  25247. if (parent.tagName === 'BLOCKQUOTE') {
  25248. editor.formatter.toggle('blockquote', null, parent);
  25249. rng = dom.createRng();
  25250. rng.setStart(container, 0);
  25251. rng.setEnd(container, 0);
  25252. selection.setRng(rng);
  25253. }
  25254. });
  25255. };
  25256. const setGeckoEditingOptions = () => {
  25257. const setOpts = () => {
  25258. setEditorCommandState('StyleWithCSS', false);
  25259. setEditorCommandState('enableInlineTableEditing', false);
  25260. if (!getObjectResizing(editor)) {
  25261. setEditorCommandState('enableObjectResizing', false);
  25262. }
  25263. };
  25264. if (!isReadOnly$1(editor)) {
  25265. editor.on('BeforeExecCommand mousedown', setOpts);
  25266. }
  25267. };
  25268. const addBrAfterLastLinks = () => {
  25269. const fixLinks = () => {
  25270. each(dom.select('a'), node => {
  25271. let parentNode = node.parentNode;
  25272. const root = dom.getRoot();
  25273. if (parentNode.lastChild === node) {
  25274. while (parentNode && !dom.isBlock(parentNode)) {
  25275. if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
  25276. return;
  25277. }
  25278. parentNode = parentNode.parentNode;
  25279. }
  25280. dom.add(parentNode, 'br', { 'data-mce-bogus': 1 });
  25281. }
  25282. });
  25283. };
  25284. editor.on('SetContent ExecCommand', e => {
  25285. if (e.type === 'setcontent' || e.command === 'mceInsertLink') {
  25286. fixLinks();
  25287. }
  25288. });
  25289. };
  25290. const setDefaultBlockType = () => {
  25291. editor.on('init', () => {
  25292. setEditorCommandState('DefaultParagraphSeparator', getForcedRootBlock(editor));
  25293. });
  25294. };
  25295. const normalizeSelection = () => {
  25296. editor.on('keyup focusin mouseup', e => {
  25297. if (!VK.modifierPressed(e)) {
  25298. selection.normalize();
  25299. }
  25300. }, true);
  25301. };
  25302. const showBrokenImageIcon = () => {
  25303. editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}');
  25304. };
  25305. const restoreFocusOnKeyDown = () => {
  25306. if (!editor.inline) {
  25307. editor.on('keydown', () => {
  25308. if (document.activeElement === document.body) {
  25309. editor.getWin().focus();
  25310. }
  25311. });
  25312. }
  25313. };
  25314. const bodyHeight = () => {
  25315. if (!editor.inline) {
  25316. editor.contentStyles.push('body {min-height: 150px}');
  25317. editor.on('click', e => {
  25318. let rng;
  25319. if (e.target.nodeName === 'HTML') {
  25320. rng = editor.selection.getRng();
  25321. editor.getBody().focus();
  25322. editor.selection.setRng(rng);
  25323. editor.selection.normalize();
  25324. editor.nodeChanged();
  25325. }
  25326. });
  25327. }
  25328. };
  25329. const blockCmdArrowNavigation = () => {
  25330. if (isMac) {
  25331. editor.on('keydown', e => {
  25332. if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) {
  25333. e.preventDefault();
  25334. const selection = editor.selection.getSel();
  25335. selection.modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary');
  25336. }
  25337. });
  25338. }
  25339. };
  25340. const tapLinksAndImages = () => {
  25341. editor.on('click', e => {
  25342. let elm = e.target;
  25343. do {
  25344. if (elm.tagName === 'A') {
  25345. e.preventDefault();
  25346. return;
  25347. }
  25348. } while (elm = elm.parentNode);
  25349. });
  25350. editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
  25351. };
  25352. const blockFormSubmitInsideEditor = () => {
  25353. editor.on('init', () => {
  25354. editor.dom.bind(editor.getBody(), 'submit', e => {
  25355. e.preventDefault();
  25356. });
  25357. });
  25358. };
  25359. const removeAppleInterchangeBrs = () => {
  25360. parser.addNodeFilter('br', nodes => {
  25361. let i = nodes.length;
  25362. while (i--) {
  25363. if (nodes[i].attr('class') === 'Apple-interchange-newline') {
  25364. nodes[i].remove();
  25365. }
  25366. }
  25367. });
  25368. };
  25369. const refreshContentEditable = noop;
  25370. const isHidden = () => {
  25371. if (!isGecko || editor.removed) {
  25372. return false;
  25373. }
  25374. const sel = editor.selection.getSel();
  25375. return !sel || !sel.rangeCount || sel.rangeCount === 0;
  25376. };
  25377. const setupRtc = () => {
  25378. if (isWebKit) {
  25379. documentElementEditingFocus();
  25380. selectControlElements();
  25381. blockFormSubmitInsideEditor();
  25382. selectAll();
  25383. if (isiOS) {
  25384. restoreFocusOnKeyDown();
  25385. bodyHeight();
  25386. tapLinksAndImages();
  25387. }
  25388. }
  25389. if (isGecko) {
  25390. focusBody();
  25391. setGeckoEditingOptions();
  25392. showBrokenImageIcon();
  25393. blockCmdArrowNavigation();
  25394. }
  25395. };
  25396. const setup = () => {
  25397. removeBlockQuoteOnBackSpace();
  25398. emptyEditorWhenDeleting();
  25399. if (!Env.windowsPhone) {
  25400. normalizeSelection();
  25401. }
  25402. if (isWebKit) {
  25403. documentElementEditingFocus();
  25404. selectControlElements();
  25405. setDefaultBlockType();
  25406. blockFormSubmitInsideEditor();
  25407. disableBackspaceIntoATable();
  25408. removeAppleInterchangeBrs();
  25409. if (isiOS) {
  25410. restoreFocusOnKeyDown();
  25411. bodyHeight();
  25412. tapLinksAndImages();
  25413. } else {
  25414. selectAll();
  25415. }
  25416. }
  25417. if (isGecko) {
  25418. removeHrOnBackspace();
  25419. focusBody();
  25420. removeStylesWhenDeletingAcrossBlockElements();
  25421. setGeckoEditingOptions();
  25422. addBrAfterLastLinks();
  25423. showBrokenImageIcon();
  25424. blockCmdArrowNavigation();
  25425. disableBackspaceIntoATable();
  25426. }
  25427. };
  25428. if (isRtc(editor)) {
  25429. setupRtc();
  25430. } else {
  25431. setup();
  25432. }
  25433. return {
  25434. refreshContentEditable,
  25435. isHidden
  25436. };
  25437. };
  25438. const DOM$6 = DOMUtils.DOM;
  25439. const appendStyle = (editor, text) => {
  25440. const body = SugarElement.fromDom(editor.getBody());
  25441. const container = getStyleContainer(getRootNode(body));
  25442. const style = SugarElement.fromTag('style');
  25443. set$2(style, 'type', 'text/css');
  25444. append$1(style, SugarElement.fromText(text));
  25445. append$1(container, style);
  25446. editor.on('remove', () => {
  25447. remove$5(style);
  25448. });
  25449. };
  25450. const getRootName = editor => editor.inline ? editor.getElement().nodeName.toLowerCase() : undefined;
  25451. const removeUndefined = obj => filter$5(obj, v => isUndefined(v) === false);
  25452. const mkParserSettings = editor => {
  25453. const getOption = editor.options.get;
  25454. const blobCache = editor.editorUpload.blobCache;
  25455. return removeUndefined({
  25456. allow_conditional_comments: getOption('allow_conditional_comments'),
  25457. allow_html_data_urls: getOption('allow_html_data_urls'),
  25458. allow_svg_data_urls: getOption('allow_svg_data_urls'),
  25459. allow_html_in_named_anchor: getOption('allow_html_in_named_anchor'),
  25460. allow_script_urls: getOption('allow_script_urls'),
  25461. allow_unsafe_link_target: getOption('allow_unsafe_link_target'),
  25462. convert_fonts_to_spans: getOption('convert_fonts_to_spans'),
  25463. fix_list_elements: getOption('fix_list_elements'),
  25464. font_size_legacy_values: getOption('font_size_legacy_values'),
  25465. forced_root_block: getOption('forced_root_block'),
  25466. forced_root_block_attrs: getOption('forced_root_block_attrs'),
  25467. preserve_cdata: getOption('preserve_cdata'),
  25468. remove_trailing_brs: getOption('remove_trailing_brs'),
  25469. inline_styles: getOption('inline_styles'),
  25470. root_name: getRootName(editor),
  25471. validate: true,
  25472. blob_cache: blobCache,
  25473. document: editor.getDoc()
  25474. });
  25475. };
  25476. const mkSchemaSettings = editor => {
  25477. const getOption = editor.options.get;
  25478. return removeUndefined({
  25479. custom_elements: getOption('custom_elements'),
  25480. extended_valid_elements: getOption('extended_valid_elements'),
  25481. invalid_elements: getOption('invalid_elements'),
  25482. invalid_styles: getOption('invalid_styles'),
  25483. schema: getOption('schema'),
  25484. valid_children: getOption('valid_children'),
  25485. valid_classes: getOption('valid_classes'),
  25486. valid_elements: getOption('valid_elements'),
  25487. valid_styles: getOption('valid_styles'),
  25488. verify_html: getOption('verify_html'),
  25489. padd_empty_block_inline_children: getOption('format_empty_lines')
  25490. });
  25491. };
  25492. const mkSerializerSettings = editor => {
  25493. const getOption = editor.options.get;
  25494. return {
  25495. ...mkParserSettings(editor),
  25496. ...mkSchemaSettings(editor),
  25497. ...removeUndefined({
  25498. url_converter: getOption('url_converter'),
  25499. url_converter_scope: getOption('url_converter_scope'),
  25500. element_format: getOption('element_format'),
  25501. entities: getOption('entities'),
  25502. entity_encoding: getOption('entity_encoding'),
  25503. indent: getOption('indent'),
  25504. indent_after: getOption('indent_after'),
  25505. indent_before: getOption('indent_before')
  25506. })
  25507. };
  25508. };
  25509. const createParser = editor => {
  25510. const parser = DomParser(mkParserSettings(editor), editor.schema);
  25511. parser.addAttributeFilter('src,href,style,tabindex', (nodes, name) => {
  25512. let i = nodes.length, node, value;
  25513. const dom = editor.dom;
  25514. const internalName = 'data-mce-' + name;
  25515. while (i--) {
  25516. node = nodes[i];
  25517. value = node.attr(name);
  25518. if (value && !node.attr(internalName)) {
  25519. if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) {
  25520. continue;
  25521. }
  25522. if (name === 'style') {
  25523. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  25524. if (!value.length) {
  25525. value = null;
  25526. }
  25527. node.attr(internalName, value);
  25528. node.attr(name, value);
  25529. } else if (name === 'tabindex') {
  25530. node.attr(internalName, value);
  25531. node.attr(name, null);
  25532. } else {
  25533. node.attr(internalName, editor.convertURL(value, name, node.name));
  25534. }
  25535. }
  25536. }
  25537. });
  25538. parser.addNodeFilter('script', nodes => {
  25539. let i = nodes.length;
  25540. while (i--) {
  25541. const node = nodes[i];
  25542. const type = node.attr('type') || 'no/type';
  25543. if (type.indexOf('mce-') !== 0) {
  25544. node.attr('type', 'mce-' + type);
  25545. }
  25546. }
  25547. });
  25548. if (editor.options.get('preserve_cdata')) {
  25549. parser.addNodeFilter('#cdata', nodes => {
  25550. let i = nodes.length;
  25551. while (i--) {
  25552. const node = nodes[i];
  25553. node.type = 8;
  25554. node.name = '#comment';
  25555. node.value = '[CDATA[' + editor.dom.encode(node.value) + ']]';
  25556. }
  25557. });
  25558. }
  25559. parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', nodes => {
  25560. let i = nodes.length;
  25561. const nonEmptyElements = editor.schema.getNonEmptyElements();
  25562. while (i--) {
  25563. const node = nodes[i];
  25564. if (node.isEmpty(nonEmptyElements) && node.getAll('br').length === 0) {
  25565. node.append(new AstNode('br', 1));
  25566. }
  25567. }
  25568. });
  25569. return parser;
  25570. };
  25571. const autoFocus = editor => {
  25572. const autoFocus = getAutoFocus(editor);
  25573. if (autoFocus) {
  25574. Delay.setEditorTimeout(editor, () => {
  25575. let focusEditor;
  25576. if (autoFocus === true) {
  25577. focusEditor = editor;
  25578. } else {
  25579. focusEditor = editor.editorManager.get(autoFocus);
  25580. }
  25581. if (!focusEditor.destroyed) {
  25582. focusEditor.focus();
  25583. }
  25584. }, 100);
  25585. }
  25586. };
  25587. const moveSelectionToFirstCaretPosition = editor => {
  25588. const root = editor.dom.getRoot();
  25589. if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) {
  25590. firstPositionIn(root).each(pos => {
  25591. const node = pos.getNode();
  25592. const caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  25593. editor.selection.setRng(caretPos.toRange());
  25594. });
  25595. }
  25596. };
  25597. const initEditor = editor => {
  25598. editor.bindPendingEventDelegates();
  25599. editor.initialized = true;
  25600. fireInit(editor);
  25601. editor.focus(true);
  25602. moveSelectionToFirstCaretPosition(editor);
  25603. editor.nodeChanged({ initial: true });
  25604. const initInstanceCallback = getInitInstanceCallback(editor);
  25605. if (isFunction(initInstanceCallback)) {
  25606. initInstanceCallback.call(editor, editor);
  25607. }
  25608. autoFocus(editor);
  25609. };
  25610. const getStyleSheetLoader$1 = editor => editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader;
  25611. const makeStylesheetLoadingPromises = (editor, css, framedFonts) => {
  25612. const promises = [getStyleSheetLoader$1(editor).loadAll(css)];
  25613. if (editor.inline) {
  25614. return promises;
  25615. } else {
  25616. return promises.concat([editor.ui.styleSheetLoader.loadAll(framedFonts)]);
  25617. }
  25618. };
  25619. const loadContentCss = editor => {
  25620. const styleSheetLoader = getStyleSheetLoader$1(editor);
  25621. const fontCss = getFontCss(editor);
  25622. const css = editor.contentCSS;
  25623. const removeCss = () => {
  25624. styleSheetLoader.unloadAll(css);
  25625. if (!editor.inline) {
  25626. editor.ui.styleSheetLoader.unloadAll(fontCss);
  25627. }
  25628. };
  25629. const loaded = () => {
  25630. if (editor.removed) {
  25631. removeCss();
  25632. } else {
  25633. editor.on('remove', removeCss);
  25634. }
  25635. };
  25636. if (editor.contentStyles.length > 0) {
  25637. let contentCssText = '';
  25638. Tools.each(editor.contentStyles, style => {
  25639. contentCssText += style + '\r\n';
  25640. });
  25641. editor.dom.addStyle(contentCssText);
  25642. }
  25643. const allStylesheets = Promise.all(makeStylesheetLoadingPromises(editor, css, fontCss)).then(loaded).catch(loaded);
  25644. const contentStyle = getContentStyle(editor);
  25645. if (contentStyle) {
  25646. appendStyle(editor, contentStyle);
  25647. }
  25648. return allStylesheets;
  25649. };
  25650. const preInit = editor => {
  25651. const doc = editor.getDoc(), body = editor.getBody();
  25652. firePreInit(editor);
  25653. if (!shouldBrowserSpellcheck(editor)) {
  25654. doc.body.spellcheck = false;
  25655. DOM$6.setAttrib(body, 'spellcheck', 'false');
  25656. }
  25657. editor.quirks = Quirks(editor);
  25658. firePostRender(editor);
  25659. const directionality = getDirectionality(editor);
  25660. if (directionality !== undefined) {
  25661. body.dir = directionality;
  25662. }
  25663. const protect = getProtect(editor);
  25664. if (protect) {
  25665. editor.on('BeforeSetContent', e => {
  25666. Tools.each(protect, pattern => {
  25667. e.content = e.content.replace(pattern, str => {
  25668. return '<!--mce:protected ' + escape(str) + '-->';
  25669. });
  25670. });
  25671. });
  25672. }
  25673. editor.on('SetContent', () => {
  25674. editor.addVisual(editor.getBody());
  25675. });
  25676. editor.on('compositionstart compositionend', e => {
  25677. editor.composing = e.type === 'compositionstart';
  25678. });
  25679. };
  25680. const loadInitialContent = editor => {
  25681. if (!isRtc(editor)) {
  25682. editor.load({
  25683. initial: true,
  25684. format: 'html'
  25685. });
  25686. }
  25687. editor.startContent = editor.getContent({ format: 'raw' });
  25688. };
  25689. const initEditorWithInitialContent = editor => {
  25690. if (editor.removed !== true) {
  25691. loadInitialContent(editor);
  25692. initEditor(editor);
  25693. }
  25694. };
  25695. const contentBodyLoaded = editor => {
  25696. const targetElm = editor.getElement();
  25697. let doc = editor.getDoc();
  25698. if (editor.inline) {
  25699. DOM$6.addClass(targetElm, 'mce-content-body');
  25700. editor.contentDocument = doc = document;
  25701. editor.contentWindow = window;
  25702. editor.bodyElement = targetElm;
  25703. editor.contentAreaContainer = targetElm;
  25704. }
  25705. const body = editor.getBody();
  25706. body.disabled = true;
  25707. editor.readonly = isReadOnly$1(editor);
  25708. if (!editor.readonly) {
  25709. if (editor.inline && DOM$6.getStyle(body, 'position', true) === 'static') {
  25710. body.style.position = 'relative';
  25711. }
  25712. body.contentEditable = 'true';
  25713. }
  25714. body.disabled = false;
  25715. editor.editorUpload = EditorUpload(editor);
  25716. editor.schema = Schema(mkSchemaSettings(editor));
  25717. editor.dom = DOMUtils(doc, {
  25718. keep_values: true,
  25719. url_converter: editor.convertURL,
  25720. url_converter_scope: editor,
  25721. update_styles: true,
  25722. root_element: editor.inline ? editor.getBody() : null,
  25723. collect: () => editor.inline,
  25724. schema: editor.schema,
  25725. contentCssCors: shouldUseContentCssCors(editor),
  25726. referrerPolicy: getReferrerPolicy(editor),
  25727. onSetAttrib: e => {
  25728. editor.dispatch('SetAttrib', e);
  25729. }
  25730. });
  25731. editor.parser = createParser(editor);
  25732. editor.serializer = DomSerializer(mkSerializerSettings(editor), editor);
  25733. editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor);
  25734. editor.annotator = Annotator(editor);
  25735. editor.formatter = Formatter(editor);
  25736. editor.undoManager = UndoManager(editor);
  25737. editor._nodeChangeDispatcher = new NodeChange(editor);
  25738. editor._selectionOverrides = SelectionOverrides(editor);
  25739. setup$o(editor);
  25740. setup$6(editor);
  25741. setup$m(editor);
  25742. if (!isRtc(editor)) {
  25743. setup$5(editor);
  25744. setup$1(editor);
  25745. }
  25746. const caret = setup$b(editor);
  25747. setup$p(editor, caret);
  25748. setup$n(editor);
  25749. setup$q(editor);
  25750. setup$7(editor);
  25751. const setupRtcThunk = setup$s(editor);
  25752. preInit(editor);
  25753. setupRtcThunk.fold(() => {
  25754. loadContentCss(editor).then(() => initEditorWithInitialContent(editor));
  25755. }, setupRtc => {
  25756. editor.setProgressState(true);
  25757. loadContentCss(editor).then(() => {
  25758. setupRtc().then(_rtcMode => {
  25759. editor.setProgressState(false);
  25760. initEditorWithInitialContent(editor);
  25761. bindEvents(editor);
  25762. }, err => {
  25763. editor.notificationManager.open({
  25764. type: 'error',
  25765. text: String(err)
  25766. });
  25767. initEditorWithInitialContent(editor);
  25768. bindEvents(editor);
  25769. });
  25770. });
  25771. });
  25772. };
  25773. const initContentBody = (editor, skipWrite) => {
  25774. if (!editor.inline) {
  25775. editor.getElement().style.visibility = editor.orgVisibility;
  25776. }
  25777. if (!skipWrite && !editor.inline) {
  25778. const iframe = editor.iframeElement;
  25779. const binder = bind$1(SugarElement.fromDom(iframe), 'load', () => {
  25780. binder.unbind();
  25781. editor.contentDocument = iframe.contentDocument;
  25782. contentBodyLoaded(editor);
  25783. });
  25784. iframe.srcdoc = editor.iframeHTML;
  25785. } else {
  25786. contentBodyLoaded(editor);
  25787. }
  25788. };
  25789. const DOM$5 = DOMUtils.DOM;
  25790. const createIframeElement = (id, title, customAttrs, tabindex) => {
  25791. const iframe = SugarElement.fromTag('iframe');
  25792. tabindex.each(t => set$2(iframe, 'tabindex', t));
  25793. setAll$1(iframe, customAttrs);
  25794. setAll$1(iframe, {
  25795. id: id + '_ifr',
  25796. frameBorder: '0',
  25797. allowTransparency: 'true',
  25798. title
  25799. });
  25800. add$2(iframe, 'tox-edit-area__iframe');
  25801. return iframe;
  25802. };
  25803. const getIframeHtml = editor => {
  25804. let iframeHTML = getDocType(editor) + '<html><head>';
  25805. if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
  25806. iframeHTML += '<base href="' + editor.documentBaseURI.getURI() + '" />';
  25807. }
  25808. iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
  25809. const bodyId = getBodyId(editor);
  25810. const bodyClass = getBodyClass(editor);
  25811. const translatedAriaText = editor.translate(getIframeAriaText(editor));
  25812. if (getContentSecurityPolicy(editor)) {
  25813. iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + getContentSecurityPolicy(editor) + '" />';
  25814. }
  25815. iframeHTML += '</head>' + `<body id="${ bodyId }" class="mce-content-body ${ bodyClass }" data-id="${ editor.id }" aria-label="${ translatedAriaText }">` + '<br>' + '</body></html>';
  25816. return iframeHTML;
  25817. };
  25818. const createIframe = (editor, boxInfo) => {
  25819. const iframeTitle = editor.translate('Rich Text Area');
  25820. const tabindex = getOpt(SugarElement.fromDom(editor.getElement()), 'tabindex').bind(toInt);
  25821. const ifr = createIframeElement(editor.id, iframeTitle, getIframeAttrs(editor), tabindex).dom;
  25822. ifr.onload = () => {
  25823. ifr.onload = null;
  25824. editor.dispatch('load');
  25825. };
  25826. editor.contentAreaContainer = boxInfo.iframeContainer;
  25827. editor.iframeElement = ifr;
  25828. editor.iframeHTML = getIframeHtml(editor);
  25829. DOM$5.add(boxInfo.iframeContainer, ifr);
  25830. };
  25831. const init$1 = (editor, boxInfo) => {
  25832. createIframe(editor, boxInfo);
  25833. if (boxInfo.editorContainer) {
  25834. DOM$5.get(boxInfo.editorContainer).style.display = editor.orgDisplay;
  25835. editor.hidden = DOM$5.isHidden(boxInfo.editorContainer);
  25836. }
  25837. editor.getElement().style.display = 'none';
  25838. DOM$5.setAttrib(editor.id, 'aria-hidden', 'true');
  25839. initContentBody(editor);
  25840. };
  25841. const DOM$4 = DOMUtils.DOM;
  25842. const initPlugin = (editor, initializedPlugins, plugin) => {
  25843. const Plugin = PluginManager.get(plugin);
  25844. const pluginUrl = PluginManager.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, '');
  25845. plugin = Tools.trim(plugin);
  25846. if (Plugin && Tools.inArray(initializedPlugins, plugin) === -1) {
  25847. if (editor.plugins[plugin]) {
  25848. return;
  25849. }
  25850. try {
  25851. const pluginInstance = Plugin(editor, pluginUrl) || {};
  25852. editor.plugins[plugin] = pluginInstance;
  25853. if (isFunction(pluginInstance.init)) {
  25854. pluginInstance.init(editor, pluginUrl);
  25855. initializedPlugins.push(plugin);
  25856. }
  25857. } catch (e) {
  25858. pluginInitError(editor, plugin, e);
  25859. }
  25860. }
  25861. };
  25862. const trimLegacyPrefix = name => {
  25863. return name.replace(/^\-/, '');
  25864. };
  25865. const initPlugins = editor => {
  25866. const initializedPlugins = [];
  25867. each$g(getPlugins(editor), name => {
  25868. initPlugin(editor, initializedPlugins, trimLegacyPrefix(name));
  25869. });
  25870. };
  25871. const initIcons = editor => {
  25872. const iconPackName = Tools.trim(getIconPackName(editor));
  25873. const currentIcons = editor.ui.registry.getAll().icons;
  25874. const loadIcons = {
  25875. ...IconManager.get('default').icons,
  25876. ...IconManager.get(iconPackName).icons
  25877. };
  25878. each$f(loadIcons, (svgData, icon) => {
  25879. if (!has$2(currentIcons, icon)) {
  25880. editor.ui.registry.addIcon(icon, svgData);
  25881. }
  25882. });
  25883. };
  25884. const initTheme = editor => {
  25885. const theme = getTheme(editor);
  25886. if (isString(theme)) {
  25887. const Theme = ThemeManager.get(theme);
  25888. editor.theme = Theme(editor, ThemeManager.urls[theme]) || {};
  25889. if (isFunction(editor.theme.init)) {
  25890. editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ''));
  25891. }
  25892. } else {
  25893. editor.theme = {};
  25894. }
  25895. };
  25896. const initModel = editor => {
  25897. const model = getModel(editor);
  25898. const Model = ModelManager.get(model);
  25899. editor.model = Model(editor, ModelManager.urls[model]);
  25900. };
  25901. const renderFromLoadedTheme = editor => {
  25902. return editor.theme.renderUI();
  25903. };
  25904. const renderFromThemeFunc = editor => {
  25905. const elm = editor.getElement();
  25906. const theme = getTheme(editor);
  25907. const info = theme(editor, elm);
  25908. if (info.editorContainer.nodeType) {
  25909. info.editorContainer.id = info.editorContainer.id || editor.id + '_parent';
  25910. }
  25911. if (info.iframeContainer && info.iframeContainer.nodeType) {
  25912. info.iframeContainer.id = info.iframeContainer.id || editor.id + '_iframecontainer';
  25913. }
  25914. info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
  25915. return info;
  25916. };
  25917. const createThemeFalseResult = element => {
  25918. return {
  25919. editorContainer: element,
  25920. iframeContainer: element,
  25921. api: {}
  25922. };
  25923. };
  25924. const renderThemeFalseIframe = targetElement => {
  25925. const iframeContainer = DOM$4.create('div');
  25926. DOM$4.insertAfter(iframeContainer, targetElement);
  25927. return createThemeFalseResult(iframeContainer);
  25928. };
  25929. const renderThemeFalse = editor => {
  25930. const targetElement = editor.getElement();
  25931. return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
  25932. };
  25933. const renderThemeUi = editor => {
  25934. const elm = editor.getElement();
  25935. editor.orgDisplay = elm.style.display;
  25936. if (isString(getTheme(editor))) {
  25937. return renderFromLoadedTheme(editor);
  25938. } else if (isFunction(getTheme(editor))) {
  25939. return renderFromThemeFunc(editor);
  25940. } else {
  25941. return renderThemeFalse(editor);
  25942. }
  25943. };
  25944. const augmentEditorUiApi = (editor, api) => {
  25945. const uiApiFacade = {
  25946. show: Optional.from(api.show).getOr(noop),
  25947. hide: Optional.from(api.hide).getOr(noop),
  25948. isEnabled: Optional.from(api.isEnabled).getOr(always),
  25949. setEnabled: state => {
  25950. if (!editor.mode.isReadOnly()) {
  25951. Optional.from(api.setEnabled).each(f => f(state));
  25952. }
  25953. }
  25954. };
  25955. editor.ui = {
  25956. ...editor.ui,
  25957. ...uiApiFacade
  25958. };
  25959. };
  25960. const init = editor => {
  25961. editor.dispatch('ScriptsLoaded');
  25962. initIcons(editor);
  25963. initTheme(editor);
  25964. initModel(editor);
  25965. initPlugins(editor);
  25966. const renderInfo = renderThemeUi(editor);
  25967. augmentEditorUiApi(editor, Optional.from(renderInfo.api).getOr({}));
  25968. const boxInfo = {
  25969. editorContainer: renderInfo.editorContainer,
  25970. iframeContainer: renderInfo.iframeContainer
  25971. };
  25972. editor.editorContainer = boxInfo.editorContainer ? boxInfo.editorContainer : null;
  25973. appendContentCssFromSettings(editor);
  25974. if (editor.inline) {
  25975. return initContentBody(editor);
  25976. } else {
  25977. return init$1(editor, boxInfo);
  25978. }
  25979. };
  25980. const DOM$3 = DOMUtils.DOM;
  25981. const hasSkipLoadPrefix = name => name.charAt(0) === '-';
  25982. const loadLanguage = (scriptLoader, editor) => {
  25983. const languageCode = getLanguageCode(editor);
  25984. const languageUrl = getLanguageUrl(editor);
  25985. if (I18n.hasCode(languageCode) === false && languageCode !== 'en') {
  25986. const url = isNotEmpty(languageUrl) ? languageUrl : `${ editor.editorManager.baseURL }/langs/${ languageCode }.js`;
  25987. scriptLoader.add(url).catch(() => {
  25988. languageLoadError(editor, url, languageCode);
  25989. });
  25990. }
  25991. };
  25992. const loadTheme = (editor, suffix) => {
  25993. const theme = getTheme(editor);
  25994. if (isString(theme) && !hasSkipLoadPrefix(theme) && !has$2(ThemeManager.urls, theme)) {
  25995. const themeUrl = getThemeUrl(editor);
  25996. const url = themeUrl ? editor.documentBaseURI.toAbsolute(themeUrl) : `themes/${ theme }/theme${ suffix }.js`;
  25997. ThemeManager.load(theme, url).catch(() => {
  25998. themeLoadError(editor, url, theme);
  25999. });
  26000. }
  26001. };
  26002. const loadModel = (editor, suffix) => {
  26003. const model = getModel(editor);
  26004. if (model !== 'plugin' && !has$2(ModelManager.urls, model)) {
  26005. const modelUrl = getModelUrl(editor);
  26006. const url = isString(modelUrl) ? editor.documentBaseURI.toAbsolute(modelUrl) : `models/${ model }/model${ suffix }.js`;
  26007. ModelManager.load(model, url).catch(() => {
  26008. modelLoadError(editor, url, model);
  26009. });
  26010. }
  26011. };
  26012. const getIconsUrlMetaFromUrl = editor => Optional.from(getIconsUrl(editor)).filter(isNotEmpty).map(url => ({
  26013. url,
  26014. name: Optional.none()
  26015. }));
  26016. const getIconsUrlMetaFromName = (editor, name, suffix) => Optional.from(name).filter(name => isNotEmpty(name) && !IconManager.has(name)).map(name => ({
  26017. url: `${ editor.editorManager.baseURL }/icons/${ name }/icons${ suffix }.js`,
  26018. name: Optional.some(name)
  26019. }));
  26020. const loadIcons = (scriptLoader, editor, suffix) => {
  26021. const defaultIconsUrl = getIconsUrlMetaFromName(editor, 'default', suffix);
  26022. const customIconsUrl = getIconsUrlMetaFromUrl(editor).orThunk(() => getIconsUrlMetaFromName(editor, getIconPackName(editor), ''));
  26023. each$g(cat([
  26024. defaultIconsUrl,
  26025. customIconsUrl
  26026. ]), urlMeta => {
  26027. scriptLoader.add(urlMeta.url).catch(() => {
  26028. iconsLoadError(editor, urlMeta.url, urlMeta.name.getOrUndefined());
  26029. });
  26030. });
  26031. };
  26032. const loadPlugins = (editor, suffix) => {
  26033. const loadPlugin = (name, url) => {
  26034. PluginManager.load(name, url).catch(() => {
  26035. pluginLoadError(editor, url, name);
  26036. });
  26037. };
  26038. each$f(getExternalPlugins$1(editor), (url, name) => {
  26039. loadPlugin(name, url);
  26040. editor.options.set('plugins', getPlugins(editor).concat(name));
  26041. });
  26042. each$g(getPlugins(editor), plugin => {
  26043. plugin = Tools.trim(plugin);
  26044. if (plugin && !PluginManager.urls[plugin] && !hasSkipLoadPrefix(plugin)) {
  26045. loadPlugin(plugin, `plugins/${ plugin }/plugin${ suffix }.js`);
  26046. }
  26047. });
  26048. };
  26049. const isThemeLoaded = editor => {
  26050. const theme = getTheme(editor);
  26051. return !isString(theme) || isNonNullable(ThemeManager.get(theme));
  26052. };
  26053. const isModelLoaded = editor => {
  26054. const model = getModel(editor);
  26055. return isNonNullable(ModelManager.get(model));
  26056. };
  26057. const loadScripts = (editor, suffix) => {
  26058. const scriptLoader = ScriptLoader.ScriptLoader;
  26059. const initEditor = () => {
  26060. if (!editor.removed && isThemeLoaded(editor) && isModelLoaded(editor)) {
  26061. init(editor);
  26062. }
  26063. };
  26064. loadTheme(editor, suffix);
  26065. loadModel(editor, suffix);
  26066. loadLanguage(scriptLoader, editor);
  26067. loadIcons(scriptLoader, editor, suffix);
  26068. loadPlugins(editor, suffix);
  26069. scriptLoader.loadQueue().then(initEditor, initEditor);
  26070. };
  26071. const getStyleSheetLoader = (element, editor) => instance.forElement(element, {
  26072. contentCssCors: hasContentCssCors(editor),
  26073. referrerPolicy: getReferrerPolicy(editor)
  26074. });
  26075. const render = editor => {
  26076. const id = editor.id;
  26077. I18n.setCode(getLanguageCode(editor));
  26078. const readyHandler = () => {
  26079. DOM$3.unbind(window, 'ready', readyHandler);
  26080. editor.render();
  26081. };
  26082. if (!EventUtils.Event.domLoaded) {
  26083. DOM$3.bind(window, 'ready', readyHandler);
  26084. return;
  26085. }
  26086. if (!editor.getElement()) {
  26087. return;
  26088. }
  26089. const element = SugarElement.fromDom(editor.getElement());
  26090. const snapshot = clone$4(element);
  26091. editor.on('remove', () => {
  26092. eachr(element.dom.attributes, attr => remove$a(element, attr.name));
  26093. setAll$1(element, snapshot);
  26094. });
  26095. editor.ui.styleSheetLoader = getStyleSheetLoader(element, editor);
  26096. if (!isInline(editor)) {
  26097. editor.orgVisibility = editor.getElement().style.visibility;
  26098. editor.getElement().style.visibility = 'hidden';
  26099. } else {
  26100. editor.inline = true;
  26101. }
  26102. const form = editor.getElement().form || DOM$3.getParent(id, 'form');
  26103. if (form) {
  26104. editor.formElement = form;
  26105. if (hasHiddenInput(editor) && !isTextareaOrInput(editor.getElement())) {
  26106. DOM$3.insertAfter(DOM$3.create('input', {
  26107. type: 'hidden',
  26108. name: id
  26109. }), id);
  26110. editor.hasHiddenInput = true;
  26111. }
  26112. editor.formEventDelegate = e => {
  26113. editor.dispatch(e.type, e);
  26114. };
  26115. DOM$3.bind(form, 'submit reset', editor.formEventDelegate);
  26116. editor.on('reset', () => {
  26117. editor.resetContent();
  26118. });
  26119. if (shouldPatchSubmit(editor) && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
  26120. form._mceOldSubmit = form.submit;
  26121. form.submit = () => {
  26122. editor.editorManager.triggerSave();
  26123. editor.setDirty(false);
  26124. return form._mceOldSubmit(form);
  26125. };
  26126. }
  26127. }
  26128. editor.windowManager = WindowManager(editor);
  26129. editor.notificationManager = NotificationManager(editor);
  26130. if (isEncodingXml(editor)) {
  26131. editor.on('GetContent', e => {
  26132. if (e.save) {
  26133. e.content = DOM$3.encode(e.content);
  26134. }
  26135. });
  26136. }
  26137. if (shouldAddFormSubmitTrigger(editor)) {
  26138. editor.on('submit', () => {
  26139. if (editor.initialized) {
  26140. editor.save();
  26141. }
  26142. });
  26143. }
  26144. if (shouldAddUnloadTrigger(editor)) {
  26145. editor._beforeUnload = () => {
  26146. if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
  26147. editor.save({
  26148. format: 'raw',
  26149. no_events: true,
  26150. set_dirty: false
  26151. });
  26152. }
  26153. };
  26154. editor.editorManager.on('BeforeUnload', editor._beforeUnload);
  26155. }
  26156. editor.editorManager.add(editor);
  26157. loadScripts(editor, editor.suffix);
  26158. };
  26159. const sectionResult = (sections, settings) => ({
  26160. sections: constant(sections),
  26161. options: constant(settings)
  26162. });
  26163. const deviceDetection = detect$2().deviceType;
  26164. const isPhone = deviceDetection.isPhone();
  26165. const isTablet = deviceDetection.isTablet();
  26166. const normalizePlugins = plugins => {
  26167. if (isNullable(plugins)) {
  26168. return [];
  26169. } else {
  26170. const pluginNames = isArray$1(plugins) ? plugins : plugins.split(/[ ,]/);
  26171. const trimmedPlugins = map$3(pluginNames, trim$3);
  26172. return filter$6(trimmedPlugins, isNotEmpty);
  26173. }
  26174. };
  26175. const extractSections = (keys, options) => {
  26176. const result = bifilter(options, (value, key) => {
  26177. return contains$2(keys, key);
  26178. });
  26179. return sectionResult(result.t, result.f);
  26180. };
  26181. const getSection = (sectionResult, name, defaults = {}) => {
  26182. const sections = sectionResult.sections();
  26183. const sectionOptions = get$a(sections, name).getOr({});
  26184. return Tools.extend({}, defaults, sectionOptions);
  26185. };
  26186. const hasSection = (sectionResult, name) => {
  26187. return has$2(sectionResult.sections(), name);
  26188. };
  26189. const getSectionConfig = (sectionResult, name) => {
  26190. return hasSection(sectionResult, name) ? sectionResult.sections()[name] : {};
  26191. };
  26192. const getMobileOverrideOptions = (mobileOptions, isPhone) => {
  26193. const defaultMobileOptions = {
  26194. table_grid: false,
  26195. object_resizing: false,
  26196. resize: false,
  26197. toolbar_mode: get$a(mobileOptions, 'toolbar_mode').getOr('scrolling'),
  26198. toolbar_sticky: false
  26199. };
  26200. const defaultPhoneOptions = { menubar: false };
  26201. return {
  26202. ...defaultMobileOptions,
  26203. ...isPhone ? defaultPhoneOptions : {}
  26204. };
  26205. };
  26206. const getExternalPlugins = (overrideOptions, options) => {
  26207. var _a;
  26208. const userDefinedExternalPlugins = (_a = options.external_plugins) !== null && _a !== void 0 ? _a : {};
  26209. if (overrideOptions && overrideOptions.external_plugins) {
  26210. return Tools.extend({}, overrideOptions.external_plugins, userDefinedExternalPlugins);
  26211. } else {
  26212. return userDefinedExternalPlugins;
  26213. }
  26214. };
  26215. const combinePlugins = (forcedPlugins, plugins) => {
  26216. return [].concat(normalizePlugins(forcedPlugins)).concat(normalizePlugins(plugins));
  26217. };
  26218. const getPlatformPlugins = (isMobileDevice, sectionResult, desktopPlugins, mobilePlugins) => {
  26219. if (isMobileDevice && hasSection(sectionResult, 'mobile')) {
  26220. return mobilePlugins;
  26221. } else {
  26222. return desktopPlugins;
  26223. }
  26224. };
  26225. const processPlugins = (isMobileDevice, sectionResult, defaultOverrideOptions, options) => {
  26226. const forcedPlugins = normalizePlugins(defaultOverrideOptions.forced_plugins);
  26227. const desktopPlugins = normalizePlugins(options.plugins);
  26228. const mobileConfig = getSectionConfig(sectionResult, 'mobile');
  26229. const mobilePlugins = mobileConfig.plugins ? normalizePlugins(mobileConfig.plugins) : desktopPlugins;
  26230. const platformPlugins = getPlatformPlugins(isMobileDevice, sectionResult, desktopPlugins, mobilePlugins);
  26231. const combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
  26232. return Tools.extend(options, {
  26233. forced_plugins: forcedPlugins,
  26234. plugins: combinedPlugins
  26235. });
  26236. };
  26237. const isOnMobile = (isMobileDevice, sectionResult) => {
  26238. return isMobileDevice && hasSection(sectionResult, 'mobile');
  26239. };
  26240. const combineOptions = (isMobileDevice, isPhone, defaultOptions, defaultOverrideOptions, options) => {
  26241. var _a;
  26242. const deviceOverrideOptions = isMobileDevice ? { mobile: getMobileOverrideOptions((_a = options.mobile) !== null && _a !== void 0 ? _a : {}, isPhone) } : {};
  26243. const sectionResult = extractSections(['mobile'], deepMerge(deviceOverrideOptions, options));
  26244. const extendedOptions = Tools.extend(defaultOptions, defaultOverrideOptions, sectionResult.options(), isOnMobile(isMobileDevice, sectionResult) ? getSection(sectionResult, 'mobile') : {}, { external_plugins: getExternalPlugins(defaultOverrideOptions, sectionResult.options()) });
  26245. return processPlugins(isMobileDevice, sectionResult, defaultOverrideOptions, extendedOptions);
  26246. };
  26247. const normalizeOptions = (defaultOverrideOptions, options) => combineOptions(isPhone || isTablet, isPhone, options, defaultOverrideOptions, options);
  26248. const addVisual = (editor, elm) => addVisual$1(editor, elm);
  26249. const registerExecCommands$3 = editor => {
  26250. const toggleFormat = (name, value) => {
  26251. editor.formatter.toggle(name, value);
  26252. editor.nodeChanged();
  26253. };
  26254. const toggleAlign = align => () => {
  26255. each$g('left,center,right,justify'.split(','), name => {
  26256. if (align !== name) {
  26257. editor.formatter.remove('align' + name);
  26258. }
  26259. });
  26260. if (align !== 'none') {
  26261. toggleFormat('align' + align);
  26262. }
  26263. };
  26264. editor.editorCommands.addCommands({
  26265. JustifyLeft: toggleAlign('left'),
  26266. JustifyCenter: toggleAlign('center'),
  26267. JustifyRight: toggleAlign('right'),
  26268. JustifyFull: toggleAlign('justify'),
  26269. JustifyNone: toggleAlign('none')
  26270. });
  26271. };
  26272. const registerQueryStateCommands$1 = editor => {
  26273. const alignStates = name => () => {
  26274. const selection = editor.selection;
  26275. const nodes = selection.isCollapsed() ? [editor.dom.getParent(selection.getNode(), editor.dom.isBlock)] : selection.getSelectedBlocks();
  26276. return exists(nodes, node => isNonNullable(editor.formatter.matchNode(node, name)));
  26277. };
  26278. editor.editorCommands.addCommands({
  26279. JustifyLeft: alignStates('alignleft'),
  26280. JustifyCenter: alignStates('aligncenter'),
  26281. JustifyRight: alignStates('alignright'),
  26282. JustifyFull: alignStates('alignjustify')
  26283. }, 'state');
  26284. };
  26285. const registerCommands$a = editor => {
  26286. registerExecCommands$3(editor);
  26287. registerQueryStateCommands$1(editor);
  26288. };
  26289. const registerCommands$9 = editor => {
  26290. editor.editorCommands.addCommands({
  26291. 'Cut,Copy,Paste': command => {
  26292. const doc = editor.getDoc();
  26293. let failed;
  26294. try {
  26295. doc.execCommand(command);
  26296. } catch (ex) {
  26297. failed = true;
  26298. }
  26299. if (command === 'paste' && !doc.queryCommandEnabled(command)) {
  26300. failed = true;
  26301. }
  26302. if (failed || !doc.queryCommandSupported(command)) {
  26303. let msg = editor.translate(`Your browser doesn't support direct access to the clipboard. ` + 'Please use the Ctrl+X/C/V keyboard shortcuts instead.');
  26304. if (Env.os.isMacOS() || Env.os.isiOS()) {
  26305. msg = msg.replace(/Ctrl\+/g, '\u2318+');
  26306. }
  26307. editor.notificationManager.open({
  26308. text: msg,
  26309. type: 'error'
  26310. });
  26311. }
  26312. }
  26313. });
  26314. };
  26315. const trimOrPadLeftRight = (dom, rng, html) => {
  26316. const root = SugarElement.fromDom(dom.getRoot());
  26317. if (needsToBeNbspLeft(root, CaretPosition.fromRangeStart(rng))) {
  26318. html = html.replace(/^ /, '&nbsp;');
  26319. } else {
  26320. html = html.replace(/^&nbsp;/, ' ');
  26321. }
  26322. if (needsToBeNbspRight(root, CaretPosition.fromRangeEnd(rng))) {
  26323. html = html.replace(/(&nbsp;| )(<br( \/)>)?$/, '&nbsp;');
  26324. } else {
  26325. html = html.replace(/&nbsp;(<br( \/)?>)?$/, ' ');
  26326. }
  26327. return html;
  26328. };
  26329. const processValue$1 = value => {
  26330. if (typeof value !== 'string') {
  26331. const details = Tools.extend({
  26332. paste: value.paste,
  26333. data: { paste: value.paste }
  26334. }, value);
  26335. return {
  26336. content: value.content,
  26337. details
  26338. };
  26339. }
  26340. return {
  26341. content: value,
  26342. details: {}
  26343. };
  26344. };
  26345. const trimOrPad = (editor, value) => {
  26346. const selection = editor.selection;
  26347. const dom = editor.dom;
  26348. if (/^ | $/.test(value)) {
  26349. return trimOrPadLeftRight(dom, selection.getRng(), value);
  26350. } else {
  26351. return value;
  26352. }
  26353. };
  26354. const insertAtCaret = (editor, value) => {
  26355. const {content, details} = processValue$1(value);
  26356. preProcessSetContent(editor, {
  26357. content: trimOrPad(editor, content),
  26358. format: 'html',
  26359. set: false,
  26360. selection: true,
  26361. paste: details.paste
  26362. }).each(args => {
  26363. const insertedContent = insertContent$1(editor, args.content, details);
  26364. postProcessSetContent(editor, insertedContent, args);
  26365. editor.addVisual();
  26366. });
  26367. };
  26368. const registerCommands$8 = editor => {
  26369. editor.editorCommands.addCommands({
  26370. mceCleanup: () => {
  26371. const bm = editor.selection.getBookmark();
  26372. editor.setContent(editor.getContent());
  26373. editor.selection.moveToBookmark(bm);
  26374. },
  26375. insertImage: (_command, _ui, value) => {
  26376. insertAtCaret(editor, editor.dom.createHTML('img', { src: value }));
  26377. },
  26378. insertHorizontalRule: () => {
  26379. editor.execCommand('mceInsertContent', false, '<hr>');
  26380. },
  26381. insertText: (_command, _ui, value) => {
  26382. insertAtCaret(editor, editor.dom.encode(value));
  26383. },
  26384. insertHTML: (_command, _ui, value) => {
  26385. insertAtCaret(editor, value);
  26386. },
  26387. mceInsertContent: (_command, _ui, value) => {
  26388. insertAtCaret(editor, value);
  26389. },
  26390. mceSetContent: (_command, _ui, value) => {
  26391. editor.setContent(value);
  26392. },
  26393. mceReplaceContent: (_command, _ui, value) => {
  26394. editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, editor.selection.getContent({ format: 'text' })));
  26395. },
  26396. mceNewDocument: () => {
  26397. editor.setContent('');
  26398. }
  26399. });
  26400. };
  26401. const legacyPropNames = {
  26402. 'font-size': 'size',
  26403. 'font-family': 'face'
  26404. };
  26405. const getSpecifiedFontProp = (propName, rootElm, elm) => {
  26406. const getProperty = elm => getRaw$1(elm, propName).orThunk(() => {
  26407. if (name(elm) === 'font') {
  26408. return get$a(legacyPropNames, propName).bind(legacyPropName => getOpt(elm, legacyPropName));
  26409. } else {
  26410. return Optional.none();
  26411. }
  26412. });
  26413. const isRoot = elm => eq(SugarElement.fromDom(rootElm), elm);
  26414. return closest$2(SugarElement.fromDom(elm), elm => getProperty(elm), isRoot);
  26415. };
  26416. const normalizeFontFamily = fontFamily => fontFamily.replace(/[\'\"\\]/g, '').replace(/,\s+/g, ',');
  26417. const getComputedFontProp = (propName, elm) => Optional.from(DOMUtils.DOM.getStyle(elm, propName, true));
  26418. const getFontProp = propName => (rootElm, elm) => Optional.from(elm).map(SugarElement.fromDom).filter(isElement$7).bind(element => getSpecifiedFontProp(propName, rootElm, element.dom).or(getComputedFontProp(propName, element.dom))).getOr('');
  26419. const getFontSize = getFontProp('font-size');
  26420. const getFontFamily = compose(normalizeFontFamily, getFontProp('font-family'));
  26421. const findFirstCaretElement = editor => firstPositionIn(editor.getBody()).map(caret => {
  26422. const container = caret.container();
  26423. return isText$8(container) ? container.parentNode : container;
  26424. });
  26425. const getCaretElement = editor => Optional.from(editor.selection.getRng()).bind(rng => {
  26426. const root = editor.getBody();
  26427. const atStartOfNode = rng.startContainer === root && rng.startOffset === 0;
  26428. return atStartOfNode ? Optional.none() : Optional.from(editor.selection.getStart(true));
  26429. });
  26430. const bindRange = (editor, binder) => getCaretElement(editor).orThunk(curry(findFirstCaretElement, editor)).map(SugarElement.fromDom).filter(isElement$7).bind(binder);
  26431. const mapRange = (editor, mapper) => bindRange(editor, compose1(Optional.some, mapper));
  26432. const fromFontSizeNumber = (editor, value) => {
  26433. if (/^[0-9.]+$/.test(value)) {
  26434. const fontSizeNumber = parseInt(value, 10);
  26435. if (fontSizeNumber >= 1 && fontSizeNumber <= 7) {
  26436. const fontSizes = getFontStyleValues(editor);
  26437. const fontClasses = getFontSizeClasses(editor);
  26438. if (fontClasses) {
  26439. return fontClasses[fontSizeNumber - 1] || value;
  26440. } else {
  26441. return fontSizes[fontSizeNumber - 1] || value;
  26442. }
  26443. } else {
  26444. return value;
  26445. }
  26446. } else {
  26447. return value;
  26448. }
  26449. };
  26450. const normalizeFontNames = font => {
  26451. const fonts = font.split(/\s*,\s*/);
  26452. return map$3(fonts, font => {
  26453. if (font.indexOf(' ') !== -1 && !(startsWith(font, '"') || startsWith(font, `'`))) {
  26454. return `'${ font }'`;
  26455. } else {
  26456. return font;
  26457. }
  26458. }).join(',');
  26459. };
  26460. const fontNameAction = (editor, value) => {
  26461. const font = fromFontSizeNumber(editor, value);
  26462. editor.formatter.toggle('fontname', { value: normalizeFontNames(font) });
  26463. editor.nodeChanged();
  26464. };
  26465. const fontNameQuery = editor => mapRange(editor, elm => getFontFamily(editor.getBody(), elm.dom)).getOr('');
  26466. const fontSizeAction = (editor, value) => {
  26467. editor.formatter.toggle('fontsize', { value: fromFontSizeNumber(editor, value) });
  26468. editor.nodeChanged();
  26469. };
  26470. const fontSizeQuery = editor => mapRange(editor, elm => getFontSize(editor.getBody(), elm.dom)).getOr('');
  26471. const lineHeightQuery = editor => mapRange(editor, elm => {
  26472. const root = SugarElement.fromDom(editor.getBody());
  26473. const specifiedStyle = closest$2(elm, elm => getRaw$1(elm, 'line-height'), curry(eq, root));
  26474. const computedStyle = () => {
  26475. const lineHeight = parseFloat(get$7(elm, 'line-height'));
  26476. const fontSize = parseFloat(get$7(elm, 'font-size'));
  26477. return String(lineHeight / fontSize);
  26478. };
  26479. return specifiedStyle.getOrThunk(computedStyle);
  26480. }).getOr('');
  26481. const lineHeightAction = (editor, lineHeight) => {
  26482. editor.formatter.toggle('lineheight', { value: String(lineHeight) });
  26483. editor.nodeChanged();
  26484. };
  26485. const registerExecCommands$2 = editor => {
  26486. const toggleFormat = (name, value) => {
  26487. editor.formatter.toggle(name, value);
  26488. editor.nodeChanged();
  26489. };
  26490. editor.editorCommands.addCommands({
  26491. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': command => {
  26492. toggleFormat(command);
  26493. },
  26494. 'ForeColor,HiliteColor': (command, _ui, value) => {
  26495. toggleFormat(command, { value });
  26496. },
  26497. 'BackColor': (_command, _ui, value) => {
  26498. toggleFormat('hilitecolor', { value });
  26499. },
  26500. 'FontName': (_command, _ui, value) => {
  26501. fontNameAction(editor, value);
  26502. },
  26503. 'FontSize': (_command, _ui, value) => {
  26504. fontSizeAction(editor, value);
  26505. },
  26506. 'LineHeight': (_command, _ui, value) => {
  26507. lineHeightAction(editor, value);
  26508. },
  26509. 'Lang': (command, _ui, lang) => {
  26510. toggleFormat(command, {
  26511. value: lang.code,
  26512. customValue: lang.customCode
  26513. });
  26514. },
  26515. 'RemoveFormat': command => {
  26516. editor.formatter.remove(command);
  26517. },
  26518. 'mceBlockQuote': () => {
  26519. toggleFormat('blockquote');
  26520. },
  26521. 'FormatBlock': (_command, _ui, value) => {
  26522. toggleFormat(isString(value) ? value : 'p');
  26523. },
  26524. 'mceToggleFormat': (_command, _ui, value) => {
  26525. toggleFormat(value);
  26526. }
  26527. });
  26528. };
  26529. const registerQueryValueCommands = editor => {
  26530. const isFormatMatch = name => editor.formatter.match(name);
  26531. editor.editorCommands.addCommands({
  26532. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': command => isFormatMatch(command),
  26533. 'mceBlockQuote': () => isFormatMatch('blockquote')
  26534. }, 'state');
  26535. editor.editorCommands.addQueryValueHandler('FontName', () => fontNameQuery(editor));
  26536. editor.editorCommands.addQueryValueHandler('FontSize', () => fontSizeQuery(editor));
  26537. editor.editorCommands.addQueryValueHandler('LineHeight', () => lineHeightQuery(editor));
  26538. };
  26539. const registerCommands$7 = editor => {
  26540. registerExecCommands$2(editor);
  26541. registerQueryValueCommands(editor);
  26542. };
  26543. const registerCommands$6 = editor => {
  26544. editor.editorCommands.addCommands({
  26545. mceAddUndoLevel: () => {
  26546. editor.undoManager.add();
  26547. },
  26548. mceEndUndoLevel: () => {
  26549. editor.undoManager.add();
  26550. },
  26551. Undo: () => {
  26552. editor.undoManager.undo();
  26553. },
  26554. Redo: () => {
  26555. editor.undoManager.redo();
  26556. }
  26557. });
  26558. };
  26559. const registerCommands$5 = editor => {
  26560. editor.editorCommands.addCommands({
  26561. Indent: () => {
  26562. indent(editor);
  26563. },
  26564. Outdent: () => {
  26565. outdent(editor);
  26566. }
  26567. });
  26568. editor.editorCommands.addCommands({ Outdent: () => canOutdent(editor) }, 'state');
  26569. };
  26570. const registerCommands$4 = editor => {
  26571. const applyLinkToSelection = (_command, _ui, value) => {
  26572. const linkDetails = isString(value) ? { href: value } : value;
  26573. const anchor = editor.dom.getParent(editor.selection.getNode(), 'a');
  26574. if (isObject(linkDetails) && isString(linkDetails.href)) {
  26575. linkDetails.href = linkDetails.href.replace(/ /g, '%20');
  26576. if (!anchor || !linkDetails.href) {
  26577. editor.formatter.remove('link');
  26578. }
  26579. if (linkDetails.href) {
  26580. editor.formatter.apply('link', linkDetails, anchor);
  26581. }
  26582. }
  26583. };
  26584. editor.editorCommands.addCommands({
  26585. unlink: () => {
  26586. if (editor.selection.isCollapsed()) {
  26587. const elm = editor.dom.getParent(editor.selection.getStart(), 'a');
  26588. if (elm) {
  26589. editor.dom.remove(elm, true);
  26590. }
  26591. return;
  26592. }
  26593. editor.formatter.remove('link');
  26594. },
  26595. mceInsertLink: applyLinkToSelection,
  26596. createLink: applyLinkToSelection
  26597. });
  26598. };
  26599. const registerExecCommands$1 = editor => {
  26600. editor.editorCommands.addCommands({
  26601. 'InsertUnorderedList,InsertOrderedList': command => {
  26602. editor.getDoc().execCommand(command);
  26603. const listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
  26604. if (listElm) {
  26605. const listParent = listElm.parentNode;
  26606. if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
  26607. const bm = editor.selection.getBookmark();
  26608. editor.dom.split(listParent, listElm);
  26609. editor.selection.moveToBookmark(bm);
  26610. }
  26611. }
  26612. }
  26613. });
  26614. };
  26615. const registerQueryStateCommands = editor => {
  26616. editor.editorCommands.addCommands({
  26617. 'InsertUnorderedList,InsertOrderedList': command => {
  26618. const list = editor.dom.getParent(editor.selection.getNode(), 'ul,ol');
  26619. return list && (command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL');
  26620. }
  26621. }, 'state');
  26622. };
  26623. const registerCommands$3 = editor => {
  26624. registerExecCommands$1(editor);
  26625. registerQueryStateCommands(editor);
  26626. };
  26627. const registerCommands$2 = editor => {
  26628. editor.editorCommands.addCommands({
  26629. insertParagraph: () => {
  26630. insert(editor);
  26631. },
  26632. mceInsertNewLine: (_command, _ui, value) => {
  26633. insert(editor, value);
  26634. },
  26635. InsertLineBreak: (_command, _ui, value) => {
  26636. insert$1(editor, value);
  26637. }
  26638. });
  26639. };
  26640. const registerCommands$1 = editor => {
  26641. editor.editorCommands.addCommands({
  26642. mceSelectNodeDepth: (_command, _ui, value) => {
  26643. let counter = 0;
  26644. editor.dom.getParent(editor.selection.getNode(), node => {
  26645. if (node.nodeType === 1 && counter++ === value) {
  26646. editor.selection.select(node);
  26647. return false;
  26648. }
  26649. }, editor.getBody());
  26650. },
  26651. mceSelectNode: (_command, _ui, value) => {
  26652. editor.selection.select(value);
  26653. },
  26654. selectAll: () => {
  26655. const editingHost = editor.dom.getParent(editor.selection.getStart(), isContentEditableTrue$4);
  26656. if (editingHost) {
  26657. const rng = editor.dom.createRng();
  26658. rng.selectNodeContents(editingHost);
  26659. editor.selection.setRng(rng);
  26660. }
  26661. }
  26662. });
  26663. };
  26664. const registerExecCommands = editor => {
  26665. editor.editorCommands.addCommands({
  26666. mceRemoveNode: (_command, _ui, value) => {
  26667. const node = value !== null && value !== void 0 ? value : editor.selection.getNode();
  26668. if (node !== editor.getBody()) {
  26669. const bm = editor.selection.getBookmark();
  26670. editor.dom.remove(node, true);
  26671. editor.selection.moveToBookmark(bm);
  26672. }
  26673. },
  26674. mcePrint: () => {
  26675. editor.getWin().print();
  26676. },
  26677. mceFocus: (_command, _ui, value) => {
  26678. focus(editor, value);
  26679. },
  26680. mceToggleVisualAid: () => {
  26681. editor.hasVisual = !editor.hasVisual;
  26682. editor.addVisual();
  26683. }
  26684. });
  26685. };
  26686. const registerCommands = editor => {
  26687. registerCommands$a(editor);
  26688. registerCommands$9(editor);
  26689. registerCommands$6(editor);
  26690. registerCommands$1(editor);
  26691. registerCommands$8(editor);
  26692. registerCommands$4(editor);
  26693. registerCommands$5(editor);
  26694. registerCommands$2(editor);
  26695. registerCommands$3(editor);
  26696. registerCommands$7(editor);
  26697. registerExecCommands(editor);
  26698. };
  26699. class EditorCommands {
  26700. constructor(editor) {
  26701. this.commands = {
  26702. state: {},
  26703. exec: {},
  26704. value: {}
  26705. };
  26706. this.editor = editor;
  26707. }
  26708. execCommand(command, ui, value, args) {
  26709. const editor = this.editor;
  26710. const lowerCaseCommand = command.toLowerCase();
  26711. const skipFocus = args === null || args === void 0 ? void 0 : args.skip_focus;
  26712. if (editor.removed) {
  26713. return false;
  26714. }
  26715. if (lowerCaseCommand !== 'mcefocus') {
  26716. if (!/^(mceAddUndoLevel|mceEndUndoLevel)$/i.test(lowerCaseCommand) && !skipFocus) {
  26717. editor.focus();
  26718. } else {
  26719. restore(editor);
  26720. }
  26721. }
  26722. const eventArgs = editor.dispatch('BeforeExecCommand', {
  26723. command,
  26724. ui,
  26725. value
  26726. });
  26727. if (eventArgs.isDefaultPrevented()) {
  26728. return false;
  26729. }
  26730. const func = this.commands.exec[lowerCaseCommand];
  26731. if (isFunction(func)) {
  26732. func(lowerCaseCommand, ui, value);
  26733. editor.dispatch('ExecCommand', {
  26734. command,
  26735. ui,
  26736. value
  26737. });
  26738. return true;
  26739. }
  26740. return false;
  26741. }
  26742. queryCommandState(command) {
  26743. if (this.editor.quirks.isHidden() || this.editor.removed) {
  26744. return false;
  26745. }
  26746. const lowerCaseCommand = command.toLowerCase();
  26747. const func = this.commands.state[lowerCaseCommand];
  26748. if (isFunction(func)) {
  26749. return func(lowerCaseCommand);
  26750. }
  26751. return false;
  26752. }
  26753. queryCommandValue(command) {
  26754. if (this.editor.quirks.isHidden() || this.editor.removed) {
  26755. return '';
  26756. }
  26757. const lowerCaseCommand = command.toLowerCase();
  26758. const func = this.commands.value[lowerCaseCommand];
  26759. if (isFunction(func)) {
  26760. return func(lowerCaseCommand);
  26761. }
  26762. return '';
  26763. }
  26764. addCommands(commandList, type = 'exec') {
  26765. const commands = this.commands;
  26766. each$f(commandList, (callback, command) => {
  26767. each$g(command.toLowerCase().split(','), command => {
  26768. commands[type][command] = callback;
  26769. });
  26770. });
  26771. }
  26772. addCommand(command, callback, scope) {
  26773. const lowerCaseCommand = command.toLowerCase();
  26774. this.commands.exec[lowerCaseCommand] = (_command, ui, value) => callback.call(scope !== null && scope !== void 0 ? scope : this.editor, ui, value);
  26775. }
  26776. queryCommandSupported(command) {
  26777. const lowerCaseCommand = command.toLowerCase();
  26778. if (this.commands.exec[lowerCaseCommand]) {
  26779. return true;
  26780. }
  26781. return false;
  26782. }
  26783. addQueryStateHandler(command, callback, scope) {
  26784. this.commands.state[command.toLowerCase()] = () => callback.call(scope !== null && scope !== void 0 ? scope : this.editor);
  26785. }
  26786. addQueryValueHandler(command, callback, scope) {
  26787. this.commands.value[command.toLowerCase()] = () => callback.call(scope !== null && scope !== void 0 ? scope : this.editor);
  26788. }
  26789. }
  26790. const internalContentEditableAttr = 'data-mce-contenteditable';
  26791. const toggleClass = (elm, cls, state) => {
  26792. if (has(elm, cls) && state === false) {
  26793. remove$7(elm, cls);
  26794. } else if (state) {
  26795. add$2(elm, cls);
  26796. }
  26797. };
  26798. const setEditorCommandState = (editor, cmd, state) => {
  26799. try {
  26800. editor.getDoc().execCommand(cmd, false, String(state));
  26801. } catch (ex) {
  26802. }
  26803. };
  26804. const setContentEditable = (elm, state) => {
  26805. elm.dom.contentEditable = state ? 'true' : 'false';
  26806. };
  26807. const switchOffContentEditableTrue = elm => {
  26808. each$g(descendants(elm, '*[contenteditable="true"]'), elm => {
  26809. set$2(elm, internalContentEditableAttr, 'true');
  26810. setContentEditable(elm, false);
  26811. });
  26812. };
  26813. const switchOnContentEditableTrue = elm => {
  26814. each$g(descendants(elm, `*[${ internalContentEditableAttr }="true"]`), elm => {
  26815. remove$a(elm, internalContentEditableAttr);
  26816. setContentEditable(elm, true);
  26817. });
  26818. };
  26819. const removeFakeSelection = editor => {
  26820. Optional.from(editor.selection.getNode()).each(elm => {
  26821. elm.removeAttribute('data-mce-selected');
  26822. });
  26823. };
  26824. const restoreFakeSelection = editor => {
  26825. editor.selection.setRng(editor.selection.getRng());
  26826. };
  26827. const toggleReadOnly = (editor, state) => {
  26828. const body = SugarElement.fromDom(editor.getBody());
  26829. toggleClass(body, 'mce-content-readonly', state);
  26830. if (state) {
  26831. editor.selection.controlSelection.hideResizeRect();
  26832. editor._selectionOverrides.hideFakeCaret();
  26833. removeFakeSelection(editor);
  26834. editor.readonly = true;
  26835. setContentEditable(body, false);
  26836. switchOffContentEditableTrue(body);
  26837. } else {
  26838. editor.readonly = false;
  26839. setContentEditable(body, true);
  26840. switchOnContentEditableTrue(body);
  26841. setEditorCommandState(editor, 'StyleWithCSS', false);
  26842. setEditorCommandState(editor, 'enableInlineTableEditing', false);
  26843. setEditorCommandState(editor, 'enableObjectResizing', false);
  26844. if (hasEditorOrUiFocus(editor)) {
  26845. editor.focus();
  26846. }
  26847. restoreFakeSelection(editor);
  26848. editor.nodeChanged();
  26849. }
  26850. };
  26851. const isReadOnly = editor => editor.readonly;
  26852. const registerFilters = editor => {
  26853. editor.parser.addAttributeFilter('contenteditable', nodes => {
  26854. if (isReadOnly(editor)) {
  26855. each$g(nodes, node => {
  26856. node.attr(internalContentEditableAttr, node.attr('contenteditable'));
  26857. node.attr('contenteditable', 'false');
  26858. });
  26859. }
  26860. });
  26861. editor.serializer.addAttributeFilter(internalContentEditableAttr, nodes => {
  26862. if (isReadOnly(editor)) {
  26863. each$g(nodes, node => {
  26864. node.attr('contenteditable', node.attr(internalContentEditableAttr));
  26865. });
  26866. }
  26867. });
  26868. editor.serializer.addTempAttr(internalContentEditableAttr);
  26869. };
  26870. const registerReadOnlyContentFilters = editor => {
  26871. if (editor.serializer) {
  26872. registerFilters(editor);
  26873. } else {
  26874. editor.on('PreInit', () => {
  26875. registerFilters(editor);
  26876. });
  26877. }
  26878. };
  26879. const isClickEvent = e => e.type === 'click';
  26880. const getAnchorHrefOpt = (editor, elm) => {
  26881. const isRoot = elm => eq(elm, SugarElement.fromDom(editor.getBody()));
  26882. return closest$3(elm, 'a', isRoot).bind(a => getOpt(a, 'href'));
  26883. };
  26884. const processReadonlyEvents = (editor, e) => {
  26885. if (isClickEvent(e) && !VK.metaKeyPressed(e)) {
  26886. const elm = SugarElement.fromDom(e.target);
  26887. getAnchorHrefOpt(editor, elm).each(href => {
  26888. e.preventDefault();
  26889. if (/^#/.test(href)) {
  26890. const targetEl = editor.dom.select(`${ href },[name="${ removeLeading(href, '#') }"]`);
  26891. if (targetEl.length) {
  26892. editor.selection.scrollIntoView(targetEl[0], true);
  26893. }
  26894. } else {
  26895. window.open(href, '_blank', 'rel=noopener noreferrer,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes,scrollbars=yes');
  26896. }
  26897. });
  26898. }
  26899. };
  26900. const registerReadOnlySelectionBlockers = editor => {
  26901. editor.on('ShowCaret', e => {
  26902. if (isReadOnly(editor)) {
  26903. e.preventDefault();
  26904. }
  26905. });
  26906. editor.on('ObjectSelected', e => {
  26907. if (isReadOnly(editor)) {
  26908. e.preventDefault();
  26909. }
  26910. });
  26911. };
  26912. const 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', ' ');
  26913. class EventDispatcher {
  26914. constructor(settings) {
  26915. this.bindings = {};
  26916. this.settings = settings || {};
  26917. this.scope = this.settings.scope || this;
  26918. this.toggleEvent = this.settings.toggleEvent || never;
  26919. }
  26920. static isNative(name) {
  26921. return !!nativeEvents[name.toLowerCase()];
  26922. }
  26923. fire(name, args) {
  26924. return this.dispatch(name, args);
  26925. }
  26926. dispatch(name, args) {
  26927. const lcName = name.toLowerCase();
  26928. const event = normalize$3(lcName, args !== null && args !== void 0 ? args : {}, this.scope);
  26929. if (this.settings.beforeFire) {
  26930. this.settings.beforeFire(event);
  26931. }
  26932. const handlers = this.bindings[lcName];
  26933. if (handlers) {
  26934. for (let i = 0, l = handlers.length; i < l; i++) {
  26935. const callback = handlers[i];
  26936. if (callback.removed) {
  26937. continue;
  26938. }
  26939. if (callback.once) {
  26940. this.off(lcName, callback.func);
  26941. }
  26942. if (event.isImmediatePropagationStopped()) {
  26943. return event;
  26944. }
  26945. if (callback.func.call(this.scope, event) === false) {
  26946. event.preventDefault();
  26947. return event;
  26948. }
  26949. }
  26950. }
  26951. return event;
  26952. }
  26953. on(name, callback, prepend, extra) {
  26954. if (callback === false) {
  26955. callback = never;
  26956. }
  26957. if (callback) {
  26958. const wrappedCallback = {
  26959. func: callback,
  26960. removed: false
  26961. };
  26962. if (extra) {
  26963. Tools.extend(wrappedCallback, extra);
  26964. }
  26965. const names = name.toLowerCase().split(' ');
  26966. let i = names.length;
  26967. while (i--) {
  26968. const currentName = names[i];
  26969. let handlers = this.bindings[currentName];
  26970. if (!handlers) {
  26971. handlers = [];
  26972. this.toggleEvent(currentName, true);
  26973. }
  26974. if (prepend) {
  26975. handlers = [
  26976. wrappedCallback,
  26977. ...handlers
  26978. ];
  26979. } else {
  26980. handlers = [
  26981. ...handlers,
  26982. wrappedCallback
  26983. ];
  26984. }
  26985. this.bindings[currentName] = handlers;
  26986. }
  26987. }
  26988. return this;
  26989. }
  26990. off(name, callback) {
  26991. if (name) {
  26992. const names = name.toLowerCase().split(' ');
  26993. let i = names.length;
  26994. while (i--) {
  26995. const currentName = names[i];
  26996. let handlers = this.bindings[currentName];
  26997. if (!currentName) {
  26998. each$f(this.bindings, (_value, bindingName) => {
  26999. this.toggleEvent(bindingName, false);
  27000. delete this.bindings[bindingName];
  27001. });
  27002. return this;
  27003. }
  27004. if (handlers) {
  27005. if (!callback) {
  27006. handlers.length = 0;
  27007. } else {
  27008. const filteredHandlers = partition$2(handlers, handler => handler.func === callback);
  27009. handlers = filteredHandlers.fail;
  27010. this.bindings[currentName] = handlers;
  27011. each$g(filteredHandlers.pass, handler => {
  27012. handler.removed = true;
  27013. });
  27014. }
  27015. if (!handlers.length) {
  27016. this.toggleEvent(name, false);
  27017. delete this.bindings[currentName];
  27018. }
  27019. }
  27020. }
  27021. } else {
  27022. each$f(this.bindings, (_value, name) => {
  27023. this.toggleEvent(name, false);
  27024. });
  27025. this.bindings = {};
  27026. }
  27027. return this;
  27028. }
  27029. once(name, callback, prepend) {
  27030. return this.on(name, callback, prepend, { once: true });
  27031. }
  27032. has(name) {
  27033. name = name.toLowerCase();
  27034. return !(!this.bindings[name] || this.bindings[name].length === 0);
  27035. }
  27036. }
  27037. const getEventDispatcher = obj => {
  27038. if (!obj._eventDispatcher) {
  27039. obj._eventDispatcher = new EventDispatcher({
  27040. scope: obj,
  27041. toggleEvent: (name, state) => {
  27042. if (EventDispatcher.isNative(name) && obj.toggleNativeEvent) {
  27043. obj.toggleNativeEvent(name, state);
  27044. }
  27045. }
  27046. });
  27047. }
  27048. return obj._eventDispatcher;
  27049. };
  27050. const Observable = {
  27051. fire(name, args, bubble) {
  27052. return this.dispatch(name, args, bubble);
  27053. },
  27054. dispatch(name, args, bubble) {
  27055. const self = this;
  27056. if (self.removed && name !== 'remove' && name !== 'detach') {
  27057. return normalize$3(name.toLowerCase(), args !== null && args !== void 0 ? args : {}, self);
  27058. }
  27059. const dispatcherArgs = getEventDispatcher(self).dispatch(name, args);
  27060. if (bubble !== false && self.parent) {
  27061. let parent = self.parent();
  27062. while (parent && !dispatcherArgs.isPropagationStopped()) {
  27063. parent.dispatch(name, dispatcherArgs, false);
  27064. parent = parent.parent();
  27065. }
  27066. }
  27067. return dispatcherArgs;
  27068. },
  27069. on(name, callback, prepend) {
  27070. return getEventDispatcher(this).on(name, callback, prepend);
  27071. },
  27072. off(name, callback) {
  27073. return getEventDispatcher(this).off(name, callback);
  27074. },
  27075. once(name, callback) {
  27076. return getEventDispatcher(this).once(name, callback);
  27077. },
  27078. hasEventListeners(name) {
  27079. return getEventDispatcher(this).has(name);
  27080. }
  27081. };
  27082. const DOM$2 = DOMUtils.DOM;
  27083. let customEventRootDelegates;
  27084. const getEventTarget = (editor, eventName) => {
  27085. if (eventName === 'selectionchange') {
  27086. return editor.getDoc();
  27087. }
  27088. if (!editor.inline && /^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(eventName)) {
  27089. return editor.getDoc().documentElement;
  27090. }
  27091. const eventRoot = getEventRoot(editor);
  27092. if (eventRoot) {
  27093. if (!editor.eventRoot) {
  27094. editor.eventRoot = DOM$2.select(eventRoot)[0];
  27095. }
  27096. return editor.eventRoot;
  27097. }
  27098. return editor.getBody();
  27099. };
  27100. const isListening = editor => !editor.hidden && !isReadOnly(editor);
  27101. const fireEvent = (editor, eventName, e) => {
  27102. if (isListening(editor)) {
  27103. editor.dispatch(eventName, e);
  27104. } else if (isReadOnly(editor)) {
  27105. processReadonlyEvents(editor, e);
  27106. }
  27107. };
  27108. const bindEventDelegate = (editor, eventName) => {
  27109. let delegate;
  27110. if (!editor.delegates) {
  27111. editor.delegates = {};
  27112. }
  27113. if (editor.delegates[eventName] || editor.removed) {
  27114. return;
  27115. }
  27116. const eventRootElm = getEventTarget(editor, eventName);
  27117. if (getEventRoot(editor)) {
  27118. if (!customEventRootDelegates) {
  27119. customEventRootDelegates = {};
  27120. editor.editorManager.on('removeEditor', () => {
  27121. if (!editor.editorManager.activeEditor) {
  27122. if (customEventRootDelegates) {
  27123. each$f(customEventRootDelegates, (_value, name) => {
  27124. editor.dom.unbind(getEventTarget(editor, name));
  27125. });
  27126. customEventRootDelegates = null;
  27127. }
  27128. }
  27129. });
  27130. }
  27131. if (customEventRootDelegates[eventName]) {
  27132. return;
  27133. }
  27134. delegate = e => {
  27135. const target = e.target;
  27136. const editors = editor.editorManager.get();
  27137. let i = editors.length;
  27138. while (i--) {
  27139. const body = editors[i].getBody();
  27140. if (body === target || DOM$2.isChildOf(target, body)) {
  27141. fireEvent(editors[i], eventName, e);
  27142. }
  27143. }
  27144. };
  27145. customEventRootDelegates[eventName] = delegate;
  27146. DOM$2.bind(eventRootElm, eventName, delegate);
  27147. } else {
  27148. delegate = e => {
  27149. fireEvent(editor, eventName, e);
  27150. };
  27151. DOM$2.bind(eventRootElm, eventName, delegate);
  27152. editor.delegates[eventName] = delegate;
  27153. }
  27154. };
  27155. const EditorObservable = {
  27156. ...Observable,
  27157. bindPendingEventDelegates() {
  27158. const self = this;
  27159. Tools.each(self._pendingNativeEvents, name => {
  27160. bindEventDelegate(self, name);
  27161. });
  27162. },
  27163. toggleNativeEvent(name, state) {
  27164. const self = this;
  27165. if (name === 'focus' || name === 'blur') {
  27166. return;
  27167. }
  27168. if (self.removed) {
  27169. return;
  27170. }
  27171. if (state) {
  27172. if (self.initialized) {
  27173. bindEventDelegate(self, name);
  27174. } else {
  27175. if (!self._pendingNativeEvents) {
  27176. self._pendingNativeEvents = [name];
  27177. } else {
  27178. self._pendingNativeEvents.push(name);
  27179. }
  27180. }
  27181. } else if (self.initialized) {
  27182. self.dom.unbind(getEventTarget(self, name), name, self.delegates[name]);
  27183. delete self.delegates[name];
  27184. }
  27185. },
  27186. unbindAllNativeEvents() {
  27187. const self = this;
  27188. const body = self.getBody();
  27189. const dom = self.dom;
  27190. if (self.delegates) {
  27191. each$f(self.delegates, (value, name) => {
  27192. self.dom.unbind(getEventTarget(self, name), name, value);
  27193. });
  27194. delete self.delegates;
  27195. }
  27196. if (!self.inline && body && dom) {
  27197. body.onload = null;
  27198. dom.unbind(self.getWin());
  27199. dom.unbind(self.getDoc());
  27200. }
  27201. if (dom) {
  27202. dom.unbind(body);
  27203. dom.unbind(self.getContainer());
  27204. }
  27205. }
  27206. };
  27207. const stringListProcessor = value => {
  27208. if (isString(value)) {
  27209. return {
  27210. value: value.split(/[ ,]/),
  27211. valid: true
  27212. };
  27213. } else if (isArrayOf(value, isString)) {
  27214. return {
  27215. value,
  27216. valid: true
  27217. };
  27218. } else {
  27219. return {
  27220. valid: false,
  27221. message: `The value must be a string[] or a comma/space separated string.`
  27222. };
  27223. }
  27224. };
  27225. const getBuiltInProcessor = type => {
  27226. const validator = (() => {
  27227. switch (type) {
  27228. case 'array':
  27229. return isArray$1;
  27230. case 'boolean':
  27231. return isBoolean;
  27232. case 'function':
  27233. return isFunction;
  27234. case 'number':
  27235. return isNumber;
  27236. case 'object':
  27237. return isObject;
  27238. case 'string':
  27239. return isString;
  27240. case 'string[]':
  27241. return stringListProcessor;
  27242. case 'object[]':
  27243. return val => isArrayOf(val, isObject);
  27244. case 'regexp':
  27245. return val => is$4(val, RegExp);
  27246. }
  27247. })();
  27248. return value => processValue(value, validator, `The value must be a ${ type }.`);
  27249. };
  27250. const isBuiltInSpec = spec => isString(spec.processor);
  27251. const getErrorMessage = (message, result) => {
  27252. const additionalText = isEmpty$3(result.message) ? '' : `. ${ result.message }`;
  27253. return message + additionalText;
  27254. };
  27255. const isValidResult = result => result.valid;
  27256. const processValue = (value, processor, message = '') => {
  27257. const result = processor(value);
  27258. if (isBoolean(result)) {
  27259. return result ? {
  27260. value: value,
  27261. valid: true
  27262. } : {
  27263. valid: false,
  27264. message
  27265. };
  27266. } else {
  27267. return result;
  27268. }
  27269. };
  27270. const processDefaultValue = (name, defaultValue, processor) => {
  27271. if (!isUndefined(defaultValue)) {
  27272. const result = processValue(defaultValue, processor);
  27273. if (isValidResult(result)) {
  27274. return result.value;
  27275. } else {
  27276. console.error(getErrorMessage(`Invalid default value passed for the "${ name }" option`, result));
  27277. }
  27278. }
  27279. return undefined;
  27280. };
  27281. const create$5 = (editor, initialOptions) => {
  27282. const registry = {};
  27283. const values = {};
  27284. const setValue = (name, value, processor) => {
  27285. const result = processValue(value, processor);
  27286. if (isValidResult(result)) {
  27287. values[name] = result.value;
  27288. return true;
  27289. } else {
  27290. console.warn(getErrorMessage(`Invalid value passed for the ${ name } option`, result));
  27291. return false;
  27292. }
  27293. };
  27294. const register = (name, spec) => {
  27295. const processor = isBuiltInSpec(spec) ? getBuiltInProcessor(spec.processor) : spec.processor;
  27296. const defaultValue = processDefaultValue(name, spec.default, processor);
  27297. registry[name] = {
  27298. ...spec,
  27299. default: defaultValue,
  27300. processor
  27301. };
  27302. const initValue = get$a(values, name).orThunk(() => get$a(initialOptions, name));
  27303. initValue.each(value => setValue(name, value, processor));
  27304. };
  27305. const isRegistered = name => has$2(registry, name);
  27306. const get = name => get$a(values, name).orThunk(() => get$a(registry, name).map(spec => spec.default)).getOrUndefined();
  27307. const set = (name, value) => {
  27308. if (!isRegistered(name)) {
  27309. console.warn(`"${ name }" is not a registered option. Ensure the option has been registered before setting a value.`);
  27310. return false;
  27311. } else {
  27312. const spec = registry[name];
  27313. if (spec.immutable) {
  27314. console.error(`"${ name }" is an immutable option and cannot be updated`);
  27315. return false;
  27316. } else {
  27317. return setValue(name, value, spec.processor);
  27318. }
  27319. }
  27320. };
  27321. const unset = name => {
  27322. const registered = isRegistered(name);
  27323. if (registered) {
  27324. delete values[name];
  27325. }
  27326. return registered;
  27327. };
  27328. const isSet = name => has$2(values, name);
  27329. return {
  27330. register,
  27331. isRegistered,
  27332. get,
  27333. set,
  27334. unset,
  27335. isSet
  27336. };
  27337. };
  27338. const defaultModes = [
  27339. 'design',
  27340. 'readonly'
  27341. ];
  27342. const switchToMode = (editor, activeMode, availableModes, mode) => {
  27343. const oldMode = availableModes[activeMode.get()];
  27344. const newMode = availableModes[mode];
  27345. try {
  27346. newMode.activate();
  27347. } catch (e) {
  27348. console.error(`problem while activating editor mode ${ mode }:`, e);
  27349. return;
  27350. }
  27351. oldMode.deactivate();
  27352. if (oldMode.editorReadOnly !== newMode.editorReadOnly) {
  27353. toggleReadOnly(editor, newMode.editorReadOnly);
  27354. }
  27355. activeMode.set(mode);
  27356. fireSwitchMode(editor, mode);
  27357. };
  27358. const setMode = (editor, availableModes, activeMode, mode) => {
  27359. if (mode === activeMode.get()) {
  27360. return;
  27361. } else if (!has$2(availableModes, mode)) {
  27362. throw new Error(`Editor mode '${ mode }' is invalid`);
  27363. }
  27364. if (editor.initialized) {
  27365. switchToMode(editor, activeMode, availableModes, mode);
  27366. } else {
  27367. editor.on('init', () => switchToMode(editor, activeMode, availableModes, mode));
  27368. }
  27369. };
  27370. const registerMode = (availableModes, mode, api) => {
  27371. if (contains$2(defaultModes, mode)) {
  27372. throw new Error(`Cannot override default mode ${ mode }`);
  27373. }
  27374. return {
  27375. ...availableModes,
  27376. [mode]: {
  27377. ...api,
  27378. deactivate: () => {
  27379. try {
  27380. api.deactivate();
  27381. } catch (e) {
  27382. console.error(`problem while deactivating editor mode ${ mode }:`, e);
  27383. }
  27384. }
  27385. }
  27386. };
  27387. };
  27388. const create$4 = editor => {
  27389. const activeMode = Cell('design');
  27390. const availableModes = Cell({
  27391. design: {
  27392. activate: noop,
  27393. deactivate: noop,
  27394. editorReadOnly: false
  27395. },
  27396. readonly: {
  27397. activate: noop,
  27398. deactivate: noop,
  27399. editorReadOnly: true
  27400. }
  27401. });
  27402. registerReadOnlyContentFilters(editor);
  27403. registerReadOnlySelectionBlockers(editor);
  27404. return {
  27405. isReadOnly: () => isReadOnly(editor),
  27406. set: mode => setMode(editor, availableModes.get(), activeMode, mode),
  27407. get: () => activeMode.get(),
  27408. register: (mode, api) => {
  27409. availableModes.set(registerMode(availableModes.get(), mode, api));
  27410. }
  27411. };
  27412. };
  27413. const each$2 = Tools.each, explode = Tools.explode;
  27414. const keyCodeLookup = {
  27415. f1: 112,
  27416. f2: 113,
  27417. f3: 114,
  27418. f4: 115,
  27419. f5: 116,
  27420. f6: 117,
  27421. f7: 118,
  27422. f8: 119,
  27423. f9: 120,
  27424. f10: 121,
  27425. f11: 122,
  27426. f12: 123
  27427. };
  27428. const modifierNames = Tools.makeMap('alt,ctrl,shift,meta,access');
  27429. const parseShortcut = pattern => {
  27430. let key;
  27431. const shortcut = {};
  27432. const isMac = Env.os.isMacOS() || Env.os.isiOS();
  27433. each$2(explode(pattern.toLowerCase(), '+'), value => {
  27434. if (value in modifierNames) {
  27435. shortcut[value] = true;
  27436. } else {
  27437. if (/^[0-9]{2,}$/.test(value)) {
  27438. shortcut.keyCode = parseInt(value, 10);
  27439. } else {
  27440. shortcut.charCode = value.charCodeAt(0);
  27441. shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);
  27442. }
  27443. }
  27444. });
  27445. const id = [shortcut.keyCode];
  27446. for (key in modifierNames) {
  27447. if (shortcut[key]) {
  27448. id.push(key);
  27449. } else {
  27450. shortcut[key] = false;
  27451. }
  27452. }
  27453. shortcut.id = id.join(',');
  27454. if (shortcut.access) {
  27455. shortcut.alt = true;
  27456. if (isMac) {
  27457. shortcut.ctrl = true;
  27458. } else {
  27459. shortcut.shift = true;
  27460. }
  27461. }
  27462. if (shortcut.meta) {
  27463. if (isMac) {
  27464. shortcut.meta = true;
  27465. } else {
  27466. shortcut.ctrl = true;
  27467. shortcut.meta = false;
  27468. }
  27469. }
  27470. return shortcut;
  27471. };
  27472. class Shortcuts {
  27473. constructor(editor) {
  27474. this.shortcuts = {};
  27475. this.pendingPatterns = [];
  27476. this.editor = editor;
  27477. const self = this;
  27478. editor.on('keyup keypress keydown', e => {
  27479. if ((self.hasModifier(e) || self.isFunctionKey(e)) && !e.isDefaultPrevented()) {
  27480. each$2(self.shortcuts, shortcut => {
  27481. if (self.matchShortcut(e, shortcut)) {
  27482. self.pendingPatterns = shortcut.subpatterns.slice(0);
  27483. if (e.type === 'keydown') {
  27484. self.executeShortcutAction(shortcut);
  27485. }
  27486. return true;
  27487. }
  27488. });
  27489. if (self.matchShortcut(e, self.pendingPatterns[0])) {
  27490. if (self.pendingPatterns.length === 1) {
  27491. if (e.type === 'keydown') {
  27492. self.executeShortcutAction(self.pendingPatterns[0]);
  27493. }
  27494. }
  27495. self.pendingPatterns.shift();
  27496. }
  27497. }
  27498. });
  27499. }
  27500. add(pattern, desc, cmdFunc, scope) {
  27501. const self = this;
  27502. const func = self.normalizeCommandFunc(cmdFunc);
  27503. each$2(explode(Tools.trim(pattern)), pattern => {
  27504. const shortcut = self.createShortcut(pattern, desc, func, scope);
  27505. self.shortcuts[shortcut.id] = shortcut;
  27506. });
  27507. return true;
  27508. }
  27509. remove(pattern) {
  27510. const shortcut = this.createShortcut(pattern);
  27511. if (this.shortcuts[shortcut.id]) {
  27512. delete this.shortcuts[shortcut.id];
  27513. return true;
  27514. }
  27515. return false;
  27516. }
  27517. normalizeCommandFunc(cmdFunc) {
  27518. const self = this;
  27519. const cmd = cmdFunc;
  27520. if (typeof cmd === 'string') {
  27521. return () => {
  27522. self.editor.execCommand(cmd, false, null);
  27523. };
  27524. } else if (Tools.isArray(cmd)) {
  27525. return () => {
  27526. self.editor.execCommand(cmd[0], cmd[1], cmd[2]);
  27527. };
  27528. } else {
  27529. return cmd;
  27530. }
  27531. }
  27532. createShortcut(pattern, desc, cmdFunc, scope) {
  27533. const shortcuts = Tools.map(explode(pattern, '>'), parseShortcut);
  27534. shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {
  27535. func: cmdFunc,
  27536. scope: scope || this.editor
  27537. });
  27538. return Tools.extend(shortcuts[0], {
  27539. desc: this.editor.translate(desc),
  27540. subpatterns: shortcuts.slice(1)
  27541. });
  27542. }
  27543. hasModifier(e) {
  27544. return e.altKey || e.ctrlKey || e.metaKey;
  27545. }
  27546. isFunctionKey(e) {
  27547. return e.type === 'keydown' && e.keyCode >= 112 && e.keyCode <= 123;
  27548. }
  27549. matchShortcut(e, shortcut) {
  27550. if (!shortcut) {
  27551. return false;
  27552. }
  27553. if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
  27554. return false;
  27555. }
  27556. if (shortcut.alt !== e.altKey || shortcut.shift !== e.shiftKey) {
  27557. return false;
  27558. }
  27559. if (e.keyCode === shortcut.keyCode || e.charCode && e.charCode === shortcut.charCode) {
  27560. e.preventDefault();
  27561. return true;
  27562. }
  27563. return false;
  27564. }
  27565. executeShortcutAction(shortcut) {
  27566. return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
  27567. }
  27568. }
  27569. const create$3 = () => {
  27570. const buttons = {};
  27571. const menuItems = {};
  27572. const popups = {};
  27573. const icons = {};
  27574. const contextMenus = {};
  27575. const contextToolbars = {};
  27576. const sidebars = {};
  27577. const add = (collection, type) => (name, spec) => collection[name.toLowerCase()] = {
  27578. ...spec,
  27579. type
  27580. };
  27581. const addIcon = (name, svgData) => icons[name.toLowerCase()] = svgData;
  27582. return {
  27583. addButton: add(buttons, 'button'),
  27584. addGroupToolbarButton: add(buttons, 'grouptoolbarbutton'),
  27585. addToggleButton: add(buttons, 'togglebutton'),
  27586. addMenuButton: add(buttons, 'menubutton'),
  27587. addSplitButton: add(buttons, 'splitbutton'),
  27588. addMenuItem: add(menuItems, 'menuitem'),
  27589. addNestedMenuItem: add(menuItems, 'nestedmenuitem'),
  27590. addToggleMenuItem: add(menuItems, 'togglemenuitem'),
  27591. addAutocompleter: add(popups, 'autocompleter'),
  27592. addContextMenu: add(contextMenus, 'contextmenu'),
  27593. addContextToolbar: add(contextToolbars, 'contexttoolbar'),
  27594. addContextForm: add(contextToolbars, 'contextform'),
  27595. addSidebar: add(sidebars, 'sidebar'),
  27596. addIcon,
  27597. getAll: () => ({
  27598. buttons,
  27599. menuItems,
  27600. icons,
  27601. popups,
  27602. contextMenus,
  27603. contextToolbars,
  27604. sidebars
  27605. })
  27606. };
  27607. };
  27608. const registry = () => {
  27609. const bridge = create$3();
  27610. return {
  27611. addAutocompleter: bridge.addAutocompleter,
  27612. addButton: bridge.addButton,
  27613. addContextForm: bridge.addContextForm,
  27614. addContextMenu: bridge.addContextMenu,
  27615. addContextToolbar: bridge.addContextToolbar,
  27616. addIcon: bridge.addIcon,
  27617. addMenuButton: bridge.addMenuButton,
  27618. addMenuItem: bridge.addMenuItem,
  27619. addNestedMenuItem: bridge.addNestedMenuItem,
  27620. addSidebar: bridge.addSidebar,
  27621. addSplitButton: bridge.addSplitButton,
  27622. addToggleButton: bridge.addToggleButton,
  27623. addGroupToolbarButton: bridge.addGroupToolbarButton,
  27624. addToggleMenuItem: bridge.addToggleMenuItem,
  27625. getAll: bridge.getAll
  27626. };
  27627. };
  27628. const DOM$1 = DOMUtils.DOM;
  27629. const extend = Tools.extend, each$1 = Tools.each;
  27630. class Editor {
  27631. constructor(id, options, editorManager) {
  27632. this.plugins = {};
  27633. this.contentCSS = [];
  27634. this.contentStyles = [];
  27635. this.loadedCSS = {};
  27636. this.isNotDirty = false;
  27637. this.editorManager = editorManager;
  27638. this.documentBaseUrl = editorManager.documentBaseURL;
  27639. extend(this, EditorObservable);
  27640. const self = this;
  27641. this.id = id;
  27642. this.hidden = false;
  27643. const normalizedOptions = normalizeOptions(editorManager.defaultOptions, options);
  27644. this.options = create$5(self, normalizedOptions);
  27645. register$7(self);
  27646. const getOption = this.options.get;
  27647. if (getOption('deprecation_warnings')) {
  27648. logWarnings(options, normalizedOptions);
  27649. }
  27650. const suffix = getOption('suffix');
  27651. if (suffix) {
  27652. editorManager.suffix = suffix;
  27653. }
  27654. this.suffix = editorManager.suffix;
  27655. const baseUrl = getOption('base_url');
  27656. if (baseUrl) {
  27657. editorManager._setBaseUrl(baseUrl);
  27658. }
  27659. this.baseUri = editorManager.baseURI;
  27660. const referrerPolicy = getReferrerPolicy(self);
  27661. if (referrerPolicy) {
  27662. ScriptLoader.ScriptLoader._setReferrerPolicy(referrerPolicy);
  27663. DOMUtils.DOM.styleSheetLoader._setReferrerPolicy(referrerPolicy);
  27664. }
  27665. AddOnManager.languageLoad = getOption('language_load');
  27666. AddOnManager.baseURL = editorManager.baseURL;
  27667. this.setDirty(false);
  27668. this.documentBaseURI = new URI(getDocumentBaseUrl(self), { base_uri: this.baseUri });
  27669. this.baseURI = this.baseUri;
  27670. this.inline = isInline(self);
  27671. this.shortcuts = new Shortcuts(this);
  27672. this.editorCommands = new EditorCommands(this);
  27673. registerCommands(this);
  27674. const cacheSuffix = getOption('cache_suffix');
  27675. if (cacheSuffix) {
  27676. Env.cacheSuffix = cacheSuffix.replace(/^[\?\&]+/, '');
  27677. }
  27678. this.ui = {
  27679. registry: registry(),
  27680. styleSheetLoader: undefined,
  27681. show: noop,
  27682. hide: noop,
  27683. setEnabled: noop,
  27684. isEnabled: always
  27685. };
  27686. this.mode = create$4(self);
  27687. editorManager.dispatch('SetupEditor', { editor: this });
  27688. const setupCallback = getSetupCallback(self);
  27689. if (isFunction(setupCallback)) {
  27690. setupCallback.call(self, self);
  27691. }
  27692. }
  27693. render() {
  27694. render(this);
  27695. }
  27696. focus(skipFocus) {
  27697. this.execCommand('mceFocus', false, skipFocus);
  27698. }
  27699. hasFocus() {
  27700. return hasFocus(this);
  27701. }
  27702. translate(text) {
  27703. return I18n.translate(text);
  27704. }
  27705. getParam(name, defaultVal, type) {
  27706. const options = this.options;
  27707. if (!options.isRegistered(name)) {
  27708. if (isNonNullable(type)) {
  27709. options.register(name, {
  27710. processor: type,
  27711. default: defaultVal
  27712. });
  27713. } else {
  27714. options.register(name, {
  27715. processor: always,
  27716. default: defaultVal
  27717. });
  27718. }
  27719. }
  27720. return !options.isSet(name) && !isUndefined(defaultVal) ? defaultVal : options.get(name);
  27721. }
  27722. hasPlugin(name, loaded) {
  27723. const hasPlugin = contains$2(getPlugins(this), name);
  27724. if (hasPlugin) {
  27725. return loaded ? PluginManager.get(name) !== undefined : true;
  27726. } else {
  27727. return false;
  27728. }
  27729. }
  27730. nodeChanged(args) {
  27731. this._nodeChangeDispatcher.nodeChanged(args);
  27732. }
  27733. addCommand(name, callback, scope) {
  27734. this.editorCommands.addCommand(name, callback, scope);
  27735. }
  27736. addQueryStateHandler(name, callback, scope) {
  27737. this.editorCommands.addQueryStateHandler(name, callback, scope);
  27738. }
  27739. addQueryValueHandler(name, callback, scope) {
  27740. this.editorCommands.addQueryValueHandler(name, callback, scope);
  27741. }
  27742. addShortcut(pattern, desc, cmdFunc, scope) {
  27743. this.shortcuts.add(pattern, desc, cmdFunc, scope);
  27744. }
  27745. execCommand(cmd, ui, value, args) {
  27746. return this.editorCommands.execCommand(cmd, ui, value, args);
  27747. }
  27748. queryCommandState(cmd) {
  27749. return this.editorCommands.queryCommandState(cmd);
  27750. }
  27751. queryCommandValue(cmd) {
  27752. return this.editorCommands.queryCommandValue(cmd);
  27753. }
  27754. queryCommandSupported(cmd) {
  27755. return this.editorCommands.queryCommandSupported(cmd);
  27756. }
  27757. show() {
  27758. const self = this;
  27759. if (self.hidden) {
  27760. self.hidden = false;
  27761. if (self.inline) {
  27762. self.getBody().contentEditable = 'true';
  27763. } else {
  27764. DOM$1.show(self.getContainer());
  27765. DOM$1.hide(self.id);
  27766. }
  27767. self.load();
  27768. self.dispatch('show');
  27769. }
  27770. }
  27771. hide() {
  27772. const self = this;
  27773. if (!self.hidden) {
  27774. self.save();
  27775. if (self.inline) {
  27776. self.getBody().contentEditable = 'false';
  27777. if (self === self.editorManager.focusedEditor) {
  27778. self.editorManager.focusedEditor = null;
  27779. }
  27780. } else {
  27781. DOM$1.hide(self.getContainer());
  27782. DOM$1.setStyle(self.id, 'display', self.orgDisplay);
  27783. }
  27784. self.hidden = true;
  27785. self.dispatch('hide');
  27786. }
  27787. }
  27788. isHidden() {
  27789. return this.hidden;
  27790. }
  27791. setProgressState(state, time) {
  27792. this.dispatch('ProgressState', {
  27793. state,
  27794. time
  27795. });
  27796. }
  27797. load(args) {
  27798. const self = this;
  27799. let elm = self.getElement(), html;
  27800. if (self.removed) {
  27801. return '';
  27802. }
  27803. if (elm) {
  27804. args = args || {};
  27805. args.load = true;
  27806. const value = isTextareaOrInput(elm) ? elm.value : elm.innerHTML;
  27807. html = self.setContent(value, args);
  27808. args.element = elm;
  27809. if (!args.no_events) {
  27810. self.dispatch('LoadContent', args);
  27811. }
  27812. args.element = elm = null;
  27813. return html;
  27814. }
  27815. }
  27816. save(args) {
  27817. const self = this;
  27818. let elm = self.getElement(), html, form;
  27819. if (!elm || !self.initialized || self.removed) {
  27820. return;
  27821. }
  27822. args = args || {};
  27823. args.save = true;
  27824. args.element = elm;
  27825. html = args.content = self.getContent(args);
  27826. if (!args.no_events) {
  27827. self.dispatch('SaveContent', args);
  27828. }
  27829. if (args.format === 'raw') {
  27830. self.dispatch('RawSaveContent', args);
  27831. }
  27832. html = args.content;
  27833. if (!isTextareaOrInput(elm)) {
  27834. if (args.is_removing || !self.inline) {
  27835. elm.innerHTML = html;
  27836. }
  27837. if (form = DOM$1.getParent(self.id, 'form')) {
  27838. each$1(form.elements, elm => {
  27839. if (elm.name === self.id) {
  27840. elm.value = html;
  27841. return false;
  27842. }
  27843. });
  27844. }
  27845. } else {
  27846. elm.value = html;
  27847. }
  27848. args.element = elm = null;
  27849. if (args.set_dirty !== false) {
  27850. self.setDirty(false);
  27851. }
  27852. return html;
  27853. }
  27854. setContent(content, args) {
  27855. return setContent(this, content, args);
  27856. }
  27857. getContent(args) {
  27858. return getContent(this, args);
  27859. }
  27860. insertContent(content, args) {
  27861. if (args) {
  27862. content = extend({ content }, args);
  27863. }
  27864. this.execCommand('mceInsertContent', false, content);
  27865. }
  27866. resetContent(initialContent) {
  27867. if (initialContent === undefined) {
  27868. setContent(this, this.startContent, { format: 'raw' });
  27869. } else {
  27870. setContent(this, initialContent);
  27871. }
  27872. this.undoManager.reset();
  27873. this.setDirty(false);
  27874. this.nodeChanged();
  27875. }
  27876. isDirty() {
  27877. return !this.isNotDirty;
  27878. }
  27879. setDirty(state) {
  27880. const oldState = !this.isNotDirty;
  27881. this.isNotDirty = !state;
  27882. if (state && state !== oldState) {
  27883. this.dispatch('dirty');
  27884. }
  27885. }
  27886. getContainer() {
  27887. const self = this;
  27888. if (!self.container) {
  27889. self.container = DOM$1.get(self.editorContainer || self.id + '_parent');
  27890. }
  27891. return self.container;
  27892. }
  27893. getContentAreaContainer() {
  27894. return this.contentAreaContainer;
  27895. }
  27896. getElement() {
  27897. if (!this.targetElm) {
  27898. this.targetElm = DOM$1.get(this.id);
  27899. }
  27900. return this.targetElm;
  27901. }
  27902. getWin() {
  27903. const self = this;
  27904. let elm;
  27905. if (!self.contentWindow) {
  27906. elm = self.iframeElement;
  27907. if (elm) {
  27908. self.contentWindow = elm.contentWindow;
  27909. }
  27910. }
  27911. return self.contentWindow;
  27912. }
  27913. getDoc() {
  27914. const self = this;
  27915. let win;
  27916. if (!self.contentDocument) {
  27917. win = self.getWin();
  27918. if (win) {
  27919. self.contentDocument = win.document;
  27920. }
  27921. }
  27922. return self.contentDocument;
  27923. }
  27924. getBody() {
  27925. const doc = this.getDoc();
  27926. return this.bodyElement || (doc ? doc.body : null);
  27927. }
  27928. convertURL(url, name, elm) {
  27929. const self = this, getOption = self.options.get;
  27930. const urlConverterCallback = getUrlConverterCallback(self);
  27931. if (isFunction(urlConverterCallback)) {
  27932. return urlConverterCallback.call(self, url, elm, true, name);
  27933. }
  27934. if (!getOption('convert_urls') || elm && elm.nodeName === 'LINK' || url.indexOf('file:') === 0 || url.length === 0) {
  27935. return url;
  27936. }
  27937. if (getOption('relative_urls')) {
  27938. return self.documentBaseURI.toRelative(url);
  27939. }
  27940. url = self.documentBaseURI.toAbsolute(url, getOption('remove_script_host'));
  27941. return url;
  27942. }
  27943. addVisual(elm) {
  27944. addVisual(this, elm);
  27945. }
  27946. remove() {
  27947. remove$1(this);
  27948. }
  27949. destroy(automatic) {
  27950. destroy(this, automatic);
  27951. }
  27952. uploadImages() {
  27953. return this.editorUpload.uploadImages();
  27954. }
  27955. _scanForImages() {
  27956. return this.editorUpload.scanForImages();
  27957. }
  27958. }
  27959. const DOM = DOMUtils.DOM;
  27960. const each = Tools.each;
  27961. let boundGlobalEvents = false;
  27962. let beforeUnloadDelegate;
  27963. let editors = [];
  27964. const globalEventDelegate = e => {
  27965. const type = e.type;
  27966. each(EditorManager.get(), editor => {
  27967. switch (type) {
  27968. case 'scroll':
  27969. editor.dispatch('ScrollWindow', e);
  27970. break;
  27971. case 'resize':
  27972. editor.dispatch('ResizeWindow', e);
  27973. break;
  27974. }
  27975. });
  27976. };
  27977. const toggleGlobalEvents = state => {
  27978. if (state !== boundGlobalEvents) {
  27979. const DOM = DOMUtils.DOM;
  27980. if (state) {
  27981. DOM.bind(window, 'resize', globalEventDelegate);
  27982. DOM.bind(window, 'scroll', globalEventDelegate);
  27983. } else {
  27984. DOM.unbind(window, 'resize', globalEventDelegate);
  27985. DOM.unbind(window, 'scroll', globalEventDelegate);
  27986. }
  27987. boundGlobalEvents = state;
  27988. }
  27989. };
  27990. const removeEditorFromList = targetEditor => {
  27991. const oldEditors = editors;
  27992. editors = filter$6(editors, editor => {
  27993. return targetEditor !== editor;
  27994. });
  27995. if (EditorManager.activeEditor === targetEditor) {
  27996. EditorManager.activeEditor = editors.length > 0 ? editors[0] : null;
  27997. }
  27998. if (EditorManager.focusedEditor === targetEditor) {
  27999. EditorManager.focusedEditor = null;
  28000. }
  28001. return oldEditors.length !== editors.length;
  28002. };
  28003. const purgeDestroyedEditor = editor => {
  28004. if (editor && editor.initialized && !(editor.getContainer() || editor.getBody()).parentNode) {
  28005. removeEditorFromList(editor);
  28006. editor.unbindAllNativeEvents();
  28007. editor.destroy(true);
  28008. editor.removed = true;
  28009. editor = null;
  28010. }
  28011. return editor;
  28012. };
  28013. const isQuirksMode = document.compatMode !== 'CSS1Compat';
  28014. const EditorManager = {
  28015. ...Observable,
  28016. baseURI: null,
  28017. baseURL: null,
  28018. defaultOptions: {},
  28019. documentBaseURL: null,
  28020. suffix: null,
  28021. majorVersion: '6',
  28022. minorVersion: '0.3',
  28023. releaseDate: '2022-05-25',
  28024. i18n: I18n,
  28025. activeEditor: null,
  28026. focusedEditor: null,
  28027. setup() {
  28028. const self = this;
  28029. let baseURL, documentBaseURL, suffix = '';
  28030. documentBaseURL = URI.getDocumentBaseUrl(document.location);
  28031. if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
  28032. documentBaseURL = documentBaseURL.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  28033. if (!/[\/\\]$/.test(documentBaseURL)) {
  28034. documentBaseURL += '/';
  28035. }
  28036. }
  28037. const preInit = window.tinymce || window.tinyMCEPreInit;
  28038. if (preInit) {
  28039. baseURL = preInit.base || preInit.baseURL;
  28040. suffix = preInit.suffix;
  28041. } else {
  28042. const scripts = document.getElementsByTagName('script');
  28043. for (let i = 0; i < scripts.length; i++) {
  28044. const src = scripts[i].src || '';
  28045. if (src === '') {
  28046. continue;
  28047. }
  28048. const srcScript = src.substring(src.lastIndexOf('/'));
  28049. if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
  28050. if (srcScript.indexOf('.min') !== -1) {
  28051. suffix = '.min';
  28052. }
  28053. baseURL = src.substring(0, src.lastIndexOf('/'));
  28054. break;
  28055. }
  28056. }
  28057. if (!baseURL && document.currentScript) {
  28058. const src = document.currentScript.src;
  28059. if (src.indexOf('.min') !== -1) {
  28060. suffix = '.min';
  28061. }
  28062. baseURL = src.substring(0, src.lastIndexOf('/'));
  28063. }
  28064. }
  28065. self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
  28066. self.documentBaseURL = documentBaseURL;
  28067. self.baseURI = new URI(self.baseURL);
  28068. self.suffix = suffix;
  28069. setup$v(self);
  28070. },
  28071. overrideDefaults(defaultOptions) {
  28072. const baseUrl = defaultOptions.base_url;
  28073. if (baseUrl) {
  28074. this._setBaseUrl(baseUrl);
  28075. }
  28076. const suffix = defaultOptions.suffix;
  28077. if (defaultOptions.suffix) {
  28078. this.suffix = suffix;
  28079. }
  28080. this.defaultOptions = defaultOptions;
  28081. const pluginBaseUrls = defaultOptions.plugin_base_urls;
  28082. if (pluginBaseUrls !== undefined) {
  28083. each$f(pluginBaseUrls, (pluginBaseUrl, pluginName) => {
  28084. AddOnManager.PluginManager.urls[pluginName] = pluginBaseUrl;
  28085. });
  28086. }
  28087. },
  28088. init(options) {
  28089. const self = this;
  28090. let result;
  28091. const 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', ' ');
  28092. const isInvalidInlineTarget = (options, elm) => options.inline && elm.tagName.toLowerCase() in invalidInlineTargets;
  28093. const createId = elm => {
  28094. let id = elm.id;
  28095. if (!id) {
  28096. id = get$a(elm, 'name').filter(name => !DOM.get(name)).getOrThunk(DOM.uniqueId);
  28097. elm.setAttribute('id', id);
  28098. }
  28099. return id;
  28100. };
  28101. const execCallback = name => {
  28102. const callback = options[name];
  28103. if (!callback) {
  28104. return;
  28105. }
  28106. return callback.apply(self, []);
  28107. };
  28108. const findTargets = options => {
  28109. if (Env.browser.isIE() || Env.browser.isEdge()) {
  28110. initError('TinyMCE does not support the browser you are using. For a list of supported' + ' browsers please see: https://www.tiny.cloud/docs/tinymce/6/support/#supportedwebbrowsers');
  28111. return [];
  28112. } else if (isQuirksMode) {
  28113. initError('Failed to initialize the editor as the document is not in standards mode. ' + 'TinyMCE requires standards mode.');
  28114. return [];
  28115. } else if (isString(options.selector)) {
  28116. return DOM.select(options.selector);
  28117. } else if (isNonNullable(options.target)) {
  28118. return [options.target];
  28119. } else {
  28120. return [];
  28121. }
  28122. };
  28123. let provideResults = editors => {
  28124. result = editors;
  28125. };
  28126. const initEditors = () => {
  28127. let initCount = 0;
  28128. const editors = [];
  28129. let targets;
  28130. const createEditor = (id, options, targetElm) => {
  28131. const editor = new Editor(id, options, self);
  28132. editors.push(editor);
  28133. editor.on('init', () => {
  28134. if (++initCount === targets.length) {
  28135. provideResults(editors);
  28136. }
  28137. });
  28138. editor.targetElm = editor.targetElm || targetElm;
  28139. editor.render();
  28140. };
  28141. DOM.unbind(window, 'ready', initEditors);
  28142. execCallback('onpageload');
  28143. targets = unique$1(findTargets(options));
  28144. Tools.each(targets, elm => {
  28145. purgeDestroyedEditor(self.get(elm.id));
  28146. });
  28147. targets = Tools.grep(targets, elm => {
  28148. return !self.get(elm.id);
  28149. });
  28150. if (targets.length === 0) {
  28151. provideResults([]);
  28152. } else {
  28153. each(targets, elm => {
  28154. if (isInvalidInlineTarget(options, elm)) {
  28155. initError('Could not initialize inline editor on invalid inline target element', elm);
  28156. } else {
  28157. createEditor(createId(elm), options, elm);
  28158. }
  28159. });
  28160. }
  28161. };
  28162. DOM.bind(window, 'ready', initEditors);
  28163. return new Promise(resolve => {
  28164. if (result) {
  28165. resolve(result);
  28166. } else {
  28167. provideResults = editors => {
  28168. resolve(editors);
  28169. };
  28170. }
  28171. });
  28172. },
  28173. get(id) {
  28174. if (arguments.length === 0) {
  28175. return editors.slice(0);
  28176. } else if (isString(id)) {
  28177. return find$2(editors, editor => {
  28178. return editor.id === id;
  28179. }).getOr(null);
  28180. } else if (isNumber(id)) {
  28181. return editors[id] ? editors[id] : null;
  28182. } else {
  28183. return null;
  28184. }
  28185. },
  28186. add(editor) {
  28187. const self = this;
  28188. const existingEditor = self.get(editor.id);
  28189. if (existingEditor === editor) {
  28190. return editor;
  28191. }
  28192. if (existingEditor === null) {
  28193. editors.push(editor);
  28194. }
  28195. toggleGlobalEvents(true);
  28196. self.activeEditor = editor;
  28197. self.dispatch('AddEditor', { editor });
  28198. if (!beforeUnloadDelegate) {
  28199. beforeUnloadDelegate = e => {
  28200. const event = self.dispatch('BeforeUnload');
  28201. if (event.returnValue) {
  28202. e.preventDefault();
  28203. e.returnValue = event.returnValue;
  28204. return event.returnValue;
  28205. }
  28206. };
  28207. window.addEventListener('beforeunload', beforeUnloadDelegate);
  28208. }
  28209. return editor;
  28210. },
  28211. createEditor(id, options) {
  28212. return this.add(new Editor(id, options, this));
  28213. },
  28214. remove(selector) {
  28215. const self = this;
  28216. let i, editor;
  28217. if (!selector) {
  28218. for (i = editors.length - 1; i >= 0; i--) {
  28219. self.remove(editors[i]);
  28220. }
  28221. return;
  28222. }
  28223. if (isString(selector)) {
  28224. each(DOM.select(selector), elm => {
  28225. editor = self.get(elm.id);
  28226. if (editor) {
  28227. self.remove(editor);
  28228. }
  28229. });
  28230. return;
  28231. }
  28232. editor = selector;
  28233. if (isNull(self.get(editor.id))) {
  28234. return null;
  28235. }
  28236. if (removeEditorFromList(editor)) {
  28237. self.dispatch('RemoveEditor', { editor });
  28238. }
  28239. if (editors.length === 0) {
  28240. window.removeEventListener('beforeunload', beforeUnloadDelegate);
  28241. }
  28242. editor.remove();
  28243. toggleGlobalEvents(editors.length > 0);
  28244. return editor;
  28245. },
  28246. execCommand(cmd, ui, value) {
  28247. var _a;
  28248. const self = this;
  28249. const editorId = isObject(value) ? (_a = value.id) !== null && _a !== void 0 ? _a : value.index : value;
  28250. switch (cmd) {
  28251. case 'mceAddEditor': {
  28252. if (!self.get(editorId)) {
  28253. const editorOptions = value.options;
  28254. new Editor(editorId, editorOptions, self).render();
  28255. }
  28256. return true;
  28257. }
  28258. case 'mceRemoveEditor': {
  28259. const editor = self.get(editorId);
  28260. if (editor) {
  28261. editor.remove();
  28262. }
  28263. return true;
  28264. }
  28265. case 'mceToggleEditor': {
  28266. const editor = self.get(editorId);
  28267. if (!editor) {
  28268. self.execCommand('mceAddEditor', false, value);
  28269. return true;
  28270. }
  28271. if (editor.isHidden()) {
  28272. editor.show();
  28273. } else {
  28274. editor.hide();
  28275. }
  28276. return true;
  28277. }
  28278. }
  28279. if (self.activeEditor) {
  28280. return self.activeEditor.execCommand(cmd, ui, value);
  28281. }
  28282. return false;
  28283. },
  28284. triggerSave: () => {
  28285. each(editors, editor => {
  28286. editor.save();
  28287. });
  28288. },
  28289. addI18n: (code, items) => {
  28290. I18n.add(code, items);
  28291. },
  28292. translate: text => {
  28293. return I18n.translate(text);
  28294. },
  28295. setActive(editor) {
  28296. const activeEditor = this.activeEditor;
  28297. if (this.activeEditor !== editor) {
  28298. if (activeEditor) {
  28299. activeEditor.dispatch('deactivate', { relatedTarget: editor });
  28300. }
  28301. editor.dispatch('activate', { relatedTarget: activeEditor });
  28302. }
  28303. this.activeEditor = editor;
  28304. },
  28305. _setBaseUrl(baseUrl) {
  28306. this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ''));
  28307. this.baseURI = new URI(this.baseURL);
  28308. }
  28309. };
  28310. EditorManager.setup();
  28311. const setup = () => {
  28312. const dataValue = value$2();
  28313. const FakeClipboardItem = items => ({
  28314. items,
  28315. types: keys(items),
  28316. getType: type => get$a(items, type).getOrUndefined()
  28317. });
  28318. const write = data => {
  28319. dataValue.set(data);
  28320. };
  28321. const read = () => dataValue.get().getOrUndefined();
  28322. const clear = dataValue.clear;
  28323. return {
  28324. FakeClipboardItem,
  28325. write,
  28326. read,
  28327. clear
  28328. };
  28329. };
  28330. const FakeClipboard = setup();
  28331. const min = Math.min, max = Math.max, round = Math.round;
  28332. const relativePosition = (rect, targetRect, rel) => {
  28333. let x = targetRect.x;
  28334. let y = targetRect.y;
  28335. const w = rect.w;
  28336. const h = rect.h;
  28337. const targetW = targetRect.w;
  28338. const targetH = targetRect.h;
  28339. const relChars = (rel || '').split('');
  28340. if (relChars[0] === 'b') {
  28341. y += targetH;
  28342. }
  28343. if (relChars[1] === 'r') {
  28344. x += targetW;
  28345. }
  28346. if (relChars[0] === 'c') {
  28347. y += round(targetH / 2);
  28348. }
  28349. if (relChars[1] === 'c') {
  28350. x += round(targetW / 2);
  28351. }
  28352. if (relChars[3] === 'b') {
  28353. y -= h;
  28354. }
  28355. if (relChars[4] === 'r') {
  28356. x -= w;
  28357. }
  28358. if (relChars[3] === 'c') {
  28359. y -= round(h / 2);
  28360. }
  28361. if (relChars[4] === 'c') {
  28362. x -= round(w / 2);
  28363. }
  28364. return create$2(x, y, w, h);
  28365. };
  28366. const findBestRelativePosition = (rect, targetRect, constrainRect, rels) => {
  28367. let pos, i;
  28368. for (i = 0; i < rels.length; i++) {
  28369. pos = relativePosition(rect, targetRect, rels[i]);
  28370. 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) {
  28371. return rels[i];
  28372. }
  28373. }
  28374. return null;
  28375. };
  28376. const inflate = (rect, w, h) => {
  28377. return create$2(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2);
  28378. };
  28379. const intersect = (rect, cropRect) => {
  28380. const x1 = max(rect.x, cropRect.x);
  28381. const y1 = max(rect.y, cropRect.y);
  28382. const x2 = min(rect.x + rect.w, cropRect.x + cropRect.w);
  28383. const y2 = min(rect.y + rect.h, cropRect.y + cropRect.h);
  28384. if (x2 - x1 < 0 || y2 - y1 < 0) {
  28385. return null;
  28386. }
  28387. return create$2(x1, y1, x2 - x1, y2 - y1);
  28388. };
  28389. const clamp = (rect, clampRect, fixedSize) => {
  28390. let x1 = rect.x;
  28391. let y1 = rect.y;
  28392. let x2 = rect.x + rect.w;
  28393. let y2 = rect.y + rect.h;
  28394. const cx2 = clampRect.x + clampRect.w;
  28395. const cy2 = clampRect.y + clampRect.h;
  28396. const underflowX1 = max(0, clampRect.x - x1);
  28397. const underflowY1 = max(0, clampRect.y - y1);
  28398. const overflowX2 = max(0, x2 - cx2);
  28399. const overflowY2 = max(0, y2 - cy2);
  28400. x1 += underflowX1;
  28401. y1 += underflowY1;
  28402. if (fixedSize) {
  28403. x2 += underflowX1;
  28404. y2 += underflowY1;
  28405. x1 -= overflowX2;
  28406. y1 -= overflowY2;
  28407. }
  28408. x2 -= overflowX2;
  28409. y2 -= overflowY2;
  28410. return create$2(x1, y1, x2 - x1, y2 - y1);
  28411. };
  28412. const create$2 = (x, y, w, h) => {
  28413. return {
  28414. x,
  28415. y,
  28416. w,
  28417. h
  28418. };
  28419. };
  28420. const fromClientRect = clientRect => {
  28421. return create$2(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
  28422. };
  28423. const Rect = {
  28424. inflate,
  28425. relativePosition,
  28426. findBestRelativePosition,
  28427. intersect,
  28428. clamp,
  28429. create: create$2,
  28430. fromClientRect
  28431. };
  28432. const awaiter = (resolveCb, rejectCb, timeout = 1000) => {
  28433. let done = false;
  28434. let timer = null;
  28435. const complete = completer => (...args) => {
  28436. if (!done) {
  28437. done = true;
  28438. if (timer !== null) {
  28439. clearTimeout(timer);
  28440. timer = null;
  28441. }
  28442. completer.apply(null, args);
  28443. }
  28444. };
  28445. const resolve = complete(resolveCb);
  28446. const reject = complete(rejectCb);
  28447. const start = (...args) => {
  28448. if (!done && timer === null) {
  28449. timer = setTimeout(() => reject.apply(null, args), timeout);
  28450. }
  28451. };
  28452. return {
  28453. start,
  28454. resolve,
  28455. reject
  28456. };
  28457. };
  28458. const create$1 = () => {
  28459. const tasks = {};
  28460. const resultFns = {};
  28461. const load = (id, url) => {
  28462. const loadErrMsg = `Script at URL "${ url }" failed to load`;
  28463. const runErrMsg = `Script at URL "${ url }" did not call \`tinymce.Resource.add('${ id }', data)\` within 1 second`;
  28464. if (tasks[id] !== undefined) {
  28465. return tasks[id];
  28466. } else {
  28467. const task = new Promise((resolve, reject) => {
  28468. const waiter = awaiter(resolve, reject);
  28469. resultFns[id] = waiter.resolve;
  28470. ScriptLoader.ScriptLoader.loadScript(url).then(() => waiter.start(runErrMsg), () => waiter.reject(loadErrMsg));
  28471. });
  28472. tasks[id] = task;
  28473. return task;
  28474. }
  28475. };
  28476. const add = (id, data) => {
  28477. if (resultFns[id] !== undefined) {
  28478. resultFns[id](data);
  28479. delete resultFns[id];
  28480. }
  28481. tasks[id] = Promise.resolve(data);
  28482. };
  28483. const unload = id => {
  28484. delete tasks[id];
  28485. };
  28486. return {
  28487. load,
  28488. add,
  28489. unload
  28490. };
  28491. };
  28492. const Resource = create$1();
  28493. const create = () => (() => {
  28494. let data = {};
  28495. let keys = [];
  28496. const storage = {
  28497. getItem: key => {
  28498. const item = data[key];
  28499. return item ? item : null;
  28500. },
  28501. setItem: (key, value) => {
  28502. keys.push(key);
  28503. data[key] = String(value);
  28504. },
  28505. key: index => {
  28506. return keys[index];
  28507. },
  28508. removeItem: key => {
  28509. keys = keys.filter(k => k === key);
  28510. delete data[key];
  28511. },
  28512. clear: () => {
  28513. keys = [];
  28514. data = {};
  28515. },
  28516. length: 0
  28517. };
  28518. Object.defineProperty(storage, 'length', {
  28519. get: () => keys.length,
  28520. configurable: false,
  28521. enumerable: false
  28522. });
  28523. return storage;
  28524. })();
  28525. let localStorage;
  28526. try {
  28527. const test = '__storage_test__';
  28528. localStorage = window.localStorage;
  28529. localStorage.setItem(test, test);
  28530. localStorage.removeItem(test);
  28531. } catch (e) {
  28532. localStorage = create();
  28533. }
  28534. var LocalStorage = localStorage;
  28535. const publicApi = {
  28536. geom: { Rect },
  28537. util: {
  28538. Delay,
  28539. Tools,
  28540. VK,
  28541. URI,
  28542. EventDispatcher,
  28543. Observable,
  28544. I18n,
  28545. LocalStorage,
  28546. ImageUploader
  28547. },
  28548. dom: {
  28549. EventUtils,
  28550. TreeWalker: DomTreeWalker,
  28551. TextSeeker,
  28552. DOMUtils,
  28553. ScriptLoader,
  28554. RangeUtils,
  28555. Serializer: DomSerializer,
  28556. StyleSheetLoader,
  28557. ControlSelection,
  28558. BookmarkManager,
  28559. Selection: EditorSelection,
  28560. Event: EventUtils.Event
  28561. },
  28562. html: {
  28563. Styles,
  28564. Entities,
  28565. Node: AstNode,
  28566. Schema,
  28567. DomParser,
  28568. Writer,
  28569. Serializer: HtmlSerializer
  28570. },
  28571. Env,
  28572. AddOnManager,
  28573. Annotator,
  28574. Formatter,
  28575. UndoManager,
  28576. EditorCommands,
  28577. WindowManager,
  28578. NotificationManager,
  28579. EditorObservable,
  28580. Shortcuts,
  28581. Editor,
  28582. FocusManager,
  28583. EditorManager,
  28584. DOM: DOMUtils.DOM,
  28585. ScriptLoader: ScriptLoader.ScriptLoader,
  28586. PluginManager,
  28587. ThemeManager,
  28588. ModelManager,
  28589. IconManager,
  28590. Resource,
  28591. FakeClipboard,
  28592. trim: Tools.trim,
  28593. isArray: Tools.isArray,
  28594. is: Tools.is,
  28595. toArray: Tools.toArray,
  28596. makeMap: Tools.makeMap,
  28597. each: Tools.each,
  28598. map: Tools.map,
  28599. grep: Tools.grep,
  28600. inArray: Tools.inArray,
  28601. extend: Tools.extend,
  28602. walk: Tools.walk,
  28603. resolve: Tools.resolve,
  28604. explode: Tools.explode,
  28605. _addCacheSuffix: Tools._addCacheSuffix
  28606. };
  28607. const tinymce = Tools.extend(EditorManager, publicApi);
  28608. const exportToModuleLoaders = tinymce => {
  28609. if (typeof module === 'object') {
  28610. try {
  28611. module.exports = tinymce;
  28612. } catch (_) {
  28613. }
  28614. }
  28615. };
  28616. const exportToWindowGlobal = tinymce => {
  28617. window.tinymce = tinymce;
  28618. window.tinyMCE = tinymce;
  28619. };
  28620. exportToWindowGlobal(tinymce);
  28621. exportToModuleLoaders(tinymce);
  28622. })();